Skip to content

Conversation

@VivekVinushanth
Copy link
Contributor

@VivekVinushanth VivekVinushanth commented Dec 19, 2025

Purpose

Describe the problems, issues, or needs driving this feature/fix and include links to related issues in the following format: Resolves issue1, issue2, etc.

Goals

Describe the solutions that this feature/fix will introduce to resolve the problems described above

Approach

Describe how you are implementing the solutions. Include an animated GIF or screenshot if the change affects the UI (email [email protected] to review all UI text). Include a link to a Markdown file or Google doc if the feature write-up is too long to paste here.

User stories

Summary of user stories addressed by this change>

Release note

Brief description of the new feature or bug fix as it will appear in the release notes

Documentation

Link(s) to product documentation that addresses the changes of this PR. If no doc impact, enter “N/A” plus brief explanation of why there’s no doc impact

Training

Link to the PR for changes to the training content in https://github.com/wso2/WSO2-Training, if applicable

Certification

Type “Sent” when you have provided new/updated certification questions, plus four answers for each question (correct answer highlighted in bold), based on this change. Certification questions/answers should be sent to [email protected] and NOT pasted in this PR. If there is no impact on certification exams, type “N/A” and explain why.

Marketing

Link to drafts of marketing content that will describe and promote this feature, including product page changes, technical articles, blog posts, videos, etc., if applicable

Automation tests

  • Unit tests

    Code coverage information

  • Integration tests

    Details about the test cases and coverage

Security checks

Samples

Provide high-level details about the samples related to this feature

Related PRs

List any other related PRs

Migrations (if applicable)

Describe migration steps and platforms on which migration has been tested

Test environment

List all JDK versions, operating systems, databases, and browser/versions on which this feature/fix was tested

Learning

Describe the research phase and any blog posts, patterns, libraries, or add-ons you used to solve the problem.

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced error handling for authentication token requests with more detailed error messages, including endpoint information and response details to improve troubleshooting and diagnostics.
  • Chores

    • Improved debug logging throughout authentication flows to provide better visibility into failures and error conditions.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Dec 19, 2025

Walkthrough

The change enhances error handling and logging in the identity client by adding detailed context (endpoint, orgId, response body) to token request errors and removing sensitive token string logging from local claims retrieval.

Changes

Cohort / File(s) Summary
Error handling & logging improvements
internal/system/client/identity_client.go
Enhanced error messages for non-200 token responses with endpoint, orgId, and response body context; added debug logging for failed requests; removed token string logging from GetLocalClaimsMap

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Verify fmt.Errorf wrapping is applied consistently across requestToken, requestTokenForOrg, and super-tenant token exchange flows
  • Ensure removed token string logging doesn't impact debugging capabilities
  • Confirm response body reading doesn't introduce resource leaks or performance issues

Poem

🐰 When tokens stumble and responses fail,
Our errors now paint a detailed tale!
With endpoints logged and context clear,
Debugging troubles soon disappear.
No secrets exposed, just truth so bright—
Error handling shines in the light! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request description contains only the template structure with placeholder text and no actual content filled in for any of the required sections. Complete all relevant sections of the template with concrete details: describe the specific problems being fixed, the implementation approach, test coverage, security confirmations, and test environment details.
Title check ❓ Inconclusive The title is vague and generic, using non-descriptive phrasing that doesn't convey meaningful information about the actual changes (enhanced error handling and logging adjustments for token endpoints). Use a more specific title that highlights the main change, such as 'Enhanced error handling and logging for token endpoint responses' or 'Improve token request error context with response details'.
✅ Passed checks (1 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

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

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

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9a25c0f and ac51693.

📒 Files selected for processing (1)
  • internal/system/client/identity_client.go (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
internal/system/client/identity_client.go (2)
internal/system/errors/error.go (2)
  • NewServerError (48-53)
  • ErrorMessage (23-28)
internal/system/errors/error_codes.go (1)
  • TOKEN_FETCH_FAILED (121-124)

Comment on lines +251 to +261
bodyBytes, _ := io.ReadAll(resp.Body)
errorMsg := fmt.Sprintf(
"Token endpoint returned status %d for org:%s. Endpoint: %s. Response: %s",
resp.StatusCode, orgId, endpoint, strings.TrimSpace(string(bodyBytes)),
)
logger.Debug(errorMsg)
return "", errors2.NewServerError(errors2.ErrorMessage{
Code: errors2.TOKEN_FETCH_FAILED.Code,
Message: errors2.TOKEN_FETCH_FAILED.Message,
Description: errorMsg,
}, err)
}, fmt.Errorf("token endpoint non-200: %d", resp.StatusCode))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Security concern: Response body may contain sensitive information.

The error handling reads and logs the full response body from the token endpoint, which may contain sensitive details such as error messages with system information, partial credentials, or security-related data. Logging this at debug level could expose secrets in application logs.

Additionally, the error from io.ReadAll is ignored on line 251, which could silently hide I/O failures.

🔎 Suggested improvements

