Skip to content

feat: single sign on#1305

Merged
bhavanakarwade merged 3 commits intodevelopfrom
feat/sso-feature
Jul 1, 2025
Merged

feat: single sign on#1305
bhavanakarwade merged 3 commits intodevelopfrom
feat/sso-feature

Conversation

@bhavanakarwade
Copy link
Copy Markdown
Contributor

@bhavanakarwade bhavanakarwade commented Jul 1, 2025

What

  • Support SSO
  • Ability to switch between client based on clientAlias instead of

Summary by CodeRabbit

  • New Features

    • Introduced Single Sign-On (SSO) multi-client support, allowing configuration and management of multiple SSO clients via environment variables.
    • Added endpoints to fetch client aliases and their URLs for enhanced client management.
    • New database table and schema support for storing client aliases and URLs.
  • Enhancements

    • Email verification flow now supports client alias and custom redirect parameters for improved multi-tenant handling.
    • Improved validation and error handling for client alias inputs.
    • Utility functions and interfaces added for secure SSO credential management.
  • Bug Fixes / Style

    • Consistent formatting, improved typing, and minor code style improvements across various modules.
  • Chores

    • Updated documentation and environment variable templates to guide SSO client configuration.
    • Updated service dependencies in docker configuration for improved startup reliability.

Signed-off-by: bhavanakarwade <bhavana.karwade@ayanworks.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jul 1, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This update introduces support for Single Sign-On (SSO) client alias management across the system. It adds environment variable templates, database schema and migration for storing client aliases and URLs, new endpoints and service methods to fetch these aliases, and utilities for handling SSO client credentials. The email verification flow is enhanced to support client alias selection and redirection.

Changes

File(s) / Group Change Summary
.env.demo, .env.sample Added SSO configuration section and templates for multiple clients with explanatory comments and sample values.
docker-compose.yml Added redis as a dependency for the issuance service.
apps/api-gateway/src/authz/authz.controller.ts, authz.service.ts, authz/decorators/user-auth-client.ts Added endpoint and service for fetching client aliases; introduced ClientAliasValidationPipe for validating client aliases; updated verification mail endpoint to accept client alias.
apps/api-gateway/src/user/dto/create-user.dto.ts Removed clientId and clientSecret from UserEmailVerificationDto; added optional clientAlias property; formatting improvements.
apps/api-gateway/src/user/utils/index.ts New utility functions for retrieving default client and credentials by alias, with encryption support.
apps/organization/repositories/organization.repository.ts Included tenantId in organization agent selection.
apps/user/repositories/user.repository.ts Added method to fetch all client aliases from the database; import and formatting adjustments.
apps/user/src/user.controller.ts, user.service.ts Added endpoint and service for fetching client aliases; updated email verification and related methods to support client alias and redirect parameters; formatting and typing consistency improvements.
apps/user/templates/user-email-template.ts Updated URL template method to accept and append redirectTo and clientAlias parameters; improved error handling.
libs/common/src/cast.helper.ts Added encryptClientCredential function for encrypting client credentials.
libs/common/src/common.module.ts Included LoggerModule and Logger in CommonModule imports and providers.
libs/common/src/interfaces/user.interface.ts Added/updated interfaces for SSO client details and client aliases; extended ISendVerificationEmail with clientAlias and redirectTo.
libs/common/src/response-messages/index.ts Added success message for fetching client aliases.
libs/prisma-service/prisma/migrations/.../migration.sql, schema.prisma Added client_aliases table/model with fields for ID, timestamps, alias, and URL; closed unclosed enum.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API-Gateway
    participant AuthzService
    participant UserService
    participant UserRepository
    participant DB

    Client->>API-Gateway: GET /clientAliases
    API-Gateway->>AuthzService: getClientAlias()
    AuthzService->>UserService: NATS message: get-client-alias-and-url
    UserService->>UserRepository: fetchClientAliases()
    UserRepository->>DB: SELECT * FROM client_aliases
    DB-->>UserRepository: client_aliases[]
    UserRepository-->>UserService: client_aliases[]
    UserService-->>AuthzService: client_aliases[]
    AuthzService-->>API-Gateway: client_aliases[]
    API-Gateway-->>Client: Response with aliases and URLs
