Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test(api): add e2e tests for secret #148

Merged
merged 2 commits into from
Feb 19, 2024
Merged

test(api): add e2e tests for secret #148

merged 2 commits into from
Feb 19, 2024

Conversation

rajdip-b
Copy link
Member

@rajdip-b rajdip-b commented Feb 19, 2024

Type

enhancement, bug_fix


Description

  • Enhanced secret management with unique constraints and improved error handling.
  • Simplified error messages across various modules for consistency.
  • Removed admin restrictions from secret controller and adjusted pagination defaults.
  • Added comprehensive E2E tests for secret management.
  • Optimized queries and cleaned up unused imports and methods.
  • Added unique constraints to Secret and SecretVersion tables in Prisma schema and migration.

Changes walkthrough

Relevant files
Enhancement
8 files
get-collective-project-authorities.ts
Optimize Role Query and Clean Up in getCollectiveProjectAuthorities

apps/api/src/common/get-collective-project-authorities.ts

  • Changed include to select for role selection to optimize query.
  • Removed commented out console log.
  • +3/-1     
    get-environment-with-authority.ts
    Improve Error Handling in getEnvironmentWithAuthority       

    apps/api/src/common/get-environment-with-authority.ts

  • Added Project to import for type completeness.
  • Implemented try-catch around environment fetching to handle potential
    errors silently.
  • +21/-9   
    get-project-with-authority.ts
    Simplify Unauthorized Error Message in getProjectWithAuthority

    apps/api/src/common/get-project-with-authority.ts

    • Simplified error message by removing specific authority mention.
    +1/-1     
    get-secret-with-authority.ts
    Enhance Secret Fetching and Error Handling in getSecretWithAuthority

    apps/api/src/common/get-secret-with-authority.ts

  • Replaced ConflictException with UnauthorizedException for consistency.
  • Added environment selection in secret fetching.
  • Implemented try-catch around secret fetching to handle potential
    errors silently.
  • Removed workspace information from the secret object for privacy.
  • +20/-19 
    secret.controller.ts
    Remove Admin Restrictions and Adjust Pagination in Secret Controller

    apps/api/src/secret/controller/secret.controller.ts

  • Removed AdminGuard and related methods for fetching all secrets and
    all versions of a secret.
  • Adjusted default page number for pagination from 1 to 0 in
    getAllSecretsOfProject.
  • +19/-30 
    secret.service.ts
    Enhance Secret Service with Unique Constraints and Decryption
    Improvements

    apps/api/src/secret/service/secret.service.ts

  • Added unique constraint handling in secret and secret version updates.
  • Improved error handling and validation in secret environment update
    and rollback.
  • Enhanced secret decryption process to support multiple versions.
  • Removed unused getAllVersionsOfSecret method.
  • +83/-78 
    workspace-role.controller.ts
    Adjust Pagination Default in WorkspaceRole Controller       

    apps/api/src/workspace-role/controller/workspace-role.controller.ts

  • Adjusted default page number for pagination from 1 to 0 in workspace
    role fetching methods.
  • +2/-2     
    workspace-role.service.ts
    Improve Workspace Role Service with Project Set and Pagination Fix

    apps/api/src/workspace-role/service/workspace-role.service.ts

  • Changed project connection method from connect to set for workspace
    role updates.
  • Adjusted pagination offset calculation to start from page 0.
  • +5/-4     
    Tests
    3 files
    environment.e2e.spec.ts
    Cleanup and Simplify Error Messages in Environment E2E Tests

    apps/api/src/environment/environment.e2e.spec.ts

  • Removed unused imports and modules for cleanup.
  • Simplified unauthorized error messages in tests.
  • +3/-12   
    project.e2e.spec.ts
    Simplify Error Messages in Project E2E Tests                         

    apps/api/src/project/project.e2e.spec.ts

    • Simplified unauthorized error messages in tests.
    +3/-3     
    secret.e2e.spec.ts
    Add Comprehensive E2E Tests for Secret Management               

    apps/api/src/secret/secret.e2e.spec.ts

  • Added extensive E2E tests for secret management including creation,
    update, rollback, and deletion.
  • +974/-0 
    Configuration changes
    2 files
    migration.sql
    Add Unique Constraints to Secret and SecretVersion Tables

    apps/api/src/prisma/migrations/20240218085410_add_unique_constraint_in_secret/migration.sql

    • Added unique constraints to Secret and SecretVersion tables.
    +12/-0   
    schema.prisma
    Define Unique Constraints in Prisma Schema for Secrets     

    apps/api/src/prisma/schema.prisma

  • Added @@unique constraints to Secret and SecretVersion models.
  • +4/-0     

    ✨ Usage guide:

    Overview:
    The describe tool scans the PR code changes, and generates a description for the PR - title, type, summary, walkthrough and labels. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.

    When commenting, to edit configurations related to the describe tool (pr_description section), use the following template:

    /describe --pr_description.some_config1=... --pr_description.some_config2=...
    

    With a configuration file, use the following template:

    [pr_description]
    some_config1=...
    some_config2=...
    
    Enabling\disabling automation
    • When you first install the app, the default mode for the describe tool is:
    pr_commands = ["/describe --pr_description.add_original_user_description=true" 
                             "--pr_description.keep_original_user_title=true", ...]
    

    meaning the describe tool will run automatically on every PR, will keep the original title, and will add the original user description above the generated description.

    • Markers are an alternative way to control the generated description, to give maximal control to the user. If you set:
    pr_commands = ["/describe --pr_description.use_description_markers=true", ...]
    

    the tool will replace every marker of the form pr_agent:marker_name in the PR description with the relevant content, where marker_name is one of the following:

    • type: the PR type.
    • summary: the PR summary.
    • walkthrough: the PR walkthrough.

    Note that when markers are enabled, if the original PR description does not contain any markers, the tool will not alter the description at all.

    Custom labels

    The default labels of the describe tool are quite generic: [Bug fix, Tests, Enhancement, Documentation, Other].

    If you specify custom labels in the repo's labels page or via configuration file, you can get tailored labels for your use cases.
    Examples for custom labels:

    • Main topic:performance - pr_agent:The main topic of this PR is performance
    • New endpoint - pr_agent:A new endpoint was added in this PR
    • SQL query - pr_agent:A new SQL query was added in this PR
    • Dockerfile changes - pr_agent:The PR contains changes in the Dockerfile
    • ...

    The list above is eclectic, and aims to give an idea of different possibilities. Define custom labels that are relevant for your repo and use cases.
    Note that Labels are not mutually exclusive, so you can add multiple label categories.
    Make sure to provide proper title, and a detailed and well-phrased description for each label, so the tool will know when to suggest it.

    Inline File Walkthrough 💎

    For enhanced user experience, the describe tool can add file summaries directly to the "Files changed" tab in the PR page.
    This will enable you to quickly understand the changes in each file, while reviewing the code changes (diffs).

    To enable inline file summary, set pr_description.inline_file_summary in the configuration file, possible values are:

    • 'table': File changes walkthrough table will be displayed on the top of the "Files changed" tab, in addition to the "Conversation" tab.
    • true: A collapsable file comment with changes title and a changes summary for each file in the PR.
    • false (default): File changes walkthrough will be added only to the "Conversation" tab.
    Utilizing extra instructions

    The describe tool can be configured with extra instructions, to guide the model to a feedback tailored to the needs of your project.

    Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Notice that the general structure of the description is fixed, and cannot be changed. Extra instructions can change the content or style of each sub-section of the PR description.

    Examples for extra instructions:

    [pr_description] 
    extra_instructions="""
    - The PR title should be in the format: '<PR type>: <title>'
    - The title should be short and concise (up to 10 words)
    - ...
    """
    

    Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

    More PR-Agent commands

    To invoke the PR-Agent, add a comment using one of the following commands:

    • /review: Request a review of your Pull Request.
    • /describe: Update the PR title and description based on the contents of the PR.
    • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
    • /ask <QUESTION>: Ask a question about the PR.
    • /update_changelog: Update the changelog based on the PR's contents.
    • /add_docs 💎: Generate docstring for new components introduced in the PR.
    • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
    • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

    See the tools guide for more details.
    To list the possible configuration parameters, add a /config comment.

    See the describe usage page for a comprehensive guide on using this tool.

    @rajdip-b rajdip-b changed the title test(api): add e2e tests for secret test(api): Add e2e tests for secret Feb 19, 2024
    Copy link

    nx-cloud bot commented Feb 19, 2024

    ☁️ Nx Cloud Report

    CI is running/has finished running commands for commit bcaaee4. As they complete they will appear below. Click to see the status, the terminal output, and the build insights.

    📂 See all runs for this CI Pipeline Execution


    ✅ Successfully ran 3 targets

    Sent with 💌 from NxCloud.

    @codiumai-pr-agent-free codiumai-pr-agent-free bot changed the title test(api): Add e2e tests for secret test(api): add e2e tests for secret Feb 19, 2024
    Copy link
    Contributor

    PR Description updated to latest commit (5dc7c8f)

    Copy link
    Contributor

    PR Review

         PR feedback                    
    ⏱️ Estimated effort to review [1-5]

    4, because the PR includes a wide range of changes across multiple files, including backend logic adjustments, error handling improvements, database schema updates, and comprehensive E2E tests. The complexity and breadth of these changes necessitate a thorough review to ensure functionality, security, and performance are not adversely affected.

    🧪 Relevant tests

    Yes

    🔍 Possible issues
    • The addition of unique constraints to the Secret and SecretVersion tables could potentially cause issues with existing data if there are any duplicates. It's important to ensure that the current data conforms to these new constraints before applying the migration.
    • The change from include to select in Prisma queries for optimization purposes is generally positive but requires careful review to ensure that no required data is omitted in the responses, which could lead to unexpected behavior.
    • The removal of admin restrictions from certain endpoints and the adjustment of pagination defaults could have implications on the application's security and performance. It's crucial to validate these changes do not inadvertently expose sensitive information or lead to inefficient data fetching.
    • The error handling logic in getEnvironmentWithAuthority and getSecretWithAuthority now silently catches exceptions without logging or rethrowing them, which could make debugging issues more difficult.
    • The removal of workspace information from the secret object in getSecretWithAuthority might impact functionalities that rely on this data.
    🔒 Security concerns
    • The PR does not appear to introduce direct security vulnerabilities in the code changes provided. However, the removal of admin restrictions and changes in error handling should be scrutinized to ensure they do not inadvertently weaken the application's security posture.
    • Given the nature of the changes, particularly around secret management, it's crucial to ensure that all modifications adhere to best practices for handling sensitive information, such as encryption in transit and at rest, access controls, and audit logging.

    ✨ Usage guide:

    Overview:
    The review tool scans the PR code changes, and generates a PR review. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on any PR.
    When commenting, to edit configurations related to the review tool (pr_reviewer section), use the following template:

    /review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=...
    

    With a configuration file, use the following template:

    [pr_reviewer]
    some_config1=...
    some_config2=...
    
    Utilizing extra instructions

    The review tool can be configured with extra instructions, which can be used to guide the model to a feedback tailored to the needs of your project.

    Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify the relevant sub-tool, and the relevant aspects of the PR that you want to emphasize.

    Examples for extra instructions:

    [pr_reviewer] # /review #
    extra_instructions="""
    In the 'possible issues' section, emphasize the following:
    - Does the code logic cover relevant edge cases?
    - Is the code logic clear and easy to understand?
    - Is the code logic efficient?
    ...
    """
    

    Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

    How to enable\disable automation
    • When you first install PR-Agent app, the default mode for the review tool is:
    pr_commands = ["/review", ...]
    

    meaning the review tool will run automatically on every PR, with the default configuration.
    Edit this field to enable/disable the tool, or to change the used configurations

    Auto-labels

    The review tool can auto-generate two specific types of labels for a PR:

    • a possible security issue label, that detects possible security issues (enable_review_labels_security flag)
    • a Review effort [1-5]: x label, where x is the estimated effort to review the PR (enable_review_labels_effort flag)
    Extra sub-tools

    The review tool provides a collection of possible feedbacks about a PR.
    It is recommended to review the possible options, and choose the ones relevant for your use case.
    Some of the feature that are disabled by default are quite useful, and should be considered for enabling. For example:
    require_score_review, require_soc2_ticket, and more.

    Auto-approve PRs

    By invoking:

    /review auto_approve
    

    The tool will automatically approve the PR, and add a comment with the approval.

    To ensure safety, the auto-approval feature is disabled by default. To enable auto-approval, you need to actively set in a pre-defined configuration file the following:

    [pr_reviewer]
    enable_auto_approval = true
    

    (this specific flag cannot be set with a command line argument, only in the configuration file, committed to the repository)

    You can also enable auto-approval only if the PR meets certain requirements, such as that the estimated_review_effort is equal or below a certain threshold, by adjusting the flag:

    [pr_reviewer]
    maximal_review_effort = 5
    
    More PR-Agent commands

    To invoke the PR-Agent, add a comment using one of the following commands:

    • /review: Request a review of your Pull Request.
    • /describe: Update the PR title and description based on the contents of the PR.
    • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
    • /ask <QUESTION>: Ask a question about the PR.
    • /update_changelog: Update the changelog based on the PR's contents.
    • /add_docs 💎: Generate docstring for new components introduced in the PR.
    • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
    • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

    See the tools guide for more details.
    To list the possible configuration parameters, add a /config comment.

    See the review usage page for a comprehensive guide on using this tool.

    Copy link
    Contributor

    codiumai-pr-agent-free bot commented Feb 19, 2024

    PR Code Suggestions

    Suggestions                                                                                                                                                     
    possible issue
    Handle the case where the environment is not found after the try block.      

    Consider handling the case where environment is null or undefined after the try block.
    This can happen if the findUnique query does not find any matching record. You should
    throw a NotFoundException if environment is not found to ensure the function's contract is
    fulfilled by always returning an Environment object or throwing an exception.

    apps/api/src/common/get-environment-with-authority.ts [29-30]

     } catch (e) {
       /* empty */
     }
    +if (!environment) {
    +  throw new NotFoundException(`Environment with id ${environmentId} not found`);
    +}
     
    Handle the case where the secret is not found after the try block.           

    Similar to the previous suggestion, consider handling the case where secret is null or
    undefined after the try block. This ensures that the function either returns a
    SecretWithProjectAndVersion object or throws an exception if the secret is not found.

    apps/api/src/common/get-secret-with-authority.ts [31-32]

     } catch (error) {
       /* empty */
     }
    +if (!secret) {
    +  throw new NotFoundException(`Secret with id ${secretId} not found`);
    +}
     
    Check for the existence of secret before accessing its properties.

    Consider checking for the existence of secret before accessing its properties like
    versions to avoid potential runtime errors. This is particularly important in asynchronous
    functions where the result might not always be guaranteed to be non-null.

    apps/api/src/secret/service/secret.service.ts [303]

    +if (!secret) {
    +  throw new NotFoundException(`Secret with id ${secretId} not found`);
    +}
     const maxVersion = secret.versions[secret.versions.length - 1].version
     
    performance
    Use Promise.all for concurrent decryption of secret versions.   

    To improve the performance and readability of the decryption process for secrets, consider
    using Promise.all to decrypt all versions concurrently instead of sequentially in a loop.
    This can significantly reduce the time taken for this operation when there are multiple
    versions.

    apps/api/src/secret/service/secret.service.ts [372-378]

    -for (let i = 0; i < secret.versions.length; i++) {
    -  const decryptedValue = await decrypt(
    -    project.privateKey,
    -    secret.versions[i].value
    -  )
    -  secret.versions[i].value = decryptedValue
    -}
    +const decryptionPromises = secret.versions.map(version =>
    +  decrypt(project.privateKey, version.value)
    +);
    +const decryptedValues = await Promise.all(decryptionPromises);
    +secret.versions.forEach((version, index) => {
    +  version.value = decryptedValues[index];
    +});
     
    bug
    Adjust the rollback version validation to exclude the current version.       

    When checking if the rollback version is valid, ensure that the comparison is against the
    maximum version number correctly. The current check might allow rolling back to the
    current version, which is likely unintended. Adjust the condition to exclude the current
    (maximum) version from being a valid rollback target.

    apps/api/src/secret/service/secret.service.ts [306]

    -if (rollbackVersion < 1 || rollbackVersion >= maxVersion) {
    +if (rollbackVersion < 1 || rollbackVersion > maxVersion) {
     
    enhancement
    Validate query parameters to ensure they are within acceptable ranges.       

    Consider validating the 'page' and 'limit' query parameters to ensure they are within
    acceptable ranges. This can prevent unexpected behavior or errors when querying the
    database.

    apps/api/src/workspace-role/controller/workspace-role.controller.ts [97-98]

    -@Query('page') page: number = 0,
    -@Query('limit') limit: number = 10,
    +@Query('page', new DefaultValuePipe(0), ParseIntPipe, new Min(0)) page: number,
    +@Query('limit', new DefaultValuePipe(10), ParseIntPipe, new Max(100)) limit: number,
     
    Add error handling for pagination parameters.                                

    Consider adding error handling for the case where 'page' or 'limit' query parameters are
    not numbers, to prevent runtime errors during pagination calculations.

    apps/api/src/workspace-role/service/workspace-role.service.ts [302]

    -skip: page * limit,
    +skip: isNaN(page) || isNaN(limit) ? 0 : page * limit,
     
    Handle existing duplicates before applying unique constraints.               

    Before applying the unique constraints, add a pre-migration script to identify and handle
    any existing duplicate records in the 'Secret' and 'SecretVersion' tables.

    apps/api/src/prisma/migrations/20240218085410_add_unique_constraint_in_secret/migration.sql [9-12]

    +-- Pre-migration script to handle duplicates
    +-- Example: DELETE FROM Secret WHERE id NOT IN (SELECT MIN(id) FROM Secret GROUP BY projectId, environmentId, name);
    +-- Example: DELETE FROM SecretVersion WHERE id NOT IN (SELECT MIN(id) FROM SecretVersion GROUP BY secretId, version);
     CREATE UNIQUE INDEX "Secret_projectId_environmentId_name_key" ON "Secret"("projectId", "environmentId", "name");
     CREATE UNIQUE INDEX "SecretVersion_secretId_version_key" ON "SecretVersion"("secretId", "version");
     
    best practice
    Use 'connectOrCreate' for better data integrity.                             

    Replace the 'set' operation with 'connectOrCreate' to ensure that project IDs are
    validated against existing records, enhancing data integrity.

    apps/api/src/workspace-role/service/workspace-role.service.ts [150]

    -set: dto.projectIds?.map((id) => ({ id }))
    +connectOrCreate: dto.projectIds?.map((id) => ({
    +  where: { id },
    +  create: { id }
    +}))
     
    Update CRUD operations to handle unique constraint violations.               

    After adding unique constraints in the Prisma schema, ensure to update any related CRUD
    operations in the application to handle potential unique constraint violations gracefully.

    apps/api/src/prisma/schema.prisma [295-317]

    -@@unique([secretId, version])
    -@@unique([projectId, environmentId, name])
    +-- Ensure application logic accounts for unique constraint violations, possibly using try-catch blocks or checking for errors after database operations.
     

    ✨ Usage guide:

    Overview:
    The improve tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.
    When commenting, to edit configurations related to the improve tool (pr_code_suggestions section), use the following template:

    /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=...
    

    With a configuration file, use the following template:

    [pr_code_suggestions]
    some_config1=...
    some_config2=...
    
    Enabling\disabling automation

    When you first install the app, the default mode for the improve tool is:

    pr_commands = ["/improve --pr_code_suggestions.summarize=true", ...]
    

    meaning the improve tool will run automatically on every PR, with summarization enabled. Delete this line to disable the tool from running automatically.

    Utilizing extra instructions

    Extra instructions are very important for the improve tool, since they enable to guide the model to suggestions that are more relevant to the specific needs of the project.

    Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify relevant aspects that you want the model to focus on.

    Examples for extra instructions:

    [pr_code_suggestions] # /improve #
    extra_instructions="""
    Emphasize the following aspects:
    - Does the code logic cover relevant edge cases?
    - Is the code logic clear and easy to understand?
    - Is the code logic efficient?
    ...
    """
    

    Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

    A note on code suggestions quality
    • While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically.
    • Suggestions are not meant to be simplistic. Instead, they aim to give deep feedback and raise questions, ideas and thoughts to the user, who can then use his judgment, experience, and understanding of the code base.
    • Recommended to use the 'extra_instructions' field to guide the model to suggestions that are more relevant to the specific needs of the project, or use the custom suggestions 💎 tool
    • With large PRs, best quality will be obtained by using 'improve --extended' mode.
    More PR-Agent commands

    To invoke the PR-Agent, add a comment using one of the following commands:

    • /review: Request a review of your Pull Request.
    • /describe: Update the PR title and description based on the contents of the PR.
    • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
    • /ask <QUESTION>: Ask a question about the PR.
    • /update_changelog: Update the changelog based on the PR's contents.
    • /add_docs 💎: Generate docstring for new components introduced in the PR.
    • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
    • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

    See the tools guide for more details.
    To list the possible configuration parameters, add a /config comment.

    See the improve usage page for a more comprehensive guide on using this tool.

    Copy link

    codecov bot commented Feb 19, 2024

    Codecov Report

    All modified and coverable lines are covered by tests ✅

    Comparison is base (7bb3d21) 62.20% compared to head (bcaaee4) 88.15%.
    Report is 13 commits behind head on develop.

    Additional details and impacted files
    @@             Coverage Diff              @@
    ##           develop     #148       +/-   ##
    ============================================
    + Coverage    62.20%   88.15%   +25.94%     
    ============================================
      Files           76       77        +1     
      Lines         1503     1486       -17     
      Branches       260      248       -12     
    ============================================
    + Hits           935     1310      +375     
    + Misses         568      176      -392     
    Flag Coverage Δ
    api-e2e-tests 88.15% <100.00%> (+25.94%) ⬆️

    Flags with carried forward coverage won't be shown. Click here to find out more.

    ☔ View full report in Codecov by Sentry.
    📢 Have feedback on the report? Share it here.

    Copy link

    Quality Gate Passed Quality Gate passed

    Issues
    0 New issues

    Measures
    0 Security Hotspots
    No data about Coverage
    13.7% Duplication on New Code

    See analysis details on SonarCloud

    @rajdip-b rajdip-b merged commit 3960581 into develop Feb 19, 2024
    7 of 8 checks passed
    @rajdip-b rajdip-b deleted the test/secret branch February 19, 2024 04:57
    @rajdip-b
    Copy link
    Member Author

    🎉 This PR is included in version 1.3.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
    Labels
    type: enhancement New feature or request
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    1 participant