Skip to content

feat(middleware): forward product on user-flow authorization#114

Merged
rodrigodh merged 1 commit into
developfrom
feat/forward-product-user-flow
Jun 23, 2026
Merged

feat(middleware): forward product on user-flow authorization#114
rodrigodh merged 1 commit into
developfrom
feat/forward-product-user-flow

Conversation

@rodrigodh

Copy link
Copy Markdown
Contributor

Contexto

Lado produtor do contrato de isolamento de permissão por produto no fluxo de usuário. O lado receptor está em plugin-access-manager PR #134 (consome o campo product quando presente; sem ele, comportamento legado).

Problema

O 1º argumento do Authorize(sub, resource, action) identifica o produto dono da rota (no M2M vira admin/<sub>-editor-role). Mas no token de usuário normal ele era descartado: o sub é sobrescrito por owner/userId do JWT, e o checkAuthorization mandava pro serviço de auth só {sub, resource, action} — sem discriminador de produto. Logo, o serviço não tinha como isolar permissões por produto no fluxo de usuário.

Mudança

  • checkAuthorization recebe um product e o encaminha como "product" no body apenas para tokens de usuário normal.
  • HTTP Authorize: passa o 1º argumento (o produto).
  • gRPC: passa "" (a Policy ainda não carrega produto) → comportamento inalterado lá; isolação por produto no gRPC fica pra quando a Policy ganhar esse campo.
  • M2M: nunca encaminha produto (o serviço de auth não usa no caminho M2M).
  • product vazio preserva o comportamento anterior → o serviço de auth adota a isolação incrementalmente, serviço a serviço, conforme cada um sobe esta versão. Sem flag, sem cutover atômico.

Testes

  • Fluxo de usuário: assere que product é encaminhado no body.
  • M2M: assere que product não é encaminhado.
  • Demais testes de checkAuthorization atualizados pro novo parâmetro. 72 testes do pacote passam, go vet limpo.

Rollout

Após release, plugin-access-manager (e demais consumidores) bumpam o lib-auth e passam a enviar o produto. Antes disso, tudo segue no caminho legado.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Jun 22, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

The Authorize middleware method is updated to accept product instead of sub. This product value is forwarded to checkAuthorization, which uses it to construct M2M subjects as admin/{product}-editor-role for non-normal-user JWTs and conditionally includes product in the auth-service request body only for normal-user token types. Tests are updated to validate both paths.

Changes

Product parameter in authorization middleware

Layer / File(s) Summary
Signature changes and subject/payload logic
auth/middleware/middleware.go
Authorize replaces the sub parameter with product. checkAuthorization gains a product string parameter, builds M2M sub as admin/{product}-editor-role for non-normal-user JWTs, refactors normal-user sub extraction into a userID variable, and conditionally sets requestBody["product"] only when userType is normalUser and product is non-empty.
Test assertions for product forwarding
auth/middleware/middleware_test.go
Normal-user test passes "midaz" as product and asserts capturedBody["product"] == "midaz". Application-user test asserts sub is admin/<product>-editor-role and that product is absent from the request body.

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

@rodrigodh rodrigodh force-pushed the feat/forward-product-user-flow branch from f25394e to a313044 Compare June 22, 2026 17:30
@rodrigodh rodrigodh force-pushed the feat/forward-product-user-flow branch from a313044 to b164be9 Compare June 22, 2026 17:34
checkAuthorization now takes the product owning the route and derives the subject internally: M2M tokens map to the product's editor role, while normal users are identified by their JWT (owner/userId). The product is forwarded as "product" for normal-user tokens only, so the auth service can isolate permissions by product. Empty product preserves the previous behavior, enabling incremental adoption.

X-Lerian-Ref: 0x1
@rodrigodh rodrigodh force-pushed the feat/forward-product-user-flow branch from b164be9 to e597ae2 Compare June 22, 2026 17:55

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
auth/middleware/middleware_test.go (1)

118-166: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add a regression test for empty-product non-normal-user behavior.

Current tests only exercise non-empty product for M2M. Please add a case with product == "" for non-normal-user tokens to lock the intended compatibility behavior and prevent regressions like malformed sub values.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@auth/middleware/middleware_test.go` around lines 118 - 166, The current test
TestCheckAuthorization_ApplicationUser_SubjectConstruction only covers
non-normal-user tokens with a product value, leaving a gap in test coverage. Add
a new regression test function that exercises the same authorization flow and
subject construction logic but with an empty product value (product == "") in
the JWT claims. This test should verify that the subject is constructed
correctly and that the product field is not forwarded even when empty, ensuring
the intended behavior is preserved and preventing future regressions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@auth/middleware/middleware.go`:
- Around line 301-307: The M2M subject derivation logic in the userType check is
not compatibility-safe. When product is empty, the sub assignment creates
malformed values like admin/-editor-role, and it doesn't preserve legacy
sub-style values that current callers may still be passing. Additionally, this
reconstruction can leak unintended product values in normal-user authorization
flows at lines 329-332. Validate that product is not empty before constructing
the M2M subject with the admin/<product>-editor-role format, and ensure that
when product is empty or when dealing with normal users, the original or
properly preserved sub value is used instead of overwriting it with a
potentially invalid constructed value.

---

Outside diff comments:
In `@auth/middleware/middleware_test.go`:
- Around line 118-166: The current test
TestCheckAuthorization_ApplicationUser_SubjectConstruction only covers
non-normal-user tokens with a product value, leaving a gap in test coverage. Add
a new regression test function that exercises the same authorization flow and
subject construction logic but with an empty product value (product == "") in
the JWT claims. This test should verify that the subject is constructed
correctly and that the product field is not forwarded even when empty, ensuring
the intended behavior is preserved and preventing future regressions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 80c9ff3e-bad0-489e-abd1-7ff8ab21bf9c

📥 Commits

Reviewing files that changed from the base of the PR and between b164be9 and e597ae2.

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

Comment thread auth/middleware/middleware.go
@rodrigodh rodrigodh merged commit 044699d into develop Jun 23, 2026
3 checks passed
@rodrigodh rodrigodh deleted the feat/forward-product-user-flow branch June 23, 2026 12:35
@lerian-studio-midaz-push-bot

Copy link
Copy Markdown

🎉 This PR is included in version 2.9.0-beta.1 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

@lerian-studio-midaz-push-bot

Copy link
Copy Markdown

🎉 This PR is included in version 2.9.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.

1 participant