Skip to content

Update application REST APIs and fix multiple bugs#2234

Open
Piumal1999 wants to merge 8 commits into
wso2:mainfrom
Piumal1999:idp-new
Open

Update application REST APIs and fix multiple bugs#2234
Piumal1999 wants to merge 8 commits into
wso2:mainfrom
Piumal1999:idp-new

Conversation

@Piumal1999

Copy link
Copy Markdown
Contributor

Purpose

Correcting the application related rest APIs
Updating docs
Fixing multiple authentication related bugs

Approach

  • Changed /applications endpoints to have o/{orgId} prefix similar to other APIs
  • Added validations to cross check the organization in the path and the session/token
  • Added an endpoint to list the applications
  • Updated the docs

@coderabbitai

coderabbitai Bot commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 36e1bc17-7bfc-4bec-b62c-8f7a8df24d87

📥 Commits

Reviewing files that changed from the base of the PR and between 66c2080 and 9f6eee2.

📒 Files selected for processing (1)
  • portals/developer-portal/src/services/apiFlowService.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • portals/developer-portal/src/services/apiFlowService.js

📝 Walkthrough

API Route Restructuring

The Developer Portal REST API endpoints for applications have been standardized to use organization-scoped routing via the /o/{orgId}/devportal/v1/ prefix. This includes:

  • Applications: listing, creation, update, and deletion now take orgId from the URL path and use /o/{orgId}/devportal/v1/applications...
  • Application key management (OAuth keys): key generation, token generation, revocation, updates, and cleanup now use the corresponding org-scoped /o/{orgId}/devportal/v1/... routes
  • New endpoint: a list applications operation is added and wired through the applications API handlers/controllers

Authentication and Authorization Enhancements

Multiple auth flow and authorization behaviors were updated to ensure correct organization scoping and more consistent request handling:

  • Added organization isolation validation that checks the orgId in the request path against the organization identifier in the user/token/session context (including UUID validation and clear HTTP status handling for missing/invalid/mismatched org context).
  • Updated request authorization outcomes to use more consistent 403 “Forbidden” responses for org-claim mismatches and unauthorized cases.
  • Improved bearer/JWT handling:
    • identity-provider context resolution was adjusted for org-scoped requests
    • certificate-based JWT verification now conditionally applies configured issuer/audience verification
  • Refined session and callback handling across login/logout and SSO flows:
    • OAuth callback validations now run sequentially with early error responses
    • logout/session-destroy and related redirects now wait for session operations where appropriate and log save/destroy issues

Backend Implementation Updates

  • Application controllers were refactored to derive orgID and userID directly from req.params and authenticated request context (rather than resolving org/user indirectly).
  • A new listApplications controller was introduced to return org-scoped application data.
  • Application create/update/delete and key generation flows were adjusted to use the derived org context consistently.
  • Logging/telemetry payloads were updated to reflect the new derived orgId/userId sources.
  • Key generation transaction initialization was adjusted to avoid unnecessary work when required org context cannot be retrieved.

Frontend and Template Updates

  • Updated frontend scripts to call org-scoped application and key management endpoints (including create/edit/delete and OAuth key generation).
  • The main layout now exposes orgId to the frontend via window.__DEVPORTAL_API__, and window.devportalApi now includes orgId for use by scripts.

Configuration and Documentation Updates

  • Updated REST API documentation for applications and application keys to reflect org-scoped routes and required orgId path parameters.
  • Updated OpenAPI spec routes to use /o/{orgId}/devportal/v1/... prefixes for the affected application and OAuth key operations.
  • Expanded Developer Portal documentation to cover external IDP authentication for API clients, including bearer token retrieval guidance.
  • Updated identity provider configuration guidance and setup docs to clarify:
    • scope enforcement differences between browser sessions and machine/API clients
    • changes to the configured org identifier claim mapping used for org scoping
    • guidance for integration behavior and scope-validation configuration.

Walkthrough

The pull request transforms the Developer Portal API to enforce explicit organization scoping, requiring all application and key-management operations to include an orgId path segment (/o/{orgId}/devportal/v1/...). Auth middleware gains a new checkOrgIsolation function that validates the request-path org against token or session org claims using organization data lookups. JWT verification is hardened with issuer and audience options across tokenUtil.js, ensureAuthenticated.js, and bearer-token resolution. Session lifecycle handling in authController.js is made more robust through sequential validation, proper session destruction callbacks, and error logging. A new listApplications controller endpoint is introduced, and existing CRUD handlers are refactored to derive org and user identity directly from request parameters instead of database lookups. The config.yaml.example updates orgIDClaim to org_name and clarifies that dp:* scopes apply to machine API clients but not browser sessions. Comprehensive Asgardeo IDP setup and bearer-token curl-based authentication guides are added. All frontend scripts and templates are updated to use the new org-scoped API endpoints.

