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 @@ -59,14 +59,30 @@ public async IAsyncEnumerable<ServerStreamEvent> RunStreamAsync(
RunCommandOptions? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
if (options?.Gid.HasValue == true && options.Uid.HasValue != true)
{
throw new InvalidArgumentException("uid is required when gid is provided");
}
if (options?.Uid.HasValue == true && options.Uid.Value < 0)
{
throw new InvalidArgumentException("uid must be >= 0");
}
if (options?.Gid.HasValue == true && options.Gid.Value < 0)
{
throw new InvalidArgumentException("gid must be >= 0");
}

var url = $"{_baseUrl}/command";
_logger.LogDebug("Running command stream (commandLength={CommandLength})", command.Length);
var requestBody = new RunCommandRequest
{
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,
Envs = options?.Envs
};

var json = JsonSerializer.Serialize(requestBody, JsonOptions);
Expand Down
35 changes: 35 additions & 0 deletions sdks/sandbox/csharp/src/OpenSandbox/Models/Execd.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,25 @@ public class RunCommandRequest
/// </summary>
[JsonPropertyName("timeout")]
public long? Timeout { get; set; }

/// <summary>
/// Gets or sets the Unix user ID used to run the command process.
/// </summary>
[JsonPropertyName("uid")]
public int? Uid { get; set; }

/// <summary>
/// Gets or sets the Unix group ID used to run the command process.
/// Requires <see cref="Uid"/> to be set.
/// </summary>
[JsonPropertyName("gid")]
public int? Gid { get; set; }

/// <summary>
/// Gets or sets environment variables injected into the command process.
/// </summary>
[JsonPropertyName("envs")]
public Dictionary<string, string>? Envs { get; set; }
}

/// <summary>
Expand All @@ -155,6 +174,22 @@ public class RunCommandOptions
/// The server terminates the command when this duration is reached.
/// </summary>
public int? TimeoutSeconds { get; set; }

/// <summary>
/// Gets or sets the Unix user ID used to run the command process.
/// </summary>
public int? Uid { get; set; }

/// <summary>
/// Gets or sets the Unix group ID used to run the command process.
/// Requires <see cref="Uid"/> to be set.
/// </summary>
public int? Gid { get; set; }

/// <summary>
/// Gets or sets environment variables injected into the command process.
/// </summary>
public Dictionary<string, string>? Envs { get; set; }
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using System.Text.Json;
using FluentAssertions;
using OpenSandbox.Adapters;
using OpenSandbox.Core;
using OpenSandbox.Internal;
using OpenSandbox.Models;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -116,6 +117,70 @@ public async Task RunStreamAsync_ShouldSendTimeoutInMilliseconds()
}
}

[Fact]
public async Task RunStreamAsync_ShouldSendUidGidAndEnvs()
{
var handler = new StubHttpMessageHandler(async (request, _) =>
{
request.Content.Should().NotBeNull();
var body = await request.Content!.ReadAsStringAsync().ConfigureAwait(false);
using var doc = JsonDocument.Parse(body);
doc.RootElement.GetProperty("uid").GetInt32().Should().Be(1000);
doc.RootElement.GetProperty("gid").GetInt32().Should().Be(1000);
var envs = doc.RootElement.GetProperty("envs");
envs.GetProperty("APP_ENV").GetString().Should().Be("test");
envs.GetProperty("LOG_LEVEL").GetString().Should().Be("debug");

return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("data: {\"type\":\"init\",\"text\":\"cmd-1\"}\n\n", Encoding.UTF8, "text/event-stream")
};
});
var adapter = CreateAdapter(handler);

var options = new RunCommandOptions
{
Uid = 1000,
Gid = 1000,
Envs = new Dictionary<string, string>
{
["APP_ENV"] = "test",
["LOG_LEVEL"] = "debug"
}
};

await foreach (var _ in adapter.RunStreamAsync("id", options))
{
// Drain events.
}
}

