Skip to content

fix(auth/middleware): handle numeric code field in auth error response#81

Merged
qnen merged 1 commit intodevelopfrom
fix/unmarshal-numeric-error-code
Mar 20, 2026
Merged

fix(auth/middleware): handle numeric code field in auth error response#81
qnen merged 1 commit intodevelopfrom
fix/unmarshal-numeric-error-code

Conversation

@qnen
Copy link
Contributor

@qnen qnen commented Mar 20, 2026

The auth service may return the 'code' field as a number (e.g. 401) instead of a string. This caused json.Unmarshal to fail with a type mismatch, surfacing as a 500 instead of propagating the actual error.

Add unmarshalErrorResponse helper using json.RawMessage to tolerate both string and numeric code values in checkAuthorization and GetApplicationToken.

X-Lerian-Ref: 0x1

Pull Request Checklist

Pull Request Type

  • Feature
  • Fix
  • Refactor
  • Pipeline
  • Tests
  • Documentation
  • Helm

Checklist

Please check each item after it's completed.

  • I have tested these changes locally.
  • I have updated the documentation accordingly.
  • I have added necessary comments to the code, especially in complex areas.
  • I have ensured that my changes adhere to the project's coding standards.
  • I have checked for any potential security issues.
  • I have ensured that all tests pass.
  • I have updated the version appropriately (if applicable).
  • I have confirmed this code is ready for review.

Additional Notes

Obs: Please, always remember to target your PR to develop branch instead of main.

The auth service may return the 'code' field as a number (e.g. 401) instead of a string. This caused json.Unmarshal to fail with a type mismatch, surfacing as a 500 instead of propagating the actual error.

Add unmarshalErrorResponse helper using json.RawMessage to tolerate both string and numeric code values in checkAuthorization and GetApplicationToken.

X-Lerian-Ref: 0x1
@qnen qnen self-assigned this Mar 20, 2026
@coderabbitai
Copy link

coderabbitai bot commented Mar 20, 2026

Walkthrough

The changes add a new helper function unmarshalErrorResponse to handle unmarshalling JSON error payloads into commons.Response objects. This helper accommodates the code field being either a string or numeric value by using json.RawMessage for conditional unmarshalling. Two existing methods, checkAuthorization and GetApplicationToken, have been updated to utilize this helper function instead of directly unmarshalling responses.

🚥 Pre-merge checks | ✅ 1 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description includes the problem statement, solution approach, and affected functions, but all checklist items remain unchecked with no completion confirmation. Check the appropriate PR type (Fix), confirm tested changes, and explicitly mark completed checklist items to demonstrate readiness for review.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main fix: handling numeric code fields in auth error responses, which aligns with the core change.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

Copy link

@gandalf-at-lerian gandalf-at-lerian left a comment

Choose a reason for hiding this comment

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

LGTM. Clean fix for a subtle type mismatch bug.

The approach is correct: json.RawMessage defers decoding so you can attempt string first, then fall back to the numeric raw bytes — which produces the expected "401" string representation. Applied consistently to both checkAuthorization and GetApplicationToken.

The helper is well-factored — better than duplicating the same try-string-then-fallback logic in both call sites. ✅

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@auth/middleware/middleware.go`:
- Around line 52-83: unmarshalErrorResponse now accepts mixed JSON types for the
"code" field but lacks tests; add table-driven tests for unmarshalErrorResponse
covering cases: string code (e.g. "ERR"), numeric code (e.g. 401), null code,
missing code, empty string, and invalid JSON for code to ensure it returns the
expected commons.Response.Code (string or raw numeric string) and no unexpected
errors/500s. In the test file create subtests that call unmarshalErrorResponse
with representative bodies and assert returned resp.Code and error match
expected values; also add tests that exercise the middleware path(s) that call
unmarshalErrorResponse so end-to-end behavior is locked in.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6f7155dc-fcee-4cba-a12a-62aef4a56ad7

📥 Commits

Reviewing files that changed from the base of the PR and between 72bfae4 and 165db5f.

📒 Files selected for processing (1)
  • auth/middleware/middleware.go

Comment on lines +52 to +83
// unmarshalErrorResponse unmarshals a JSON response body into commons.Response,
// tolerating a numeric "code" field (the auth service may return code as a number).
func unmarshalErrorResponse(body []byte) (commons.Response, error) {
var raw struct {
EntityType string `json:"entityType,omitempty"`
Title string `json:"title,omitempty"`
Message string `json:"message,omitempty"`
Code json.RawMessage `json:"code,omitempty"`
}

if err := json.Unmarshal(body, &raw); err != nil {
return commons.Response{}, err
}

resp := commons.Response{
EntityType: raw.EntityType,
Title: raw.Title,
Message: raw.Message,
}

if len(raw.Code) > 0 {
var code string
if err := json.Unmarshal(raw.Code, &code); err == nil {
resp.Code = code
} else {
// Numeric code — use raw representation (e.g. "401")
resp.Code = string(raw.Code)
}
}

return resp, nil
}
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

Add regression tests for mixed code types before merging.

This helper changes auth error parsing behavior in a critical middleware path, but there’s no test coverage for string/number/null/invalid code variants. Please add table-driven tests to lock this behavior and avoid reintroducing 500s on auth errors.

I can draft a complete table-driven _test.go for this helper and both call paths if you want.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@auth/middleware/middleware.go` around lines 52 - 83, unmarshalErrorResponse
now accepts mixed JSON types for the "code" field but lacks tests; add
table-driven tests for unmarshalErrorResponse covering cases: string code (e.g.
"ERR"), numeric code (e.g. 401), null code, missing code, empty string, and
invalid JSON for code to ensure it returns the expected commons.Response.Code
(string or raw numeric string) and no unexpected errors/500s. In the test file
create subtests that call unmarshalErrorResponse with representative bodies and
assert returned resp.Code and error match expected values; also add tests that
exercise the middleware path(s) that call unmarshalErrorResponse so end-to-end
behavior is locked in.

@qnen qnen merged commit 3b30577 into develop Mar 20, 2026
3 checks passed
@qnen qnen deleted the fix/unmarshal-numeric-error-code branch March 20, 2026 22:04
@lerian-studio-midaz-push-bot
Copy link

🎉 This PR is included in version 2.5.0-beta.9 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

@lerian-studio-midaz-push-bot
Copy link

🎉 This PR is included in version 2.5.0 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

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