Loading
sequenceDiagram
    participant Client
    participant API-Gateway
    participant AuthzService
    participant UserService
    participant Utils

    Client->>API-Gateway: POST /verification-mail?clientAlias=ALIAS
    API-Gateway->>AuthzService: sendVerificationMail({email, ..., clientAlias})
    AuthzService->>UserService: NATS message: sendVerificationMail with clientAlias
    UserService->>Utils: getCredentialsByAlias(clientAlias)
    Utils-->>UserService: client credentials
    UserService->>UserService: sendEmailForVerification(..., clientAlias)
    UserService-->>AuthzService: user
    AuthzService-->>API-Gateway: user
    API-Gateway-->>Client: Response
Loading

Poem

🐇
A hop, a skip, a client alias found,
Across the fields, new SSO bounds!
With secrets locked and URLs in tow,
The gateway now knows just where to go.
Rabbits rejoice, credentials in hand—
Secure and swift, across the land!
🌱✨


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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@bhavanakarwade bhavanakarwade self-assigned this Jul 1, 2025
@GHkrishna
Copy link
Copy Markdown
Contributor

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jul 1, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@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: 8

🧹 Nitpick comments (8)
libs/prisma-service/prisma/schema.prisma (1)

524-530: Consider adding indexes for better query performance.

The client_aliases model structure is appropriate for SSO functionality. Consider adding unique constraints or indexes if clientAlias should be unique or if queries will frequently filter by these fields.

If clientAlias should be unique, apply this diff:

 model client_aliases {
   id                   String        @id @default(uuid()) @db.Uuid
   createDateTime       DateTime      @default(now()) @db.Timestamptz(6)
   lastChangedDateTime  DateTime      @default(now()) @db.Timestamptz(6)
-  clientAlias          String?
+  clientAlias          String?       @unique
   clientUrl            String        
 }
libs/prisma-service/prisma/migrations/20250701025741_added_client_alias/migration.sql (1)

1-11: Consider adding indexes for query performance.

The table schema is well-designed for storing client alias mappings. Consider adding indexes on frequently queried columns like clientAlias if this table will be queried often.

If frequent lookups are expected, consider adding an index:

CREATE INDEX "client_aliases_clientAlias_idx" ON "client_aliases"("clientAlias");
apps/user/repositories/user.repository.ts (1)

38-42: Improve JSDoc documentation.

The JSDoc comment is incomplete and doesn't follow the established pattern in the file.

Apply this diff to improve the documentation:

-  /**
-   *
-   * @returns Client alias and its url
-   */
+  /**
+   * Fetches all client aliases from the database
+   * @returns Promise<client_aliases[]> Array of client alias records
+   */
apps/api-gateway/src/authz/authz.controller.ts (2)

46-46: Fix typo in JSDoc comment

-   * Fetch client aliase.
+   * Fetch client aliases.

54-54: Fix typo in API operation description

-    description: 'Fetch client aliases and itr url'
+    description: 'Fetch client aliases and its url'
apps/user/src/user.service.ts (1)

92-95: Move the eslint-disable comment to the correct position

The eslint-disable comment should be placed immediately before the line that uses snake_case.