[Fact]
public async Task RunStreamAsync_ShouldRejectGidWithoutUid()
{
var handler = new StubHttpMessageHandler((_, _) =>
{
throw new InvalidOperationException("HTTP should not be called when options are invalid.");
});
var adapter = CreateAdapter(handler);

var options = new RunCommandOptions
{
Gid = 1000
};

var act = async () =>
{
await foreach (var _ in adapter.RunStreamAsync("id", options))
{
// Drain events.
}
};

await act.Should().ThrowAsync<InvalidArgumentException>()
.WithMessage("*uid is required when gid is provided*");
}

private static CommandsAdapter CreateAdapter(HttpMessageHandler httpHandler)
{
var baseUrl = "http://execd.local";
Expand Down
11 changes: 10 additions & 1 deletion sdks/sandbox/csharp/tests/OpenSandbox.Tests/ModelsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -307,13 +307,22 @@ public void RunCommandOptions_ShouldStoreProperties()
{
WorkingDirectory = "/home/user",
Background = true,
TimeoutSeconds = 30
TimeoutSeconds = 30,
Uid = 1000,
Gid = 1000,
Envs = new Dictionary<string, string>
{
["APP_ENV"] = "test"
}
};

// Assert
options.WorkingDirectory.Should().Be("/home/user");
options.Background.Should().BeTrue();
options.TimeoutSeconds.Should().Be(30);
options.Uid.Should().Be(1000);
options.Gid.Should().Be(1000);
options.Envs.Should().ContainKey("APP_ENV");
}

[Fact]
Expand Down
14 changes: 14 additions & 0 deletions sdks/sandbox/javascript/src/adapters/commandsAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ function joinUrl(baseUrl: string, pathname: string): string {
return `${base}${path}`;
}

/** Request body for POST /command (from generated spec; includes uid, gid, envs). */
type ApiRunCommandRequest =
ExecdPaths["/command"]["post"]["requestBody"]["content"]["application/json"];
type ApiCommandStatusOk =
Expand All @@ -41,6 +42,10 @@ type ApiCommandLogsOk =
ExecdPaths["/command/{id}/logs"]["get"]["responses"][200]["content"]["text/plain"];

