Skip to content
Closed
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
12 changes: 8 additions & 4 deletions components/execd/pkg/runtime/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,9 @@ func (c *Controller) runCommand(ctx context.Context, request *ExecuteCodeRequest
})

cmd.Dir = request.Cwd
// use a dedicated process group so signals propagate to children.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if err := applyCommandSysProcAttr(cmd, request); err != nil {
return err
}

err = cmd.Start()
if err != nil {
Expand Down Expand Up @@ -151,7 +152,6 @@ func (c *Controller) runCommand(ctx context.Context, request *ExecuteCodeRequest
// runBackgroundCommand executes shell commands in detached mode.
func (c *Controller) runBackgroundCommand(ctx context.Context, cancel context.CancelFunc, request *ExecuteCodeRequest) error {
session := c.newContextID()
request.Hooks.OnExecuteInit(session)

pipe, err := c.combinedOutputDescriptor(session)
if err != nil {
Expand All @@ -171,10 +171,14 @@ func (c *Controller) runBackgroundCommand(ctx context.Context, cancel context.Ca
cmd := exec.CommandContext(ctx, "bash", "-c", request.Code)

cmd.Dir = request.Cwd
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Stdout = pipe
cmd.Stderr = pipe
cmd.Env = mergeEnvs(os.Environ(), loadExtraEnvFromFile())
if err := applyCommandSysProcAttr(cmd, request); err != nil {
cancel()
return err
}
request.Hooks.OnExecuteInit(session)

// use DevNull as stdin so interactive programs exit immediately.
cmd.Stdin = os.NewFile(uintptr(syscall.Stdin), os.DevNull)
Expand Down
43 changes: 43 additions & 0 deletions components/execd/pkg/runtime/command_credentials_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright 2026 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build !windows
// +build !windows

package runtime

import (
"os"
"os/exec"
"syscall"
)

func applyCommandSysProcAttr(cmd *exec.Cmd, request *ExecuteCodeRequest) error {
sysProcAttr := &syscall.SysProcAttr{Setpgid: true}
if request.Uid != nil || request.Gid != nil {
credential := &syscall.Credential{
Uid: uint32(os.Getuid()),
Gid: uint32(os.Getgid()),
}
Comment on lines +29 to +32

Choose a reason for hiding this comment

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

P1 Badge Set NoSetGroups when applying POSIX credentials

Creating syscall.Credential without NoSetGroups: true makes Go call setgroups(0, nil) whenever uid/gid is provided, and that fails with operation not permitted in non-root execd deployments even if the requested IDs equal the current user/group. This means the new uid/gid feature can break command start for common hardened setups that run execd as an unprivileged user; please set NoSetGroups (or explicitly manage groups) when building the credential.

Useful? React with 👍 / 👎.

if request.Uid != nil {
credential.Uid = *request.Uid
}
if request.Gid != nil {
credential.Gid = *request.Gid
}
sysProcAttr.Credential = credential
}
cmd.SysProcAttr = sysProcAttr
return nil
}
49 changes: 49 additions & 0 deletions components/execd/pkg/runtime/command_credentials_unix_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright 2026 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build !windows
// +build !windows

package runtime

import (
"os"
"os/exec"
"testing"
)

func TestApplyCommandSysProcAttr_UsesCurrentIdentityFallback(t *testing.T) {
cmd := exec.Command("bash", "-lc", "true")
gid := uint32(2002)

err := applyCommandSysProcAttr(cmd, &ExecuteCodeRequest{Gid: &gid})
if err != nil {
t.Fatalf("applyCommandSysProcAttr returned error: %v", err)
}
if cmd.SysProcAttr == nil {
t.Fatalf("expected SysProcAttr to be populated")
}
if !cmd.SysProcAttr.Setpgid {
t.Fatalf("expected Setpgid to be true")
}
if cmd.SysProcAttr.Credential == nil {
t.Fatalf("expected Credential to be set when gid is provided")
}
if cmd.SysProcAttr.Credential.Uid != uint32(os.Getuid()) {
t.Fatalf("expected uid fallback to current process uid")
}
if cmd.SysProcAttr.Credential.Gid != gid {
t.Fatalf("expected gid %d, got %d", gid, cmd.SysProcAttr.Credential.Gid)
}
}
27 changes: 27 additions & 0 deletions components/execd/pkg/runtime/command_credentials_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright 2026 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build windows
// +build windows

package runtime

import "os/exec"

func applyCommandSysProcAttr(_ *exec.Cmd, request *ExecuteCodeRequest) error {
if request.Uid != nil || request.Gid != nil {
return ErrCommandCredentialsUnsupported
}
return nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2026 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build windows
// +build windows

package runtime

import (
"errors"
"os/exec"
"testing"
)

func TestApplyCommandSysProcAttr_RejectsCredentials(t *testing.T) {
cmd := exec.Command("cmd", "/C", "echo ok")
uid := uint32(1001)

err := applyCommandSysProcAttr(cmd, &ExecuteCodeRequest{Uid: &uid})
if !errors.Is(err, ErrCommandCredentialsUnsupported) {
t.Fatalf("expected unsupported credentials error, got %v", err)
}
}
2 changes: 2 additions & 0 deletions components/execd/pkg/runtime/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@ package runtime
import "errors"

var ErrContextNotFound = errors.New("context not found")

var ErrCommandCredentialsUnsupported = errors.New("uid/gid are only supported on POSIX platforms")
2 changes: 2 additions & 0 deletions components/execd/pkg/runtime/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ type ExecuteCodeRequest struct {
Timeout time.Duration `json:"timeout"`
Cwd string `json:"cwd"`
Envs map[string]string `json:"envs"`
Uid *uint32 `json:"uid,omitempty"`
Gid *uint32 `json:"gid,omitempty"`
Hooks ExecuteResultHook
}

Expand Down
30 changes: 30 additions & 0 deletions components/execd/pkg/web/controller/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ package controller

import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"time"
goruntime "runtime"

"github.com/alibaba/opensandbox/execd/pkg/flag"
"github.com/alibaba/opensandbox/execd/pkg/runtime"
Expand Down Expand Up @@ -47,6 +49,14 @@ func (c *CodeInterpretingController) RunCommand() {
)
return
}
if goruntime.GOOS == "windows" && (request.Uid != nil || request.Gid != nil) {
c.RespondError(
http.StatusBadRequest,
model.ErrorCodeInvalidRequest,
runtime.ErrCommandCredentialsUnsupported.Error(),
)
return
}

ctx, cancel := context.WithCancel(c.ctx.Request.Context())
defer cancel()
Expand All @@ -58,6 +68,14 @@ func (c *CodeInterpretingController) RunCommand() {
c.setupSSEResponse()
err = codeRunner.Execute(runCodeRequest)
if err != nil {
if errors.Is(err, runtime.ErrCommandCredentialsUnsupported) {
c.RespondError(
http.StatusBadRequest,
model.ErrorCodeInvalidRequest,
err.Error(),
)
return
}
c.RespondError(
http.StatusInternalServerError,
model.ErrorCodeRuntimeError,
Expand Down Expand Up @@ -133,13 +151,25 @@ func (c *CodeInterpretingController) buildExecuteCommandRequest(request model.Ru
Code: request.Command,
Cwd: request.Cwd,
Timeout: timeout,
Uid: toOptionalUint32(request.Uid),
Gid: toOptionalUint32(request.Gid),
}
} else {
return &runtime.ExecuteCodeRequest{
Language: runtime.Command,
Code: request.Command,
Cwd: request.Cwd,
Timeout: timeout,
Uid: toOptionalUint32(request.Uid),
Gid: toOptionalUint32(request.Gid),
}
}
}

func toOptionalUint32(value *int64) *uint32 {
if value == nil {
return nil
}
converted := uint32(*value)
return &converted
}
30 changes: 30 additions & 0 deletions components/execd/pkg/web/controller/command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ import (
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/alibaba/opensandbox/execd/pkg/runtime"
"github.com/alibaba/opensandbox/execd/pkg/web/model"
)

Expand Down Expand Up @@ -70,3 +72,31 @@ func TestGetBackgroundCommandOutput_MissingID(t *testing.T) {
t.Fatalf("unexpected message: %s", resp.Message)
}
}

func TestBuildExecuteCommandRequest_MapsUidGidAndTimeout(t *testing.T) {
ctrl := &CodeInterpretingController{}
uid := int64(1001)
gid := int64(1002)

execReq := ctrl.buildExecuteCommandRequest(model.RunCommandRequest{
Command: "id",
Cwd: "/tmp",
TimeoutMs: 2500,
Uid: &uid,
Gid: &gid,
Background: true,
})

if execReq.Language != runtime.BackgroundCommand {
t.Fatalf("expected background command language, got %s", execReq.Language)
}
if execReq.Timeout != 2500*time.Millisecond {
t.Fatalf("unexpected timeout: %s", execReq.Timeout)
}
if execReq.Uid == nil || *execReq.Uid != 1001 {
t.Fatalf("unexpected uid: %#v", execReq.Uid)
}
if execReq.Gid == nil || *execReq.Gid != 1002 {
t.Fatalf("unexpected gid: %#v", execReq.Gid)
}
}
4 changes: 4 additions & 0 deletions components/execd/pkg/web/model/codeinterpreting.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ type RunCommandRequest struct {
Background bool `json:"background,omitempty"`
// TimeoutMs caps execution duration; 0 uses server default.
TimeoutMs int64 `json:"timeout,omitempty" validate:"omitempty,gte=1"`
// Uid selects the POSIX user id for command execution.
Uid *int64 `json:"uid,omitempty" validate:"omitempty,gte=0,lte=4294967295"`
// Gid selects the POSIX group id for command execution.
Gid *int64 `json:"gid,omitempty" validate:"omitempty,gte=0,lte=4294967295"`
}

func (r *RunCommandRequest) Validate() error {
Expand Down
21 changes: 21 additions & 0 deletions components/execd/pkg/web/model/codeinterpreting_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,23 @@ func TestRunCommandRequestValidate(t *testing.T) {
if err := req.Validate(); err == nil {
t.Fatalf("expected validation error when command is empty")
}

req.Command = "ls"
req.Uid = int64Ptr(-1)
if err := req.Validate(); err == nil {
t.Fatalf("expected validation error when uid is negative")
}

req.Uid = int64Ptr(42)
req.Gid = int64Ptr(4_294_967_296)
if err := req.Validate(); err == nil {
t.Fatalf("expected validation error when gid exceeds uint32 range")
}

req.Gid = int64Ptr(0)
if err := req.Validate(); err != nil {
t.Fatalf("expected success with explicit uid/gid: %v", err)
}
}

func TestServerStreamEventToJSON(t *testing.T) {
Expand All @@ -77,6 +94,10 @@ func TestServerStreamEventToJSON(t *testing.T) {
}
}

func int64Ptr(value int64) *int64 {
return &value
}

func TestServerStreamEventSummary(t *testing.T) {
longText := strings.Repeat("a", 120)
tests := []struct {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ public async IAsyncEnumerable<ServerStreamEvent> RunStreamAsync(
Command = command,
Cwd = options?.WorkingDirectory,
Background = options?.Background,
Timeout = options?.TimeoutSeconds.HasValue == true ? options.TimeoutSeconds.Value * 1000L : null
Timeout = options?.TimeoutSeconds.HasValue == true ? options.TimeoutSeconds.Value * 1000L : null,
Uid = options?.Uid,
Gid = options?.Gid,
};

var json = JsonSerializer.Serialize(requestBody, JsonOptions);
Expand Down
Loading