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

fix: secret leak when recovering #965

Merged
merged 3 commits into from
Jan 20, 2025
Merged

fix: secret leak when recovering #965

merged 3 commits into from
Jan 20, 2025

Conversation

michael-0acf4
Copy link
Contributor

@michael-0acf4 michael-0acf4 commented Jan 17, 2025

Migration notes

None

  • The change comes with new or modified tests
  • Hard-to-understand functions have explanatory comments
  • End-user documentation is updated to reflect the change

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a deep cloning utility function to prevent unintended data mutations
    • Introduced a new workflow management capability with a sayHello function
    • Enhanced replay request filtering in agent runtime
  • Improvements

    • Refined runtime configuration handling
    • Improved code modularity and error handling in agent runtime
  • Testing

    • Updated sync test configuration with new Redis backend
    • Added new workflow test script

Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

📝 Walkthrough

Walkthrough

This pull request introduces several modifications across different files in the typegate and test directories. The changes include adding a new deepClone utility function, enhancing runtime configuration handling, introducing a new workflow method, and updating test configurations. The modifications focus on improving code reliability, data integrity, and workflow management by implementing stricter type handling, separating filtering logic, and adding new functionality for workflow interactions.

Changes

File Change Summary
src/typegate/src/runtimes/substantial.ts Updated agentConfig initialization with non-null assertion operator for pollIntervalSec, leaseLifespanSec, and maxAcquirePerTick
src/typegate/src/runtimes/substantial/agent.ts Added private method #selectReplayRequestsFor for filtering replay requests and modified #nextIteration method
src/typegate/src/typegraph/mod.ts Imported deepClone and modified runtime initialization to use deep cloning of data
src/typegate/src/utils.ts Added new deepClone utility function for creating deep copies of objects
tests/sync/scripts/workflow.ts Added new Context interface and sayHello function
tests/sync/sync.py Added new helloWorkflow method and Redis backend configuration
tests/sync/sync_force_remove_test.ts Added SUB_REDIS secret and updated initial objects count expectation

Sequence Diagram

sequenceDiagram
    participant Runtime as SubstantialRuntime
    participant Agent as Agent
    participant Workflow as Workflow

    Runtime->>Agent: Initialize with config
    Agent->>Agent: #selectReplayRequestsFor
    Agent-->>Runtime: Filtered replay requests
    Workflow->>Runtime: Start workflow
    Runtime->>Workflow: Execute sayHello
Loading

Possibly related PRs

Suggested reviewers

  • Yohe-Am
  • luckasRanarison

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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. (Beta)
  • @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
Contributor

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

🔭 Outside diff range comments (1)
tests/sync/sync.py (1)

Line range hint 19-26: Security Risk: Public endpoint exposing secrets

The hello endpoint is configured with public policy while using secrets ("ULTRA_SECRET"). This combination could potentially lead to secret leakage.

Consider:

  1. Implementing appropriate access controls instead of using public policy
  2. Reviewing if the secret is actually needed for this endpoint
  3. If the secret is required, implement proper secret rotation mechanisms
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 30d8b1e and 14316af.

⛔ Files ignored due to path filters (1)
  • .ghjk/deno.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • src/typegate/src/runtimes/substantial.ts (1 hunks)
  • src/typegate/src/runtimes/substantial/agent.ts (2 hunks)
  • src/typegate/src/typegraph/mod.ts (2 hunks)
  • src/typegate/src/utils.ts (1 hunks)
  • tests/sync/scripts/workflow.ts (1 hunks)
  • tests/sync/sync.py (2 hunks)
  • tests/sync/sync_force_remove_test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: bulid-docker (linux/arm64, custom-arm)
  • GitHub Check: bulid-docker (linux/amd64, custom-ubuntu-large)
  • GitHub Check: test-full
  • GitHub Check: lint-compat (macos-14, aarch64-apple-darwin, false)
  • GitHub Check: lint-compat (macos-13, x86_64-apple-darwin, false)
