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

feat: get secret by ID #3181

Merged
merged 3 commits into from
Mar 7, 2025
Merged

feat: get secret by ID #3181

merged 3 commits into from
Mar 7, 2025

Conversation

DanielHougaard
Copy link
Contributor

@DanielHougaard DanielHougaard commented Mar 5, 2025

Description 📣

This PR allows for fetching secrets by ID. This endpoint is intended for internal usage, specifically for terraform import support for the infisical_secret resource.

This PR serves as prerequisite for Infisical/terraform-provider-infisical#102

Type ✨

  • Bug fix
  • New feature
  • Improvement
  • Breaking change
  • Documentation

Summary by CodeRabbit

  • New Features
    • Launched a secure method for retrieving secrets by their identifier, now returning enriched metadata with robust access controls.
    • Enhanced the secret management interface with a new copy-to-clipboard button for secret IDs, complete with tooltip feedback for a smoother user experience.

@DanielHougaard DanielHougaard self-assigned this Mar 5, 2025
Copy link

coderabbitai bot commented Mar 5, 2025

Walkthrough

A new GET endpoint has been added to the secret router for retrieving a secret by its ID, which includes authentication verification, rate limiting, and schema validation for both request parameters and response structure. The backend services have been updated to support this new endpoint, with modifications to the data access layer (DAL) that introduce new join operations to retrieve additional contextual data related to folders and environments. A new service function has been implemented to retrieve a secret by its ID, incorporating permission checks and decryption of sensitive information before returning a structured result. Relevant type definitions have been introduced and updated to facilitate the new functionality in secret retrieval. Additionally, the frontend has been modified to include a new icon button for copying the secret ID and to reorganize the layout for secret deletion controls.

Possibly related PRs

  • Batch upsert operation #3078: The changes in this PR enhance the secret router with a new route for retrieving a secret by ID, which is related to batch update functionality in the other PR.
  • feat(api/secrets): view secret value permission #3128: This PR introduces enhancements in permission handling for secret value access, which directly relates to the new route for retrieving secrets by ID and its structured response with metadata.

Suggested reviewers

  • scott-ray-wilson
  • maidul98

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "@typescript-eslint/eslint-plugin".

