Skip to content

Conversation

@elibosley
Copy link
Member

@elibosley elibosley commented Apr 10, 2025

@pujitm This broke with the plugins service. Rather than fix the logging, I decided to fix the parser to be more permissive.

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced the SSO login process by improving the handling of response data. This update increases reliability when unexpected response formats occur during authentication.
  • New Features
    • Introduced a new function for validating user credentials and SSO tokens, enhancing the login functionality with improved error handling.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 10, 2025

Warning

Rate limit exceeded

@elibosley has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 2 minutes and 49 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 9e246ff and 8d1f981.

📒 Files selected for processing (1)
  • api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts (2 hunks)

Walkthrough

The changes update the verifyUsernamePasswordAndSSO function to improve how it handles JSON responses from SSO token validation. The function now splits the output string at the first occurrence of { to isolate the JSON data. It checks for the presence of valid JSON before decoding it; if none is found, it logs an error message and returns false.

Changes

Files Change Summary
api/src/unraid-api/unraid-file-modifier/.../sso.modification.ts Modified the verifyUsernamePasswordAndSSO function's JSON parsing. The output is first split on { to isolate the JSON. Logs a message and returns false if JSON is missing; otherwise, decodes the JSON after prepending {.
api/src/unraid-api/unraid-file-modifier/.../__test__/snapshots/.login.php.modified.snapshot.php Updated the handling of the SSO login response in the test snapshot to reflect changes in JSON parsing and error handling in verifyUsernamePasswordAndSSO.
api/src/unraid-api/unraid-file-modifier/.../patches/sso.patch Introduced the verifyUsernamePasswordAndSSO function, replacing the previous logic for credential validation and enhancing error handling for SSO token validation.

Possibly related PRs

  • fix: logrotate error #1005: The changes in the main PR regarding the verifyUsernamePasswordAndSSO function's JSON response handling are directly related to similar modifications made in the retrieved PR, which also addresses the same function's response processing.
  • fix: OEM plugin issues #1288: The changes in the main PR and the retrieved PR both involve modifications to the verifyUsernamePasswordAndSSO function, specifically in how the JSON response is processed, indicating a direct relationship at the code level.
  • feat: begin building plugin with node instead of bash #1120: The changes in the main PR regarding the verifyUsernamePasswordAndSSO function's handling of SSO token validation are directly related to the modifications in the retrieved PR, which also involve the same function and improvements in error handling for the SSO login process.

Suggested reviewers

  • pujitm
  • mdatelle

Poem

In code we split and parse with care,
A little brace reveals data rare.
Logs note the truth when JSON hides,
Conditions checked on binary rides.
Brighter flows emerge as errors subside.


🪧 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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
Contributor

@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

🧹 Nitpick comments (1)
api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts (1)

54-54: Consider potential JSON formatting edge cases.

The current implementation assumes all valid JSON responses are objects (starting with '{'). While this likely covers your use case, it doesn't account for valid JSON that starts with arrays '[' or other formats.

If you need to handle all JSON types, consider a more comprehensive approach:

- $response = json_decode('{' + $jsonPart[1], true);
+ $jsonString = $output[0];
+ // Find the position of the first JSON-like structure (object or array)
+ $objectPos = strpos($jsonString, '{');
+ $arrayPos = strpos($jsonString, '[');
+ 
+ // Determine which comes first (if both exist)
+ $startPos = -1;
+ $startChar = '';
+ if ($objectPos !== false && $arrayPos !== false) {
+     $startPos = min($objectPos, $arrayPos);
+     $startChar = ($startPos === $objectPos) ? '{' : '[';
+ } elseif ($objectPos !== false) {
+     $startPos = $objectPos;
+     $startChar = '{';
+ } elseif ($arrayPos !== false) {
+     $startPos = $arrayPos;
+     $startChar = '[';
+ }
+ 
+ if ($startPos === -1) {
+     my_logger("SSO Login Attempt Failed: No JSON found in response");
+     return false;
+ }
+ 
+ $jsonPart = substr($jsonString, $startPos);
+ $response = json_decode($jsonPart, true);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8bb9efc and 3e152f4.

📒 Files selected for processing (1)
  • api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Build Web App
  • GitHub Check: Test API
  • GitHub Check: Build API
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (1)
api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts (1)

48-54: Improved JSON parsing robustness.

This change correctly handles cases where the SSO validation command outputs additional content before the JSON data. By splitting on the first '{' character, the code can extract the relevant JSON portion from mixed output.

Copy link
Contributor

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 3e152f4 and 1e5f275.

📒 Files selected for processing (2)
  • api/src/unraid-api/unraid-file-modifier/modifications/__test__/snapshots/.login.php.modified.snapshot.php (1 hunks)
  • api/src/unraid-api/unraid-file-modifier/modifications/patches/sso.patch (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Build Web App
  • GitHub Check: Build API
  • GitHub Check: Test API
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (3)
api/src/unraid-api/unraid-file-modifier/modifications/patches/sso.patch (3)

9-56: Good approach for improving JSON parsing robustness

The implementation of verifyUsernamePasswordAndSSO is a good enhancement to handle cases where the API response might contain content before the JSON data. After fixing the syntax issues, this will solve the unreliable SSO problem mentioned in the PR title.


69-70: Function replacement looks good

Correctly replaces the call to verifyUsernamePassword with the new verifyUsernamePasswordAndSSO function.


82-82: SSO login include added

The addition of the SSO login include file aligns with the enhanced functionality.

@elibosley elibosley requested a review from pujitm April 14, 2025 15:32
Copy link
Contributor

@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

🧹 Nitpick comments (3)
api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts (3)

15-15: Fix formatting issue

Fix the whitespace issue flagged by the static analysis tools.

-        const newFunction = /** PHP */`
+        const newFunction = /** PHP */ `
🧰 Tools
🪛 GitHub Check: Build API

[failure] 15-15:
Insert ·

🪛 GitHub Check: Test API

[failure] 15-15:
Insert ·


47-61: Consider enhancing JSON parsing to handle arrays

The current implementation assumes JSON responses will be objects (starting with {). Consider adding support for JSON arrays (starting with [) for complete robustness.

-            // Split on first { and take everything after it
-            $jsonParts = explode('{', $output[0], 2);
-            if (count($jsonParts) < 2) {
-                my_logger("SSO Login Attempt Failed: No JSON found in response");
-                return false;
-            }
-            $response = json_decode('{' . $jsonParts[1], true);
+            // Extract JSON from potentially mixed content
+            $output_str = $output[0];
+            // Look for start of JSON object or array
+            $json_start_obj = strpos($output_str, '{');
+            $json_start_arr = strpos($output_str, '[');
+            
+            // Determine which JSON delimiter comes first (if any)
+            if ($json_start_obj === false && $json_start_arr === false) {
+                my_logger("SSO Login Attempt Failed: No JSON found in response");
+                return false;
+            }
+            
+            // Choose the first occurring delimiter
+            if ($json_start_obj === false) {
+                $json_start = $json_start_arr;
+                $delim = '[';
+            } elseif ($json_start_arr === false) {
+                $json_start = $json_start_obj;
+                $delim = '{';
+            } else {
+                $json_start = min($json_start_obj, $json_start_arr);
+                $delim = ($json_start == $json_start_obj) ? '{' : '[';
+            }
+            
+            // Extract and parse JSON
+            $json_str = substr($output_str, $json_start);
+            $response = json_decode($json_str, true);

37-37: Consider removing or redacting sensitive data in logs

The current implementation logs the entire response which might contain sensitive data. Consider redacting sensitive information before logging.

-        my_logger("SSO Login Attempt Response: " . print_r($output, true));
+        // Redact sensitive data before logging
+        $logOutput = is_array($output) ? array_map(function($line) {
+            // Redact potential JWT tokens
+            return preg_replace('/[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+/', '[REDACTED_TOKEN]', $line);
+        }, $output) : $output;
+        my_logger("SSO Login Attempt Response: " . print_r($logOutput, true));
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 1e5f275 and c7e9609.

📒 Files selected for processing (1)
  • api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts (2 hunks)
🧰 Additional context used
🪛 GitHub Check: Build API
api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts

[failure] 15-15:
Insert ·

🪛 GitHub Check: Test API
api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts

[failure] 15-15:
Insert ·

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build Web App
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (1)
api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts (1)

48-54: Improved robustness of JSON parsing

The changes effectively handle cases where the API response contains non-JSON content before the JSON object. This makes the SSO login process more reliable.

@elibosley elibosley force-pushed the fix/sso-breaks-with-api-output branch from fbd0669 to 9e246ff Compare April 14, 2025 15:45
Copy link
Contributor

@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

🔭 Outside diff range comments (1)
api/src/unraid-api/unraid-file-modifier/modifications/patches/sso.patch (1)

21-21: ⚠️ Potential issue

Fix regex pattern for JWT token validation.

The current regex pattern is missing escape characters for the dots in the JWT token format. In regex, a dot is a wildcard that matches any character, but you want to match literal dots in the JWT format.

-        if (!preg_match('/^[A-Za-z0-9-_]+.[A-Za-z0-9-_]+.[A-Za-z0-9-_]+$/', $password)) {
+        if (!preg_match('/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+$/', $password)) {
🧹 Nitpick comments (1)
api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts (1)

15-15: Fix whitespace in template literal declaration.

The static analysis tools are flagging a missing space here. You should add a space after the backtick in this template literal declaration.

-        const newFunction = /** PHP */`
+        const newFunction = /** PHP */ `
🧰 Tools
🪛 GitHub Check: Test API

[failure] 15-15:
Insert ·

🪛 GitHub Check: Build API

[failure] 15-15:
Insert ·

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between fbd0669 and 9e246ff.

📒 Files selected for processing (3)
  • api/src/unraid-api/unraid-file-modifier/modifications/__test__/snapshots/.login.php.modified.snapshot.php (1 hunks)
  • api/src/unraid-api/unraid-file-modifier/modifications/patches/sso.patch (4 hunks)
  • api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/src/unraid-api/unraid-file-modifier/modifications/test/snapshots/.login.php.modified.snapshot.php
🧰 Additional context used
🪛 GitHub Check: Test API
api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts

[failure] 15-15:
Insert ·

🪛 GitHub Check: Build API
api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts

[failure] 15-15:
Insert ·

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build Web App
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (2)
api/src/unraid-api/unraid-file-modifier/modifications/sso.modification.ts (1)

48-54: Good approach to handle non-JSON content in the response.

This is a robust solution that efficiently handles cases where the API response contains additional content before the JSON. Splitting at the first { and then rebuilding the JSON is a clean approach.

api/src/unraid-api/unraid-file-modifier/modifications/patches/sso.patch (1)

41-47: Robust JSON parsing implementation.

The approach to handling mixed content in the API response is well-implemented. By splitting at the first { and checking for valid JSON parts, you've made the SSO login more reliable.

@github-actions
Copy link
Contributor

This plugin has been deployed to Cloudflare R2 and is available for testing.
Download it at this URL:

https://preview.dl.unraid.net/unraid-api/tag/PR1353/dynamix.unraid.net.plg

@elibosley
Copy link
Member Author

Just tested this on my server and it works well.

@elibosley elibosley merged commit e65775f into main Apr 14, 2025
9 checks passed
@elibosley elibosley deleted the fix/sso-breaks-with-api-output branch April 14, 2025 16:10
mdatelle pushed a commit that referenced this pull request Apr 14, 2025
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Bug Fixes**
- Enhanced the SSO login process by improving the handling of response
data. This update increases reliability when unexpected response formats
occur during authentication.
- **New Features**
- Introduced a new function for validating user credentials and SSO
tokens, enhancing the login functionality with improved error handling.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
elibosley pushed a commit that referenced this pull request Apr 24, 2025
🤖 I have created a release *beep* *boop*
---


## [4.7.0](v4.6.6...v4.7.0)
(2025-04-24)


### Features

* add basic docker network listing
([#1317](#1317))
([c4fdff8](c4fdff8))
* add permission documentation by using a custom decorator
([#1355](#1355))
([45ecab6](45ecab6))
* basic vm controls ([#1293](#1293))
([bc3ca92](bc3ca92))
* code first graphql
([#1347](#1347))
([f5724ab](f5724ab))


### Bug Fixes

* container names always null
([#1335](#1335))
([8a5b238](8a5b238))
* **deps:** update all non-major dependencies
([#1337](#1337))
([2345732](2345732))
* hide reboot notice for patch releases
([#1341](#1341))
([4b57439](4b57439))
* move docker mutations to the mutations resolver
([#1333](#1333))
([1bbe7d2](1bbe7d2))
* PR build issue
([457d338](457d338))
* remove some unused fields from the report object
([#1342](#1342))
([cd323ac](cd323ac))
* sso unreliable if API outputs more than raw json
([#1353](#1353))
([e65775f](e65775f))
* vms now can detect starting of libvirt and start local hypervisor
([#1356](#1356))
([ad0f4c8](ad0f4c8))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
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