function toRunCommandRequest(command: string, opts?: RunCommandOpts): ApiRunCommandRequest {
if (opts?.gid != null && opts.uid == null) {
throw new Error("uid is required when gid is provided");
}

const body: ApiRunCommandRequest = {
command,
cwd: opts?.workingDirectory,
Expand All @@ -49,6 +54,15 @@ function toRunCommandRequest(command: string, opts?: RunCommandOpts): ApiRunComm
if (opts?.timeoutSeconds != null) {
body.timeout = Math.round(opts.timeoutSeconds * 1000);
}
if (opts?.uid != null) {
body.uid = opts.uid;
}
if (opts?.gid != null) {
body.gid = opts.gid;
}
if (opts?.envs != null) {
body.envs = opts.envs;
}
return body;
}

Expand Down
25 changes: 24 additions & 1 deletion sdks/sandbox/javascript/src/api/execd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,8 @@ export interface paths {
* The command can run in foreground or background mode. The response includes stdout, stderr,
* execution status, and completion events.
* Optionally specify `timeout` (milliseconds) to enforce a maximum runtime; the server will
* terminate the process when the timeout is reached.
* terminate the process when the timeout is reached. You can also pass `uid`/`gid` to run
* with specific user/group IDs, and `envs` to inject environment variables.
*/
post: operations["runCommand"];
/**
Expand Down Expand Up @@ -527,6 +528,28 @@ export interface components {
* @example 60000
*/
timeout?: number;
/**
* Format: int32
* @description Unix user ID used to run the command. If `gid` is provided, `uid` is required.
* @example 1000
*/
uid?: number;
/**
* Format: int32
* @description Unix group ID used to run the command. Requires `uid` to be provided.
* @example 1000
*/
gid?: number;
/**
* @description Environment variables injected into the command process.
* @example {
* "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
* "PYTHONUNBUFFERED": "1"
* }
*/
envs?: {
[key: string]: string;
};
};
/** @description Command execution status (foreground or background) */
CommandStatusResponse: {
Expand Down
15 changes: 10 additions & 5 deletions sdks/sandbox/javascript/src/api/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -800,15 +800,20 @@ export interface components {
path: string;
};
/**
* @description Kubernetes PersistentVolumeClaim mount backend. References an existing
* PVC in the same namespace as the sandbox pod.
* @description Platform-managed named volume backend. A runtime-neutral abstraction
* for referencing a pre-existing, platform-managed named volume.
*
* Only available in Kubernetes runtime.
* - Kubernetes: maps to a PersistentVolumeClaim in the same namespace.
* - Docker: maps to a Docker named volume (created via `docker volume create`).
*
* The volume must already exist on the target platform before sandbox
* creation.
*/
PVC: {
/**
* @description Name of the PersistentVolumeClaim in the same namespace.
* Must be a valid Kubernetes resource name.
* @description Name of the volume on the target platform.
* In Kubernetes this is the PVC name; in Docker this is the named
* volume name. Must be a valid DNS label.
*/
claimName: string;
};
Expand Down
12 changes: 12 additions & 0 deletions sdks/sandbox/javascript/src/models/execd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ export interface RunCommandOpts {
* If omitted, the server will not enforce any timeout.
*/
timeoutSeconds?: number;
/**
* Unix user ID used to run the command process.
*/
uid?: number;
/**
* Unix group ID used to run the command process. Requires `uid`.
*/
gid?: number;
/**
* Environment variables injected into the command process.
*/
envs?: Record<string, string>;
}

export interface CommandStatus {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,19 @@ import kotlin.time.Duration
* @property background Whether to run in background (detached)
* @property workingDirectory Directory to execute command in
* @property timeout Maximum execution time; server will terminate when reached. Null means the server will not enforce any timeout.
* @property uid Unix user ID used to run the command process
* @property gid Unix group ID used to run the command process. Requires uid.
* @property envs Environment variables injected into the command process
* @property handlers Optional execution handlers
*/
class RunCommandRequest private constructor(
val command: String,
val background: Boolean,
val workingDirectory: String?,
val timeout: Duration?,
val uid: Int?,
val gid: Int?,
val envs: Map<String, String>,
val handlers: ExecutionHandlers?,
) {
companion object {
Expand All @@ -44,6 +50,9 @@ class RunCommandRequest private constructor(
private var background: Boolean = false
private var workingDirectory: String? = null
private var timeout: Duration? = null
private var uid: Int? = null
private var gid: Int? = null
private val envs: MutableMap<String, String> = mutableMapOf()
private var handlers: ExecutionHandlers? = null

fun command(command: String): Builder {
Expand Down Expand Up @@ -71,18 +80,51 @@ class RunCommandRequest private constructor(
return this
}

fun uid(uid: Int?): Builder {
require(uid == null || uid >= 0) { "Uid must be >= 0" }
this.uid = uid
return this
}

fun gid(gid: Int?): Builder {
require(gid == null || gid >= 0) { "Gid must be >= 0" }
this.gid = gid
return this
}

fun env(
key: String,
value: String,
): Builder {
require(key.isNotBlank()) { "Environment variable key cannot be blank" }
this.envs[key] = value
return this
}

fun envs(envs: Map<String, String>): Builder {
envs.keys.forEach { key ->
require(key.isNotBlank()) { "Environment variable key cannot be blank" }
}
this.envs.putAll(envs)
return this
}

fun handlers(handlers: ExecutionHandlers?): Builder {
this.handlers = handlers
return this
}

fun build(): RunCommandRequest {
val commandValue = command ?: throw IllegalArgumentException("Command must be specified")
require(gid == null || uid != null) { "Uid is required when gid is provided" }
return RunCommandRequest(
command = commandValue,
background = background,
workingDirectory = workingDirectory,
timeout = timeout,
uid = uid,
gid = gid,
envs = envs.toMap(),
handlers = handlers,
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ object ExecutionConverter {
background = background,
cwd = workingDirectory,
timeout = timeout?.inWholeMilliseconds,
uid = uid,
gid = gid,
envs = envs
)
}

Expand Down
Loading