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

add jwt token back to wsl connections #1841

Merged
merged 7 commits into from
Jan 24, 2025
Merged

add jwt token back to wsl connections #1841

merged 7 commits into from
Jan 24, 2025

Conversation

sawka
Copy link
Member

@sawka sawka commented Jan 24, 2025

No description provided.

Copy link
Contributor

coderabbitai bot commented Jan 24, 2025

Walkthrough

The pull request introduces changes across several files: pkg/shellexec/shellexec.go, pkg/util/shellutil/tokenswap.go, pkg/wshrpc/wshserver/wshserver.go, cmd/wsh/cmd/wshcmd-setbg.go, frontend/app/app-bg.tsx, and pkg/remote/connparse/connparse.go. In shellexec.go, the command construction logic is modified to include a JWT token as an environment variable during shell execution, extracted from the cmdOpts.SwapToken.Env map. The tokenswap.go file sees the removal of the JwtToken field from the TokenSwapEntry struct, indicating a change in token management. The wshserver.go file introduces a new method, AuthenticateTokenCommand, which authenticates a token and returns relevant data. Additionally, wshcmd-setbg.go updates the path processing method, app-bg.tsx expands URL safety checks to include Windows-style paths, and connparse.go adds a regex for parsing wsl:// URIs.

✨ 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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4035974 and 0035b6c.

📒 Files selected for processing (2)
  • pkg/shellexec/shellexec.go (1 hunks)
  • pkg/util/shellutil/tokenswap.go (0 hunks)
💤 Files with no reviewable changes (1)
  • pkg/util/shellutil/tokenswap.go
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
  • GitHub Check: Build for TestDriver.ai