Suggested Reviewers

  • RakhithaRR
  • Tharsanan1
  • VirajSalaka
  • malinthaprasan
  • AnuGayan
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request description is incomplete compared to the required template. It lacks details on User stories, Documentation links, Automation tests (unit and integration), Security checks, Samples, Related PRs, and Test environment. Complete the description by adding the missing template sections: User stories, Documentation, Automation tests (unit and integration tests with coverage), Security checks (secure coding standards, FindSecurityBugs, secret verification), Samples, Related PRs, and Test environment details.
Docstring Coverage ⚠️ Warning Docstring coverage is 21.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: updating application REST APIs and fixing authentication bugs, which aligns with the significant restructuring of endpoints and bug fixes throughout the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
portals/developer-portal/src/controllers/authController.js (2)

224-230: ⚡ Quick win

Misleading await on callback-based API.

req.session.save(callback) uses callback style and does not return a Promise. The await resolves immediately to undefined rather than waiting for the save to complete. The code works correctly because all logic is inside the callback, but the await is misleading and could confuse future maintainers.

Suggested fix
     req.session.returnTo = req.originalUrl;
     req.session.silentAuthRedirected = true;
-    await req.session.save((err) => {
+    req.session.save((err) => {
         if (err) {
             logger.error('Session save failed during silent SSO', { error: err.message });
             return next();
         }
         passport.authenticate('oauth2', { prompt: 'none' })(req, res, next);
     });
🤖 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 `@portals/developer-portal/src/controllers/authController.js` around lines 224
- 230, The await keyword on the callback-based req.session.save() call is
misleading because this API does not return a Promise, so await resolves
immediately to undefined rather than waiting for the callback to complete.
Remove the await keyword from the req.session.save invocation in the silent SSO
authentication handler, as the callback pattern already properly handles the
asynchronous flow and all logic is correctly contained within the callback.

163-170: 💤 Low value

Redundant header assignment.

Cache-Control is already set at line 151 before entering the conditional branches. This duplicate set on line 167 is unnecessary.

Suggested fix
             req.session.destroy((destroyErr) => {
                 if (destroyErr) {
                     logger.error('Session destroy failed on local-auth logout', { error: destroyErr.message });
                 }
-                res.set('Cache-Control', 'no-store');
                 res.redirect(req.originalUrl.replace('/logout', '/login'));
             });
🤖 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 `@portals/developer-portal/src/controllers/authController.js` around lines 163
- 170, The Cache-Control header is being set twice in the logout flow: once at
line 151 and again inside the req.session.destroy callback at line 167. Remove
the duplicate res.set('Cache-Control', 'no-store'); statement from inside the
session destroy callback since the header is already configured earlier in the
control flow before entering the conditional branches.
🤖 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 `@portals/developer-portal/src/controllers/devportalController.js`:
- Line 165: Fix the typo in the delete success response message in
devportalController.js where "Resouce" is misspelled and should be "Resource".
Update the response text in the res.status(200).send() call to correctly spell
"Resource Deleted Successfully" instead of "Resouce Deleted Successfully". This
typo appears in multiple locations (at lines 165 and 175), so make sure to
correct all occurrences throughout the file.
- Line 75: The request parameters being logged directly in error messages (such
as orgId in req.params.orgId) need to be normalized to remove CR/LF characters
before being attached to log metadata. Extract and normalize the route
parameters (req.params.orgId and any other request-path values) by removing
carriage returns and line feeds early in the request handler, then use these
sanitized values in all subsequent logger.error calls that reference them. This
normalization should be applied consistently across the error logging statements
at lines 75, 90, 109, and 178 to ensure logs remain safe and reliable for
downstream processing.

In `@portals/developer-portal/src/middlewares/authMiddleware.js`:
- Around line 96-131: The checkOrgIsolation function currently treats all errors
from orgDao.get() as internal server errors, but the upstream contract indicates
that a missing organization throws Sequelize.EmptyResultError rather than
returning a falsy value, making the !orgDetails check unreachable. Modify the
catch block that handles the orgDao.get() call to distinguish between
Sequelize.EmptyResultError (which should return a 404 status) and other errors
(which should return 500 status). This will ensure that missing organizations
are properly reported as 404 Not Found instead of 500 Internal Server Error, and
you can remove the now-reachable !orgDetails check.

---

Nitpick comments:
In `@portals/developer-portal/src/controllers/authController.js`:
- Around line 224-230: The await keyword on the callback-based
req.session.save() call is misleading because this API does not return a
Promise, so await resolves immediately to undefined rather than waiting for the
callback to complete. Remove the await keyword from the req.session.save
invocation in the silent SSO authentication handler, as the callback pattern
already properly handles the asynchronous flow and all logic is correctly
contained within the callback.
- Around line 163-170: The Cache-Control header is being set twice in the logout
flow: once at line 151 and again inside the req.session.destroy callback at line
167. Remove the duplicate res.set('Cache-Control', 'no-store'); statement from
inside the session destroy callback since the header is already configured
earlier in the control flow before entering the conditional branches.
🪄 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: CHILL

Plan: Pro

Run ID: d72555f5-946a-4ca6-b073-a5c622fb9b1b

📥 Commits

Reviewing files that changed from the base of the PR and between 01d2cb2 and b3af367.

📒 Files selected for processing (15)
  • docs/rest-apis/devportal/README.md
  • docs/rest-apis/devportal/application-keys.md
  • docs/rest-apis/devportal/applications.md
  • portals/developer-portal/configs/config.yaml.example
  • portals/developer-portal/docs/README.md
  • portals/developer-portal/docs/administer/api-token-curl.md
  • portals/developer-portal/docs/administer/asgardeo-setup.md
  • portals/developer-portal/docs/devportal-openapi-spec-v1.yaml
  • portals/developer-portal/src/controllers/authController.js
  • portals/developer-portal/src/controllers/devportalController.js
  • portals/developer-portal/src/middlewares/authMiddleware.js
  • portals/developer-portal/src/middlewares/ensureAuthenticated.js
  • portals/developer-portal/src/middlewares/passportConfig.js
  • portals/developer-portal/src/routes/api/handlers/applicationsHandler.js
  • portals/developer-portal/src/utils/tokenUtil.js

Comment thread portals/developer-portal/src/controllers/devportalController.js Outdated
Comment thread portals/developer-portal/src/controllers/devportalController.js Outdated
Comment thread portals/developer-portal/src/middlewares/authMiddleware.js

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@portals/developer-portal/src/services/apiFlowService.js`:
- Around line 186-192: Move the orgDao.get(orgID) call and
sequelize.transaction() creation from before the try block into inside the try
block so that failures in these operations are caught by the existing catch
handler. Additionally, update the catch block to only perform transaction
rollback when the transaction variable t was successfully created, by checking
if t exists before calling rollback.
🪄 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: CHILL

Plan: Pro

Run ID: 4aa8be90-e794-4a29-ab76-06fe626b0f8f

📥 Commits

Reviewing files that changed from the base of the PR and between b3af367 and 66c2080.

📒 Files selected for processing (13)
  • portals/developer-portal/src/controllers/applicationsContentController.js
  • portals/developer-portal/src/controllers/authController.js
  • portals/developer-portal/src/controllers/devportalController.js
  • portals/developer-portal/src/defaultContent/layout/main.hbs
  • portals/developer-portal/src/middlewares/authMiddleware.js
  • portals/developer-portal/src/middlewares/ensureAuthenticated.js
  • portals/developer-portal/src/scripts/add-application-form.js
  • portals/developer-portal/src/scripts/common.js
  • portals/developer-portal/src/scripts/edit-application-form.js
  • portals/developer-portal/src/scripts/oauth2-key-generation.js
  • portals/developer-portal/src/scripts/warning.js
  • portals/developer-portal/src/services/apiFlowService.js
  • portals/developer-portal/src/services/apiMetadataService.js
💤 Files with no reviewable changes (1)
  • portals/developer-portal/src/services/apiMetadataService.js
🚧 Files skipped from review as they are similar to previous changes (4)
  • portals/developer-portal/src/middlewares/authMiddleware.js
  • portals/developer-portal/src/controllers/devportalController.js
  • portals/developer-portal/src/middlewares/ensureAuthenticated.js
  • portals/developer-portal/src/controllers/authController.js

Comment thread portals/developer-portal/src/services/apiFlowService.js Outdated
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.

1 participant