Skip to content

feature: Added FGTs support in github integration #648

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

sahitya-chandra
Copy link
Contributor

@sahitya-chandra sahitya-chandra commented Apr 22, 2025

Linked Issue(s)

fixed #643

Acceptance Criteria fulfillment

Added FGT support for GIthub Integration while retaining the PAT usage.

Proposed changes (including videos or screenshots)

Integration using FGT

Screencast.from.2025-04-22.18-48-15.webm

Integration using PAT

Screencast.from.2025-04-22.18-49-07.webm

Further comments

Renamed getMissingPATScopes to getMissingTokenScopes for handling FGTs and PATs both.

Updated the UI text to mention both PATs and FGTs and modified handleSubmission function.

Summary by CodeRabbit

  • New Features
    • Improved support for both GitHub Personal Access Tokens (PAT) and Fine-Grained Tokens (FGT), including detection and validation of token type.
    • Enhanced error messages now specify whether missing requirements are "scopes" or "permissions" based on token type.
  • UI Improvements
    • Updated token input labels and instructions to reference both PAT and FGT.
    • Changed link text to "Generate new token" and standardized capitalization of "GitHub".
  • Bug Fixes
    • More accurate detection and messaging for missing GitHub token permissions or scopes.

Copy link

coderabbitai bot commented Apr 22, 2025

"""

Walkthrough

The changes introduce support for GitHub Fine-Grained Tokens (FGT) in addition to Personal Access Tokens (PAT) for integration within the application. The token validation, permission checking, and linking logic have been refactored to handle both token types. The user interface and instructional text have been updated to reflect support for FGTs. Internal utility functions now distinguish between PAT and FGT, adapting permission checks accordingly, and the linking process records the token type. No changes were made to exported component signatures or GitLab-related logic.

Changes

File(s) Change Summary
web-server/src/content/Dashboards/ConfigureGithubModalBody.tsx Refactored token validation and linking logic to async/await pattern; updated to support both PAT and FGT, including dynamic error messages and success notifications. Updated UI text and labels to reference both token types and clarified instructions. Minor style and whitespace adjustments.
web-server/src/utils/auth.ts Updated checkGitHubValidity to return both validity and token type by inspecting API headers. Generalized and renamed getMissingPATScopes to getMissingTokenScopes, adding logic to check FGT permissions. Modified linkProvider to always include tokenType in meta_data. No changes to GitLab logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ConfigureGithubModalBody
    participant authUtils as Auth Utils (auth.ts)
    participant GitHubAPI

    User->>ConfigureGithubModalBody: Submit GitHub token
    ConfigureGithubModalBody->>authUtils: checkGitHubValidity(token)
    authUtils->>GitHubAPI: Validate token
    GitHubAPI-->>authUtils: Response with headers
    authUtils-->>ConfigureGithubModalBody: { isValid, tokenType }

    alt Token invalid
        ConfigureGithubModalBody-->>User: Show error
    else Token valid
        ConfigureGithubModalBody->>authUtils: getMissingTokenScopes(token, tokenType)
        alt Missing scopes/permissions
            ConfigureGithubModalBody-->>User: Show missing scopes/permissions error
        else All required permissions present
            ConfigureGithubModalBody->>authUtils: linkProvider(token, orgId, 'github', { tokenType })
            authUtils->>GitHubAPI: Link provider
            GitHubAPI-->>authUtils: Success
            authUtils-->>ConfigureGithubModalBody: Success
            ConfigureGithubModalBody-->>User: Show success message with token type
        end
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Support use of GitHub fine-grained tokens in the GitHub integration (#643)
Update permission checking and validation logic to handle both PAT and FGT (#643)
Update UI and instructional text to reference both token types (#643)

Poem

A rabbit hopped to GitHub’s gate,
“PATs and FGTs, now both are great!”
With tokens checked and scopes in view,
The linking’s smooth—permissions too!
So hop along, integrations grow,
Fine-grained or classic—just let us know!
🐇✨
"""

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 2

