Skip to content
Open
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
68 changes: 68 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ $ aio runtime --help
* [`aio runtime rule status NAME`](#aio-runtime-rule-status-name)
* [`aio runtime rule update NAME TRIGGER ACTION`](#aio-runtime-rule-update-name-trigger-action)
* [`aio runtime sandbox`](#aio-runtime-sandbox)
* [`aio runtime sandbox exec`](#aio-runtime-sandbox-exec)
* [`aio runtime sandbox run`](#aio-runtime-sandbox-run)
* [`aio runtime trigger`](#aio-runtime-trigger)
* [`aio runtime trigger create TRIGGERNAME`](#aio-runtime-trigger-create-triggername)
Expand Down Expand Up @@ -2184,6 +2185,73 @@ ALIASES

_See code: [src/commands/runtime/sandbox/index.js](https://github.com/adobe/aio-cli-plugin-runtime/blob/8.4.0/src/commands/runtime/sandbox/index.js)_

## `aio runtime sandbox exec`

[Alpha] Sandboxes are in a closed alpha. Your namespace must have

```
USAGE
$ aio runtime sandbox exec [--cert] [--key] [--apiversion] [--apihost] [-u] [-i] [--debug <value>] [-v] [--version]
[--help] [-n <value>] [-e <value>...] [-p <value>...] [--max-lifetime <value>] [--command-timeout <value>]
[--fail-fast]

FLAGS
-e, --egress=<value>... egress rule in host:port[:protocol][|METHOD:path] format, or "allow-all" (repeatable)
-i, --insecure bypass certificate check
-n, --name=<value> [default: aio-sandbox] sandbox name
-p, --port=<value>... Port to expose via a preview URL (repeatable)
-u, --auth [env: WHISK_AUTH] whisk auth
-v, --verbose Verbose output
--apihost [env: WHISK_APIHOST] whisk API host
--apiversion [env: WHISK_APIVERSION] whisk API version
--cert client cert
--command-timeout=<value> [default: 30000] per-command timeout in milliseconds
--debug=<value> Debug level output
--fail-fast stop execution when a command returns a non-zero exit code
--help Show help
--key client key
--max-lifetime=<value> [default: 3600] maximum sandbox lifetime in seconds
--version Show version

DESCRIPTION

[Alpha] Sandboxes are in a closed alpha. Your namespace must have
sandboxes enabled before you can use this command; contact Adobe to request
access.

Create a sandbox and run one or more commands non-interactively, then destroy it.

Provide a one-shot command after "--" and/or pipe a newline-separated list of
commands on stdin. When both are given, the one-shot command runs first,
followed by the piped commands in order.

Each command runs in a fresh process. Shell state (working directory, env
exports) does not persist between commands. Chain commands to work around
this: cd mydir && npm install

By default every command runs and the process exits with the last non-zero
exit code. Use --fail-fast to stop at the first failure. Each command is
capped at --command-timeout milliseconds (default 30000).

For an interactive session, use "aio runtime sandbox run" instead.

ALIASES
$ aio rt sandbox exec

EXAMPLES
$ aio runtime sandbox exec -- node --version

$ aio runtime sandbox exec < commands.txt

$ aio runtime sandbox exec -- node --version < commands.txt

$ aio runtime sandbox exec -e allow-all -p 5173 < commands.txt

$ aio runtime sandbox exec --fail-fast --command-timeout 120000 < commands.txt
```

_See code: [src/commands/runtime/sandbox/exec.js](https://github.com/adobe/aio-cli-plugin-runtime/blob/8.4.0/src/commands/runtime/sandbox/exec.js)_

## `aio runtime sandbox run`

[Alpha] Sandboxes are in a closed alpha. Your namespace must have
Expand Down
191 changes: 191 additions & 0 deletions src/commands/runtime/sandbox/exec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
/*
Comment thread
riddhi2910 marked this conversation as resolved.
Copyright 2026 Adobe Inc. All rights reserved.
This file is licensed to you 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 REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

const { Sandbox } = require('@adobe/aio-lib-sandbox')
const { Flags } = require('@oclif/core')
const RuntimeBaseCommand = require('../../../RuntimeBaseCommand')
const {
buildNetworkPolicy,
parsePortFlags,
parseEgressFlags,
splitArgvAtDoubleDash,
buildCommandList,
shellQuote,
logPolicy,
logPreviewUrls
} = require('../../../sandbox-helpers')

const DEFAULT_COMMAND_TIMEOUT_MS = 30000

class SandboxExec extends RuntimeBaseCommand {
async init () {
const rawArgv = [...this.argv]
const { cliArgs } = splitArgvAtDoubleDash(rawArgv)

await this.parse(SandboxExec, cliArgs)
this.argv = rawArgv
}

async run () {
const { cliArgs, commandArgs } = splitArgvAtDoubleDash(this.argv)
const { flags } = await this.parse(SandboxExec, cliArgs)

const stdinText = process.stdin.isTTY === true ? '' : await this._readStdin()
const commands = buildCommandList(commandArgs, stdinText)

if (commands.length === 0) {
this._failUsage('No commands to run. Pass a command after "--" and/or pipe a newline-separated list on stdin. For an interactive session use "aio runtime sandbox run".')
return
}

let sandbox
try {
const policy = buildNetworkPolicy(flags.egress)
const ports = parsePortFlags(flags.port)
const options = await this.getOptions()

this.log('\nCreating sandbox...')
sandbox = await Sandbox.create({
apiHost: options.apihost,
namespace: options.namespace,
auth: options.api_key,
name: flags.name,
maxLifetime: flags['max-lifetime'],
envs: {},
...(ports && { ports }),
...(policy && { policy })
})
this.log(`Created: ${sandbox.id}`)

logPolicy(policy, msg => this.log(msg))
await logPreviewUrls(sandbox, ports, msg => this.log(msg))

await this._runCommands(sandbox, commands, flags)
} catch (err) {
await this.handleError('failed to exec in sandbox', err)
} finally {
if (sandbox) {
try {
await sandbox.destroy()
this.log('Sandbox destroyed.')
} catch (destroyErr) {
this.log(`failed to destroy sandbox: ${destroyErr.message || destroyErr}`)
}
}
}
}

_readStdin () {
return new Promise((resolve, reject) => {
const chunks = []
process.stdin.on('data', chunk => chunks.push(chunk))
process.stdin.on('end', () => resolve(Buffer.concat(chunks).toString()))
process.stdin.on('error', reject)
})
}

_failUsage (message) {
process.stderr.write(`${message}\n`)
process.exitCode = 2
}

async _runCommands (sandbox, commands, flags) {
const timeout = flags['command-timeout']
for (const cmd of commands) {
this.log(`\n$ ${cmd}`)
const result = await sandbox.exec(cmd, { timeout })
if (result.stdout) process.stdout.write(result.stdout)
if (result.stderr) process.stderr.write(result.stderr)
this.log(`[exit: ${result.exitCode}]`)

if (result.exitCode !== 0) {
process.exitCode = result.exitCode
if (flags['fail-fast']) {
this.log('Stopping: command exited non-zero (--fail-fast).')
return
}
}
}
}
}

SandboxExec.description = `
[Alpha] Sandboxes are in a closed alpha. Your namespace must have
sandboxes enabled before you can use this command; contact Adobe to request
access.

Create a sandbox and run one or more commands non-interactively, then destroy it.

Provide a one-shot command after "--" and/or pipe a newline-separated list of
commands on stdin. When both are given, the one-shot command runs first,
followed by the piped commands in order.

Each command runs in a fresh process. Shell state (working directory, env
exports) does not persist between commands. Chain commands to work around
this: cd mydir && npm install

By default every command runs and the process exits with the last non-zero
exit code. Use --fail-fast to stop at the first failure. Each command is
capped at --command-timeout milliseconds (default 30000).

For an interactive session, use "aio runtime sandbox run" instead.`

SandboxExec.flags = {
...RuntimeBaseCommand.flags,
name: Flags.string({
char: 'n',
description: 'sandbox name',
default: 'aio-sandbox'
}),
egress: Flags.string({
char: 'e',
description: 'egress rule in host:port[:protocol][|METHOD:path] format, or "allow-all" (repeatable)',
multiple: true
}),
port: Flags.string({
char: 'p',
description: 'Port to expose via a preview URL (repeatable)',
multiple: true
}),
'max-lifetime': Flags.integer({
description: 'maximum sandbox lifetime in seconds',
default: 3600
}),
'command-timeout': Flags.integer({
description: 'per-command timeout in milliseconds',
default: DEFAULT_COMMAND_TIMEOUT_MS
}),
'fail-fast': Flags.boolean({
description: 'stop execution when a command returns a non-zero exit code',
default: false
})
}

SandboxExec.examples = [
'<%= config.bin %> <%= command.id %> -- node --version',
'<%= config.bin %> <%= command.id %> < commands.txt',
'<%= config.bin %> <%= command.id %> -- node --version < commands.txt',
'<%= config.bin %> <%= command.id %> -e allow-all -p 5173 < commands.txt',
'<%= config.bin %> <%= command.id %> --fail-fast --command-timeout 120000 < commands.txt'
]

SandboxExec.aliases = ['rt:sandbox:exec']

// exposed for testing
SandboxExec.parseEgressFlags = parseEgressFlags
SandboxExec.parsePortFlags = parsePortFlags
SandboxExec.buildNetworkPolicy = buildNetworkPolicy
SandboxExec.splitArgvAtDoubleDash = splitArgvAtDoubleDash
SandboxExec.buildCommandList = buildCommandList
SandboxExec.shellQuote = shellQuote

module.exports = SandboxExec
40 changes: 7 additions & 33 deletions src/commands/runtime/sandbox/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ const {
buildNetworkPolicy,
parsePortFlags,
parseEgressFlags,
splitArgvAtDoubleDash
splitArgvAtDoubleDash,
logPolicy,
logPreviewUrls
} = require('../../../sandbox-helpers')

const EXEC_TIMEOUT_MS = 30000
Expand Down Expand Up @@ -72,12 +74,12 @@ class SandboxRun extends RuntimeBaseCommand {
const { flags } = await this.parse(SandboxRun, cliArgs)

if (commandArgs.length > 0) {
this._failUsage('This command only supports interactive use. Omit "-- <command>" and type commands when prompted.')
this._failUsage('This command only supports interactive use. Type commands when prompted, or use "aio runtime sandbox exec" for one-shot or scripted commands.')
return
}

if (process.stdin.isTTY !== true) {
this._failUsage('This command requires an interactive terminal. Piped stdin is not supported.')
this._failUsage('This command requires an interactive terminal. Piped stdin is not supported; use "aio runtime sandbox exec" to run a piped list of commands.')
return
}

Expand All @@ -101,8 +103,8 @@ class SandboxRun extends RuntimeBaseCommand {
})
this.log(`Created: ${sandbox.id}`)

this._logPolicy(policy)
await this._logPreviewUrls(sandbox, ports)
logPolicy(policy, msg => this.log(msg))
await logPreviewUrls(sandbox, ports, msg => this.log(msg))

this.log('\nSandbox ready. Type "exit" to destroy and quit.\n')

Expand Down Expand Up @@ -131,34 +133,6 @@ class SandboxRun extends RuntimeBaseCommand {
process.exitCode = 2
}

_logPolicy (policy) {
if (!policy) {
this.log('Network policy: default-deny (DNS + NATS only)')
return
}
if (policy.network.egress === 'allow-all') {
this.log('Network policy: allow-all egress')
return
}
this.log('Network policy: custom egress')
policy.network.egress.forEach(rule => {
const proto = rule.protocol || 'TCP'
const l7 = rule.rules ? ' ' + rule.rules.map(r => `${r.methods.join(',')}:${r.pathPattern}`).join(' ') : ''
this.log(` - ${rule.host}:${rule.port} (${proto})${l7}`)
})
}

async _logPreviewUrls (sandbox, ports) {
if (!ports) {
return
}

this.log('Preview URLs:')
for (const port of ports) {
this.log(` - ${port}: ${await sandbox.getUrl(port)}`)
}
}

async _repl (rl, sandbox) {
while (true) {
const cmd = await this._ask(rl)
Expand Down
Loading
Loading