Consider these changes:

 if resp.StatusCode != http.StatusOK {
-	bodyBytes, _ := io.ReadAll(resp.Body)
+	bodyBytes, readErr := io.ReadAll(resp.Body)
+	if readErr != nil {
+		logger.Debug("Failed to read response body", log.Error(readErr))
+		bodyBytes = []byte("unable to read response body")
+	}
+	// Limit response body to avoid logging excessive data
+	responsePreview := string(bodyBytes)
+	if len(responsePreview) > 200 {
+		responsePreview = responsePreview[:200] + "..."
+	}
 	errorMsg := fmt.Sprintf(
-		"Token endpoint returned status %d for org:%s. Endpoint: %s. Response: %s",
-		resp.StatusCode, orgId, endpoint, strings.TrimSpace(string(bodyBytes)),
+		"Token endpoint returned status %d for org:%s. Endpoint: %s. Response: %s",
+		resp.StatusCode, orgId, endpoint, strings.TrimSpace(responsePreview),
 	)
 	logger.Debug(errorMsg)

Alternatively, consider logging only the status code and endpoint without the response body, as token endpoint errors often don't require full response details for debugging.

📝 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
bodyBytes, _ := io.ReadAll(resp.Body)
errorMsg := fmt.Sprintf(
"Token endpoint returned status %d for org:%s. Endpoint: %s. Response: %s",
resp.StatusCode, orgId, endpoint, strings.TrimSpace(string(bodyBytes)),
)
logger.Debug(errorMsg)
return "", errors2.NewServerError(errors2.ErrorMessage{
Code: errors2.TOKEN_FETCH_FAILED.Code,
Message: errors2.TOKEN_FETCH_FAILED.Message,
Description: errorMsg,
}, err)
}, fmt.Errorf("token endpoint non-200: %d", resp.StatusCode))
if resp.StatusCode != http.StatusOK {
bodyBytes, readErr := io.ReadAll(resp.Body)
if readErr != nil {
logger.Debug("Failed to read response body", log.Error(readErr))
bodyBytes = []byte("unable to read response body")
}
// Limit response body to avoid logging excessive data
responsePreview := string(bodyBytes)
if len(responsePreview) > 200 {
responsePreview = responsePreview[:200] + "..."
}
errorMsg := fmt.Sprintf(
"Token endpoint returned status %d for org:%s. Endpoint: %s. Response: %s",
resp.StatusCode, orgId, endpoint, strings.TrimSpace(responsePreview),
)
logger.Debug(errorMsg)
return "", errors2.NewServerError(errors2.ErrorMessage{
Code: errors2.TOKEN_FETCH_FAILED.Code,
Message: errors2.TOKEN_FETCH_FAILED.Message,
Description: errorMsg,
}, fmt.Errorf("token endpoint non-200: %d", resp.StatusCode))
}
🤖 Prompt for AI Agents
internal/system/client/identity_client.go lines 251-261: the code reads and logs
the entire token endpoint response body (and ignores io.ReadAll error), which
may expose sensitive data; change it to safely read with error handling and
avoid logging full body — call io.ReadAll and handle the error (return a server
error if read fails), but do not include the raw body in logs: either omit the
body from the log or include a sanitized/truncated excerpt (e.g., first N bytes
with non-printables stripped) or just log status code and endpoint; ensure the
returned error description does not contain sensitive response contents.

Comment on lines +323 to +333
bodyBytes, _ := io.ReadAll(resp.Body)
errorMsg := fmt.Sprintf(
"Token endpoint returned status %d for org:%s. Endpoint: %s. Response: %s",
resp.StatusCode, orgId, endpoint, strings.TrimSpace(string(bodyBytes)),
)
logger.Debug(errorMsg)
return "", errors2.NewServerError(errors2.ErrorMessage{
Code: errors2.TOKEN_FETCH_FAILED.Code,
Message: errors2.TOKEN_FETCH_FAILED.Message,
Description: errorMsg,
}, err)
}, fmt.Errorf("token endpoint non-200: %d", resp.StatusCode))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Security concern: Response body may contain sensitive information.

This error handling has the same issue as in requestToken (lines 251-261): the full response body from the token exchange endpoint is logged and included in error messages, potentially exposing sensitive information. The token exchange flow involves authentication tokens, making this especially sensitive.

Additionally, the error from io.ReadAll is ignored on line 323.

🔎 Suggested improvements

Apply the same fix pattern as suggested for lines 251-261:

 if resp.StatusCode != http.StatusOK {
-	bodyBytes, _ := io.ReadAll(resp.Body)
+	bodyBytes, readErr := io.ReadAll(resp.Body)
+	if readErr != nil {
+		logger.Debug("Failed to read response body", log.Error(readErr))
+		bodyBytes = []byte("unable to read response body")
+	}
+	// Limit response body to avoid logging excessive data
+	responsePreview := string(bodyBytes)
+	if len(responsePreview) > 200 {
+		responsePreview = responsePreview[:200] + "..."
+	}
 	errorMsg := fmt.Sprintf(
-		"Token endpoint returned status %d for org:%s. Endpoint: %s. Response: %s",
-		resp.StatusCode, orgId, endpoint, strings.TrimSpace(string(bodyBytes)),
+		"Token endpoint returned status %d for org:%s. Endpoint: %s. Response: %s",
+		resp.StatusCode, orgId, endpoint, strings.TrimSpace(responsePreview),
 	)
 	logger.Debug(errorMsg)

Consider whether the response body is necessary at all for token exchange errors, as the status code and endpoint may be sufficient for debugging.

🤖 Prompt for AI Agents
In internal/system/client/identity_client.go around lines 323 to 333, the code
reads and logs the full response body (and ignores the io.ReadAll error), which
may leak sensitive token data; change the logic to handle the ReadAll error
(return or include a safe placeholder if read fails) and avoid logging or
embedding the full response body—either omit the body entirely from logs/errors
or replace it with a redacted/truncated placeholder (e.g., "<redacted-response>"
or first N bytes only) and include only status code and endpoint in the error
message returned to callers; ensure the processLogger.Debug call and the
returned errors2.NewServerError use the sanitized message and not the raw body.

@VivekVinushanth VivekVinushanth merged commit 635215f into wso2:main Dec 19, 2025
5 checks passed
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