🔇 Additional comments (5)
tests/sync/sync.py (1)

12-16: Verify Redis connection security

The new Redis backend is using "SUB_REDIS" secret. Ensure:

  1. The Redis connection uses TLS
  2. The connection string is properly sanitized
tests/sync/scripts/workflow.ts (1)

10-12: Security consideration: Input sanitization

The sayHello function directly interpolates user input into the output string. While this may be safe in the current context, ensure that:

  1. The output is properly escaped if used in HTML context
  2. Input validation is added if there are length or character restrictions
src/typegate/src/runtimes/substantial/agent.ts (2)

143-143: LGTM! Good refactoring.

The extraction of filtering logic into a dedicated method improves code readability and maintainability.


167-184: ⚠️ Potential issue

Enhance error handling for bad runIds.

The current implementation logs bad runIds but continues execution without proper error handling. This could potentially lead to security issues if malformed runIds are not properly sanitized.

Consider these improvements:

 #selectReplayRequestsFor(workflowName: string, runsInScope: Array<NextRun>) {
   const runsToDo = [];
   for (const run of runsInScope) {
     try {
       if (getTaskNameFromId(run.run_id) == workflowName) {
         runsToDo.push(run);
       }
     } catch(err) {
-      this.logger.warn(`Bad runId ${run.run_id}`);
-      this.logger.error(err);
-
-      // TODO:
-      // Force remove?
+      this.logger.error(`Invalid runId format detected: ${run.run_id}`, err);
+      // Remove the invalid run from the backend to prevent potential security issues
+      await Meta.substantial.storeCloseSchedule({
+        backend: this.backend,
+        queue: this.queue,
+        run_id: run.run_id,
+        schedule: run.schedule_date,
+      });
     }
   }

   return runsToDo;
 }

Let's verify the format of runIds in the codebase:

src/typegate/src/typegraph/mod.ts (1)

8-8: LGTM! Good security improvement.

Using deepClone on runtime data prevents unintended mutations of the original data structure, which could lead to secret leaks. This change aligns well with the PR's objective of fixing secret leaks during recovery.

Let's verify the usage of deepClone in the codebase:

Also applies to: 232-232

✅ Verification successful

Verified: deepClone is consistently used for sensitive data protection

The usage of deepClone is properly implemented across the codebase for protecting sensitive data, including runtime data, operation results, and event arguments. This defensive programming approach effectively prevents unintended mutations of the original data structures.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of deepClone for sensitive data.

# Test: Search for other instances where deepClone should be used
ast-grep --pattern '$obj = $data'

# Test: Search for potential data mutation patterns
ast-grep --pattern '$obj.$prop = $data'

Length of output: 77


Script:

#!/bin/bash
# Find all imports of deepClone
echo "=== deepClone imports ==="
rg "import.*deepClone" -l

# Find actual usage of deepClone
echo -e "\n=== deepClone usage ==="
rg "deepClone\(" -A 2

# Find potential direct assignments without cloning
echo -e "\n=== Direct assignments ==="
rg "const\s+\w+\s*=\s*(?!deepClone).*data" --type ts

Length of output: 1294


Script:

#!/bin/bash
# Find potential sensitive data assignments
echo "=== Sensitive data assignments ==="
rg "=.*data|=.*args|=.*kwargs|=.*runtime|=.*result" --type ts -A 1

# Check the utils implementation
echo -e "\n=== deepClone implementation ==="
rg -A 5 "export function deepClone"

Length of output: 66099

tests/sync/sync_force_remove_test.ts Show resolved Hide resolved
src/typegate/src/utils.ts Show resolved Hide resolved
src/typegate/src/runtimes/substantial.ts Show resolved Hide resolved
Signed-off-by: michael-0acf4 <[email protected]>
@michael-0acf4 michael-0acf4 merged commit 68cfb17 into main Jan 20, 2025
10 of 11 checks passed
@michael-0acf4 michael-0acf4 deleted the secret-fix branch January 20, 2025 07:40
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