Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Add user option to fs methods in Template (#976)

Mish Ushakov83243d5b43f9
diff --git a/.changeset/warm-seals-design.md b/.changeset/warm-seals-design.md
new file mode 100644
index 000000000..d4d8d2a33
--- /dev/null
+++ b/.changeset/warm-seals-design.md
@@ -0,0 +1,6 @@
+---
+'@e2b/python-sdk': patch
+'e2b': patch
+---
+
+added user option to fs-related commands in template builder
diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.ts
index 86ec7d480..a732ec7ee 100644
--- a/packages/js-sdk/src/template/index.ts
+++ b/packages/js-sdk/src/template/index.ts
@@ -309,7 +309,7 @@ export class TemplateBase
remove(
path: PathLike | PathLike[],
- options?: { force?: boolean; recursive?: boolean }
+ options?: { force?: boolean; recursive?: boolean; user?: string }
): TemplateBuilder {
const paths = Array.isArray(path) ? path : [path]
const args = ['rm']
@@ -320,24 +320,28 @@ export class TemplateBase
args.push('-f')
}
args.push(...paths.map((p) => p.toString()))
- return this.runInNewStackTraceContext(() => this.runCmd(args.join(' ')))
+ return this.runInNewStackTraceContext(() =>
+ this.runCmd(args.join(' '), { user: options?.user })
+ )
}
rename(
src: PathLike,
dest: PathLike,
- options?: { force?: boolean }
+ options?: { force?: boolean; user?: string }
): TemplateBuilder {
const args = ['mv', src.toString(), dest.toString()]
if (options?.force) {
args.push('-f')
}
- return this.runInNewStackTraceContext(() => this.runCmd(args.join(' ')))
+ return this.runInNewStackTraceContext(() =>
+ this.runCmd(args.join(' '), { user: options?.user })
+ )
}
makeDir(
path: PathLike | PathLike[],
- options?: { mode?: number }
+ options?: { mode?: number; user?: string }
): TemplateBuilder {
const paths = Array.isArray(path) ? path : [path]
const args = ['mkdir', '-p']
@@ -345,12 +349,20 @@ export class TemplateBase
args.push(`-m ${padOctal(options.mode)}`)
}
args.push(...paths.map((p) => p.toString()))
- return this.runInNewStackTraceContext(() => this.runCmd(args.join(' ')))
+ return this.runInNewStackTraceContext(() =>
+ this.runCmd(args.join(' '), { user: options?.user })
+ )
}
- makeSymlink(src: PathLike, dest: PathLike): TemplateBuilder {
+ makeSymlink(
+ src: PathLike,
+ dest: PathLike,
+ options?: { user?: string }
+ ): TemplateBuilder {
const args = ['ln', '-s', src.toString(), dest.toString()]
- return this.runInNewStackTraceContext(() => this.runCmd(args.join(' ')))
+ return this.runInNewStackTraceContext(() =>
+ this.runCmd(args.join(' '), { user: options?.user })
+ )
}
runCmd(command: string, options?: { user?: string }): TemplateBuilder
@@ -470,7 +482,7 @@ export class TemplateBase
gitClone(
url: string,
path?: PathLike,
- options?: { branch?: string; depth?: number }
+ options?: { branch?: string; depth?: number; user?: string }
): TemplateBuilder {
const args = ['git', 'clone', url]
if (options?.branch) {
@@ -484,7 +496,9 @@ export class TemplateBase
args.push(path.toString())
}
- return this.runInNewStackTraceContext(() => this.runCmd(args.join(' ')))
+ return this.runInNewStackTraceContext(() =>
+ this.runCmd(args.join(' '), { user: options?.user })
+ )
}
setStartCmd(
diff --git a/packages/js-sdk/src/template/types.ts b/packages/js-sdk/src/template/types.ts
index 396fdcc5f..d6ad942f8 100644
--- a/packages/js-sdk/src/template/types.ts
+++ b/packages/js-sdk/src/template/types.ts
@@ -305,11 +305,12 @@ export interface TemplateBuilder {
* @example
* ```ts
* template.remove('/tmp/cache', { recursive: true, force: true })
+ * template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' })
* ```
*/
remove(
path: PathLike | PathLike[],
- options?: { force?: boolean; recursive?: boolean }
+ options?: { force?: boolean; recursive?: boolean; user?: string }
): TemplateBuilder
/**
@@ -321,12 +322,13 @@ export interface TemplateBuilder {
* @example
* ```ts
* template.rename('/tmp/old.txt', '/tmp/new.txt')
+ * template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' })
* ```
*/
rename(
src: PathLike,
dest: PathLike,
- options?: { force?: boolean }
+ options?: { force?: boolean; user?: string }
): TemplateBuilder
/**
@@ -338,24 +340,31 @@ export interface TemplateBuilder {
* ```ts
* template.makeDir('/app/data', { mode: 0o755 })
* template.makeDir(['/app/logs', '/app/cache'])
+ * template.makeDir('/app/data', { mode: 0o755, user: 'root' })
* ```
*/
makeDir(
path: PathLike | PathLike[],
- options?: { mode?: number }
+ options?: { mode?: number; user?: string }
): TemplateBuilder
/**
* Create a symbolic link.
* @param src Source path (target)
* @param dest Destination path (symlink location)
+ * @param options Symlink options
*
* @example
* ```ts
* template.makeSymlink('/usr/bin/python3', '/usr/bin/python')
+ * template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' })
* ```
*/
- makeSymlink(src: PathLike, dest: PathLike): TemplateBuilder
+ makeSymlink(
+ src: PathLike,
+ dest: PathLike,
+ options?: { user?: string }
+ ): TemplateBuilder
/**
* Run a shell command.
@@ -472,12 +481,15 @@ export interface TemplateBuilder {
* branch: 'main',
* depth: 1
* })
+ * template.gitClone('https://github.com/user/repo.git', '/app/repo', {
+ * user: 'root'
+ * })
* ```
*/
gitClone(
url: string,
path?: PathLike,
- options?: { branch?: string; depth?: number }
+ options?: { branch?: string; depth?: number; user?: string }
): TemplateBuilder
/**
diff --git a/packages/js-sdk/tests/template/methods/runCmd.test.ts b/packages/js-sdk/tests/template/methods/runCmd.test.ts
new file mode 100644
index 000000000..549d19c45
--- /dev/null
+++ b/packages/js-sdk/tests/template/methods/runCmd.test.ts
@@ -0,0 +1,39 @@
+import { randomUUID } from 'node:crypto'
+import { expect, test } from 'vitest'
+import { Template } from '../../../src'
+
+test('run command', { timeout: 180000 }, async () => {
+ const template = Template().fromImage('ubuntu:22.04').runCmd('ls -l')
+
+ await Template.build(template, {
+ alias: randomUUID(),
+ })
+})
+
+test('run command as a different user', { timeout: 180000 }, async () => {
+ const template = Template()
+ .fromImage('ubuntu:22.04')
+ .runCmd('test "$(whoami)" = "root"', { user: 'root' })
+
+ await Template.build(template, {
+ alias: randomUUID(),
+ })
+})
+
+test(
+ 'run command as user that does not exist',
+ { timeout: 180000 },
+ async () => {
+ const template = Template()
+ .fromImage('ubuntu:22.04')
+ .runCmd('whoami', { user: 'root123' })
+
+ await expect(
+ Template.build(template, {
+ alias: randomUUID(),
+ })
+ ).rejects.toThrow(
+ "failed to run command 'whoami': command failed: unauthenticated: invalid username: 'root123'"
+ )
+ }
+)
diff --git a/packages/python-sdk/e2b/template/main.py b/packages/python-sdk/e2b/template/main.py
index e7a982e03..e2485cea7 100644
--- a/packages/python-sdk/e2b/template/main.py
+++ b/packages/python-sdk/e2b/template/main.py
@@ -121,6 +121,7 @@ class TemplateBuilder:
path: Union[Union[str, Path], List[Union[str, Path]]],
force: bool = False,
recursive: bool = False,
+ user: Optional[str] = None,
) -> "TemplateBuilder":
"""
Remove files or directories in the template.
@@ -128,12 +129,14 @@ class TemplateBuilder:
:param path: File(s) or directory path(s) to remove
:param force: Force removal without prompting
:param recursive: Remove directories recursively
+ :param user: User to run the command as
:return: `TemplateBuilder` class
Example
```python
template.remove('/tmp/cache', recursive=True, force=True)
+ template.remove('/tmp/cache', recursive=True, force=True, user='root')
```
"""
paths = [path] if isinstance(path, (str, Path)) else path
@@ -145,11 +148,15 @@ class TemplateBuilder:
args.extend([str(p) for p in paths])
return self._template._run_in_new_stack_trace_context(
- lambda: self.run_cmd(" ".join(args))
+ lambda: self.run_cmd(" ".join(args), user=user)
)
def rename(
- self, src: Union[str, Path], dest: Union[str, Path], force: bool = False
+ self,
+ src: Union[str, Path],
+ dest: Union[str, Path],
+ force: bool = False,
+ user: Optional[str] = None,
) -> "TemplateBuilder":
"""
Rename or move a file or directory in the template.
@@ -157,12 +164,14 @@ class TemplateBuilder:
:param src: Source path
:param dest: Destination path
:param force: Force rename without prompting
+ :param user: User to run the command as
:return: `TemplateBuilder` class
Example
```python
template.rename('/tmp/old.txt', '/tmp/new.txt')
+ template.rename('/tmp/old.txt', '/tmp/new.txt', user='root')
```
"""
args = ["mv", str(src), str(dest)]
@@ -170,19 +179,21 @@ class TemplateBuilder:
args.append("-f")
return self._template._run_in_new_stack_trace_context(
- lambda: self.run_cmd(" ".join(args))
+ lambda: self.run_cmd(" ".join(args), user=user)
)
def make_dir(
self,
path: Union[Union[str, Path], List[Union[str, Path]]],
mode: Optional[int] = None,
+ user: Optional[str] = None,
) -> "TemplateBuilder":
"""
Create directory(ies) in the template.
:param path: Directory path(s) to create
:param mode: Directory permissions in octal format (e.g., 0o755)
+ :param user: User to run the command as
:return: `TemplateBuilder` class
@@ -190,6 +201,7 @@ class TemplateBuilder:
```python
template.make_dir('/app/data', mode=0o755)
template.make_dir(['/app/logs', '/app/cache'])
+ template.make_dir('/app/data', mode=0o755, user='root')
```
"""
path_list = [path] if isinstance(path, (str, Path)) else path
@@ -199,28 +211,33 @@ class TemplateBuilder:
args.extend([str(p) for p in path_list])
return self._template._run_in_new_stack_trace_context(
- lambda: self.run_cmd(" ".join(args))
+ lambda: self.run_cmd(" ".join(args), user=user)
)
def make_symlink(
- self, src: Union[str, Path], dest: Union[str, Path]
+ self,
+ src: Union[str, Path],
+ dest: Union[str, Path],
+ user: Optional[str] = None,
) -> "TemplateBuilder":
"""
Create a symbolic link in the template.
:param src: Source path (target of the symlink)
:param dest: Destination path (location of the symlink)
+ :param user: User to run the command as
:return: `TemplateBuilder` class
Example
```python
template.make_symlink('/usr/bin/python3', '/usr/bin/python')
+ template.make_symlink('/usr/bin/python3', '/usr/bin/python', user='root')
```
"""
args = ["ln", "-s", str(src), str(dest)]
return self._template._run_in_new_stack_trace_context(
- lambda: self.run_cmd(" ".join(args))
+ lambda: self.run_cmd(" ".join(args), user=user)
)
def run_cmd(
@@ -404,6 +421,7 @@ class TemplateBuilder:
path: Optional[Union[str, Path]] = None,
branch: Optional[str] = None,
depth: Optional[int] = None,
+ user: Optional[str] = None,
) -> "TemplateBuilder":
"""
Clone a git repository into the template.
@@ -412,6 +430,7 @@ class TemplateBuilder:
:param path: Destination path for the clone
:param branch: Branch to clone
:param depth: Clone depth for shallow clones
+ :param user: User to run the command as
:return: `TemplateBuilder` class
@@ -419,6 +438,7 @@ class TemplateBuilder:
```python
template.git_clone('https://github.com/user/repo.git', '/app/repo')
template.git_clone('https://github.com/user/repo.git', branch='main', depth=1)
+ template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root')
```
"""
args = ["git", "clone", url]
@@ -430,7 +450,7 @@ class TemplateBuilder:
if path:
args.append(str(path))
return self._template._run_in_new_stack_trace_context(
- lambda: self.run_cmd(" ".join(args))
+ lambda: self.run_cmd(" ".join(args), user=user)
)
def set_envs(self, envs: Dict[str, str]) -> "TemplateBuilder":
diff --git a/packages/python-sdk/tests/async/template_async/methods/test_run_cmd.py b/packages/python-sdk/tests/async/template_async/methods/test_run_cmd.py
new file mode 100644
index 000000000..e71aaba21
--- /dev/null
+++ b/packages/python-sdk/tests/async/template_async/methods/test_run_cmd.py
@@ -0,0 +1,46 @@
+import pytest
+from uuid import uuid4
+
+from e2b import AsyncTemplate
+
+
+async def test_run_command():
+ template = AsyncTemplate().from_image("ubuntu:22.04").run_cmd("ls -l")
+
+ await AsyncTemplate.build(
+ template,
+ alias=str(uuid4()),
+ )
+
+
+async def test_run_command_as_different_user():
+ template = (
+ AsyncTemplate()
+ .from_image("ubuntu:22.04")
+ .run_cmd('test "$(whoami)" = "root"', user="root")
+ )
+
+ await AsyncTemplate.build(
+ template,
+ alias=str(uuid4()),
+ )
+
+
+async def test_run_command_as_user_that_does_not_exist():
+ template = (
+ AsyncTemplate().from_image("ubuntu:22.04").run_cmd("whoami", user="root123")
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ await AsyncTemplate.build(
+ template,
+ alias=str(uuid4()),
+ )
+
+ assert (
+ "failed to run command 'whoami': command failed: unauthenticated: invalid username: 'root123'"
+ in str(exc_info.value)
+ )
diff --git a/packages/python-sdk/tests/sync/template_sync/methods/test_run_cmd.py b/packages/python-sdk/tests/sync/template_sync/methods/test_run_cmd.py
new file mode 100644
index 000000000..8e5228e8f
--- /dev/null
+++ b/packages/python-sdk/tests/sync/template_sync/methods/test_run_cmd.py
@@ -0,0 +1,44 @@
+import pytest
+from uuid import uuid4
+
+from e2b import Template
+
+
+def test_run_command():
+ template = Template().from_image("ubuntu:22.04").run_cmd("ls -l")
+
+ Template.build(
+ template,
+ alias=str(uuid4()),
+ )
+
+
+def test_run_command_as_different_user():
+ template = (
+ Template()
+ .from_image("ubuntu:22.04")
+ .run_cmd('test "$(whoami)" = "root"', user="root")
+ )
+
+ Template.build(
+ template,
+ alias=str(uuid4()),
+ )
+
+
+def test_run_command_as_user_that_does_not_exist():
+ template = Template().from_image("ubuntu:22.04").run_cmd("whoami", user="root123")
+
+ with pytest.raises(Exception) as exc_info:
+ Template.build(
+ template,
+ alias=str(uuid4()),
+ )
+
+ assert (
+ "failed to run command 'whoami': command failed: unauthenticated: invalid username: 'root123'"
+ in str(exc_info.value)
+ )