Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,10 @@ describe('[AUTH] SandboxController', () => {
const methodName = trackMethod('validateSshAccess')
expect(isPublicEndpoint(SandboxController, methodName)).toBe(false)
expectArrayMatch(getAllowedAuthStrategies(SandboxController, methodName), [AuthStrategyType.API_KEY])
expectArrayMatch(getAuthContextGuards(SandboxController, methodName), [SshGatewayAuthContextGuard])
expectArrayMatch(getAuthContextGuards(SandboxController, methodName), [
SshGatewayAuthContextGuard,
ProxyAuthContextGuard,
])
})

it('getToolboxProxyUrl', () => {
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/sandbox/controllers/sandbox.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1449,7 +1449,7 @@ export class SandboxController {
type: SshAccessValidationDto,
})
@AuthStrategy(AuthStrategyType.API_KEY)
@UseGuards(SshGatewayAuthContextGuard)
@UseGuards(OrGuard([SshGatewayAuthContextGuard, ProxyAuthContextGuard]))
async validateSshAccess(@Query('token') token: string): Promise<SshAccessValidationDto> {
const result = await this.sandboxService.validateSshAccess(token)
return SshAccessValidationDto.fromValidationResult(result.valid, result.sandboxId)
Expand Down
1 change: 1 addition & 0 deletions apps/daemon/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ require (
github.com/kelseyhightower/envconfig v1.4.0
github.com/lmittmann/tint v1.1.2
github.com/mattn/go-isatty v0.0.20
github.com/modelcontextprotocol/go-sdk v1.6.1
github.com/orcaman/concurrent-map/v2 v2.0.1
github.com/pkg/sftp v1.13.6
github.com/ramr/go-reaper v0.3.1
Expand Down
3 changes: 3 additions & 0 deletions apps/daemon/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,8 @@ github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27k
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modelcontextprotocol/go-sdk v1.6.1 h1:0zOSupjKUxPKSocPT1Wtago+mUHU2/uZ4xSOY0FGReU=
github.com/modelcontextprotocol/go-sdk v1.6.1/go.mod h1:kzm3kzFL1/+AziGOE0nUs3gvPoNxMCvkxokMkuFapXQ=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
Expand Down Expand Up @@ -321,6 +323,7 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
Expand Down
163 changes: 163 additions & 0 deletions apps/daemon/pkg/session/exec_support.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// Copyright 2025 Daytona Platforms Inc.
// SPDX-License-Identifier: AGPL-3.0

package session

import (
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"

common_errors "github.com/daytonaio/common-go/pkg/errors"
)

// inputHolderPidFileName is written by cmdWrapperFormat next to the command's
// log file and holds the PID of the async stdin-holder process.
const inputHolderPidFileName = "input_holder.pid"

// CommandLogPaths returns the log file and exit-code file paths for a
// command, so streaming consumers (e.g. the exec WebSocket endpoint) can tail
// output and detect completion without going through the REST endpoints.
func (s *SessionService) CommandLogPaths(sessionId, commandId string) (logPath, exitCodePath string, err error) {
session, ok := s.sessions.Get(sessionId)
if !ok {
return "", "", common_errors.NewNotFoundError(errors.New("session not found"))
}

command, ok := session.commands.Get(commandId)
if !ok {
return "", "", common_errors.NewNotFoundError(errors.New("command not found"))
}

logPath, exitCodePath = command.LogFilePath(session.Dir(s.configDir))
return logPath, exitCodePath, nil
}

// WriteInput writes raw bytes to a running command's stdin FIFO. Unlike
// SendInput it adds no trailing newline and does not echo into the log —
// semantics required by byte-exact protocols (exec-over-WebSocket stdin
// frames). The FIFO is opened non-blocking first so a missing reader
// (command already gone) fails fast instead of hanging the caller.
func (s *SessionService) WriteInput(sessionId, commandId string, data []byte) error {
session, ok := s.sessions.Get(sessionId)
if !ok {
return common_errors.NewNotFoundError(errors.New("session not found"))
}

if session.cmd == nil || session.cmd.Process == nil {
return common_errors.NewGoneError(errors.New("session process is not running"))
}

if session.cmd.ProcessState != nil && session.cmd.ProcessState.Exited() {
return common_errors.NewGoneError(errors.New("session process has exited"))
}

command, ok := session.commands.Get(commandId)
if !ok {
return common_errors.NewNotFoundError(errors.New("command not found"))
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

if command.ExitCode != nil {
return common_errors.NewGoneError(fmt.Errorf("command has already completed with exit code %d", *command.ExitCode))
}

inputFilePath := command.InputFilePath(session.Dir(s.configDir))

fd, err := syscall.Open(inputFilePath, syscall.O_WRONLY|syscall.O_NONBLOCK, 0)
if err != nil {
if errors.Is(err, syscall.ENXIO) || os.IsNotExist(err) {
return common_errors.NewGoneError(errors.New("command stdin is closed"))
}
return common_errors.NewInternalServerError(fmt.Errorf("failed to open input pipe: %w", err))
}
defer func() { _ = syscall.Close(fd) }()

// Restore blocking semantics for the write itself so large frames don't
// fail with EAGAIN on a full pipe buffer.
if err := syscall.SetNonblock(fd, false); err != nil {
return common_errors.NewInternalServerError(fmt.Errorf("failed to configure input pipe: %w", err))
}

// write(2) may return fewer bytes than requested (partial write), so loop
// until the whole frame has been delivered.
for remaining := data; len(remaining) > 0; {
n, err := syscall.Write(fd, remaining)
if err != nil {
return common_errors.NewInternalServerError(fmt.Errorf("failed to write to input pipe: %w", err))
}
remaining = remaining[n:]
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

return nil
}

// CloseInput delivers stdin EOF to a running command by tearing down the
// input-holder process that cmdWrapperFormat keeps alive for async commands.
// The holder is a single process (see execute.go), so killing it drops the
// FIFO's last writer and the command's stdin sees EOF — SSH channel EOF
// semantics. Best effort: if the holder is not up yet or already gone, the
// command's stdin stays as-is and nil is returned.
func (s *SessionService) CloseInput(sessionId, commandId string) error {
session, ok := s.sessions.Get(sessionId)
if !ok {
return common_errors.NewNotFoundError(errors.New("session not found"))
}

command, ok := session.commands.Get(commandId)
if !ok {
return common_errors.NewNotFoundError(errors.New("command not found"))
}

if command.ExitCode != nil {
return common_errors.NewGoneError(fmt.Errorf("command has already completed with exit code %d", *command.ExitCode))
}

pidFilePath := filepath.Join(session.Dir(s.configDir), commandId, inputHolderPidFileName)
pidBytes, err := os.ReadFile(pidFilePath)
if err != nil {
return nil
}

pid, err := strconv.Atoi(strings.TrimSpace(string(pidBytes)))
if err != nil || pid <= 0 {
return nil
}

// Kill the holder (and any descendants, defensively) so no process keeps
// the FIFO's write end open.
_ = s.signalProcessTree(pid, syscall.SIGKILL)
if holder, err := os.FindProcess(pid); err == nil {
_ = holder.Signal(syscall.SIGKILL)
}

// The pid file is single-use: remove it so a later CloseInput doesn't
// signal a recycled PID.
_ = os.Remove(pidFilePath)

return nil
}

// SignalDescendants delivers sig to every descendant of the session's shell
// process — i.e. the currently running command pipeline (command subshell,
// labelers, stdin holder) — without touching the shell itself, so the wrapper
// survives to record the command's exit code (e.g. 130 for SIGINT).
func (s *SessionService) SignalDescendants(sessionId string, sig syscall.Signal) error {
session, ok := s.sessions.Get(sessionId)
if !ok {
return common_errors.NewNotFoundError(errors.New("session not found"))
}

if session.cmd == nil || session.cmd.Process == nil {
return common_errors.NewGoneError(errors.New("session process is not running"))
}

if session.cmd.ProcessState != nil && session.cmd.ProcessState.Exited() {
return common_errors.NewGoneError(errors.New("session process has exited"))
}

return s.signalProcessTree(session.cmd.Process.Pid, sig)
}
9 changes: 8 additions & 1 deletion apps/daemon/pkg/session/execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,11 @@ func (s *SessionService) Execute(sessionId, cmdId, cmd string, async, isCombined

inputPipeCommand := `cat /dev/null > "$ip" &`
if async {
inputPipeCommand = `while :; do sleep 3600; done > "$ip" &`
// The holder must be a single process: killing the recorded PID alone
// must drop the FIFO's last writer so CloseInput delivers EOF
// immediately. A `while :; do sleep; done` loop leaves its sleep child
// holding the FIFO open after the loop shell is killed.
inputPipeCommand = `exec tail -f /dev/null > "$ip" &`
}

cmdToExec := fmt.Sprintf(cmdWrapperFormat+"\n",
Expand Down Expand Up @@ -216,6 +220,9 @@ var cmdWrapperFormat string = `
%s
ip_pid=$!

# Record the input-holder PID so CloseInput can deliver stdin EOF later.
echo "$ip_pid" > "$dir/input_holder.pid" 2>/dev/null || true
Comment thread
coderabbitai[bot] marked this conversation as resolved.

# Run your command from file (avoids heredoc parsing issues with pipe-fed shells)
{ . %q; } < "$ip" > "$sp" 2> "$ep"
_ec=$?
Expand Down
90 changes: 89 additions & 1 deletion apps/daemon/pkg/toolbox/docs/docs.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading