- Notifications
You must be signed in to change notification settings - Fork35
fix: Inject coder ssh configuration between comments#48
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes from14 commits
Commits
Show all changes
23 commits Select commitHold shift + click to select a range
48d16a6 fix: Removes first matching Host block
BrunoQuaresma3c31777 Abstract SSH update
BrunoQuaresmaace35dd Remove package
BrunoQuaresmaf4eeba8 Remove unused import
BrunoQuaresmacfe3c9c Update src/SSHConfig.ts
BrunoQuaresmac359a19 Apply review suggestions
BrunoQuaresma5e7ebb8 Merge branch 'bq/fix-42' of github.com:coder/vscode-coder into bq/fix-42
BrunoQuaresma9db792e Remove unused dep
BrunoQuaresma30b7020 Cleanup tests
BrunoQuaresma93c02d8 Cleanup tests
BrunoQuaresma5ce8e68 Add tests
BrunoQuaresma0199cc3 Improve comments
BrunoQuaresma98f26dd Clean up old config
BrunoQuaresma33f0eb6 Remove bad dir
BrunoQuaresma7dcd5da Fix name and remove package-lock.json
BrunoQuaresmae3ac21b Fix command
BrunoQuaresma77ea26f Add test to CI
BrunoQuaresma1949890 Improve scripts
BrunoQuaresma4b75882 Fix lint
BrunoQuaresmabc6d1f8 Update workflow
BrunoQuaresma1c1beb1 Fix names
BrunoQuaresma0e63d49 Delete SSHConfig.test.ts
BrunoQuaresma307ba0e Delete SSHConfig.ts
BrunoQuaresmaFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
22 changes: 2 additions & 20 deletions.vscode/launch.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
17 changes: 4 additions & 13 deletionspackage.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
169 changes: 169 additions & 0 deletionssrc/SSHConfig.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| /* eslint-disable @typescript-eslint/ban-ts-comment */ | ||
| import { it, afterEach, vi, expect } from "vitest" | ||
| import { SSHConfig } from "./SSHConfig" | ||
| const sshFilePath = "~/.config/ssh" | ||
| const mockFileSystem = { | ||
| readFile: vi.fn(), | ||
| ensureDir: vi.fn(), | ||
| writeFile: vi.fn(), | ||
| } | ||
| afterEach(() => { | ||
| vi.clearAllMocks() | ||
| }) | ||
| it("creates a new file and adds the config", async () => { | ||
| mockFileSystem.readFile.mockRejectedValueOnce("No file found") | ||
| const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) | ||
| await sshConfig.load() | ||
| await sshConfig.update({ | ||
| Host: "coder--vscode--*", | ||
| ProxyCommand: "some-command-here", | ||
| ConnectTimeout: "0", | ||
| StrictHostKeyChecking: "no", | ||
| UserKnownHostsFile: "/dev/null", | ||
| LogLevel: "ERROR", | ||
| }) | ||
| const expectedOutput = `# --- START CODER VSCODE --- | ||
| Host coder--vscode--* | ||
| ProxyCommand some-command-here | ||
| ConnectTimeout 0 | ||
| StrictHostKeyChecking no | ||
| UserKnownHostsFile /dev/null | ||
| LogLevel ERROR | ||
| # --- END CODER VSCODE ---` | ||
| expect(mockFileSystem.readFile).toBeCalledWith(sshFilePath, expect.anything()) | ||
| expect(mockFileSystem.writeFile).toBeCalledWith(sshFilePath, expectedOutput, expect.anything()) | ||
| }) | ||
| it("adds a new coder config in an existent SSH configuration", async () => { | ||
| const existentSSHConfig = `Host coder.something | ||
| HostName coder.something | ||
| ConnectTimeout=0 | ||
| StrictHostKeyChecking=no | ||
| UserKnownHostsFile=/dev/null | ||
| LogLevel ERROR | ||
| ProxyCommand command` | ||
| mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) | ||
| const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) | ||
| await sshConfig.load() | ||
| await sshConfig.update({ | ||
| Host: "coder--vscode--*", | ||
| ProxyCommand: "some-command-here", | ||
| ConnectTimeout: "0", | ||
| StrictHostKeyChecking: "no", | ||
| UserKnownHostsFile: "/dev/null", | ||
| LogLevel: "ERROR", | ||
| }) | ||
| const expectedOutput = `${existentSSHConfig} | ||
| # --- START CODER VSCODE --- | ||
| Host coder--vscode--* | ||
| ProxyCommand some-command-here | ||
| ConnectTimeout 0 | ||
| StrictHostKeyChecking no | ||
| UserKnownHostsFile /dev/null | ||
| LogLevel ERROR | ||
| # --- END CODER VSCODE ---` | ||
| expect(mockFileSystem.writeFile).toBeCalledWith(sshFilePath, expectedOutput, { | ||
| encoding: "utf-8", | ||
| mode: 384, | ||
| }) | ||
| }) | ||
| it("updates an existent coder config", async () => { | ||
| const existentSSHConfig = `Host coder.something | ||
| HostName coder.something | ||
| ConnectTimeout=0 | ||
| StrictHostKeyChecking=no | ||
| UserKnownHostsFile=/dev/null | ||
| LogLevel ERROR | ||
| ProxyCommand command | ||
| # --- START CODER VSCODE --- | ||
| Host coder--vscode--* | ||
| ProxyCommand some-command-here | ||
| ConnectTimeout 0 | ||
| StrictHostKeyChecking no | ||
| UserKnownHostsFile /dev/null | ||
| LogLevel ERROR | ||
| # --- END CODER VSCODE ---` | ||
| mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) | ||
| const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) | ||
| await sshConfig.load() | ||
| await sshConfig.update({ | ||
| Host: "coder--updated--vscode--*", | ||
| ProxyCommand: "some-command-here", | ||
| ConnectTimeout: "0", | ||
| StrictHostKeyChecking: "no", | ||
| UserKnownHostsFile: "/dev/null", | ||
| LogLevel: "ERROR", | ||
| }) | ||
| const expectedOutput = `Host coder.something | ||
| HostName coder.something | ||
| ConnectTimeout=0 | ||
| StrictHostKeyChecking=no | ||
| UserKnownHostsFile=/dev/null | ||
| LogLevel ERROR | ||
| ProxyCommand command | ||
| # --- START CODER VSCODE --- | ||
| Host coder--updated--vscode--* | ||
| ProxyCommand some-command-here | ||
| ConnectTimeout 0 | ||
| StrictHostKeyChecking no | ||
| UserKnownHostsFile /dev/null | ||
| LogLevel ERROR | ||
| # --- END CODER VSCODE ---` | ||
| expect(mockFileSystem.writeFile).toBeCalledWith(sshFilePath, expectedOutput, { | ||
| encoding: "utf-8", | ||
| mode: 384, | ||
| }) | ||
| }) | ||
| it("removes old coder SSH config and adds the new one", async () => { | ||
| const existentSSHConfig = `Host coder--vscode--* | ||
| HostName coder.something | ||
| ConnectTimeout=0 | ||
| StrictHostKeyChecking=no | ||
| UserKnownHostsFile=/dev/null | ||
| LogLevel ERROR | ||
| ProxyCommand command` | ||
| mockFileSystem.readFile.mockResolvedValueOnce(existentSSHConfig) | ||
| const sshConfig = new SSHConfig(sshFilePath, mockFileSystem) | ||
| await sshConfig.load() | ||
| await sshConfig.update({ | ||
| Host: "coder--vscode--*", | ||
| ProxyCommand: "some-command-here", | ||
| ConnectTimeout: "0", | ||
| StrictHostKeyChecking: "no", | ||
| UserKnownHostsFile: "/dev/null", | ||
| LogLevel: "ERROR", | ||
| }) | ||
| const expectedOutput = `# --- START CODER VSCODE --- | ||
| Host coder--vscode--* | ||
| ProxyCommand some-command-here | ||
| ConnectTimeout 0 | ||
| StrictHostKeyChecking no | ||
| UserKnownHostsFile /dev/null | ||
| LogLevel ERROR | ||
| # --- END CODER VSCODE ---` | ||
| expect(mockFileSystem.writeFile).toBeCalledWith(sshFilePath, expectedOutput, { | ||
| encoding: "utf-8", | ||
| mode: 384, | ||
| }) | ||
| }) |
142 changes: 142 additions & 0 deletionssrc/SSHConfig.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| import { ensureDir } from "fs-extra" | ||
BrunoQuaresma marked this conversation as resolved. OutdatedShow resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| import { writeFile, readFile } from "fs/promises" | ||
| import path from "path" | ||
| class SSHConfigBadFormat extends Error {} | ||
| interface Block { | ||
| raw: string | ||
| } | ||
| interface SSHValues { | ||
| Host: string | ||
| ProxyCommand: string | ||
| ConnectTimeout: string | ||
| StrictHostKeyChecking: string | ||
| UserKnownHostsFile: string | ||
| LogLevel: string | ||
| } | ||
| // Interface for the file system to make it easier to test | ||
| export interface FileSystem { | ||
| readFile: typeof readFile | ||
| ensureDir: typeof ensureDir | ||
| writeFile: typeof writeFile | ||
| } | ||
| const defaultFileSystem: FileSystem = { | ||
| readFile, | ||
| ensureDir, | ||
| writeFile, | ||
| } | ||
| export class SSHConfig { | ||
| private filePath: string | ||
| private fileSystem: FileSystem | ||
| private raw: string | undefined | ||
| private startBlockComment = "# --- START CODER VSCODE ---" | ||
| private endBlockComment = "# --- END CODER VSCODE ---" | ||
| constructor(filePath: string, fileSystem: FileSystem = defaultFileSystem) { | ||
| this.filePath = filePath | ||
| this.fileSystem = fileSystem | ||
| } | ||
| async load() { | ||
| try { | ||
| this.raw = await this.fileSystem.readFile(this.filePath, "utf-8") | ||
| } catch (ex) { | ||
| // Probably just doesn't exist! | ||
| this.raw = "" | ||
| } | ||
| } | ||
| async update(values: SSHValues) { | ||
| // We should remove this in March 2023 because there is not going to have | ||
| // old configs | ||
| this.cleanUpOldConfig() | ||
| const block = this.getBlock() | ||
| if (block) { | ||
| this.eraseBlock(block) | ||
| } | ||
| this.appendBlock(values) | ||
| await this.save() | ||
| } | ||
| private async cleanUpOldConfig() { | ||
| const raw = this.getRaw() | ||
| const oldConfig = raw.split("\n\n").find((config) => config.includes("Host coder--vscode--*")) | ||
| if (oldConfig) { | ||
| this.raw = raw.replace(oldConfig, "") | ||
| } | ||
| } | ||
| private getBlock(): Block | undefined { | ||
| const raw = this.getRaw() | ||
| const startBlockIndex = raw.indexOf(this.startBlockComment) | ||
| const endBlockIndex = raw.indexOf(this.endBlockComment) | ||
| const hasBlock = startBlockIndex > -1 && endBlockIndex > -1 | ||
| if (!hasBlock) { | ||
| return | ||
| } | ||
| if (startBlockIndex === -1) { | ||
| throw new SSHConfigBadFormat("Start block not found") | ||
| } | ||
| if (startBlockIndex === -1) { | ||
| throw new SSHConfigBadFormat("End block not found") | ||
| } | ||
| if (endBlockIndex < startBlockIndex) { | ||
| throw new SSHConfigBadFormat("Malformed config, end block is before start block") | ||
| } | ||
| return { | ||
| raw: raw.substring(startBlockIndex, endBlockIndex + this.endBlockComment.length), | ||
| } | ||
| } | ||
| private eraseBlock(block: Block) { | ||
| this.raw = this.getRaw().replace(block.raw, "") | ||
| } | ||
| private appendBlock({ Host, ...otherValues }: SSHValues) { | ||
| const lines = [this.startBlockComment, `Host ${Host}`] | ||
| const keys = Object.keys(otherValues) as Array<keyof typeof otherValues> | ||
| keys.forEach((key) => { | ||
| lines.push(this.withIndentation(`${key} ${otherValues[key]}`)) | ||
| }) | ||
| lines.push(this.endBlockComment) | ||
| const raw = this.getRaw() | ||
| if (this.raw === "") { | ||
| this.raw = lines.join("\n") | ||
| } else { | ||
| this.raw = `${raw.trimEnd()}\n\n${lines.join("\n")}` | ||
| } | ||
| } | ||
| private withIndentation(text: string) { | ||
| return ` ${text}` | ||
BrunoQuaresma marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| } | ||
| private async save() { | ||
| await this.fileSystem.ensureDir(path.dirname(this.filePath), { | ||
| mode: 0o700, // only owner has rwx permission, not group or everyone. | ||
| }) | ||
| return this.fileSystem.writeFile(this.filePath, this.getRaw(), { | ||
| mode: 0o600, // owner rw | ||
| encoding: "utf-8", | ||
| }) | ||
| } | ||
| private getRaw() { | ||
| if (this.raw === undefined) { | ||
| throw new Error("SSHConfig is not loaded. Try sshConfig.load()") | ||
| } | ||
| return this.raw | ||
| } | ||
| } | ||
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.