Align Keycloak Realms and Roadmap Transition to Sprint 11#200
Align Keycloak Realms and Roadmap Transition to Sprint 11#200
Conversation
… Roadmap to Sprint 11
📝 Walkthrough🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (3 warnings)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@docs/roadmap.md`:
- Line 55: Replace the non-rendered reference string "@issue `#141`" in the Sprint
10 bullet (the line starting with "**Sprint 10**: Módulo de Ratings...") with a
GitHub-friendly issue reference such as "#141" or "Issue `#141`" so the Markdown
will render a clickable issue link.
- Around line 9-17: O documento está auto-contraditório entre a tag "**Sprint
Atual**" e o bloco "## 💰 Sprint 11 - Monetização & Polimento (27 Abr - 11 Mai
2026) 🚧 [EM ANDAMENTO]": atualize ou harmonize as metainformações — ou ajuste a
data da janela para começar antes de hoje (14 Abr 2026) ou altere "**Status**" /
o sufixo "[EM ANDAMENTO]" para "Planejamento" (ou outra etiqueta apropriada) até
27 Abr 2026 — editar as entradas "**Sprint Atual**", "**Status**" e o título do
bloco "Sprint 11 - Monetização & Polimento (27 Abr - 11 Mai 2026)" para que
todas mostrem a mesma data/estado.
In `@infrastructure/keycloak/realms/meajudaai-realm.prod.json`:
- Around line 42-89: The new Keycloak realm introduces role names like
"meajudaai-system-admin" but the backend still checks legacy role names
("system-admin" in
RejectDocumentCommandHandler.Handle/RejectDocumentCommandHandler.cs and
"super-admin" in SecurityExtensions.cs), so either add composite/alias roles in
the realm mapping those new roles to the legacy names (e.g., create composite
roles or role mappings that map meajudaai-system-admin -> system-admin and
meajudaai-super-admin -> super-admin) or update the backend checks in
RejectDocumentCommandHandler and SecurityExtensions to use the new role names;
ensure the chosen approach is applied consistently so users with meajudaai-*
roles continue to pass existing authorization checks during rollout.
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 63c6ffb4-0af7-4128-8b53-80a059fd8061
📒 Files selected for processing (4)
docs/roadmap-history.mddocs/roadmap.mddocs/technical-debt.mdinfrastructure/keycloak/realms/meajudaai-realm.prod.json
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (2)
src/Modules/Documents/Tests/Unit/Application/RequestVerificationCommandHandlerTests.cs (1)
14-14: Cobertura de autorização pode ficar mais robusta com roles administrativas adicionais.O teste cobre
RoleConstants.Admin, mas o handler também aceitaRoleConstants.SystemAdmineRoleConstants.LegacySystemAdmin. Recomendo parametrizar esse cenário para evitar regressão de autorização.Also applies to: 146-147
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/Modules/Documents/Tests/Unit/Application/RequestVerificationCommandHandlerTests.cs` at line 14, The test RequestVerificationCommandHandlerTests currently only asserts authorization for RoleConstants.Admin; update it to parametrize the scenario to include RoleConstants.SystemAdmin and RoleConstants.LegacySystemAdmin as well (e.g., convert the test to a [Theory] with InlineData or use MemberData) so the same arrange/act/assert runs for each role constant; change the test method signature and test data to iterate over RoleConstants.Admin, RoleConstants.SystemAdmin, RoleConstants.LegacySystemAdmin and keep the existing assertions intact (also apply the same parametrization fix to the other occurrence around the code referenced as lines 146-147).src/Bootstrapper/MeAjudaAi.ApiService/Extensions/SecurityExtensions.cs (1)
474-484: Sugestão: centralizar o conjunto de roles administrativas reutilizável.A policy ficou correta, mas essa mesma lista está duplicada nos handlers e já apareceu divergência. Extrair um conjunto único (ex.:
RoleConstants.AdminEquivalentRoles) reduz risco de drift.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/Bootstrapper/MeAjudaAi.ApiService/Extensions/SecurityExtensions.cs` around lines 474 - 484, The role lists used in the "AdminOnly" and "SuperAdminOnly" policies are duplicated and cause potential divergence. To fix this, define a single reusable collection (e.g., RoleConstants.AdminEquivalentRoles) containing all administrative roles. Then update the policy definitions in SecurityExtensions to reference this collection instead of hardcoding the role strings, ensuring consistency and maintainability.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@docs/roadmap.md`:
- Line 55: Update the "Sprint 10" entry (the bullet line starting with "*
**Sprint 10**") to include the two missing completed items from the history:
"Infra CI/CD (OpenAPI gating)" and "Documentação (coleções Bruno)"; locate the
"Concluído Recentemente" / Sprint 10 summary and append these exact phrases so
the roadmap summary matches the detailed history referenced in
docs/roadmap-history.md (the historical entries for those two items).
In `@infrastructure/keycloak/realms/meajudaai-realm.dev.json`:
- Around line 44-45: The role description string "Administrador do sistema -
todas as permissões" contains mojibake; update the role's "description" value
to the correct UTF-8 Portuguese text "Administrador do sistema - todas as
permissões" and ensure the JSON file (the realm role entry where the
"description" property is set) is saved with UTF-8 encoding (no BOM) so Keycloak
UI/export shows the accented characters correctly.
In `@infrastructure/keycloak/realms/meajudaai-realm.prod.json`:
- Around line 42-45: A descrição do papel "meajudaai-system-admin" contém texto
corrompido ("permissões") — abra o campo "description" para o role
meajudaai-system-admin e corrija o valor para "Administrador do sistema - todas
as permissões"; em seguida garanta que o arquivo JSON esteja salvo em UTF-8 (sem
BOM) para evitar novos problemas de encoding ao importar no Keycloak/Admin
Console.
- Line 195: Os clients públicos "customer-app" e "provider-app" têm
directAccessGrantsEnabled: true, o que habilita ROPC; abra os objetos de client
correspondentes (os entries com clientId "customer-app" e "provider-app") e
altere directAccessGrantsEnabled para false; mantenha as configurações de
standardFlowEnabled e PKCE inalteradas para continuar usando o fluxo padrão
seguro.
- Around line 267-282: O cliente de serviço "meajudaai-api-service" está criado
com serviceAccountsEnabled=true mas sem os role mappings necessários para
acessar o Admin API; corrija adicionando mapeamentos de roles do cliente
"realm-management" (por exemplo "realm-admin", "manage-users", "view-realm")
para a conta técnica "service-account-meajudaai-api-service" no export JSON
(campo roleMappings/roleMapping em meajudaai-realm.prod.json) ou implementando
um passo no bootstrap (em keycloak-init-prod.sh) que realiza a chamada POST
/admin/realms/meajudaai/users/{service-account-id}/role-mappings/clients/{realm-management-id}
para anexar essas roles ao service-account do clientId "meajudaai-api-service".
- Around line 131-145: O bloco que usa providerId: "instagram" está dependente
do broker nativo e deve ser substituído antes do upgrade; atualize esse cliente
para usar providerId: "oidc" (ou "facebook" se preferir seguir o
redirecionamento atual do Instagram via Facebook), remova/pare de usar
providerId "instagram", e na configuração do provedor (config) adicione os
endpoints OIDC necessários
(issuer/authorizationUrl/tokenUrl/userInfoUrl/logoutUrl) e mantenha
clientId/clientSecret; verifique também firstBrokerLoginFlowAlias e outras flags
relacionadas para compatibilidade com o fluxo OIDC.
In `@src/Modules/Documents/Application/Handlers/RejectDocumentCommandHandler.cs`:
- Line 10: The local admin-role check inside RejectDocumentCommandHandler (in
the Handle method) currently only allows Admin, SystemAdmin and
LegacySystemAdmin; update the conditional that checks user roles (the admin
guard around lines 52-55) to also accept SuperAdmin and LegacySuperAdmin so they
are treated as local administrators consistent with the API policy—ensure you
reference and extend the same role enum/constant values used (e.g.,
Role.SuperAdmin / Roles.LegacySuperAdmin) when adding the checks.
---
Nitpick comments:
In `@src/Bootstrapper/MeAjudaAi.ApiService/Extensions/SecurityExtensions.cs`:
- Around line 474-484: The role lists used in the "AdminOnly" and
"SuperAdminOnly" policies are duplicated and cause potential divergence. To fix
this, define a single reusable collection (e.g.,
RoleConstants.AdminEquivalentRoles) containing all administrative roles. Then
update the policy definitions in SecurityExtensions to reference this collection
instead of hardcoding the role strings, ensuring consistency and
maintainability.
In
`@src/Modules/Documents/Tests/Unit/Application/RequestVerificationCommandHandlerTests.cs`:
- Line 14: The test RequestVerificationCommandHandlerTests currently only
asserts authorization for RoleConstants.Admin; update it to parametrize the
scenario to include RoleConstants.SystemAdmin and
RoleConstants.LegacySystemAdmin as well (e.g., convert the test to a [Theory]
with InlineData or use MemberData) so the same arrange/act/assert runs for each
role constant; change the test method signature and test data to iterate over
RoleConstants.Admin, RoleConstants.SystemAdmin, RoleConstants.LegacySystemAdmin
and keep the existing assertions intact (also apply the same parametrization fix
to the other occurrence around the code referenced as lines 146-147).
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: e32a00b6-6c25-4038-ab95-198ad68ab0bb
📒 Files selected for processing (13)
docs/roadmap.mdinfrastructure/keycloak/realms/meajudaai-realm.dev.jsoninfrastructure/keycloak/realms/meajudaai-realm.prod.jsonsrc/Bootstrapper/MeAjudaAi.ApiService/Extensions/SecurityExtensions.cssrc/Modules/Documents/Application/Handlers/ApproveDocumentCommandHandler.cssrc/Modules/Documents/Application/Handlers/RejectDocumentCommandHandler.cssrc/Modules/Documents/Application/Handlers/RequestVerificationCommandHandler.cssrc/Modules/Documents/Application/Handlers/UploadDocumentCommandHandler.cssrc/Modules/Documents/Tests/Unit/Application/ApproveDocumentCommandHandlerTests.cssrc/Modules/Documents/Tests/Unit/Application/RejectDocumentCommandHandlerTests.cssrc/Modules/Documents/Tests/Unit/Application/RequestVerificationCommandHandlerTests.cssrc/Modules/Documents/Tests/Unit/Application/UploadDocumentCommandHandlerTests.cssrc/Shared/Utilities/Constants/RoleConstants.cs
✅ Files skipped from review due to trivial changes (3)
- src/Modules/Documents/Tests/Unit/Application/ApproveDocumentCommandHandlerTests.cs
- src/Modules/Documents/Tests/Unit/Application/UploadDocumentCommandHandlerTests.cs
- src/Shared/Utilities/Constants/RoleConstants.cs
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@infrastructure/keycloak/realms/meajudaai-realm.prod.json`:
- Around line 296-300: A service account "meajudaai-api-service" is assigned the
overly-broad "realm-admin" role; edit the realm JSON entry for that
client/service account and remove "realm-admin" from the "realm-management"
roles array so it only contains "manage-users" and "view-realm" (keep
"manage-users" for CreateUserAsync/DeactivateUserAsync/AssignRolesToUserAsync
and "view-realm" as needed), ensuring no other references expect "realm-admin"
for this service account.
- Around line 131-149: O bloco de provedor com alias "instagram" está usando
providerId: "oidc" e configurações OIDC; troque para o provedor nativo do
Keycloak (InstagramIdentityProvider / providerId: "instagram"), remova/ignore
campos específicos de OIDC (como issuer/.well-known, ID token/jwks) e
mantenha/ajuste apenas os parâmetros OAuth2 corretos em config (clientId,
clientSecret, authorizationUrl, tokenUrl, userInfoUrl apropriados da API Basic
Display do Instagram, por exemplo userInfoUrl apontando para
graph.instagram.com/me com fields necessários) para que Keycloak utilize o
provedor Instagram nativo em vez do OIDC genérico.
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 8fbae8a2-209e-4c8f-abfb-0dbee8cce853
📒 Files selected for processing (12)
docs/roadmap.mdinfrastructure/keycloak/realms/meajudaai-realm.dev.jsoninfrastructure/keycloak/realms/meajudaai-realm.prod.jsonsrc/Bootstrapper/MeAjudaAi.ApiService/Extensions/SecurityExtensions.cssrc/Modules/Documents/Application/Handlers/ApproveDocumentCommandHandler.cssrc/Modules/Documents/Application/Handlers/RejectDocumentCommandHandler.cssrc/Modules/Documents/Application/Handlers/RequestVerificationCommandHandler.cssrc/Modules/Documents/Application/Handlers/UploadDocumentCommandHandler.cssrc/Modules/Documents/Tests/Unit/Application/ApproveDocumentCommandHandlerTests.cssrc/Modules/Documents/Tests/Unit/Application/RejectDocumentCommandHandlerTests.cssrc/Modules/Documents/Tests/Unit/Application/RequestVerificationCommandHandlerTests.cssrc/Shared/Utilities/Constants/RoleConstants.cs
✅ Files skipped from review due to trivial changes (1)
- infrastructure/keycloak/realms/meajudaai-realm.dev.json
🚧 Files skipped from review as they are similar to previous changes (7)
- src/Modules/Documents/Application/Handlers/RejectDocumentCommandHandler.cs
- src/Modules/Documents/Application/Handlers/RequestVerificationCommandHandler.cs
- src/Modules/Documents/Application/Handlers/ApproveDocumentCommandHandler.cs
- src/Bootstrapper/MeAjudaAi.ApiService/Extensions/SecurityExtensions.cs
- src/Modules/Documents/Tests/Unit/Application/RequestVerificationCommandHandlerTests.cs
- src/Shared/Utilities/Constants/RoleConstants.cs
- src/Modules/Documents/Tests/Unit/Application/ApproveDocumentCommandHandlerTests.cs
…m to native provider
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
infrastructure/keycloak/realms/meajudaai-realm.prod.json (1)
131-151:⚠️ Potential issue | 🟠 MajorRevalidar a estratégia de Instagram com
providerId: "oidc"antes de fechar o fix.Este bloco repete um ponto já levantado anteriormente: Instagram Basic Display costuma ser OAuth2 (não OIDC completo). Se não houver discovery/issuer/id_token compatíveis, o login falha em runtime mesmo com import OK.
Keycloak 26.x generic OIDC identity provider requirements (issuer, discovery, id_token, jwks) and whether Instagram Basic Display API endpoints (api.instagram.com/oauth/*, graph.instagram.com/me) are OIDC-compliant for providerId=oidc.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@infrastructure/keycloak/realms/meajudaai-realm.prod.json` around lines 131 - 151, The Instagram identity-provider block using providerId: "oidc" (alias "instagram") must be revalidated: confirm the configured config keys (issuer, authorizationUrl, tokenUrl, userInfoUrl, logoutUrl) actually expose OIDC discovery, id_token and JWKS endpoints Keycloak requires; if Instagram Basic Display does not provide OIDC discovery/id_token/jwks, change the provider configuration to the correct non-OIDC flow (e.g., use Keycloak's generic OAuth2 provider or providerId that matches Basic Display) and update the config endpoints accordingly (or remove the provider) so runtime login will succeed.
🧹 Nitpick comments (1)
infrastructure/keycloak/realms/meajudaai-realm.prod.json (1)
216-231: Evitar mapper sem efeito prático no pipeline atual de autorização.Os novos mappers gravam roles na claim raiz
roles, mas o extractor atual da API (emsrc/Bootstrapper/MeAjudaAi.ApiService/Extensions/SecurityExtensions.cs) lê apenasrealm_access.roleseresource_access.{client}.roles. Isso tende a gerar configuração redundante e confusão operacional.Considere escolher um padrão único: ou consumir
rolesno backend, ou remover esse mapper dos clients.Also applies to: 256-271
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@infrastructure/keycloak/realms/meajudaai-realm.prod.json` around lines 216 - 231, O mapper "realm-roles" que grava roles na claim raiz "roles" é redundante porque SecurityExtensions.cs só extrai "realm_access.roles" e "resource_access.{client}.roles"; escolha e aplique uma única solução: ou remova este mapper (todos objetos com "name": "realm-roles" no JSON) para evitar claims inúteis, ou atualize o extrator em SecurityExtensions.cs (função(s) que parseiam claims de autenticação) para também ler a claim "roles" além de "realm_access.roles" e "resource_access.{client}.roles" e mapear para o mesmo modelo interno de roles.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@infrastructure/keycloak/realms/meajudaai-realm.prod.json`:
- Around line 42-93: The realm role names were changed to the meajudaai-*
namespace but the backend still validates legacy role names in UserRoles.cs and
assigns via AssignRolesToUserAsync, causing missing assignments; fix by either
(A) updating the backend canonical role list in UserRoles.cs and any logic in
AssignRolesToUserAsync to use the new meajudaai-* role names everywhere, or (B)
add legacy-to-new mappings in the realm (create composite/alias roles in the
realm JSON so each new meajudaai-* role includes the legacy role names as
composites) so AssignRolesToUserAsync can continue sending legacy names until
backend migration is complete.
---
Duplicate comments:
In `@infrastructure/keycloak/realms/meajudaai-realm.prod.json`:
- Around line 131-151: The Instagram identity-provider block using providerId:
"oidc" (alias "instagram") must be revalidated: confirm the configured config
keys (issuer, authorizationUrl, tokenUrl, userInfoUrl, logoutUrl) actually
expose OIDC discovery, id_token and JWKS endpoints Keycloak requires; if
Instagram Basic Display does not provide OIDC discovery/id_token/jwks, change
the provider configuration to the correct non-OIDC flow (e.g., use Keycloak's
generic OAuth2 provider or providerId that matches Basic Display) and update the
config endpoints accordingly (or remove the provider) so runtime login will
succeed.
---
Nitpick comments:
In `@infrastructure/keycloak/realms/meajudaai-realm.prod.json`:
- Around line 216-231: O mapper "realm-roles" que grava roles na claim raiz
"roles" é redundante porque SecurityExtensions.cs só extrai "realm_access.roles"
e "resource_access.{client}.roles"; escolha e aplique uma única solução: ou
remova este mapper (todos objetos com "name": "realm-roles" no JSON) para evitar
claims inúteis, ou atualize o extrator em SecurityExtensions.cs (função(s) que
parseiam claims de autenticação) para também ler a claim "roles" além de
"realm_access.roles" e "resource_access.{client}.roles" e mapear para o mesmo
modelo interno de roles.
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 8c9ba2fc-556f-42b3-9c3f-d6d37f1e26ae
📒 Files selected for processing (2)
infrastructure/keycloak/realms/meajudaai-realm.dev.jsoninfrastructure/keycloak/realms/meajudaai-realm.prod.json
🚧 Files skipped from review as they are similar to previous changes (1)
- infrastructure/keycloak/realms/meajudaai-realm.dev.json
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
♻️ Duplicate comments (1)
src/Shared/Utilities/UserRoles.cs (1)
44-45:⚠️ Potential issue | 🟠 MajorOs novos papéis de visualização/prestador não batem com o catálogo real do Keycloak.
Os exports
infrastructure/keycloak/realms/meajudaai-realm.dev.jsoneinfrastructure/keycloak/realms/meajudaai-realm.prod.jsondesta PR continuam definindomeajudaai-report-vieweremeajudaai-provider, e o dev ainda seedaprovider.democommeajudaai-provider. Com esses novos valores,IsValidRolepassa a aceitar papéis que o Keycloak não entrega eIsProviderRoledeixa de reconhecer o papel real do prestador. Alinhe o catálogo em um lado só antes do merge.Also applies to: 59-74
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/Shared/Utilities/UserRoles.cs` around lines 44 - 45, Atualize os constantes de papel na classe UserRoles para coincidir com o catálogo real do Keycloak (use "meajudaai-report-viewer" e "meajudaai-provider" em vez de "meajudaai-viewer" e qualquer outro valor novo) e garanta que os métodos IsValidRole e IsProviderRole continuem a validar/identificar papéis com esses nomes; especificamente, edite os campos públicos (por exemplo Viewer, Provider, ReportViewer) em UserRoles e ajustar qualquer array/coleção usada por IsValidRole e a lógica em IsProviderRole para referenciar as constantes corrigidas para que o código aceite apenas os papéis que o Keycloak realmente entrega.
🧹 Nitpick comments (1)
tests/MeAjudaAi.ApiService.Tests/Unit/Handlers/SelfOrAdminHandlerTests.cs (1)
40-46: Cubra também o caminho real deClaimTypes.Role.O handler agora aceita
roleseClaimTypes.Role, mas o pipeline real emsrc/Bootstrapper/MeAjudaAi.ApiService/Extensions/SecurityExtensions.csmaterializa as roles comoClaimTypes.Role. Do jeito atual, uma regressão nesse caminho passa despercebida porque a teoria só exercitaAuthConstants.Claims.Roles.💡 Ajuste sugerido
[Theory] - [InlineData(RoleConstants.Admin)] - [InlineData(RoleConstants.SystemAdmin)] - [InlineData(RoleConstants.SuperAdmin)] - [InlineData(RoleConstants.LegacySystemAdmin)] - [InlineData(RoleConstants.LegacySuperAdmin)] - public async Task HandleRequirementAsync_WithAdminRole_ShouldSucceed(string adminRole) + [InlineData(RoleConstants.Admin, AuthConstants.Claims.Roles)] + [InlineData(RoleConstants.Admin, ClaimTypes.Role)] + [InlineData(RoleConstants.SystemAdmin, AuthConstants.Claims.Roles)] + [InlineData(RoleConstants.SystemAdmin, ClaimTypes.Role)] + public async Task HandleRequirementAsync_WithAdminRole_ShouldSucceed(string adminRole, string roleClaimType) { var claims = new List<Claim> { new Claim(AuthConstants.Claims.Subject, "user123"), - new Claim(AuthConstants.Claims.Roles, adminRole) + new Claim(roleClaimType, adminRole) };Also applies to: 49-53
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/MeAjudaAi.ApiService.Tests/Unit/Handlers/SelfOrAdminHandlerTests.cs` around lines 40 - 46, Update the unit tests in SelfOrAdminHandlerTests so they also exercise the real pipeline claim name by covering ClaimTypes.Role in addition to AuthConstants.Claims.Roles: modify or add the HandleRequirementAsync_WithAdminRole_ShouldSucceed (and the similar test at lines 49-53) to parameterize the claim type (or duplicate the theory) and assert the SelfOrAdminHandler behavior when roles are provided under ClaimTypes.Role, ensuring the handler (SelfOrAdminHandler) is exercised with both AuthConstants.Claims.Roles and System.Security.Claims.ClaimTypes.Role.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@src/Shared/Utilities/UserRoles.cs`:
- Around line 44-45: Atualize os constantes de papel na classe UserRoles para
coincidir com o catálogo real do Keycloak (use "meajudaai-report-viewer" e
"meajudaai-provider" em vez de "meajudaai-viewer" e qualquer outro valor novo) e
garanta que os métodos IsValidRole e IsProviderRole continuem a
validar/identificar papéis com esses nomes; especificamente, edite os campos
públicos (por exemplo Viewer, Provider, ReportViewer) em UserRoles e ajustar
qualquer array/coleção usada por IsValidRole e a lógica em IsProviderRole para
referenciar as constantes corrigidas para que o código aceite apenas os papéis
que o Keycloak realmente entrega.
---
Nitpick comments:
In `@tests/MeAjudaAi.ApiService.Tests/Unit/Handlers/SelfOrAdminHandlerTests.cs`:
- Around line 40-46: Update the unit tests in SelfOrAdminHandlerTests so they
also exercise the real pipeline claim name by covering ClaimTypes.Role in
addition to AuthConstants.Claims.Roles: modify or add the
HandleRequirementAsync_WithAdminRole_ShouldSucceed (and the similar test at
lines 49-53) to parameterize the claim type (or duplicate the theory) and assert
the SelfOrAdminHandler behavior when roles are provided under ClaimTypes.Role,
ensuring the handler (SelfOrAdminHandler) is exercised with both
AuthConstants.Claims.Roles and System.Security.Claims.ClaimTypes.Role.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 59fb6433-49bd-4551-ac1c-1180aca968f1
📒 Files selected for processing (8)
infrastructure/keycloak/realms/meajudaai-realm.dev.jsoninfrastructure/keycloak/realms/meajudaai-realm.prod.jsonsrc/Bootstrapper/MeAjudaAi.ApiService/Extensions/SecurityExtensions.cssrc/Bootstrapper/MeAjudaAi.ApiService/Handlers/SelfOrAdminHandler.cssrc/Modules/Documents/Tests/Unit/Application/RequestVerificationCommandHandlerTests.cssrc/Shared/Utilities/UserRoles.cstests/MeAjudaAi.ApiService.Tests/Unit/Handlers/SelfOrAdminHandlerTests.cstests/MeAjudaAi.Shared.Tests/Unit/Utilities/UserRolesTests.cs
🚧 Files skipped from review as they are similar to previous changes (2)
- src/Modules/Documents/Tests/Unit/Application/RequestVerificationCommandHandlerTests.cs
- src/Bootstrapper/MeAjudaAi.ApiService/Extensions/SecurityExtensions.cs
…rRepositoryIntegrationTests
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
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)
src/Shared/Utilities/UserRoles.cs (1)
84-153:⚠️ Potential issue | 🟠 Major
UserRolesnão representa mais o catálogo real de roles.
AllRoles/AdminRolesagora deixam de fora roles que continuam existindo emRoleConstantse nos realms, comoadmin,meajudaai-user-admin,meajudaai-user,meajudaai-order-admin,meajudaai-order-operator,meajudaai-report-adminemeajudaai-location-manager. Com isso,IsValidRoleeIsAdminRolepassam a retornarfalsepara roles que o próprio Keycloak ainda emite. Ou complete essas listas com todas as roles canônicas, ou restrinja/renomeie esta API para deixar claro que ela representa só um subconjunto. Ajuste também os testes deste PR para cobrir o catálogo correto.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/Shared/Utilities/UserRoles.cs` around lines 84 - 153, The AllRoles and AdminRoles arrays in UserRoles no longer reflect the canonical role catalog (e.g., roles present in RoleConstants and Keycloak such as admin, mejudaai-user-admin, mejudaai-user, mejudaai-order-admin, mejudaai-order-operator, mejudaai-report-admin, mejudaai-location-manager), causing IsValidRole and IsAdminRole to return false for legitimate roles; fix by either (A) synchronizing AllRoles and AdminRoles with the full canonical set from RoleConstants/Keycloak so IsValidRole/IsAdminRole validate against the true catalog, or (B) explicitly renaming/scoping this API (e.g., to KnownPortalRoles or SubsetUserRoles) and updating its XML doc/comments/tests to state it covers only that subset; also update or add unit tests to assert the chosen behavior (include examples of the missing role names in tests) and ensure references to IsValidRole/IsAdminRole across the codebase still match the intended semantics.
♻️ Duplicate comments (1)
infrastructure/keycloak/realms/meajudaai-realm.prod.json (1)
63-69:⚠️ Potential issue | 🟠 MajorInclua as roles de tier de prestador no realm.
O catálogo exportado ainda não declara
meajudaai-provider-standard,meajudaai-provider-silver,meajudaai-provider-goldemeajudaai-provider-platinum, mas o código já as trata como válidas emsrc/Shared/Utilities/UserRoles.csesrc/Modules/Providers/Domain/Enums/ProviderTierExtensions.cs. Quando algum fluxo tentar atribuí-las no Keycloak, a operação vai falhar por role inexistente. Vale espelhar o mesmo ajuste no realm de desenvolvimento também.🛠️ Ajuste sugerido
{ "name": "meajudaai-provider", "description": "Prestador - apenas leitura" + }, + { + "name": "meajudaai-provider-standard", + "description": "Prestador Standard - plano gratuito" + }, + { + "name": "meajudaai-provider-silver", + "description": "Prestador Silver - plano pago" + }, + { + "name": "meajudaai-provider-gold", + "description": "Prestador Gold - plano pago" + }, + { + "name": "meajudaai-provider-platinum", + "description": "Prestador Platinum - plano pago" },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@infrastructure/keycloak/realms/meajudaai-realm.prod.json` around lines 63 - 69, O export do realm não inclui as roles de tier de prestador necessárias; adicione as roles meajudaai-provider-standard, meajudaai-provider-silver, meajudaai-provider-gold e meajudaai-provider-platinum ao JSON do realm (mesmo bloco onde estão meajudaai-provider-admin e meajudaai-provider) com descrições claras, e replique a mesma alteração no realm de desenvolvimento; isso garante que as referências em src/Shared/Utilities/UserRoles.cs e em src/Modules/Providers/Domain/Enums/ProviderTierExtensions.cs correspondam a roles existentes no Keycloak.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@infrastructure/keycloak/realms/meajudaai-realm.prod.json`:
- Around line 131-149: The Instagram identity provider is using providerId
"facebook" which hardcodes Facebook endpoints and ignores the configured URLs;
change providerId from "facebook" to the generic "oauth2" or "oidc" for the
"instagram" alias so authorizationUrl/tokenUrl/userInfoUrl are respected, then
configure the generic provider's claim mappings to map id → userID and username
→ username and mark email as optional; alternatively implement a custom
Instagram provider if you need Facebook-specific behavior.
---
Outside diff comments:
In `@src/Shared/Utilities/UserRoles.cs`:
- Around line 84-153: The AllRoles and AdminRoles arrays in UserRoles no longer
reflect the canonical role catalog (e.g., roles present in RoleConstants and
Keycloak such as admin, mejudaai-user-admin, mejudaai-user,
mejudaai-order-admin, mejudaai-order-operator, mejudaai-report-admin,
mejudaai-location-manager), causing IsValidRole and IsAdminRole to return false
for legitimate roles; fix by either (A) synchronizing AllRoles and AdminRoles
with the full canonical set from RoleConstants/Keycloak so
IsValidRole/IsAdminRole validate against the true catalog, or (B) explicitly
renaming/scoping this API (e.g., to KnownPortalRoles or SubsetUserRoles) and
updating its XML doc/comments/tests to state it covers only that subset; also
update or add unit tests to assert the chosen behavior (include examples of the
missing role names in tests) and ensure references to IsValidRole/IsAdminRole
across the codebase still match the intended semantics.
---
Duplicate comments:
In `@infrastructure/keycloak/realms/meajudaai-realm.prod.json`:
- Around line 63-69: O export do realm não inclui as roles de tier de prestador
necessárias; adicione as roles meajudaai-provider-standard,
meajudaai-provider-silver, meajudaai-provider-gold e meajudaai-provider-platinum
ao JSON do realm (mesmo bloco onde estão meajudaai-provider-admin e
meajudaai-provider) com descrições claras, e replique a mesma alteração no realm
de desenvolvimento; isso garante que as referências em
src/Shared/Utilities/UserRoles.cs e em
src/Modules/Providers/Domain/Enums/ProviderTierExtensions.cs correspondam a
roles existentes no Keycloak.
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 371d6028-b9af-4e5e-9953-4ed391569842
📒 Files selected for processing (9)
infrastructure/keycloak/realms/meajudaai-realm.dev.jsoninfrastructure/keycloak/realms/meajudaai-realm.prod.jsonsrc/Bootstrapper/MeAjudaAi.ApiService/Extensions/SecurityExtensions.cssrc/Bootstrapper/MeAjudaAi.ApiService/Handlers/SelfOrAdminHandler.cssrc/Modules/Documents/Tests/Unit/Application/RequestVerificationCommandHandlerTests.cssrc/Shared/Utilities/UserRoles.cstests/MeAjudaAi.ApiService.Tests/Unit/Handlers/SelfOrAdminHandlerTests.cstests/MeAjudaAi.Integration.Tests/Modules/Users/UserRepositoryIntegrationTests.cstests/MeAjudaAi.Shared.Tests/Unit/Utilities/UserRolesTests.cs
✅ Files skipped from review due to trivial changes (1)
- tests/MeAjudaAi.Integration.Tests/Modules/Users/UserRepositoryIntegrationTests.cs
🚧 Files skipped from review as they are similar to previous changes (3)
- src/Modules/Documents/Tests/Unit/Application/RequestVerificationCommandHandlerTests.cs
- src/Bootstrapper/MeAjudaAi.ApiService/Extensions/SecurityExtensions.cs
- tests/MeAjudaAi.ApiService.Tests/Unit/Handlers/SelfOrAdminHandlerTests.cs
Code Coverage Report
|
Minimum allowed line rate is |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/Shared/Utilities/UserRoles.cs (1)
81-84: Considerar moverCustomerparaRoleConstants.A role
customerestá hardcoded aqui enquanto as demais delegam paraRoleConstants. Para manter consistência total, considere adicionarCustomer = "customer"emRoleConstants.cse referenciar aqui.♻️ Sugestão de refatoração
Em
RoleConstants.cs:+ // Role de cliente + public const string Customer = "customer";Em
UserRoles.cs:- public const string Customer = "customer"; + public const string Customer = RoleConstants.Customer;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/Shared/Utilities/UserRoles.cs` around lines 81 - 84, Move the hardcoded Customer constant into the central RoleConstants class and change UserRoles to reference it: add a public const string Customer = "customer" to RoleConstants and replace the literal in UserRoles (the public const string Customer) with a reference to RoleConstants.Customer (e.g., public static readonly string Customer = RoleConstants.Customer or direct reference), ensuring namespaces/imports remain correct and removing the duplicate constant from UserRoles.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@infrastructure/keycloak/realms/meajudaai-realm.dev.json`:
- Around line 190-199: O mapper de Identity Provider "instagram-id-to-userid"
está usando "userAttribute": "userID" com D maiúsculo; atualize esse valor para
"userId" (camelCase) no bloco de configuração do mapper para garantir
compatibilidade com os consumidores C# (referências: GetUserId(),
GetUserIdGuid(), MaskUserId()) e evitar falhas no mapeamento do atributo.
---
Nitpick comments:
In `@src/Shared/Utilities/UserRoles.cs`:
- Around line 81-84: Move the hardcoded Customer constant into the central
RoleConstants class and change UserRoles to reference it: add a public const
string Customer = "customer" to RoleConstants and replace the literal in
UserRoles (the public const string Customer) with a reference to
RoleConstants.Customer (e.g., public static readonly string Customer =
RoleConstants.Customer or direct reference), ensuring namespaces/imports remain
correct and removing the duplicate constant from UserRoles.
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 88e79ddf-5376-4bcd-8175-c691212c6f4b
📒 Files selected for processing (4)
infrastructure/keycloak/realms/meajudaai-realm.dev.jsoninfrastructure/keycloak/realms/meajudaai-realm.prod.jsonsrc/Shared/Utilities/UserRoles.cstests/MeAjudaAi.Shared.Tests/Unit/Utilities/UserRolesTests.cs
🚧 Files skipped from review as they are similar to previous changes (1)
- tests/MeAjudaAi.Shared.Tests/Unit/Utilities/UserRolesTests.cs
Changes\n- Aligned Production realm with Development granular roles, clients, and identity providers.\n- Resolved Issue #141 by synchronizing Instagram login configuration.\n- Transferred Sprint 10 to history and promoted Sprint 11 as the current one.\n- Updated technical debt status for #141.\n\nFixes #141
Summary by CodeRabbit
Documentação
Novas Funcionalidades
Infraestrutura
Tests