-
-  // eslint-disable-next-line camelcase
-  async getClientAliases(): Promise<client_aliases[]> {
+  // eslint-disable-next-line camelcase
+  async getClientAliases(): Promise<client_aliases[]> {
apps/user/src/user.controller.ts (2)

39-39: Fix typo in JSDoc comment

-   * Description: Fetch client aliases are its url
+   * Description: Fetch client aliases and its url

44-46: Fix eslint-disable comment placement

The eslint-disable comment should be placed immediately before the line that uses snake_case.

-  // eslint-disable-next-line camelcase
-  async getClientAliases(): Promise<client_aliases[]> {
+  // eslint-disable-next-line camelcase
+  async getClientAliases(): Promise<client_aliases[]> {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f5ce197 and 21ef364.

📒 Files selected for processing (19)
  • .env.demo (1 hunks)
  • .env.sample (1 hunks)
  • apps/api-gateway/src/authz/authz.controller.ts (6 hunks)
  • apps/api-gateway/src/authz/authz.service.ts (3 hunks)
  • apps/api-gateway/src/authz/decorators/user-auth-client.ts (1 hunks)
  • apps/api-gateway/src/user/dto/create-user.dto.ts (1 hunks)
  • apps/api-gateway/src/user/utils/index.ts (1 hunks)
  • apps/organization/repositories/organization.repository.ts (1 hunks)
  • apps/user/repositories/user.repository.ts (6 hunks)
  • apps/user/src/user.controller.ts (6 hunks)
  • apps/user/src/user.service.ts (29 hunks)
  • apps/user/templates/user-email-template.ts (2 hunks)
  • docker-compose.yml (1 hunks)
  • libs/common/src/cast.helper.ts (3 hunks)
  • libs/common/src/common.module.ts (1 hunks)
  • libs/common/src/interfaces/user.interface.ts (1 hunks)
  • libs/common/src/response-messages/index.ts (1 hunks)
  • libs/prisma-service/prisma/migrations/20250701025741_added_client_alias/migration.sql (1 hunks)
  • libs/prisma-service/prisma/schema.prisma (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (6)
libs/common/src/common.module.ts (1)
libs/logger/src/logger.interface.ts (1)
  • Logger (6-20)
apps/user/repositories/user.repository.ts (1)
apps/user/interfaces/user.interface.ts (1)
  • IUserDeletedActivity (210-218)
apps/api-gateway/src/user/utils/index.ts (2)
libs/common/src/interfaces/user.interface.ts (1)
  • IClientDetailsSSO (24-29)
libs/common/src/cast.helper.ts (1)
  • encryptClientCredential (442-456)
libs/common/src/interfaces/user.interface.ts (1)
apps/user/interfaces/user.interface.ts (4)
  • IVerifyUserEmail (173-176)
  • ISendVerificationEmail (51-56)
  • IOrgRole (22-26)
  • IOrganisation (27-38)
apps/api-gateway/src/user/dto/create-user.dto.ts (2)
libs/common/src/cast.helper.ts (2)
  • trim (39-43)
  • toLowerCase (35-37)
libs/validations/maxLength.ts (1)
  • MaxLength (3-28)
apps/user/src/user.controller.ts (6)
libs/common/src/interfaces/user.interface.ts (6)
  • ISendVerificationEmail (13-22)
  • IVerifyUserEmail (9-12)
  • ISignInUser (1-8)
  • IResetPasswordResponse (54-57)
  • IUserInvitations (30-33)
  • ISignUpUserResponse (59-61)
apps/user/interfaces/user.interface.ts (10)
  • ISendVerificationEmail (51-56)
  • IVerifyUserEmail (173-176)
  • IUserSignIn (178-182)
  • IUserResetPassword (184-190)
  • IUserForgotPassword (191-196)
  • Payload (167-171)
  • IOrgUsers (112-115)
  • ICheckUserDetails (104-110)
  • IUserInformation (58-65)
  • IUserDeletedActivity (210-218)
apps/api-gateway/src/authz/authz.service.ts (1)
  • refreshToken (68-70)
apps/organization/interfaces/organization.interface.ts (1)
  • Payload (144-149)
libs/user-activity/interface/index.ts (1)
  • IUsersActivity (1-9)
apps/api-gateway/src/user/dto/add-user.dto.ts (1)
  • AddPasskeyDetailsDto (45-51)
🔇 Additional comments (27)
apps/organization/repositories/organization.repository.ts (1)

685-686: LGTM! Clean addition of tenant ID for multi-tenant support.

The addition of tenantId to the org_agents selection is appropriate for the SSO and client alias functionality being introduced. This change expands the data retrieved for organization agents without affecting existing logic or performance.

docker-compose.yml (1)

64-64: LGTM! Proper service dependency management.

The addition of redis as a dependency for the issuance service ensures proper startup ordering and aligns with the SSO functionality enhancements.

libs/common/src/cast.helper.ts (2)

1-2: LGTM! Required imports for encryption functionality.

The CryptoJS import supports the new client credential encryption feature.


28-28: LGTM! Logger instance for encryption operations.

The logger instance will be used for debugging and error reporting in the encryption function.

libs/common/src/response-messages/index.ts (1)

7-7: LGTM! Proper response message addition.

The new success message for fetching client aliases follows the existing pattern and supports the SSO functionality.

libs/common/src/common.module.ts (3)

1-1: LGTM! Required imports for logging functionality.

The Logger import supports the encryption operations added in cast.helper.ts.


5-5: LGTM! LoggerModule import for proper module integration.

The LoggerModule import enables logging capabilities throughout the common module.


8-9: LGTM! Proper module configuration for logging.

The LoggerModule is correctly added to imports and Logger service to providers, enabling consistent logging across the module.

libs/prisma-service/prisma/schema.prisma (1)

522-522: LGTM! Fixes unclosed enum.

The closing brace for CloudWalletType enum was missing and is now properly added.

.env.demo (1)

160-180: Well-structured SSO configuration template.

The SSO configuration section is well-organized with clear documentation and follows good practices for multi-client support. The template structure makes it easy to add additional clients.

apps/user/repositories/user.repository.ts (1)

6-16: Approve import reorganization and formatting improvements.

The import reorganization and formatting improvements (including consistent arrow function parentheses) enhance code readability.

Also applies to: 780-796

apps/api-gateway/src/authz/decorators/user-auth-client.ts (1)

1-27: Excellent implementation of validation pipe.

This validation pipe follows NestJS best practices with:

  • Proper environment variable parsing and filtering
  • Correct handling of optional values
  • Clear error messages including allowed values
  • Uppercase conversion for consistency
  • Clean constructor initialization

The implementation is robust and will provide good user feedback for invalid client aliases.

.env.sample (1)

180-200: Consistent SSO configuration template.

The SSO configuration section maintains consistency with .env.demo and provides clear documentation for multi-client setup.

apps/user/templates/user-email-template.ts (4)

2-11: LGTM! Method signature properly expanded for multi-client SSO support.

The addition of optional redirectTo and clientAlias parameters aligns well with the broader SSO client alias functionality being implemented across the system.


17-23: LGTM! Query parameter handling is secure and well-implemented.

The conditional appending of redirectTo and clientAlias parameters is properly implemented with appropriate checks to prevent adding undefined values to the URL.


80-82: Good improvement in error handling.

Replacing silent failure with a descriptive error message is a best practice that will help with debugging and monitoring.


12-12: Ignore path-determination-env-check concern

There is no prior comparison of clientId to an environment variable in URLUserEmailTemplate.getUserURLTemplate. The truthy check on clientId is the intended behavior (use '/verify-email-success' when a client ID is provided, otherwise leave the base path untouched). You can disregard the suggestion about an env-based comparison here.

Likely an incorrect or invalid review comment.

apps/api-gateway/src/authz/authz.service.ts (3)

8-19: LGTM! Import consolidation improves code organization.

The import statements are better organized with proper grouping and the addition of the user type from Prisma aligns with the service method changes.


32-34: LGTM! New method follows established service patterns.

The getClientAlias() method properly follows the same NATS messaging pattern used by other methods in this service.


41-41: No return type inconsistencies detected
All sendVerificationMail implementations and calls consistently use Promise<user> as their return type across:

  • apps/api-gateway/src/authz/authz.service.ts
  • apps/user/src/user.service.ts
  • apps/user/src/user.controller.ts

The recent change affected only the input DTO (UserEmailVerificationDto), not the return type. No further changes are required.

apps/api-gateway/src/user/utils/index.ts (2)

4-9: LGTM! Default client configuration properly encrypts credentials.

The getDefaultClient function correctly uses environment variables and encrypts sensitive credentials using the encryptClientCredential helper function.


41-43: Good error handling for missing configuration.

The validation and error throwing for incomplete client configuration helps prevent runtime issues and provides clear feedback about missing environment variables.

libs/common/src/interfaces/user.interface.ts (3)

24-29: LGTM! Well-defined interface for SSO client details.

The IClientDetailsSSO interface is properly structured with all necessary fields for client authentication and identification.


63-69: LGTM! Database-aligned interface for client aliases.

The IClientAliases interface properly reflects the database schema structure with appropriate timestamp and identifier fields.


59-61: Good fix for missing semicolon.

The formatting correction in ISignUpUserResponse improves consistency with other interfaces.

apps/api-gateway/src/user/dto/create-user.dto.ts (1)

1-1: LGTM! Better import organization.

Moving ApiProperty and ApiPropertyOptional to the top improves code readability and follows common conventions.

apps/user/src/user.service.ts (1)

134-134: No additional try-catch needed for getCredentialsByAlias
The getCredentialsByAlias implementation already throws an Error when the alias is invalid or missing required fields (clientId, clientSecret, domain). No further error handling is required at the call site in sendVerificationMail unless you need to transform the error or provide a fallback.

Comment on lines +442 to +456
export const encryptClientCredential = async (clientCredential: string): Promise<string> => {
try {
const encryptedToken = CryptoJS.AES.encrypt(
JSON.stringify(clientCredential),
process.env.CRYPTO_PRIVATE_KEY
).toString();

logger.debug('Client credentials encrypted successfully');

return encryptedToken;
} catch (error) {
logger.error('An error occurred during encryptClientCredential:', error);
throw error;
}
};
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add environment variable validation for security.

The encryption function is well-structured but lacks validation for the CRYPTO_PRIVATE_KEY environment variable. This could cause runtime failures if the variable is undefined.

Apply this diff to add proper validation:

 export const encryptClientCredential = async (clientCredential: string): Promise<string> => {
   try {
+    if (!process.env.CRYPTO_PRIVATE_KEY) {
+      throw new Error('CRYPTO_PRIVATE_KEY environment variable is not configured');
+    }
+
     const encryptedToken = CryptoJS.AES.encrypt(
       JSON.stringify(clientCredential),
       process.env.CRYPTO_PRIVATE_KEY
     ).toString();
📝 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
export const encryptClientCredential = async (clientCredential: string): Promise<string> => {
try {
const encryptedToken = CryptoJS.AES.encrypt(
JSON.stringify(clientCredential),
process.env.CRYPTO_PRIVATE_KEY
).toString();
logger.debug('Client credentials encrypted successfully');
return encryptedToken;
} catch (error) {
logger.error('An error occurred during encryptClientCredential:', error);
throw error;
}
};
export const encryptClientCredential = async (clientCredential: string): Promise<string> => {
try {
if (!process.env.CRYPTO_PRIVATE_KEY) {
throw new Error('CRYPTO_PRIVATE_KEY environment variable is not configured');
}
const encryptedToken = CryptoJS.AES.encrypt(
JSON.stringify(clientCredential),
process.env.CRYPTO_PRIVATE_KEY
).toString();
logger.debug('Client credentials encrypted successfully');
return encryptedToken;
} catch (error) {
logger.error('An error occurred during encryptClientCredential:', error);
throw error;
}
};
🤖 Prompt for AI Agents
In libs/common/src/cast.helper.ts around lines 442 to 456, the
encryptClientCredential function uses the CRYPTO_PRIVATE_KEY environment
variable without validating its presence, which can cause runtime errors. Add a
check at the start of the function to verify that process.env.CRYPTO_PRIVATE_KEY
is defined and throw a clear error if it is missing. This ensures the function
fails fast and securely if the key is not set.

Comment thread .env.demo Outdated
Comment thread apps/user/repositories/user.repository.ts
Comment thread .env.sample Outdated
Comment thread apps/api-gateway/src/user/utils/index.ts
Comment on lines +12 to +31
function getClientDetails(alias: string): IClientDetailsSSO {
const clientIdKey = `${alias}_KEYCLOAK_MANAGEMENT_CLIENT_ID`;
const clientSecretKey = `${alias}_KEYCLOAK_MANAGEMENT_CLIENT_SECRET`;
const domainKey = `${alias}_DOMAIN`;
const aliasNameKey = `${alias}_ALIAS`;

const clientId = process.env[clientIdKey];
const clientSecret = process.env[clientSecretKey];
const domain = process.env[domainKey];
const aliasName = process.env[aliasNameKey] || alias;

const clientDetails: IClientDetailsSSO = {
clientId,
clientSecret,
domain,
alias: aliasName
};

return clientDetails;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Inconsistent credential encryption in client details.

The getClientDetails function returns unencrypted clientId and clientSecret from environment variables, while getDefaultClient encrypts these same credentials. This creates an inconsistency in how credentials are handled.

-function getClientDetails(alias: string): IClientDetailsSSO {
+async function getClientDetails(alias: string): Promise<IClientDetailsSSO> {
   const clientIdKey = `${alias}_KEYCLOAK_MANAGEMENT_CLIENT_ID`;
   const clientSecretKey = `${alias}_KEYCLOAK_MANAGEMENT_CLIENT_SECRET`;
   const domainKey = `${alias}_DOMAIN`;
   const aliasNameKey = `${alias}_ALIAS`;

   const clientId = process.env[clientIdKey];
   const clientSecret = process.env[clientSecretKey];
   const domain = process.env[domainKey];
   const aliasName = process.env[aliasNameKey] || alias;

   const clientDetails: IClientDetailsSSO = {
-    clientId,
-    clientSecret,
+    clientId: await encryptClientCredential(clientId),
+    clientSecret: await encryptClientCredential(clientSecret),
     domain,
     alias: aliasName
   };

   return clientDetails;
 }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/api-gateway/src/user/utils/index.ts around lines 12 to 31, the
getClientDetails function returns clientId and clientSecret directly from
environment variables without encryption, causing inconsistency with
getDefaultClient which encrypts these credentials. To fix this, modify
getClientDetails to encrypt clientId and clientSecret before returning them,
using the same encryption method as getDefaultClient to ensure consistent
credential handling.

Comment thread libs/common/src/interfaces/user.interface.ts
Comment thread apps/api-gateway/src/user/dto/create-user.dto.ts
Signed-off-by: bhavanakarwade <bhavana.karwade@ayanworks.com>
Signed-off-by: bhavanakarwade <bhavana.karwade@ayanworks.com>
@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud Bot commented Jul 1, 2025

@bhavanakarwade bhavanakarwade merged commit fca8aba into develop Jul 1, 2025
8 checks passed
ankita-p17 pushed a commit that referenced this pull request Sep 30, 2025
* feat: single sign on

Signed-off-by: bhavanakarwade <bhavana.karwade@ayanworks.com>

* fix: rabbit suggestions

Signed-off-by: bhavanakarwade <bhavana.karwade@ayanworks.com>

* update: send verification mail template

Signed-off-by: bhavanakarwade <bhavana.karwade@ayanworks.com>

---------

Signed-off-by: bhavanakarwade <bhavana.karwade@ayanworks.com>
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