-
Notifications
You must be signed in to change notification settings - Fork 24
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 14 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
48d16a6
fix: Removes first matching Host block
BrunoQuaresma 3c31777
Abstract SSH update
BrunoQuaresma ace35dd
Remove package
BrunoQuaresma f4eeba8
Remove unused import
BrunoQuaresma cfe3c9c
Update src/SSHConfig.ts
BrunoQuaresma c359a19
Apply review suggestions
BrunoQuaresma 5e7ebb8
Merge branch 'bq/fix-42' of github.com:coder/vscode-coder into bq/fix-42
BrunoQuaresma 9db792e
Remove unused dep
BrunoQuaresma 30b7020
Cleanup tests
BrunoQuaresma 93c02d8
Cleanup tests
BrunoQuaresma 5ce8e68
Add tests
BrunoQuaresma 0199cc3
Improve comments
BrunoQuaresma 98f26dd
Clean up old config
BrunoQuaresma 33f0eb6
Remove bad dir
BrunoQuaresma 7dcd5da
Fix name and remove package-lock.json
BrunoQuaresma e3ac21b
Fix command
BrunoQuaresma 77ea26f
Add test to CI
BrunoQuaresma 1949890
Improve scripts
BrunoQuaresma 4b75882
Fix lint
BrunoQuaresma bc6d1f8
Update workflow
BrunoQuaresma 1c1beb1
Fix names
BrunoQuaresma 0e63d49
Delete SSHConfig.test.ts
BrunoQuaresma 307ba0e
Delete SSHConfig.ts
BrunoQuaresma File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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, | ||
}) | ||
}) |
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" | ||
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 resolved
Hide resolved
|
||
} | ||
|
||
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.
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.
Uh oh!
There was an error while loading. Please reload this page.