Comment on lines +265 to +268
jwtToken := cmdOpts.SwapToken.Env[wavebase.WaveJwtTokenVarName]
if jwtToken != "" {
cmdCombined = fmt.Sprintf(`%s=%s %s`, wavebase.WaveJwtTokenVarName, jwtToken, cmdCombined)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent nil-pointer dereference and sensitive token leakage

  1. Potential nil-pointer dereference
    cmdOpts.SwapToken can be nil, leading to a panic when accessing cmdOpts.SwapToken.Env. Ensure SwapToken and its Env map are non-nil before referencing them.

  2. Avoid leaking JWT tokens in logs
    Immediately after appending the JWT token to cmdCombined, the full command is logged:

    log.Printf("full combined command: %s", cmdCombined)
    

    This exposes the token in logs, creating a significant security risk. Mask or omit the token to protect sensitive credentials.

Below are sample diffs to mitigate both issues:

--- a/pkg/shellexec/shellexec.go
+++ b/pkg/shellexec/shellexec.go
@@ -264,7 +264,11 @@ func StartWslShellProc(ctx context.Context, termSize waveobj.TermSize, cmdStr st
 	}
 
-	jwtToken := cmdOpts.SwapToken.Env[wavebase.WaveJwtTokenVarName]
+	if cmdOpts.SwapToken == nil || cmdOpts.SwapToken.Env == nil {
+		conn.Infof(ctx, "warning: SwapToken or SwapToken.Env is nil; skipping JWT token injection")
+	} else {
+		jwtToken := cmdOpts.SwapToken.Env[wavebase.WaveJwtTokenVarName]
+		if jwtToken != "" {
+			cmdCombined = fmt.Sprintf(`%s=%s %s`, wavebase.WaveJwtTokenVarName, jwtToken, cmdCombined)
+		}
+	}
 
 	log.Printf("full combined command: %s", cmdCombined) // Potential token leak

And to mask the leaked token in logs (outside the annotated lines):

- log.Printf("full combined command: %s", cmdCombined)
+ // Avoid logging sensitive token
+ maskedCommand := strings.ReplaceAll(
+     cmdCombined,
+     fmt.Sprintf("%s=%s", wavebase.WaveJwtTokenVarName, jwtToken),
+     fmt.Sprintf("%s=***REDACTED***", wavebase.WaveJwtTokenVarName),
+ )
+ log.Printf("full combined command: %s", maskedCommand)

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

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

🧹 Nitpick comments (1)
pkg/wshrpc/wshserver/wshserver.go (1)

55-66: Add validation & error handling for token-based authentication.
The function checks if the token entry is nil and returns an error if it is invalid. Consider adding additional safeguards:

  • Verify the authenticity of the token or incorporate an expiration mechanism.
  • Log or track invalid attempts if needed.
  • Remove the TODO comment once multiproxy integration is complete.

Additionally, ensure proper unit tests cover valid tokens, invalid tokens, and concurrency edge cases for shellutil.GetAndRemoveTokenSwapEntry.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0035b6c and d5fa489.

📒 Files selected for processing (1)
  • pkg/wshrpc/wshserver/wshserver.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
  • GitHub Check: Build for TestDriver.ai
🔇 Additional comments (1)
pkg/wshrpc/wshserver/wshserver.go (1)

31-31: Confirm usage of newly introduced import.
The shellutil import is introduced here. Make sure it is only used for retrieving and removing token entries—and confirm no overlapping or redundant imports exist within the file or codebase.

Use this script to locate other possible references to shellutil:

✅ Verification successful

Import usage verified - properly scoped to token operations
The shellutil import in wshserver.go is used exclusively for token management via GetAndRemoveTokenSwapEntry(). No overlapping or redundant imports exist within the file.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searching for 'shellutil' references throughout the codebase
rg -A 5 'shellutil'

Length of output: 27960

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: 1

🧹 Nitpick comments (2)
pkg/remote/connparse/connparse.go (1)

26-26: Consider validating the presence of a host segment in the compiled regex.

The regexp.MustCompile("^wsl://[^/]+") pattern allows for scenarios like wsl:// without any subsequent characters. This returns an empty match on .FindString() if there's no host. Ensure your design either expects this or gracefully handles this edge case.

frontend/app/app-bg.tsx (1)

57-57: Expand or constrain Windows path handling as appropriate.

By allowing Windows-style paths (e.g., C:\), you open the door for local file inclusion as backgrounds. Consider adding checks or warnings to ensure users do not unintentionally expose sensitive files.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d5fa489 and bf7d820.

📒 Files selected for processing (3)
  • cmd/wsh/cmd/wshcmd-setbg.go (1 hunks)
  • frontend/app/app-bg.tsx (1 hunks)
  • pkg/remote/connparse/connparse.go (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • cmd/wsh/cmd/wshcmd-setbg.go
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (go)
  • GitHub Check: Build for TestDriver.ai
🔇 Additional comments (1)
pkg/remote/connparse/connparse.go (1)

125-131: Approved fallback logic for non-WSL URIs.

The current logic correctly splits the string by the first slash to separate host and path for other schemes. No concerns found.

Comment on lines +121 to +123
if strings.HasPrefix(rest, "wsl://") {
host = wslConnRegex.FindString(rest)
remotePath = strings.TrimPrefix(rest, host)
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Empty WSL host validation is required

The review is correct. The regex pattern ^wsl://[^/]+ would match an empty string after "wsl://" prefix, and the codebase expects a valid distro name in multiple places (wslconn, wshserver, blockcontroller). The suggested fix to validate the host is appropriate to prevent potential issues downstream.

🔗 Analysis chain

Handle empty host scenario for WSL URIs.

If the pattern fails to match (e.g., wsl:// with no host), .FindString(rest) will be "", passing an empty host downstream unintentionally. Consider returning an error in that scenario.

Apply the following diff snippet to validate the host:

 host = wslConnRegex.FindString(rest)
+if host == "" {
+  return nil, fmt.Errorf("invalid wsl:// URI: missing host segment")
+}
 remotePath = strings.TrimPrefix(rest, host)
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Find wslConnRegex definition and surrounding context
rg "wslConnRegex" pkg/remote/connparse/connparse.go -B 2 -A 2

# Look for test files and WSL-related tests
fd ".*_test\.go" pkg/remote/connparse/ --exec cat {}

# Search for WSL URI patterns in the codebase
rg "wsl://" -A 2 -B 2

Length of output: 16431

@sawka sawka merged commit bba94a6 into main Jan 24, 2025
8 checks passed
@sawka sawka deleted the sawka/wsl-fix branch January 24, 2025 22:24
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