🧹 Nitpick comments (6)
web-server/src/utils/auth.ts (3)

23-24: Prefer descriptive metadata field names
meta_data is a new top‑level property sent to the backend. We’ve been gradually standardising on metadata (no underscore) in other endpoints – using a single naming style prevents confusion server‑side and in analytics queries. Consider aligning here before the field becomes entrenched.


40-44: Header access might be case‑sensitive in some environments
Axios lower‑cases all header keys (response.headers['x-oauth-scopes']).
If another HTTP layer is swapped in later (e.g., fetch), header names will
need normalisation. Small defensive tweak:

-const scopesString = response.headers['x-oauth-scopes'] as string;
+const scopesString = (response.headers['x-oauth-scopes'] ||
+                      response.headers['X-OAuth-Scopes']) as string | undefined;

51-52: Parameter name still references “pat”
Now that the function handles both PATs and FGTs, the parameter name
pat is misleading.

-export const getMissingTokenScopes = async (pat: string, tokenType: 'PAT' | 'FGT') => {
+export const getMissingTokenScopes = async (token: string, tokenType: 'PAT' | 'FGT') => {

Remember to rename occurrences inside the function.

web-server/src/content/Dashboards/ConfigureGithubModalBody.tsx (3)

52-61: Error message conflates scopes & permissions
For PATs we speak of “scopes”, for FGTs of “permissions”; nice touch.
However, the message currently lumps the whole array into a single string which can overflow the snackbar.

Consider:

-`Token is missing ${tokenType === 'PAT' ? 'scopes' : 'permissions'}: ${missingScopes.join(', ')}`
+`Token is missing ${tokenType === 'PAT' ? 'scopes' : 'permissions'}:\n• ${missingScopes.join('\n• ')}`

This formats the list vertically and keeps each message readable.


64-70: Race‑condition guard for rapid double‑click / Enter presses
isLoading.true() is set after the early‑return validations, but a very quick
double‑click (or the user pressing Enter twice) can still fire handleSubmission again
before the promise chain toggles the flag back. A simple debounce or an
if (isLoading.value) return check at the top prevents accidental duplicate
requests.


95-113: Label and helper text mention PAT/FGT – screenshot still says PAT only
/assets/PAT_permissions.png shows the classic token permission screen.
Users testing FGTs might be confused. Either update the asset or dynamically
switch images based on tokenType once detected.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8a545c0 and c3b92e6.

📒 Files selected for processing (2)
  • web-server/src/content/Dashboards/ConfigureGithubModalBody.tsx (6 hunks)
  • web-server/src/utils/auth.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
web-server/src/utils/auth.ts (1)
web-server/http-server.js (1)
  • axios (5-5)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: All file linting

Comment on lines 51 to 72
export const getMissingTokenScopes = async (pat: string, tokenType: 'PAT' | 'FGT') => {
if (tokenType === 'FGT') {
try {
// For FGTs, check repository permissions (example endpoint)
const response = await axios.get('https://api.github.com/user/repos', {
headers: {
Authorization: `token ${pat}`
},
params: { per_page: 1 } // Fetch one repo to check permissions
});

// FGTs don't return scopes in headers, so we infer permissions from API access
// Example: Check if user has access to repos (simplified)
if (!response.data.length) {
return ['repository_access']; // Custom error for missing repo access
}
// Note: For precise FGT permission checking, use /repos/{owner}/{repo} or specific endpoints
return []; // Assume permissions are sufficient for this example
} catch (error) {
throw new Error('Failed to verify FGT permissions', error);
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

getMissingTokenScopes re‑throws with an invalid Error signature
new Error(message, error) is not valid JS/TS and will throw another error,
masking the real cause.

-      throw new Error('Failed to verify FGT permissions', error);
+      // Node ≥ 16 supports `cause`; fall back to message concat otherwise.
+      throw new Error('Failed to verify FGT permissions', { cause: error as any });

The same pattern exists for the PAT branch (line 88 – unchanged). Fixing both prevents double‑faults in the modal.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const getMissingTokenScopes = async (pat: string, tokenType: 'PAT' | 'FGT') => {
if (tokenType === 'FGT') {
try {
// For FGTs, check repository permissions (example endpoint)
const response = await axios.get('https://api.github.com/user/repos', {
headers: {
Authorization: `token ${pat}`
},
params: { per_page: 1 } // Fetch one repo to check permissions
});
// FGTs don't return scopes in headers, so we infer permissions from API access
// Example: Check if user has access to repos (simplified)
if (!response.data.length) {
return ['repository_access']; // Custom error for missing repo access
}
// Note: For precise FGT permission checking, use /repos/{owner}/{repo} or specific endpoints
return []; // Assume permissions are sufficient for this example
} catch (error) {
throw new Error('Failed to verify FGT permissions', error);
}
}
} catch (error) {
// Node ≥ 16 supports `cause`; fall back to message concat otherwise.
throw new Error('Failed to verify FGT permissions', { cause: error as any });
}

Comment on lines 30 to 46
export async function checkGitHubValidity(
good_stuff: string
): Promise<boolean> {
): Promise<{ isValid: boolean; tokenType: 'PAT' | 'FGT' }> {
try {
await axios.get('https://api.github.com/user', {
const response = await axios.get('https://api.github.com/user', {
headers: {
Authorization: `token ${good_stuff}`
}
});
return true;

const scopesString = response.headers['x-oauth-scopes'] as string;
// PATs have scopes in x-oauth-scopes, FGTs do not
const tokenType = scopesString ? 'PAT' : 'FGT';
return { isValid: true, tokenType };
} catch (error) {
return false;
return { isValid: false, tokenType: 'PAT' }; // Default to PAT for error handling
}
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

❓ Verification inconclusive

Invalid‑token path always labels the token as a PAT
Inside the catch block we return { isValid: false, tokenType: 'PAT' }.
If the call fails because the user supplied an FGT with no user scope, we’ll still tell the UI it’s a PAT. The UI then shows “PAT” in its error toast, which can mislead users.

Diff suggestion:

-    return { isValid: false, tokenType: 'PAT' }; // Default to PAT for error handling
+    // We can’t know the type here – surface the uncertainty
+    return { isValid: false, tokenType: 'unknown' as never };

You can branch on 'unknown' in the caller to render a neutral error message.


#!/bin/bash
set -e

echo "=== checkGitHubValidity implementation ==="
rg -n "export async function checkGitHubValidity" -A10 -B3 web-server/src/utils/auth.ts || true

echo
echo "=== All references to checkGitHubValidity ==="
rg -n "checkGitHubValidity" -n || true


Revise catch handling to avoid mis‑labeling tokens

The catch block today always returns { isValid: false, tokenType: 'PAT' }, which misleads callers when the failure was for an FGT (no scopes). Instead, we should surface “unknown” and update the function’s signature and callers accordingly.

Changes required:

  • Expand the return type to include an "UNKNOWN" variant.
  • In the catch, return { isValid: false, tokenType: 'UNKNOWN' }.
  • Update all call sites of checkGitHubValidity to handle the new "UNKNOWN" branch and render a neutral error.

Diff in web-server/src/utils/auth.ts:

-export async function checkGitHubValidity(
-  githubToken: string
-): Promise<{ isValid: boolean; tokenType: 'PAT' | 'FGT' }> {
+export async function checkGitHubValidity(
+  githubToken: string
+): Promise<{ isValid: boolean; tokenType: 'PAT' | 'FGT' | 'UNKNOWN' }> {
   try {
     const response = await axios.get('https://api.github.com/user', {
       headers: { Authorization: `token ${githubToken}` }
     });
     const scopesString = response.headers['x-oauth-scopes'] as string;
     const tokenType = scopesString ? 'PAT' : 'FGT';
     return { isValid: true, tokenType };
   } catch (error) {
-    return { isValid: false, tokenType: 'PAT' }; // Default to PAT for error handling
+    // Couldn’t verify scopes – type is unknown
+    return { isValid: false, tokenType: 'UNKNOWN' };
   }
 }

And in each caller:

  • Add a case for tokenType === 'UNKNOWN' and show a neutral “couldn’t verify token” message.

Committable suggestion skipped: line range outside the PR's diff.

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

♻️ Duplicate comments (2)
web-server/src/utils/auth.ts (2)

45-45: ⚠️ Potential issue

Consider returning 'UNKNOWN' for token type during validation failures

When validation fails, returning a default of 'PAT' could be misleading if the error occurred while validating an FGT. This might cause incorrect error messaging in the UI.

-    return { isValid: false, tokenType: 'PAT' };
+    return { isValid: false, tokenType: 'UNKNOWN' as never };

You'll also need to update the function's return type signature and handle the 'UNKNOWN' case in callers.


70-70: ⚠️ Potential issue

Fix invalid Error constructor usage

The current Error constructor usage is not valid JavaScript/TypeScript. The second parameter should be an options object with a cause property for modern Node.js, or you need another approach for older versions.

-      throw new Error('Failed to verify FGT permissions', error);
+      // For Node.js ≥16.9.0
+      throw new Error('Failed to verify FGT permissions', { cause: error });
+      // For older Node.js versions
+      // const e = new Error('Failed to verify FGT permissions');
+      // e.cause = error;
+      // throw e;

The same issue exists in the PAT error handling at line 87, which should also be fixed.

🧹 Nitpick comments (2)
web-server/src/utils/auth.ts (2)

51-54: Rename parameter for clarity

The parameter name pat is now misleading since it could be either a PAT or an FGT. Consider using a more neutral name like token.

export const getMissingTokenScopes = async (
-  pat: string,
+  token: string,
  tokenType: 'PAT' | 'FGT'
) => {

Remember to update all references to this parameter inside the function body.


57-62: Consider adding timeout to API request

Network requests can hang indefinitely without proper timeout settings. It's a good practice to add a timeout to API requests, especially for authentication-related functionality.

      const response = await axios.get('https://api.github.com/user/repos', {
        headers: {
          Authorization: `token ${pat}`
        },
        params: { per_page: 1 },
+       timeout: 10000 // 10 seconds
      });

This would also be beneficial for other API requests in this file.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2997bf1 and 7e19386.

📒 Files selected for processing (2)
  • web-server/src/content/Dashboards/ConfigureGithubModalBody.tsx (6 hunks)
  • web-server/src/utils/auth.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • web-server/src/content/Dashboards/ConfigureGithubModalBody.tsx
🧰 Additional context used
🧬 Code Graph Analysis (1)
web-server/src/utils/auth.ts (1)
web-server/http-server.js (1)
  • axios (5-5)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: All file linting
🔇 Additional comments (2)
web-server/src/utils/auth.ts (2)

23-23: Good addition of default token type

The addition of a default token type ensures backward compatibility with existing code while supporting the new FGT functionality.


40-43: Effective token type detection mechanism

Using the presence of scopes in the response headers to differentiate between PAT and FGT is an elegant solution. The comment explains the logic clearly.

Comment on lines +65 to +67
if (!response.data.length) {
return ['repository_access'];
}
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Clarify repository access requirement logic

The current logic assumes that if no repositories are returned, it means the token lacks repository access. However, this could also happen if the user genuinely has no repositories. Consider adding a more robust check.


🌐 Web query:

How to verify GitHub Fine-Grained Token permissions for repository access?

💡 Result:

Verifying GitHub Fine-Grained Token Permissions for Repository Access

Overview

GitHub Fine-Grained Personal Access Tokens (PATs) allow you to specify exactly which repositories and permissions a token has, providing more control and security compared to classic tokens[7]. However, verifying what a fine-grained token can access after it's been created is less straightforward than with classic tokens.


How to Check Permissions of a Fine-Grained Token

1. Review Token Settings in the GitHub UI

  • Navigate to Settings > Developer settings > Personal access tokens > Fine-grained tokens in your GitHub account.
  • Here, you can see each token, its associated repositories, and the granularity of its permissions (read, write, admin, etc.)[2][9].
  • This section presents the most complete view of the token's capabilities after creation.

2. Understand Permissions via the API

  • When you use a fine-grained token with the REST API, GitHub responds with a special HTTP header:
    X-Accepted-GitHub-Permissions
  • This header indicates the permissions your token provided during the request and what permissions are required for the endpoint. By making test API requests (e.g., to a repository endpoint), you can see if your token is authorized for the action you desire[1][4].

Note: There is currently no single API endpoint that returns a list of all permissions granted to a fine-grained token. Unlike classic tokens, simply requesting the API root does not reveal detailed permissions for fine-grained tokens[3].

3. Testing Permissions

  • Attempt actions (via CLI or API) that require specific permissions (e.g., listing issues, pushing commits). If your token lacks the required permission, the request will fail with an error indicating insufficient permissions.
  • The API documentation for each endpoint specifies which fine-grained permissions are required[1][4][10].

4. Reference Documentation

  • GitHub REST API docs list the fine-grained permissions required for each endpoint, helping you cross-check your token's settings with the needs of your automation or integration[1][4][10].

Key Points to Remember

  • Fine-grained PATs are limited to only those repositories you specify at creation, and only with the precise permissions granted.
  • To verify access, consult the token management page in GitHub or use the REST API and inspect the X-Accepted-GitHub-Permissions header in API responses[1][2][4].
  • If your token needs access to additional repositories or permissions, you must generate a new token or edit the existing one, as permissions cannot be expanded by the token itself after creation.
  • Classic methods for checking token scopes (e.g., requesting the API root) do not work with fine-grained PATs[3].

Summary Table: Fine-Grained Token Verification Methods

Method What You Learn Where to Use
GitHub UI (Token Settings) See repositories/permissions assigned Personal access tokens management page
REST API + X-Accepted-GitHub-Permissions See if a specific API call will succeed Any API request using the fine-grained PAT
Test Actions (CLI/API) Confirm permission by success/failure Command line or custom scripts
API Docs Understand required permissions GitHub REST API documentation

Conclusion

To verify a fine-grained PAT's permissions for repository access, review the token's configuration in GitHub account settings and test API or CLI actions for required functionality. For specific API permission details, inspect the X-Accepted-GitHub-Permissions header in API responses. There is no direct API endpoint to enumerate all permissions granted to a fine-grained token at this time[1][2][3][4].

Citations:


Clarify repository‐access check vs. “no repos” case

Right now, an empty response.data always signals missing repo permissions—even if the user simply has no repos. Instead, inspect the X-Accepted-GitHub-Permissions header to distinguish “no repos because you’re not allowed” from “no repos because there aren’t any.” For example:

- if (!response.data.length) {
-   return ['repository_access'];
- }
+ const perms = response.headers['x-accepted-github-permissions'] as string;
+ if (!response.data.length) {
+   // If the token wasn’t granted repository read access, flag it
+   if (!perms?.includes('contents:read')) {
+     return ['repository_access'];
+   }
+   // Otherwise it’s just an empty repo list
+   return [];
+ }

• File: web-server/src/utils/auth.ts (around lines 65–67)

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!response.data.length) {
return ['repository_access'];
}
const perms = response.headers['x-accepted-github-permissions'] as string;
if (!response.data.length) {
// If the token wasn’t granted repository read access, flag it
if (!perms?.includes('contents:read')) {
return ['repository_access'];
}
// Otherwise it’s just an empty repo list
return [];
}

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.

Allow using GitHub fine grained tokens
1 participant