Skip to content
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
33443b1
cmux ssh: test that replay and reconnect filters drop OSC 52 clipboar…
austinywang Sep 30, 2026
6784022
cmux ssh: drop replayed OSC 52 clipboard reads and their reconnect re…
austinywang Sep 30, 2026
ae41937
cmux ssh: test that a read gap inside an OSC 52 reply keeps discarding
austinywang Sep 30, 2026
98f1449
cmux ssh: keep discarding an OSC 52 reply across a read gap
austinywang Sep 30, 2026
0d7f4e5
cmux ssh: test that the live release manifest cannot override the emb…
austinywang Sep 30, 2026
6f5ad60
cmux ssh: never let the live release manifest override the embedded d…
austinywang Sep 30, 2026
30c7650
cmux vm ssh: test that an unlaunched SSH startup script is removed
austinywang Sep 30, 2026
c256079
cmux vm ssh: remove SSH startup scripts no terminal will run
austinywang Sep 30, 2026
6d26925
cmux ssh relay: test that the remote CLI requires the relay to prove …
austinywang Sep 30, 2026
f4837ed
cmux ssh relay: make the relay prove it holds the token
austinywang Sep 30, 2026
4c6a002
cmux ssh relay: test that idle pre-auth connections cannot block the …
austinywang Sep 30, 2026
15a0916
cmux ssh relay: give unauthenticated connections their own budget
austinywang Sep 30, 2026
0f5dfcf
cmux ssh: test that differently routed connections do not share a master
austinywang Sep 30, 2026
887f0ae
cmux ssh: give each security-relevant route its own control socket
austinywang Sep 30, 2026
622c9b2
cmux ssh relay: share the relay handshake between the app and the mac…
austinywang Sep 30, 2026
b8b1e73
cmux ssh relay: test that the macOS CLI requires the relay to prove t…
austinywang Sep 30, 2026
6a925f0
cmux ssh relay: make the macOS CLI require the relay to prove the token
austinywang Sep 30, 2026
632e8fc
cmux ssh: compare the PTY bridge token in constant time
austinywang Sep 30, 2026
c7801d3
cmux ssh relay: make relay authentication an instantiated value
austinywang Sep 30, 2026
ba50fb1
cmux ssh: test that a stalled or oversized replay cannot swallow inpu…
austinywang Sep 30, 2026
0acc306
cmux ssh: bound the attach replay phase and never drop buffered replay
austinywang Sep 30, 2026
06b1909
cmux ssh: test that relayed remote status withholds the local window
austinywang Sep 30, 2026
48e1128
cmux ssh: withhold the local window from relayed remote status
austinywang Sep 30, 2026
bc93864
cmux ssh: test that npm bootstrap verifies the pinned binary digest
austinywang Sep 30, 2026
e7ebb27
cmux ssh: verify npm-installed remote binaries against pinned digests
austinywang Sep 30, 2026
a399afc
cmux ssh: test that squatted /tmp socket directories do not block sta…
austinywang Sep 30, 2026
8f57994
cmux ssh: fall back to a private socket directory when /tmp is squatted
austinywang Sep 30, 2026
ecac151
test(hermes): prime fixture executables before the timed wrapper launch
austinywang Sep 30, 2026
191b525
cmux ssh: count the auth cleanup fork budget by real uid
austinywang Sep 30, 2026
b88013b
cmux ssh: test that a stalled-replay deadline keeps the replay query …
austinywang Sep 30, 2026
ce0874c
cmux ssh: keep stripping replay queries after the replay deadline
austinywang Sep 30, 2026
29aa234
cmux ssh: test that a stop request mid clipboard reply drops the rest
austinywang Sep 30, 2026
1ac877d
cmux ssh: keep discarding a clipboard reply after a reconnect stop
austinywang Sep 30, 2026
5fbb7ed
cmux ssh: test that bootstrap works when the remote login shell is no…
austinywang Sep 30, 2026
48a0326
cmux ssh: run bootstrap shell scripts under sh -c on any login shell
austinywang Sep 30, 2026
ec14967
cmux ssh: test that aliases with a %n proxy do not share a master
austinywang Sep 30, 2026
e45aec6
cmux ssh: key route-specific masters by the destination alias
austinywang Sep 30, 2026
4e15f1e
cmux ssh: test that a stalled reconnect replay can drop its partial p…
austinywang Sep 30, 2026
efc5c9c
cmux ssh: drop a partial reconnect prefix when the replay deadline fires
austinywang Sep 30, 2026
f5ba754
cmux ssh: test that SSH launchers are created owner-only without foll…
austinywang Sep 30, 2026
3f49e5e
cmux ssh: create SSH launchers owner-only with O_EXCL and O_NOFOLLOW
austinywang Sep 30, 2026
cc55b32
test(hermes): prime the fixtures the test wrote instead of scanning tmp
austinywang Sep 30, 2026
e11dc98
cmux ssh: test that a stdout notice before the npm digest is not tamp…
austinywang Sep 30, 2026
bd6c812
cmux ssh: read the pinned npm digest from a marker line
austinywang Sep 30, 2026
ef56c4f
cmux ssh: test that a delayed publisher keeps the recorded socket dir…
austinywang Sep 30, 2026
7962f5d
cmux ssh: replace a stale socket-dir record only under its lock
austinywang Sep 30, 2026
4214178
cmux ssh: test that suppressed replay bytes move the query filter bou…
austinywang Sep 30, 2026
ffcf732
cmux ssh: move the replay query boundary past suppressed replay bytes
austinywang Sep 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions CLI/CMUXCLI+SSHStartupScripts.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ extension CMUXCLI {
isShellSnippet: Bool = false,
passwordCredential: String? = nil,
controlPathPreflightShellFunction: String? = nil,
reconnectLimitDefault: Int = 20
reconnectLimitDefault: Int = 20,
launchScripts: SSHStartupLaunchScripts
) throws -> String {
let script = buildSSHStartupScriptBody(
sshCommand: sshCommand,
Expand All @@ -21,7 +22,7 @@ extension CMUXCLI {
oneTimeCommand: nil,
reconnectLimitDefault: reconnectLimitDefault
)
return try writeSSHStartupScript(script, remoteRelayPort: remoteRelayPort)
return try writeSSHStartupScript(script, remoteRelayPort: remoteRelayPort, launchScripts: launchScripts)
}

func buildReusableSSHStartupCommand(
Expand Down Expand Up @@ -423,13 +424,12 @@ extension CMUXCLI {
]
return scriptLines.joined(separator: "\n")
}
private func writeSSHStartupScript(_ scriptBody: String, remoteRelayPort: Int) throws -> String {
let scriptURL = FileManager.default.temporaryDirectory.appendingPathComponent(
"cmux-ssh-startup-\(remoteRelayPort)-\(UUID().uuidString.lowercased()).sh"
)
let script = "#!/bin/sh\n\(scriptBody)\n"
try script.write(to: scriptURL, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: scriptURL.path)
private func writeSSHStartupScript(
_ scriptBody: String,
remoteRelayPort: Int,
launchScripts: SSHStartupLaunchScripts
) throws -> String {
let scriptURL = try launchScripts.write(scriptBody: scriptBody, remoteRelayPort: remoteRelayPort)
return shellQuote(scriptURL.path)
}
private func reusableShellStartupCommand(
Expand Down
180 changes: 101 additions & 79 deletions CLI/cmux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3573,7 +3573,7 @@ final class SocketClient {
let environment = ProcessInfo.processInfo.environment
if let relayID = trimmedEnvValue(environment["CMUX_RELAY_ID"]),
let relayTokenHex = trimmedEnvValue(environment["CMUX_RELAY_TOKEN"]),
let relayToken = hexData(from: relayTokenHex) {
let relayToken = Data(relayHex: relayTokenHex) {
return RelayCredentials(relayID: relayID, relayToken: relayToken)
}

Expand All @@ -3583,37 +3583,13 @@ final class SocketClient {
let authObject = try? JSONSerialization.jsonObject(with: authData) as? [String: Any],
let relayID = trimmedEnvValue(authObject["relay_id"] as? String),
let relayTokenHex = trimmedEnvValue(authObject["relay_token"] as? String),
let relayToken = hexData(from: relayTokenHex) else {
let relayToken = Data(relayHex: relayTokenHex) else {
throw CLIError(message: "Missing relay auth metadata for \(endpoint.host):\(endpoint.port)")
}

return RelayCredentials(relayID: relayID, relayToken: relayToken)
}

private static func hexData(from string: String) -> Data? {
let normalized = string.trimmingCharacters(in: .whitespacesAndNewlines)
guard !normalized.isEmpty,
normalized.count.isMultiple(of: 2) else {
return nil
}

var data = Data(capacity: normalized.count / 2)
var cursor = normalized.startIndex
while cursor < normalized.endIndex {
let next = normalized.index(cursor, offsetBy: 2)
guard let byte = UInt8(normalized[cursor..<next], radix: 16) else {
return nil
}
data.append(byte)
cursor = next
}
return data
}

private static func hexString(from data: Data) -> String {
data.map { String(format: "%02x", $0) }.joined()
}

private func connectToRelay(
endpoint: RelayEndpoint,
responseTimeout: TimeInterval? = nil,
Expand Down Expand Up @@ -3734,47 +3710,45 @@ final class SocketClient {
responseTimeout: TimeInterval,
deadline: Date
) throws {
let challengeLine = try readLine(
responseTimeout: responseTimeout,
deadline: deadline
)
guard let challengeData = challengeLine.data(using: .utf8),
let challenge = try JSONSerialization.jsonObject(with: challengeData) as? [String: Any],
(challenge["protocol"] as? String) == "cmux-relay-auth",
let version = challenge["version"] as? Int,
let relayID = challenge["relay_id"] as? String,
relayID == credentials.relayID,
let nonce = challenge["nonce"] as? String,
!nonce.isEmpty else {
throw CLIError(message: "Invalid relay authentication challenge")
}

let authMessage = Data("relay_id=\(relayID)\nnonce=\(nonce)\nversion=\(version)".utf8)
let key = SymmetricKey(data: credentials.relayToken)
let mac = Data(HMAC<SHA256>.authenticationCode(for: authMessage, using: key))
let authPayload = try JSONSerialization.data(withJSONObject: [
"relay_id": relayID,
"mac": Self.hexString(from: mac),
])
try configureSocketWriteSafety(remainingSocketTimeout(
responseTimeout: responseTimeout,
deadline: deadline
))
try writeAllNonBlocking(
authPayload + Data([0x0A]),
deadline: deadline,
timeoutMessage: "Relay command timed out",
failureMessage: "Failed to write to relay socket"
let handshake = RemoteRelayClientHandshake(
relayID: credentials.relayID,
relayToken: credentials.relayToken
)
do {
try handshake.perform(
readLine: {
try readLine(responseTimeout: responseTimeout, deadline: deadline)
},
writeLine: { line in
try configureSocketWriteSafety(remainingSocketTimeout(
responseTimeout: responseTimeout,
deadline: deadline
))
try writeAllNonBlocking(
line,
deadline: deadline,
timeoutMessage: "Relay command timed out",
failureMessage: "Failed to write to relay socket"
)
}
)
} catch let failure as RemoteRelayClientHandshake.Failure {
throw CLIError(message: Self.relayHandshakeFailureMessage(failure))
}
}

let authResponseLine = try readLine(
responseTimeout: responseTimeout,
deadline: deadline
)
guard let authResponseData = authResponseLine.data(using: .utf8),
let authResponse = try JSONSerialization.jsonObject(with: authResponseData) as? [String: Any],
(authResponse["ok"] as? Bool) == true else {
throw CLIError(message: "Relay authentication failed")
private static func relayHandshakeFailureMessage(
_ failure: RemoteRelayClientHandshake.Failure
) -> String {
switch failure {
case .invalidChallenge:
return "Invalid relay authentication challenge"
case .rejected:
return "Relay authentication failed"
case .relayNotProven:
return "Relay did not prove it holds the relay token; reconnect this SSH workspace"
case .nonceUnavailable:
return "Failed to create relay authentication nonce"
}
}

Expand Down Expand Up @@ -12059,7 +12033,12 @@ struct CMUXCLI {
explicitOptions: inputSSHOptions.sshOptions
)
},
routeSensitiveOptions: inputSSHOptions.identityFile.map { ["IdentityFile=\($0)"] } ?? []
routeSensitiveOptions: inputSSHOptions.identityFile.map { ["IdentityFile=\($0)"] } ?? [],
// `%C` ignores proxy, identity and host-key options; a route that
// sets them gets a master keyed by its whole resolved route.
routeIdentifier: resolvedUserSSHConfiguration.flatMap {
sharingOptions.routeIdentifier(fromSSHConfigOutput: $0)
}
)
if resolvedUserSSHConfiguration != nil {
sshOptions.sshOptions = resolvedCmuxControlPathOptions(for: sshOptions)
Expand Down Expand Up @@ -12167,6 +12146,11 @@ struct CMUXCLI {
options: sshOptions,
localCommandScript: combinedLocalCommandScript
)
// One-shot launchers can carry the Cloud VM password. Only a new
// workspace's first terminal runs one, and it then deletes itself;
// every other exit removes them here.
let launchScripts = SSHStartupLaunchScripts(directory: FileManager.default.temporaryDirectory)
defer { launchScripts.removeUnlaunched() }
var initialSSHStartupCommand: String
var remoteTerminalSSHStartupCommand: String
if let remoteTerminalBootstrapScript, !remoteTerminalBootstrapScript.isEmpty {
Expand All @@ -12177,7 +12161,8 @@ struct CMUXCLI {
remoteRelayPort: sshOptions.remoteRelayPort,
localCommandScript: combinedLocalCommandScript,
passwordCredential: sshOptions.passwordCredential,
controlPathPreflightShellFunction: controlPathPreflightShellFunction
controlPathPreflightShellFunction: controlPathPreflightShellFunction,
launchScripts: launchScripts
)
remoteTerminalSSHStartupCommand = buildReusableBootstrapSSHStartupCommand(
options: sshOptions,
Expand All @@ -12195,7 +12180,8 @@ struct CMUXCLI {
remoteRelayPort: sshOptions.remoteRelayPort,
isShellSnippet: true,
passwordCredential: sshOptions.passwordCredential,
controlPathPreflightShellFunction: controlPathPreflightShellFunction
controlPathPreflightShellFunction: controlPathPreflightShellFunction,
launchScripts: launchScripts
)
remoteTerminalSSHStartupCommand = buildReusableSSHStartupCommand(
sshCommand: rawRemoteCommandSnippet,
Expand All @@ -12211,7 +12197,8 @@ struct CMUXCLI {
shellFeatures: "",
remoteRelayPort: sshOptions.remoteRelayPort,
passwordCredential: sshOptions.passwordCredential,
controlPathPreflightShellFunction: controlPathPreflightShellFunction
controlPathPreflightShellFunction: controlPathPreflightShellFunction,
launchScripts: launchScripts
)
remoteTerminalSSHStartupCommand = buildReusableSSHStartupCommand(
sshCommand: startupRemoteTerminalSSHCommand,
Expand Down Expand Up @@ -12246,6 +12233,8 @@ struct CMUXCLI {
)
reusableTerminalStartupCommand = splitAttachCommand
initialSSHStartupCommand = reusableTerminalStartupCommand; remoteTerminalSSHStartupCommand = reusableTerminalStartupCommand
// The attach loop fetches its own credential, so no terminal runs the launcher.
launchScripts.removeUnlaunched()
} else {
let splitAttachCommand = [
"env",
Expand Down Expand Up @@ -12465,6 +12454,10 @@ struct CMUXCLI {
}
throw error
}
if didCreateWorkspace {
// The new workspace's first terminal runs the launcher, which deletes itself.
launchScripts.handOff()
}

var payload = configuredPayload

Expand Down Expand Up @@ -12863,7 +12856,8 @@ struct CMUXCLI {
remoteRelayPort: Int,
localCommandScript: String? = nil,
passwordCredential: String? = nil,
controlPathPreflightShellFunction: String? = nil
controlPathPreflightShellFunction: String? = nil,
launchScripts: SSHStartupLaunchScripts
) throws -> String {
let commandSnippet = buildSSHBootstrapCommandSnippet(
options: options,
Expand All @@ -12876,7 +12870,8 @@ struct CMUXCLI {
remoteRelayPort: remoteRelayPort,
isShellSnippet: true,
passwordCredential: passwordCredential,
controlPathPreflightShellFunction: controlPathPreflightShellFunction
controlPathPreflightShellFunction: controlPathPreflightShellFunction,
launchScripts: launchScripts
)
}

Expand Down Expand Up @@ -15896,6 +15891,25 @@ struct CMUXCLI {
throw CLIError(message: "ssh-pty-attach: bridge write failed")
}
}
func storeReplayStateIfComplete() {
guard !replayStateStored, outputProgress.replayBytesRemaining == 0 else { return }
replayState.storeSnapshot(
replayBytes: outputProgress.deliveredReplayBytes,
fingerprint: outputProgress.completedReplayFingerprint ??
SSHPTYAttachOutputProgress.fingerprint(of: Data())
)
replayStateStored = true
}
// The replay length is declared by the remote peer. Bound the replay
// phase so a peer that declares more than it sends cannot hold input
// forwarding off indefinitely.
var replayDeadline = SSHPTYAttachReplayDeadline(startedAt: bridgeReadyUptime)
func endStalledReplay() throws {
try writeReplayFilteredOutput(outputProgress.endReplay())
replayOutputFilter.endReplay()
storeReplayStateIfComplete()
try startInputForwardingAfterReplay()
}
try startInputForwardingAfterReplay()
func finishBridgeClosedNormally() throws {
resizeMonitor.cancel()
Expand All @@ -15913,9 +15927,24 @@ struct CMUXCLI {

var outputBuffer = [UInt8](repeating: 0, count: 32768)
while true {
if !inputPumpStarted, outputProgress.replayBytesRemaining > 0 {
let wait = replayDeadline.remainingWait(at: ProcessInfo.processInfo.systemUptime)
var pollFD = pollfd(fd: fd, events: Int16(POLLIN), revents: 0)
let ready = wait > 0 ? poll(&pollFD, 1, Int32(min(wait * 1000, 60_000).rounded(.up))) : 0
try checkSSHPTYCancellation(signalMonitor)
if ready == 0 {
if replayDeadline.remainingWait(at: ProcessInfo.processInfo.systemUptime) == 0 {
try endStalledReplay()
}
continue
}
// Other poll failures fall through so read reports them.
if ready < 0, errno == EINTR { continue }
}
let count = Darwin.read(fd, &outputBuffer, outputBuffer.count)
try checkSSHPTYCancellation(signalMonitor)
if count > 0 {
replayDeadline.recordOutput(at: ProcessInfo.processInfo.systemUptime)
let output = outputProgress.terminalOutput(
from: Data(outputBuffer.prefix(count)),
suppressingReplay: suppressReplay
Expand All @@ -15926,14 +15955,7 @@ struct CMUXCLI {
}
try writeReplayFilteredOutput(output)
}
if !replayStateStored, outputProgress.replayBytesRemaining == 0 {
replayState.storeSnapshot(
replayBytes: bridgeReplayBytes,
fingerprint: outputProgress.completedReplayFingerprint ??
SSHPTYAttachOutputProgress.fingerprint(of: Data())
)
replayStateStored = true
}
storeReplayStateIfComplete()
try startInputForwardingAfterReplay()
} else if count == 0 {
try finishBridgeClosedNormally()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -773,7 +773,10 @@ extension ControlCommandCoordinator {

/// Shapes the shared remote-mutation result for disconnect / reconnect /
/// foreground_auth_ready / status.
private func workspaceRemoteResult(_ resolution: ControlWorkspaceRemoteResolution?) -> ControlCallResult {
private func workspaceRemoteResult(
_ resolution: ControlWorkspaceRemoteResolution?,
params: [String: JSONValue] = [:]
) -> ControlCallResult {
switch resolution ?? .missingWorkspaceID {
case .missingWorkspaceID:
return .err(code: "invalid_params", message: "Missing workspace_id", data: nil)
Expand All @@ -793,13 +796,11 @@ extension ControlCommandCoordinator {
"workspace_ref": ref(.workspace, workspaceID),
]))
case .resolved(let windowID, let workspaceID, let remoteStatus):
return .ok(.object([
"window_id": orNull(windowID?.uuidString),
"window_ref": ref(.window, windowID),
return .ok(.object(addingLocalWindow(windowID, for: params, to: [
"workspace_id": .string(workspaceID.uuidString),
"workspace_ref": ref(.workspace, workspaceID),
"remote": remoteStatus,
]))
])))
}
}

Expand Down Expand Up @@ -908,7 +909,7 @@ extension ControlCommandCoordinator {
remoteStatus: self.remoteStatus(remoteStatus, for: params)
)
}
return workspaceRemoteResult(status)
return workspaceRemoteResult(status, params: params)
}

/// `workspace.remote.pty_attach_end` — record a remote PTY attach end.
Expand Down
Loading
Loading