(The package "@typescript-eslint/eslint-plugin" was not found when loaded as a Node module from the directory "/backend".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install @typescript-eslint/eslint-plugin@latest --save-dev

The plugin "@typescript-eslint/eslint-plugin" was referenced from the config file in "backend/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

backend/src/server/routes/v3/secret-router.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "@typescript-eslint/eslint-plugin".

(The package "@typescript-eslint/eslint-plugin" was not found when loaded as a Node module from the directory "/backend".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install @typescript-eslint/eslint-plugin@latest --save-dev

The plugin "@typescript-eslint/eslint-plugin" was referenced from the config file in "backend/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "@typescript-eslint/eslint-plugin".

(The package "@typescript-eslint/eslint-plugin" was not found when loaded as a Node module from the directory "/backend".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install @typescript-eslint/eslint-plugin@latest --save-dev

The plugin "@typescript-eslint/eslint-plugin" was referenced from the config file in "backend/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

  • 2 others

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 77d9128 and 07b93c5.

📒 Files selected for processing (6)
  • backend/src/server/routes/v3/secret-router.ts (1 hunks)
  • backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts (2 hunks)
  • backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts (4 hunks)
  • backend/src/services/secret/secret-service.ts (4 hunks)
  • backend/src/services/secret/secret-types.ts (2 hunks)
  • frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
  • backend/src/services/secret/secret-types.ts
  • backend/src/services/secret/secret-service.ts
🧰 Additional context used
🧠 Learnings (1)
backend/src/server/routes/v3/secret-router.ts (1)
Learnt from: DanielHougaard
PR: Infisical/infisical#3153
File: backend/src/server/routes/v1/secret-requests-router.ts:14-55
Timestamp: 2025-03-03T17:46:52.142Z
Learning: The GET /:id endpoint in backend/src/server/routes/v1/secret-requests-router.ts is intentionally public (doesn't use verifyAuth) to allow accessing secret requests without authentication.
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Check Frontend Type and Lint check
  • GitHub Check: Check TS and Lint
  • GitHub Check: Run integration test
  • GitHub Check: Check API Changes
🔇 Additional comments (6)
backend/src/server/routes/v3/secret-router.ts (1)

383-423: Well-implemented endpoint for retrieving secrets by ID.

The new GET endpoint for retrieving secrets by ID is well-structured with proper authentication, rate limiting, and schema validation. This implementation aligns with the PR's objective of supporting Terraform import for the infisical_secret resource.

Some observations:

  • Authentication is correctly enforced through verifyAuth middleware
  • The route uses appropriate rate limiting
  • Request parameters and response schema are properly defined
  • The handler passes necessary parameters to the service layer
frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx (1)

994-1037: Good addition of secret ID copy functionality with improved UI organization.

The implementation of the secret ID copy feature is clean and follows existing patterns in the codebase. The UI changes properly maintain permission checks while reorganizing the controls in a more logical grouping.

Key improvements:

  • The copy operation uses proper async/await pattern
  • User feedback is provided through tooltips and notifications
  • The existing permission checks for deletion are preserved
  • Button placement and styling is consistent with the application design
backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts (4)

31-31: Import looks good.

The new import for TGetASecretByIdDTO properly supports the added functionality for retrieving secrets by ID.


75-84: Appropriate folderDAL interface update.

The folderDAL type definition has been correctly extended to include the new findSecretPathByFolderIds method, which is necessary for the new functionality to retrieve folder paths based on folder IDs.


965-1030: Well-implemented getSecretById function with proper permission checks.

The new function follows the same patterns as existing methods in the codebase and correctly implements:

  • Proper error handling (NotFoundError for missing secrets/folders)
  • Permission validation through CASL
  • Personal secret ownership verification
  • Value and comment decryption
  • Secret reshaping for consistent API responses

This implementation aligns with the PR objective of supporting Terraform import for the infisical_secret resource.


2314-2315: Properly exported new functionality.

Both getSecretsByFolderMappings and getSecretById have been added to the service's return object, making them available to consumers of this service.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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.

Copy link

coderabbitai bot commented Mar 5, 2025

Caution

No docstrings were generated.

Copy link

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

🧹 Nitpick comments (2)
backend/src/server/routes/v3/secret-router.ts (1)

383-423: Consider adding audit logging and telemetry tracking for consistency.

The new endpoint for retrieving secrets by ID is well implemented with proper schema validation and authentication. However, unlike similar GET endpoints in this file (such as /raw/:secretName), it's missing audit logging and telemetry tracking.

Consider adding audit logging and telemetry tracking for security and consistency:

  server.route({
    method: "GET",
    url: "/raw/id/:secretId",
    config: {
      rateLimit: secretsLimit
    },
    schema: {
      params: z.object({
        secretId: z.string()
      }),
      response: {
          secret: secretRawSchema.extend({
            secretPath: z.string(),
            tags: SecretTagsSchema.pick({
              id: true,
              slug: true,
              color: true
            })
              .extend({ name: z.string() })
              .array()
              .optional(),
            secretMetadata: ResourceMetadataSchema.optional()
          })
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
    handler: async (req) => {
      const { secretId } = req.params;
      const secret = await server.services.secret.getSecretByIdRaw({
        actorId: req.permission.id,
        actor: req.permission.type,
        actorAuthMethod: req.permission.authMethod,
        actorOrgId: req.permission.orgId,
        secretId
      });

+     await server.services.auditLog.createAuditLog({
+       projectId: secret.workspace,
+       ...req.auditLogInfo,
+       event: {
+         type: EventType.GET_SECRET,
+         metadata: {
+           environment: secret.environment,
+           secretPath: secret.secretPath,
+           secretId: secret.id,
+           secretKey: secret.secretKey,
+           secretVersion: secret.version
+         }
+       }
+     });
+
+     if (getUserAgentType(req.headers["user-agent"]) !== UserAgentType.K8_OPERATOR) {
+       await server.services.telemetry.sendPostHogEvents({
+         event: PostHogEventTypes.SecretPulled,
+         distinctId: getTelemetryDistinctId(req),
+         properties: {
+           numberOfSecrets: 1,
+           workspaceId: secret.workspace,
+           environment: secret.environment,
+           secretPath: secret.secretPath,
+           channel: getUserAgentType(req.headers["user-agent"]),
+           ...req.auditLogInfo
+         }
+       });
+     }

      return { secret };
    }
  });
frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx (1)

909-951: Great addition of the secret ID copy functionality.

The implementation of the copy button with proper user feedback through tooltips and notifications is well done and enhances usability.

Consider extracting the clipboard functionality into a reusable utility function, as there are multiple places in this file where copy-to-clipboard functionality is implemented (here and in the version history section around line 654).

// Example utility function that could be defined in a separate file or at component level
const copyToClipboard = async (text: string, successMessage: string) => {
  await navigator.clipboard.writeText(text);
  createNotification({
    title: "Copied",
    text: successMessage,
    type: "success"
  });
};

// Usage in component
onClick={() => copyToClipboard(secret.id, "The secret ID has been copied to your clipboard.")}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c00ea0f and f640a48.

📒 Files selected for processing (6)
  • backend/src/server/routes/v3/secret-router.ts (1 hunks)
  • backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts (2 hunks)
  • backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts (4 hunks)
  • backend/src/services/secret/secret-service.ts (4 hunks)
  • backend/src/services/secret/secret-types.ts (2 hunks)
  • frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • backend/src/services/secret/secret-types.ts
  • backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
  • backend/src/services/secret/secret-service.ts
🧰 Additional context used
🧠 Learnings (1)
backend/src/server/routes/v3/secret-router.ts (1)
Learnt from: DanielHougaard
PR: Infisical/infisical#3153
File: backend/src/server/routes/v1/secret-requests-router.ts:14-55
Timestamp: 2025-03-03T17:46:52.142Z
Learning: The GET /:id endpoint in backend/src/server/routes/v1/secret-requests-router.ts is intentionally public (doesn't use verifyAuth) to allow accessing secret requests without authentication.
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Run integration test
  • GitHub Check: Check API Changes
  • GitHub Check: Check TS and Lint
  • GitHub Check: Check Frontend Type and Lint check
🔇 Additional comments (6)
frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx (2)

8-8: LGTM! Good addition of the copy icon.


196-205: LGTM! Improved function readability.

The refactoring of handleReminderSubmit enhances code readability while maintaining the same functionality.

backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts (4)

31-31: New import to support the getSecretById function.

The import for TGetASecretByIdDTO is needed for the new feature that fetches secrets by their ID.


77-83: Updated the folderDAL factory type to include the findSecretPathByFolderIds method.

The TSecretV2BridgeServiceFactoryDep type has been properly updated to include the new findSecretPathByFolderIds method needed for the getSecretById functionality.


957-1022: Implementation of getSecretById with proper security checks.

The getSecretById function follows the secure pattern established in the codebase:

  1. Checks for secret existence
  2. Retrieves the folder path
  3. Verifies user permissions
  4. Checks if the user can access personal secrets
  5. Decrypts sensitive data
  6. Returns the properly reshaped secret

The implementation includes all necessary security checks and handles errors appropriately.


2281-2282: Exported the new getSecretById method as part of the service interface.

The new method is correctly exposed in the factory return statement.

@DanielHougaard DanielHougaard merged commit de480b5 into main Mar 7, 2025
8 checks passed
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.

2 participants