<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by SinghDevHub on Medium]]></title>
        <description><![CDATA[Stories by SinghDevHub on Medium]]></description>
        <link>https://medium.com/@SinghDevHub?source=rss-5e40f9f854c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jB3OgpHrJzFLJSBjy5wNiQ.jpeg</url>
            <title>Stories by SinghDevHub on Medium</title>
            <link>https://medium.com/@SinghDevHub?source=rss-5e40f9f854c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:58:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SinghDevHub/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[sandboxing your ai agent — from first principles | Part 3]]></title>
            <link>https://medium.com/@SinghDevHub/sandboxing-your-ai-agent-from-first-principles-part-3-a4ae625dd793?source=rss-5e40f9f854c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4ae625dd793</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-agent-in-action]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[SinghDevHub]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 15:36:27 GMT</pubDate>
            <atom:updated>2026-11-30T15:36:27.634Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last article (<a href="https://medium.com/@SinghDevHub/sandboxing-your-ai-agent-from-first-principles-part-2-bf021c9f7eb3">Part 2</a>) we discussed about docker architecture, container internals and how we can isolate filesystem or repository from the agent’s working instance. <br>In this part i will discuss about Networking, stronger sandboxing using gVisor &amp; microVMs, Docker commands cheatsheet and finally discussing applications of all these concepts in our AI Agent <a href="https://github.com/singhdevhub-lovepreet/omega">omega</a>.</p><h4>Networking — How does a container access the internet ?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kq31iVCg_j3ZigCZ" /><figcaption>containers accessing the internet</figcaption></figure><p>Imagine our agent needs internet access from the sandbox (container). Inside the container, a network namespace is created and initially that will contain only lo interface and that too is down.</p><p><strong>Important networking terms:-</strong></p><ol><li>Loopback lo — a virtual (software-defined) interface that routes traffic back to the same device (127.0.0.1) instead of sending it over a physical network cable.</li><li>veth pair — Virtual ethernet pair. Treat it as virtual network cable whose one end is in container and other one is on the host.</li><li>docker0 bridge — Its a virtual switch of the host and it connects the multiple containers.</li><li>NAT — Network address translation. Container’s private IP is not directly routed to the internet and Host translates the packet’s source IP address through NAT.</li><li>DNS — converts the domain name to IP address. ex: google.com -&gt; IP address</li></ol><p>Complete networking flow —</p><pre>Container<br>   |<br>  eth0<br>   |<br> veth pair<br>   |<br> docker0 bridge<br>   |<br> NAT / MASQUERADE<br>   |<br> Host network<br>   |<br> Internet</pre><p>Disabling complete network:- docker run --network none ubuntu:24.04 It wouldn’t give external network access to the container. This is recommended for AI agents by default especially when code is untrusted. But how would dependencies download:-</p><p>go mod download will try to download the dependencies and allowing network everytime is also not safe. So, the solution is: <strong>Egress Proxy.</strong></p><h4><strong>Egress Proxy</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bNNmZj-yDp739HaW" /><figcaption>network isolation</figcaption></figure><p><strong>Concept:-</strong> container doesn’t connect to the internet directly. It connects to the proxy server and proxy decides which domains are allowed. example allowlist:-</p><pre>proxy.golang.org<br>sum.golang.org<br>registry.npmjs.org<br>pypi.org<br>files.pythonhosted.org</pre><p>Container environment variables:-</p><pre>HTTP_PROXY=http://proxy:8080<br>HTTPS_PROXY=http://proxy:8080</pre><p>and for HTTPS:-</p><pre>CONNECT proxy.golang.org:443</pre><p>Proxy hostname checks and then allow/deny accordingly.</p><p>Benefit:<br>1. Restricted network access<br>2. Every request logged<br>3. Unnecessary internet access blocked</p><h4>DNS exfiltration — sneaky security risk</h4><p>lets suppose you blocked the HTTP access but DNS access is open. Malicious code can encode the secret data in DNS query and can send to the attacker’s server. ex:- nslookup encoded-secret.attacker.com and Attacker’s DNS can receive the query and its called DNS exfiltration. That’s why it’s better to give DNS resolution to the egress proxy’s proxy and arbitrary DNS access shouldn’t be given to the sandbox.</p><p>Takeaway:- Keep network’s access off by default. And if you want to download the dependencies then use the allowlisted proxy instead of giving unrestricted internet access.</p><h4>Stronger Sandboxing — gVisor and microVMs</h4><p>gVisor vs microVMs — till now, we have discussed the normal containers but normal container has a major weakness which is host’s kernel is shared. And if kernel vulnerability is exploited then container boundry might get breached. This problem has two stronger solutions.</p><h4>gVisor — this is a sandboxing technology</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IwRvpLClyLp74t63" /><figcaption>gVisor architecture</figcaption></figure><p>Normal container:-</p><pre>Application<br>     |<br>  Syscalls<br>     |<br>Host Linux Kernel</pre><p>gVisor:-</p><pre>Application<br>     |<br>  Syscalls<br>     |<br>Sentry (User-space kernel)<br>     |<br>Limited host syscalls<br>     |<br>Host Linux Kernel</pre><p><strong>What is sentry?</strong> — This is the user space component implemented in Golang that implements a lot of behaviours of linux kernel’s syscalls.</p><p>Application thinks that they are communicating with the real linux kernel but in actual it would be communicating with the sentry.</p><p>Sentry has these components:-</p><ul><li>Virtual filesystems</li><li>Memory management</li><li>Process table</li><li>Network stack</li></ul><p>Important terms:-</p><p>Sentry:- gVisor’s core user-space kernel</p><p>Gofer:- Helper process to handle the file access. Its purpose is to isolate the access of filesystem. In the newer versions directfs is also available.</p><p>Platform:- Mechanism to intercept the syscalls.</p><p><strong>Important platforms:-</strong></p><p>systrap — seccomp based mechanism</p><p>KVM — Hardware virtualization</p><p>ptrace — Older interception mechanism</p><p>Advantage of gVisor:- Suppose linux kernel has io_uring vulnerability. In the normal container it might reach the real linux kernel but in gVisor sentry can intercept and reject the syscall without sending it to the host’s io_turing implementation. This reduces the host kernel’s attack surface.</p><p>Disadvantages:-</p><ul><li>syscall-heavy workloads might get slow</li><li>Build operations or npm installations performance might be impacted</li></ul><h4>MicroVMs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yRqf6Bayovra1Roe" /><figcaption>KVMs</figcaption></figure><p>MicroVM is an extremely lightweight virtual machine. In the normal container, host kernel is shared. In MicroVMs, every VM has its guest kernel. This provides a much stronger isolation.</p><p><strong>Hardware virtualisation — </strong>Normal process :-</p><pre>Virtual Address<br>      |<br>   Page Tables<br>      |<br>Physical Memory</pre><p>VM has an extra translation layer:-</p><pre>Guest Virtual Address<br>         |<br>     Guest Page Tables<br>         |<br>   Guest Physical Address<br>         |<br>   Second-level Page Tables<br>         |<br>   Host Physical Address</pre><p>Two important things:-</p><ul><li>Intel EPT — extended page tables</li><li>AMD NPT — nested page tables</li></ul><p>Using these, guest VM manages its physical memory from actual memory independently</p><p>VM exit — When Guest VM performs some privileged operation then CPU control might transfer to host/hypervisor. This is called VM exit.</p><p>KVM — its an linux kernel module which exposes hardware virtualisation.</p><p>interface:- /dev/kvm</p><p><strong>VMM</strong> — Virtual machine monitor, is an user-space software which manages virtual machines using KVM. exampls:- QEMU, Firecracker. Firecracker is a minimal VMM implemented in RUST. This emulate limited devices as compared to the full VMs which reduces the attack surface.</p><p><strong>Firecracker Jailer</strong> — it restricts the VMM processes using namespaces, cgroups and seccomp, means VM management software is also sandboxed which is called defence in depth.</p><p><strong>vsock</strong> — this is a special socket mechanism for the communication btw VM and host. ex:- host agent wants to execute a command inside the VM and also wanted to receive the output.</p><p><strong>Snapshot and restore</strong> — MicroVMs frequent starts are expensive and the solution is:-</p><ul><li>boot the VM once</li><li>take the snapshot of the memory and the disk</li><li>use the snapshots in the future runs</li></ul><p>Using this, sandbox can be started quickly.</p><p><strong>Comparing our sandboxing approaches till now:-</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*dCK-FFXXX-PNmzGzX-iabg.png" /></figure><p>runc — shared kernel, separate view<br>gVisor — user space kernel in between<br>microVM — separate real guest kernel</p><p><strong>Docker Commands Cheatsheet:-</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*dZEj8GdSjP818AslV98_jw.png" /><figcaption>container isolation commands</figcaption></figure><p>Commands that should never be used —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*IJjbxqPCtcUUqFBcJFRGmg.png" /><figcaption>risky containerisation commands</figcaption></figure><p>Two features which docker doesn’t provide:-</p><p><strong>Wall-clock timeout:-</strong></p><p>in Golang:-</p><pre>ctx, cancel := context.WithTimeout(<br>    context.Background(),<br>    5*time.Minute,<br>)<br>defer cancel()</pre><p>using this, we are setting a 5min deadline and after that runner has to terminate the container or process.</p><p><strong>Output cap:-</strong></p><p>your runner will enforce the maximum bytes while capturing from stdout/stderr. ex:- do not capture output exceeding 1MB.</p><h3>Roadmap to Build Isolation for Omega</h3><p>We now understand the individual building blocks of Linux sandboxing. Let’s put them together and design an isolation layer for Omega, our AI agent.</p><p>Our objective is straightforward:</p><p>Omega should be able to execute shell commands, modify repositories, install dependencies, run tests, and perform development tasks without getting unrestricted access to the host machine.</p><p>Even if the agent executes malicious code or makes an unexpected decision, the impact should remain confined to its execution environment.</p><p>Instead of trying to build a complete isolation system from scratch, we’ll use Docker as our initial runtime and gradually add the security controls we need.</p><h3>1. High-Level Architecture</h3><p>Let’s first understand how the different components will interact.</p><pre>                   HOST MACHINE<br>                         |<br>                         |<br>                  +--------------+<br>                  | Omega Agent  |<br>                  +--------------+<br>                         |<br>                         v<br>                +-------------------+<br>                | Sandbox Manager   |<br>                +-------------------+<br>                   |       |       |<br>                   |       |       |<br>                   v       v       v<br>                Create  Workspace  Lifecycle<br>                Sandbox Manager   Manager<br>                   |       |       |<br>                   +-------+-------+<br>                           |<br>                           v<br>                    Docker Runtime<br>                           |<br>                           v<br>                  +------------------+<br>                  |  Agent Sandbox   |<br>                  |                  |<br>                  |  Linux Container |<br>                  |                  |<br>                  |  /workspace      |<br>                  |  /tmp            |<br>                  |                  |<br>                  |  CPU Limit       |<br>                  |  Memory Limit    |<br>                  |  PID Limit       |<br>                  |  Seccomp         |<br>                  |  Capabilities    |<br>                  |  Network Policy  |<br>                  +------------------+<br>                           |<br>                           v<br>                   Execution Results<br>                           |<br>                           v<br>                    Sandbox Manager<br>                           |<br>                           v<br>                    Host Application</pre><p>We’ll introduce a dedicated Sandbox Manager inside Omega.</p><p>Its responsibility will be to manage the complete lifecycle of an isolated execution environment.</p><p>The agent itself should not directly interact with the Docker daemon or decide its own security configuration.</p><p>Instead, it requests an operation from the Sandbox Manager, which executes that operation inside the configured environment.</p><p>This separation is important: the agent decides what work needs to be done, while the Sandbox Manager decides where and under what restrictions that work can happen.</p><h3>2. Build the Sandbox Manager</h3><p>The first implementation milestone is to introduce a Sandbox Manager.</p><p>We can expose a small interface that hides the underlying container runtime.</p><p>For example:</p><pre>type Sandbox interface {<br>    Create(ctx context.Context) error<br>    CopyWorkspace(ctx context.Context, source string) error<br>    Execute(<br>        ctx context.Context,<br>        command string,<br>    ) (*ExecutionResult, error)<br>    GetChanges(ctx context.Context) ([]byte, error)<br>    Destroy(ctx context.Context) error<br>}</pre><p>The exact implementation can evolve, but the responsibilities should remain clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*v_9B4L1je3LNaP-C6kfLlQ.png" /><figcaption>methods — responsibilities</figcaption></figure><p>The important design decision is that the agent interacts with this interface rather than directly managing containers.</p><p>Initially, we’ll implement this interface using Docker Engine APIs and the Go Docker SDK.</p><p>This also gives us the flexibility to introduce another runtime later without changing the agent’s execution interface.</p><h3>3. Configure the Docker Sandbox</h3><p>Now let’s translate our security requirements into an actual container configuration.</p><p>Every execution environment should be created with a predefined security configuration.</p><p>Our initial configuration will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*V4aLG7Q705xo1nUeb1v9Hg.png" /><figcaption>requirements — docker config</figcaption></figure><p>We should also use an appropriate AppArmor or SELinux policy where available.</p><p>A representative Docker command would look like:</p><pre>docker run --rm \<br>  --name omega-sandbox \<br>  --user 1000:1000 \<br>  --cap-drop ALL \<br>  --security-opt no-new-privileges \<br>  --read-only \<br>  --tmpfs /tmp:size=64m \<br>  --memory 512m \<br>  --memory-swap 512m \<br>  --cpus 1 \<br>  --pids-limit 128 \<br>  --ulimit nofile=1024:1024 \<br>  --network none \<br>  --init \<br>  ubuntu:24.04 \<br>  sleep infinity</pre><p>The production implementation will use the equivalent Docker Engine API fields rather than constructing shell commands.</p><p>One important detail: /workspace must be a separate writable volume because the container&#39;s root filesystem is read-only.</p><p>The archive API used by docker cp can transfer files into that volume. It should not be confused with writing directly into the read-only root filesystem or a tmpfs mount.</p><p>This gives us a reusable, restricted execution environment.</p><h3>4. Workspace Management: How Does Omega Access the Repository?</h3><p>This is one of the most important architectural decisions.</p><p>Omega needs access to the user’s repository to perform development tasks. However, giving the sandbox direct access to the original repository means that the agent can immediately modify the host’s files.</p><p>We have several options:</p><ul><li>Bind mount the original repository.</li><li>Copy the repository into the sandbox.</li><li>Use an OverlayFS snapshot.</li><li>Copy the repository in and return a Git patch.</li></ul><p>For Omega’s initial implementation, we’ll choose <strong>copy in, return a patch</strong>.</p><p>The workflow will look like this:</p><pre>            HOST MACHINE<br>                  |<br>                  |<br>            Original Repo<br>                  |<br>                  | Copy In<br>                  v<br>          +------------------+<br>          |  Omega Sandbox   |<br>          |                  |<br>          |   /workspace     |<br>          |                  |<br>          |  Agent modifies  |<br>          |  files, installs |<br>          |  dependencies,   |<br>          |  runs tests      |<br>          +------------------+<br>                  |<br>                  |<br>                  | Generate Git Patch<br>                  v<br>             changes.patch<br>                  |<br>                  | Copy Out<br>                  v<br>             HOST MACHINE<br>                  |<br>                  v<br>             Patch Review<br>                  |<br>                  v<br>             Human Approval<br>                  |<br>                  v<br>             Apply Changes</pre><h3>4.1 Copying the Repository Into the Sandbox</h3><p>Docker exposes an archive API that allows us to transfer files between the host and a container.</p><p>The relevant endpoints are:</p><pre>PUT /containers/{id}/archive?path=/workspace<br>GET /containers/{id}/archive?path=/workspace</pre><p>The first endpoint transfers files into the container. The second retrieves files from it.</p><p>This is the functionality used by docker cp.</p><p>Our implementation will:</p><ol><li>Create a container.</li><li>Create or attach its writable workspace volume.</li><li>Copy the repository into /workspace.</li><li>Start the container.</li><li>Allow Omega to execute commands inside it.</li></ol><p>We should avoid copying unnecessary directories such as node_modules, build outputs, and large caches when they can be recreated.</p><p>The workspace should also be treated as untrusted input. File transfers need to account for symbolic links, ownership, and archive extraction behaviour.</p><h3>4.2 Execute File Operations Inside the Sandbox</h3><p>This is a particularly important design decision.</p><p>Once the sandbox exists, Omega’s file operations should run inside it.</p><p>For example:</p><pre>read_file(&quot;README.md&quot;)<br>write_file(&quot;main.go&quot;)<br>list_files(&quot;/workspace&quot;)</pre><p>These operations should resolve paths against the sandbox filesystem rather than directly opening files on the host.</p><p>Why?</p><p>Consider a malicious symbolic link created by the agent:</p><pre>ln -s /Users/user/.ssh/id_ed25519 /workspace/notes.txt</pre><p>If a host-side file tool reads notes.txt, it might follow that link and access the host&#39;s private key.</p><p>The sandbox did not access the key. The host-side tool did.</p><p>Moving file operations inside the sandbox ensures that paths are resolved against the container’s filesystem, where the host’s home directory is not mounted.</p><p>This prevents an entire class of accidental host-side filesystem exposure.</p><h3>4.3 Returning Changes as a Git Patch</h3><p>We should avoid blindly copying the entire modified workspace back to the host.</p><p>Instead, Omega can generate a Git patch inside the sandbox:</p><pre>git diff --binary &gt; /tmp/changes.patch</pre><p>The Sandbox Manager retrieves only this patch.</p><p>On the host, we can validate it:</p><pre>git apply --check changes.patch</pre><p>After successful validation and review:</p><pre>git apply changes.patch</pre><p>This gives us a controlled boundary between the isolated environment and the actual repository.</p><p>The human can inspect which files changed, review additions and deletions, and approve the modifications.</p><p>A patch is still untrusted input. We should pay particular attention to changes involving build scripts, Makefiles, CI configurations, Git hooks, and other files that may execute code later.</p><p><strong>Decision for Omega:</strong> Copy the repository into the sandbox, perform all agent file operations inside the sandbox, and return changes as a reviewable Git patch.</p><h3>5. Command Execution and Lifecycle Management</h3><p>Now that the sandbox exists and contains the repository, Omega needs a way to execute commands.</p><p>For example:</p><pre>go test ./...<br>npm install<br>npm run build<br>python main.py</pre><p>The Sandbox Manager will execute these commands inside the container using Docker’s execution API.</p><p>The execution flow should look like this:</p><pre>Omega Agent<br>     |<br>     | Execute(&quot;go test ./...&quot;)<br>     v<br>Sandbox Manager<br>     |<br>     v<br>Docker Exec API<br>     |<br>     v<br>Container<br>     |<br>     v<br>Command Execution<br>     |<br>     +------ stdout<br>     |<br>     +------ stderr<br>     |<br>     +------ exit code<br>     |<br>     v<br>Sandbox Manager<br>     |<br>     v<br>Omega Agent</pre><p>Every execution should return structured information.</p><p>For example:</p><pre>type ExecutionResult struct {<br>    Stdout   string<br>    Stderr   string<br>    ExitCode int<br>    Duration time.Duration<br>}</pre><p>The agent can then use the output to understand whether a command succeeded or failed.</p><h3>5.1 Execution Timeout</h3><p>A command should never be allowed to run indefinitely.</p><p>For example, an agent might accidentally start an infinite loop or a process that hangs forever.</p><p>We can use Go’s context package:</p><pre>ctx, cancel := context.WithTimeout(<br>    context.Background(),<br>    5*time.Minute,<br>)<br>defer cancel()</pre><p>The Docker execution should be associated with this context.</p><p>When the deadline expires, the Sandbox Manager should terminate the execution, wait for it to stop, and clean up any remaining processes.</p><p>A production implementation should also have a cleanup timeout independent of the expired execution context.</p><h3>5.2 Output Limits</h3><p>An agent could generate enormous amounts of output.</p><p>For example:</p><pre>while true; do<br>    echo &quot;Generating output...&quot;<br>done</pre><p>If Omega continuously captures this output, it can consume large amounts of memory and overwhelm the model’s context.</p><p>Therefore, the Sandbox Manager should enforce:</p><ul><li>Maximum stdout size.</li><li>Maximum stderr size.</li><li>Maximum combined output size.</li><li>Maximum execution duration.</li></ul><p>Once the output limit is reached, it should stop capturing additional output and follow the configured termination policy.</p><h3>5.3 Cleanup</h3><p>After an execution finishes, Omega should not leave unnecessary containers or processes running.</p><p>The cleanup sequence should:</p><ol><li>Stop active executions.</li><li>Terminate remaining processes.</li><li>Stop the container.</li><li>Remove the container.</li><li>Remove per-execution volumes.</li><li>Clean up temporary artifacts.</li><li>Record the final execution status.</li></ol><p>We should also assign Docker labels to containers managed by Omega.</p><p>For example:</p><pre>omega.managed=true<br>omega.execution_id=&lt;execution-id&gt;</pre><p>These labels make it possible to identify and clean up orphaned containers if Omega crashes or restarts.</p><h3>6. Networking: Start With No Network Access</h3><p>For the initial implementation, our sandbox will use:</p><pre>NetworkMode = &quot;none&quot;</pre><p>This means the agent cannot automatically access the internet or other network services.</p><p>However, development agents frequently need to download dependencies.</p><p>For example:</p><pre>go mod download<br>npm install<br>pip install requests</pre><p>We don’t want to permanently disable networking if it prevents the agent from completing useful tasks.</p><p>Instead, we can introduce controlled outbound access in a later milestone.</p><p>The proposed architecture:</p><pre>              Agent Sandbox<br>                    |<br>                    |<br>                    v<br>               Egress Proxy<br>                    |<br>             Domain Allowlist<br>                    |<br>                    v<br>             Approved Domains</pre><p>The proxy will:</p><ul><li>Check destination hostnames.</li><li>Allow approved package registries.</li><li>Reject unknown destinations.</li><li>Log outbound requests.</li><li>Apply request and bandwidth limits.</li></ul><p>DNS access should also be controlled to prevent data exfiltration through DNS queries.</p><p><strong>Initial decision:</strong> No network access by default. Introduce an egress proxy when dependency installation and external access become necessary.</p><h3>7. Handling Dependency Caches</h3><p>There is another practical consideration.</p><p>If every execution starts with a clean environment, the agent may need to download the same dependencies repeatedly.</p><p>For example, multiple Go projects may download many of the same modules.</p><p>A shared cache can improve performance, but a shared writable cache creates a security problem.</p><p>Imagine:</p><ol><li>Execution A modifies a shared dependency cache.</li><li>Execution B uses the modified dependency.</li><li>Execution B unknowingly builds against malicious cached content.</li></ol><p>This is called cache poisoning.</p><p>For Omega, we should initially use per-execution or per-user caches.</p><p>Later, we can introduce read-only pre-warmed caches containing verified dependencies.</p><p>For multi-tenant environments, writable caches should not be shared between unrelated users.</p><p>We should also rely on dependency integrity mechanisms such as Go module checksums and npm lockfile integrity hashes.</p><h3>8. The Complete Omega Execution Flow</h3><p>Let’s combine the decisions into one end-to-end workflow.</p><pre>                 USER REQUEST<br>                      |<br>                      v<br>                  OMEGA AGENT<br>                      |<br>                      v<br>              Identify Required Work<br>                      |<br>                      v<br>              SANDBOX MANAGER<br>                      |<br>                      v<br>              Create Container<br>                      |<br>                      v<br>             Apply Security Policy<br>                      |<br>                      v<br>              Copy Repository In<br>                      |<br>                      v<br>             Start Agent Execution<br>                      |<br>             +--------+--------+<br>             |        |        |<br>             v        v        v<br>           CPU      Memory   Process<br>           Limit     Limit    Limit<br>             |        |        |<br>             +--------+--------+<br>                      |<br>                      v<br>               Execute Commands<br>                      |<br>                      v<br>                Run Tests<br>                      |<br>                      v<br>               Generate Patch<br>                      |<br>                      v<br>              Retrieve Patch<br>                      |<br>                      v<br>               Validate Changes<br>                      |<br>                      v<br>               Human Approval<br>                      |<br>                      v<br>                Apply Patch<br>                      |<br>                      v<br>              Destroy Sandbox</pre><p>This is the execution lifecycle we want Omega to follow.</p><p>Every execution starts in a controlled environment, works on an isolated copy of the repository, and returns a reviewable result.</p><h3>9. Implementation Roadmap</h3><p>We should build this incrementally rather than trying to implement every advanced security mechanism immediately.</p><h3>Milestone 1: Basic Docker Sandbox</h3><p>Implement:</p><ul><li>Docker SDK integration in Go.</li><li>Container creation and destruction.</li><li>Non-root execution.</li><li>Dropped capabilities.</li><li>no_new_privileges.</li><li>Read-only root filesystem.</li><li>Restricted /tmp.</li><li>Memory, CPU, and PID limits.</li><li>Default seccomp profile.</li><li>Network disabled by default.</li></ul><p><strong>Deliverable:</strong> Omega can execute shell commands inside a restricted Docker container.</p><h3>Milestone 2: Workspace Isolation</h3><p>Implement:</p><ul><li>Create a workspace volume.</li><li>Copy repositories into /workspace.</li><li>Run file operations inside the container.</li><li>Execute builds and tests.</li><li>Generate Git patches.</li><li>Retrieve patches for host-side review.</li></ul><p><strong>Deliverable:</strong> Omega can modify and test a real repository without directly modifying the host’s original files.</p><h3>Milestone 3: Execution Lifecycle</h3><p>Implement:</p><ul><li>Execution timeouts.</li><li>Process termination.</li><li>stdout and stderr limits.</li><li>Exit-code reporting.</li><li>Container cleanup.</li><li>Orphan-container cleanup.</li><li>Execution IDs and Docker labels.</li><li>Resource usage tracking.</li></ul><p><strong>Deliverable:</strong> Every execution has a bounded lifetime and predictable cleanup behavior.</p><h3>Milestone 4: Controlled Networking</h3><p>Implement:</p><ul><li>Egress proxy.</li><li>Domain allowlisting.</li><li>DNS restrictions.</li><li>Request logging.</li><li>Network access policies.</li></ul><p><strong>Deliverable:</strong> Omega can access approved dependency registries without unrestricted network access.</p><h3>Milestone 5: Stronger Isolation</h3><p>Evaluate:</p><ul><li>Custom seccomp profiles.</li><li>AppArmor or SELinux policies.</li><li>User namespace remapping.</li><li>gVisor through runsc.</li><li>Firecracker microVMs.</li></ul><p><strong>Deliverable:</strong> A stronger isolation layer for workloads that require additional protection.</p><h3>Milestone 6: Security Testing and Observability</h3><p>Build automated tests that attempt to:</p><ul><li>Read files outside the workspace.</li><li>Modify the read-only root filesystem.</li><li>Exhaust memory.</li><li>Exhaust CPU.</li><li>Create excessive processes.</li><li>Access external networks.</li><li>Escape the workspace through symbolic links.</li><li>Escalate privileges.</li><li>Leave background processes running.</li></ul><p>Track resource usage, execution time, OOM events, throttling, exit codes, and cleanup failures.</p><p><strong>Deliverable:</strong> We can continuously verify that Omega’s sandbox is enforcing the intended security boundaries.</p><h3>10. What We Are Actually Building</h3><p>The most important architectural decision is that sandboxing should be a separate responsibility within Omega.</p><p>The agent should not need to understand Docker, Linux namespaces, cgroups, or container lifecycle management.</p><p>It should simply request an operation:</p><pre>Execute this command in my workspace.</pre><p>The Sandbox Manager handles everything else:</p><ul><li>Where the command runs.</li><li>Which files it can access.</li><li>Which permissions it receives.</li><li>How much CPU and memory it can consume.</li><li>Whether it can access the network.</li><li>How long it can execute.</li><li>How its output is captured.</li><li>How its changes are returned.</li><li>How its environment is destroyed.</li></ul><p>This gives us a clean separation between the intelligence of the agent and the security of the execution environment.</p><p>Our first version will use Docker with restricted container configuration, copy-in workspace isolation, and patch-based output.</p><p>As Omega evolves, we can replace or extend the runtime with gVisor or microVMs without fundamentally changing the agent’s interface.</p><p><strong>The end goal is simple: Omega should be powerful enough to execute arbitrary development tasks, but the environment in which it executes those tasks should have strictly limited access to everything outside it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4ae625dd793" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[sandboxing your ai agent — from first principles | Part 2]]></title>
            <link>https://medium.com/@SinghDevHub/sandboxing-your-ai-agent-from-first-principles-part-2-bf021c9f7eb3?source=rss-5e40f9f854c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf021c9f7eb3</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[SinghDevHub]]></dc:creator>
            <pubDate>Sat, 21 Nov 2026 14:46:45 GMT</pubDate>
            <atom:updated>2026-11-21T14:46:45.065Z</atom:updated>
            <content:encoded><![CDATA[<p>In our <a href="https://medium.com/@SinghDevHub/sandboxing-your-ai-agent-from-first-principles-part-1-3bb8a53a69a7">Part 1</a> of sandboxing our AI agent, I discussed the fundamentals of Linux permissions, privileges and capabilities. Here, we will continue our journey of digging more deeper and eventually arriving at Docker internals and security compiling all our discussed concepts.</p><ol><li><strong>LSM and no_new_privs</strong></li></ol><p>LSM means Linux security modules which provides security hooks in linux kernel. Three important implementations of LSM:-</p><p>AppArmor — Path-based security policies<br>SELinux — Labels-based security policies<br>Landlocked- Unprev. process can restrict their filesystem’s access</p><p>ex:- AppArmor policy can say <br>- /workspace read/write is allowed<br>- /etc/shadow access is denied</p><p>In SELinux files and process’s labels are used to control the access and Landlock is an interesting concept using which Unprivileged process also can restrict its own access. Most of the policies like for nginx, Apache, SSH comes in the distro itself but users or system admin can also write some.</p><p>1.1 no_new_privs</p><p>docker run --security-opt no-new-privileges ubuntu:24:04 , this is a kind of security flag which just means in future process can’t gain the extra privileges. in simple words, whatever permissions i give to my agent at the start it can’t run any other executable later on to gain extra privileges or even can’t give extra privs. to its child exec()</p><p>1.2 Complete security layers discussed till now</p><p>cgroups — how much one can use ?<br>namespaces — what one can see ?<br>capabilities — what powerful permissions one have ?<br>seccomp — what syscalls are allowed ?<br>LSM — what resources it can access ?<br>no_new_privs — if one can increase the privileges in future ?<br>non-root — what identity its using to run ?</p><p>Let’s make our sandbox using all of these.</p><p>— — — — — — — — — — — — — — — — — — — —</p><h4><strong>2. How Docker works internally ?</strong></h4><p>Till now we have read individual concepts and mechanisms but what happens internally when docker creates a container ?</p><p><strong><em>Most important thing is container is just a normal linux process around which isolation and resources restriction has been configured.</em></strong></p><p>in other words, container is not a magical technology, it uses multiple linux features.</p><p>2.1 OCI — open container initiative</p><p>OCI defines a standard using which different containers can follow a common pattern to run. Two important specifications —</p><ul><li>Image spec: container image’s structure and layer’s format</li><li>Runtime spec: config to run the container</li></ul><p>Runtime configuration:- config.json it defines:-</p><ul><li>which command to run</li><li>which user will be used</li><li>which namespaces will be created</li><li>how much memory/cpu will it get</li><li>which mounts will be present</li><li>which seccomp profile will be used</li><li>which capabilities will be allowed</li></ul><p><strong>2.2 what is runC ?</strong></p><p>runC is an OCI runtime and its work is to prepare environment for the container and to execture the actual processes. runc performs these steps:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*PIDYFhcvP5URNqYwdCST6g.png" /><figcaption>steps that runc runs</figcaption></figure><p>The order is very important because if you drop CAP_SYS_ADMIN first and then trying to setup the mount then its impossible. That’s why required things are setuped first and then permissions are dropped.</p><p><strong>Runtime (runc) is interchangeable:-</strong></p><p>runc — Normal linux namespaces + cgroups</p><p>runsc — gVisor-based isolation</p><p>kata-runtime — Lightweight VM-based isolation</p><p>example:- HostConfig.Runtime = &quot;runsc&quot; using this configuration, docker will be asked to use gVisor runtime provided the runtime is installed and configured.</p><p><strong>2.3 Docker architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*Lw4fCT2VdCpi8_mVVlCoeQ.png" /><figcaption>different layers in a container</figcaption></figure><p>This architecture has to be understood clearly. Docker has multiple components:-</p><ol><li>Docker CLI — terminal where we run the commands docker run ubuntu CLI sends the command to docker daemon process.</li><li>dockerd — its a docker daemon process which has responsibilities:-</li></ol><ul><li>Docker API</li><li>Images</li><li>Networks</li><li>Volumes</li><li>Container management</li></ul><p>3. containerd — this handles container lifecycle and image management</p><p>4. containerd-shim — every container has a shim process and its responsibilities are:-</p><ul><li>To be a parent of the container process always</li><li>To maintain the standard input/output pipes</li><li>To collect the exit status</li></ul><p>Its benefit: even if docker daemon restarts then also running containers can continue.</p><p>5. runc — it sets up the actual container and executes the command and then exits. Remember, runc is not a supervisor.</p><p>ex:- docker run -d --name myapp ubuntu:24:04 sleep 1000</p><ul><li>run = create container and start</li><li>-d = run in background</li><li>--name = name of the container</li><li>ubuntu:24:04 = image</li><li>sleep 1000 = command executing inside the container</li></ul><p>6. docker exec — docker exec myapp ls/ this means running an command in an existing running container. on kernel level, roughly we do this:-</p><ul><li>To locate PID 1 inside the container</li><li>To join the process in its namespaces using setns()</li><li>To be placed in the same cgroup</li><li>To apply the same security restrictions</li><li>execve() is used to execute the requested command</li></ul><p>Important:- docker exec runs a new process in the existing container, it doesn’t create a new independent container. ex: docker exec myapp bash opens a shell in your existing container.</p><p>3. Host vs Container — What is shared actually ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uuyyIqMQZYG5wx4j" /><figcaption>container &amp; host layers</figcaption></figure><p>container is isolated but its not a complete independent machine.</p><p>3.1 what does container shares ?</p><p>Most important is Kernel. Host and containers uses the same Linux kernel which means:-</p><ul><li>Container run syscalls</li><li>Syscalls are being executed by the host</li><li>and if kernel has vulnerabilities then container can try to exploit that vulnerability</li></ul><p>That is why we can not say container’s security as a perfect security.</p><p>3.2 What does host can do with the container?</p><p>docker top myapp — Host side view of container’s process</p><p>docker exec myapp ps aux — Process view running inside the container</p><p>nsenter --target &lt;PID&gt; --all — Host admin can enter target process’s namespace</p><p>/proc/&lt;PID&gt;/root/ gives you a path to inspect the root filesystem of a specific running process on a Linux host.</p><p>Key Lesson:- Sandbox protects the host from the untrusted code but sandbox is not designed to protect from the host root.</p><p>3.3 The 10 important paths of container escape</p><ol><li>Dangerous bind mounts — exposing host’s sensitive files in the container</li><li>Docker socket — giving access of docker api to the container</li><li>Privileged container — Removing almost all the restrictions</li><li>Host PID namespace — Making host’s processes visible</li><li>Host network — Sharing host’s network stack</li><li>Host IPC — Exposing the host’s IPC resources</li><li>Extra capabilities — Allowing unnecessary powerful operations</li><li>Device access — Exposing hardware/kernel interfaces</li><li>Kernel vulnerabilities — Having shared kernel’s bug exploited</li><li>Environment secrets — Exposing API keys or credentials</li></ol><p>lets understand the important ones:-</p><p>Risk 1:- Bind mounts — docker run -v /:/host ubuntu:24.04 using this host’s complete filesystem can get exposed inside the container</p><p>Risk 2:- Docker socket — /var/run/docker.sock this is the Docker daemon’s control interface and if container gets this socket then he can use docker API calls to create highly privileged containers. That’s why docker socket access is effectively host-root-equivalent access.</p><p>Risk 3:- Privileged mode:- docker run --privileged ubuntu:24.04 it gives additional permissions and devices access to the container. This should never be run in the real sandbox.</p><p>Risk 4:- Host PID namespace:- docker run --pid=host ubuntu:24.04 it shares the host process’s namespace to the container</p><p>Risk 5:- Host networking:- docker run --network=host ubuntu:24.04 it shares the host network’s namespace to the container and using these things normal network isolation is out.</p><p><strong>4. Docker Desktop on mac</strong></p><p>On mac, containers do not directly run on the macOS kernel. Docker desktop runs a Linux VM on the OS and then containers are feasible.</p><pre>macOS -&gt; Docker Desktop -&gt; Linux VM -&gt; Docker containers</pre><p>Which means, inside the container linux kernel operations are actually executed using linux VM kernel. Even if container is compromised or escaped then the attacker would reach the Linux VM not to macOS kernel directly. But if you mount mac filesystem to the LinuxVM then it can be accessible by the attacker.</p><p>So, in macos Docker naturally adds one more layer of security i.e. Linux VMs but whatever host directories you mount are still exposed to that VM and its containers.</p><p>— — — — — — — — — — — —</p><h4>Handling AI Agent’s workspace safely</h4><p>suppose we say “fix the bug in my Go repository” and AI agent have to do this in the repository:-</p><ul><li>Reading the files</li><li>Modifying the files</li><li>run go build</li><li>run go test</li></ul><p>Question is:- How we will transfer the repository to the sandbox and how to get changes safely ? lets see 3 approaches:-</p><p><strong>Strategy A: Bind Mount</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rIb1JISXYliWopsJ" /><figcaption>giving and taking files back from sandbox</figcaption></figure><p>docker run -v /Users/user/project:/workspace ubuntu:24.04 using this Host’s repository is directly visible in the container.</p><p>Advantages:-</p><ul><li>Do not need to copy</li><li>Changes are instantly visible on the host</li><li>Start is fast</li></ul><p>Disadvantages:-</p><ul><li>Agent can modify the real files</li><li>rm -rf /workspace can delete the actual repository</li><li>Can create malicious symlinks</li><li>Filesystem performance can be slow on your mac</li></ul><p><strong>Symlink attack:- most important to know !!</strong></p><p>ln -s /Users/user/.ssh/id_ed25519 /workspace/notes.txt using this a symbolic link would be created in the workspace. Now, if host side file reading tool opens notes.txt it can read SSH private key.</p><p>Now, problem here was not the sandbox escape, it is because of host side tool’s symlink. that’s why host side file ops should be handled carefully.</p><p>Three important security functions:-</p><p>filepath.EvalSymlinks(path) — resolves symlinks</p><p>openat(dirfd, path, O_NOFOLLOW) — prevents following the symlink</p><p>openat2(dirfd, path, RESOLVE_BENEATH) — provides stricter mechanism to operate under the specific directory and restricts it heavily</p><p>Best approach:- Execute the file tools in the sandbox so that symlinks resolves under the container’s filesystem context.</p><p><strong>Strategy B:- Copy in Copy out</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YVHFo3_Adr5vlXGH" /><figcaption>copy in copy out</figcaption></figure><p>In this mechanism, Host’s repository’s copy goes inside the sandbox and agent works on that copy and original repository remains untouched.</p><p>Commands:-</p><p>docker create --name cptest -v /workspace ubuntu:24.04 sleep 1000 — creates the container but do not start immediately</p><p>docker cp ./some-repo/. cptest:/workspace — Copies the files from the host to the container</p><p>docker start cptest — starts the container</p><p>docker exec cptest ls /workspace — lists the files in the workspace</p><p>docker cp cptest:/workspace/README.md ./out.md — copies the files from the container to the host</p><p>docker rm -f cptest — removes the container</p><p><strong>Docker archive API</strong></p><p>docker cp internally uses docker engine archive API and two important endpoints:-</p><p>PUT /containers/{id}/archive?path=/workspace — uploads files into the container</p><p>GET /containers/{id}/archive?path=/workspace — downloads the files from the container</p><p>Data transfer occurs in the tar format and one important detail is docker archive API works with filesystem layers and volumes but do not access tmpfs mounts.</p><p><strong>Copy-out security risk</strong> — Untrusted tar archive is dangerous to extract on the host, ex: ../../.bashrc this path target can try to write outside of the target directory. this is called path traversal and has other risks:-</p><ul><li>Malicious symlinks</li><li>Hard links</li><li>Device nodes</li><li>setuid permissions</li><li>Zip bombs/size bombs</li></ul><p><strong>Conclusion:-</strong> The code inside the sandbox is not trusted and hence the output of the sandbox cant be extracted out blindly.</p><p><strong>Strategy C: Overlay snapshot</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6RTF3O5TzH9ZSskP" /><figcaption>union fs overview</figcaption></figure><p>This is an elegant solution:-</p><pre>lowerdir = Original repository (read-only)<br>upperdir = changes of the Agent (read-write)<br>merged   = visible workspace to the Agent</pre><p>Agent sees normal writeable repository but actual repository doesnt get modified and all changes goes in the upper dir.</p><p>Advantages:-</p><ul><li>Original repository safe</li><li>Agent’s changes isolated</li><li>can track new/modified/deleted files</li></ul><p>Disadvantages:-</p><ul><li>overlay mount setup has to be managed ourselves</li></ul><p><strong>Strategy D:- Copy in — Patch out</strong></p><p>This is the recommended approach and is an hybrid strategy.</p><p>Workflow:-</p><pre>1. Repository copy into sandbox<br>2. Agent modifies files<br>3. Agent builds and tests<br>4. Generate Git patch<br>5. Pull patch out<br>6. Human reviews changes<br>7. Apply patch on host</pre><p>Important commands:-</p><p>git diff --binary &gt; /tmp/changes.patch saves the current uncommited changes into the patch file</p><p>git format-patch converts the git commits into email-style patch files</p><p>git apply --check changes.patch checks if patch can be applied or not</p><p>git apply changes.patch applying the patch to the actual repository</p><p><strong>Why Patch is better?</strong></p><p>suppose your agent modified 3 files and added 40 lines of code and you can view human readable diff and apply the changes after you approve. This is better than blind extraction.</p><p>But patch is automatically not safe, /.git/hooks, Makefile , CI files and scripts should be reviewed.</p><p><strong>Caches — Performance vs Security</strong></p><p>Everytime in the sandbox running go mod download or npm install will slow down the sandbox. That’s why the idea of cache sharing comes but writeable shared cache has cache poisoning risk.</p><p>Example:-</p><ul><li>Run 1 writes malicious code in the shared cache</li><li>Run 2 consumes other user’s project from that package</li></ul><p>Solution:-</p><ul><li>Read-only shared cache</li><li>per-user/per-tenant cache</li><li>Go go.sum and npm lockfile integrity checks</li></ul><p><strong>Final concusion for omega build (our ai agent):-</strong></p><ul><li>Copy the repository in the sandbox</li><li>Run the file ops in the sandbox</li><li>generate the path from the agent</li><li>on host, apply the patch after the review</li></ul><p>Part 3 would be our final part on sharing networking, using gVisor and our approach to build the sandbox.</p><p><strong>Chio !!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf021c9f7eb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[sandboxing your ai agent — from first principles | Part 1]]></title>
            <link>https://medium.com/@SinghDevHub/sandboxing-your-ai-agent-from-first-principles-part-1-3bb8a53a69a7?source=rss-5e40f9f854c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bb8a53a69a7</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[build-your-own-claude]]></category>
            <category><![CDATA[ai-engineering-skills]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <dc:creator><![CDATA[SinghDevHub]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 19:55:32 GMT</pubDate>
            <atom:updated>2026-11-07T19:55:32.065Z</atom:updated>
            <content:encoded><![CDATA[<h3>No BS:-</h3><p>straight to the point:- so when we give the permissions to the ai agent to edit, read and execute our code how you will protect your actual computer.</p><p>ex: if your ai agent is working in your go project but it mistakenly ran rm -rf / or some malicious code it ran, you are basically f****</p><p>so in a nutshell we dont want:-<br>- our computer’s files to be deleted<br>- SSH keys to be revealed to the agent<br>- our CPU, memory to be consumed by ai agent to 100%<br>- our network to be accessible to the agent using which it can access others</p><p>starting bottom to top:- below is the high level view of isolations, kernel and a process’s accessibility in an OS (linux here).</p><figure><img alt="high level picture of processes, isolation and kernel in an OS" src="https://cdn-images-1.medium.com/max/1024/0*VrnTUnKTRy2Vgp_2" /><figcaption>High level view of diff isolations</figcaption></figure><p>In Linux we have multiple layers of isolation and they are achievable using different mechanisms. Lets see the simple meanings first:-</p><p><strong>Namespaces</strong> — what a process can see?<br><strong>cgroups</strong> — how much resources one can use?<br><strong>capabilities</strong> — which powerful operations one can do?<br><strong>seccomp</strong> — which system calls one can execute?<br><strong>LSM</strong>/<strong>AppArmor</strong> — which security policies to follow?<br><strong>no_new_privs</strong> — one cant gain extra privileges going forward.<br><strong>Non</strong>-<strong>root</strong> <strong>user</strong> — one wouldn’t get default admin identity.</p><h3>Section by Section Explanation:-</h3><ol><li>Everything is shared —</li></ol><p>first of all, lets understand what a process is?<br>so, basically whenever we execute a program in the linux, it creates a process. ex:- go run main.go will result in the creation of a process.</p><p>Every process has:-</p><p><strong>Virtual memory<br>Threads<br>File descriptors<br>Process ID (PID)<br>User credentials<br>Working directory</strong></p><p>But the problem is when you run fork() or exec() even then machine has a lot of shared resources. ex:- ps aux lists the running processes and all processes:-</p><p><strong>Shares the same filesystem tree<br>Uses the same network stack<br>Shares the same hostname<br>Uses the same kernel<br>Shares the CPU and Memory pool</strong></p><p>Note:- they might think they own everything because of the abstractions of Virtual memory etc, but global resources like CPU, memory etc they share. Similarly, an ai agent is also a process and we have to put it in isolation.</p><p>Three important solutions (high level):-<br>- Private copy of resources — <strong>Namespaces</strong><br>- Limited resource usage — <strong>cgroups</strong><br>- Restricted ops — <strong>capabilities and seccomp</strong></p><p><strong>One limitation</strong>:- Normal containers do not have their independent kernel, they do use the host’s kernel and thats why we need gVisor or microVMs.</p><p>2. Users, permissions and root —</p><p>Linux doesnt care about user’s name, kernel usually use numerical IDs.<br><strong>UID &amp; GID — userid and groupid. </strong>Every file in the linux has — owner, group &amp; permission</p><p>example:- ls -l config.yaml <br>output:- -rw-r----- 1 1000 1000 config.yaml<br>meaning of -rw-r----- 1 1000 1000 config.yaml is —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*ww0SVK4Iqwzfu5Yw7jwMvg.png" /><figcaption>ls -l config.yaml</figcaption></figure><p>File &amp; Directory Permissions — <br>the meaning of permissions in file and directory is different.</p><p>r: you can list the name of the files under the directory<br>w: you can create/delete the files<br>x: you can enter and traverse in a directory</p><p>Note:- Root has UID as 0. and Root is the administrator and it can usually do anything. ex: sudo cat /etc/shadow and normal user generally cant read /etc/shadow</p><p>But if we see in permissions there is s written then it means maybe setuid is enabled which means when executing a program its effective UID could be owner’s UID.</p><p>Security risk: setuid can make an effective user as a user with owner’s permissions and if there is a malicious file using which a user can access root access and can exploit using host level permissions. That’s why no_new_privs exists which we will talk soon.</p><p>3. Capabilities — dividing root into pieces</p><p>Previously, Linux used to have almost every power but do we need all the powers to run a program ? ex: web server might need port 80 to run but it shouldn’t be using kernel to load modules right ? And thats why Linux has divided the root’s powers into small small permissions and those are called capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hL_nPeMGRPGFTqTNFeJZ3A.png" /><figcaption>capabilities &amp; their usage</figcaption></figure><p>use grep Cap /proc/self/status to check what capability information current process has and it will give you something like cap --decode=00000000a80425fb , a hexadecimal capability which you can convert using masking.</p><p><strong>Capabilities are of two types: Effective and Bounding.</strong><br>Effective:- what is the capability one can use ?<br>Bounding:- Maximum capability process can gain?</p><p>docker run --cap-drop ALL ubuntu means container which has all linux capabilities removed.</p><p>ex: If my go program is compiling the code then able to load kernel, configure network interfaces or debug other processes capabilities makes no sense for that program. So, acc. to the principle of least privileges we should only give permissions as needed.</p><p><strong>4. Filesystem — Mounts, bind mounts, chroot, pivot_root, overlayfs</strong></p><p>This section, we will understand how one container gets its separate file system?</p><p>4.1 Mounts</p><p>Linux’s file system is a single directory tree whose root is / <br>But this tree can mount different different filesystems. ex: findmnt shows the mounted filesystems on the machine. cat /proc/self/mounts shows the current process’s mount table.</p><p>Let’s look at some of the important file systems:-</p><p>ext4 — Normal disk filesystem<br>tmpfs — RAM based filesystem<br>proc — process/kernel information<br>sysfs — kernel devices and system information</p><p>Important mount options:-</p><p>ro — read only mode<br>nosuid — ignore setuid permissions <br>noexec — do not let files to be executable<br>nodev — do not let device files to be functional<br>ex: docker run --read-only ubuntu:24.04 which runs a container with root file-system as read only. Basically, we want our ai agent to run in its environment without modifying the OS files.</p><p>4.2 Bind mounts</p><p>Bind mount means making one directory to be accessible on from the different location. ex: mount --bind /home/user/project /workspace , now /workspace and /home/user/project are the same directories. This is not a copy but a kind of pointer which means if you modify at one place the other one would also be modified.<br>In docker:-</p><p>docker run -v /home/user/project:/workspace ubuntu:24.04 Left side is the host path and right side is the container path.</p><p>docker run -v /home/user/project:/workspace:ro ubuntu:24.04 Now container can read the files but can not modify them.</p><p>Security risk: If you mount a complete home folder then your ai agent can access or read your SSH files.</p><p>4.3 chroot</p><p>chroom’s full form is Change root, as name specifies, normally process’s root is / but chroot /srv/jail makes process see /srv/jail as new root than / . ex: in original filesystem /srv/jail/etc/passwd is available then after chroot it would appear as /etc/passwd .</p><p>4.4 pivot_root</p><p>This is the stronger version of chroot.<br><em>chroot:- old filesystem is still in the process’s environment.</em><br><em>pivot_root:- set a new root and move the old root to a different location and then unmount the old root.</em></p><p>So basically, container can make new filesystem as new root and can unmount the old root i.e. removing the old root filesystem from the mount table.</p><p>4.5 overlayfs — docker images magic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*PAc7r990QiEefSC6c3Jjtw.png" /><figcaption>upper lower directories concept</figcaption></figure><p>Lets suppose, you have a docker image whose size is 800MB &amp; if you want to start 100 containers then 100 copies of 800MBs has to be created. But no, Linux uses overlayFS and it has three important concepts:- Lowerdir, Upperdir and Merged.</p><p>Lowerdir — meaning original read-only image<br>Upperdir — Container’s private writable changes<br>Merged — filsystem visible to the container which combines both of the above</p><p>Lets understand this thing:- <br>Image — clean template<br>Upperdir — your changes<br>Merged — both world’s combined view</p><p>These are the four important ops being run:-<br>1. Read: First upperdir has been checked and then lower one<br>2. Modify: Lowerdir has been copied into the upperdir and its called copy-up<br>3. Create: New file directly goes into upperdir<br>4. Delete: Lowerdir files cant be deleted physically, overlayFS creates a whiteout marker instead</p><p>docker diff &lt;containers&gt; tells what are the changes carried out in the container’s file system. In output:- A = Added, C = Changed, D = Deleted</p><p>docker inspect -f &#39;{{json .GraphDriver.Data}}&#39; &lt;container&gt; inspects information in clasic docker overlay2 driver’s lower and upperdir.</p><p>Conclusion: if i create 10 containers from a fixed ubuntu image, all of them will use same image layer as read-only and each container’s changes will go into their separate upperdirs. And if i delete the container, then the changes of that container would also get deleted and original image will still be safe.</p><p>4.6 tmpfs — RAM-backed filesystem</p><p>docker run --tmpfs /tmp:size=64m ubuntu:24.04 means /tmp would be writeable, maximum size would be 64MB, temp data would be deleted on container stoppage, memory usage of that container would be counted in its memory budget.<br>use case:- temporary build files, caches and scratch data.</p><p>4.7 Recommended sandboxed filesystem</p><pre>/             Read-only root filesystem<br>/workspace    Actual project, writable<br>/tmp          Temporary RAM storage<br>/home/agent   Writable temporary home<br>/proc         Restricted process information<br>/sys          Read-only system information<br>/dev          Minimal devices</pre><p>This layout makes sure that agent would be making changes in its designated workspace.</p><p>5. Namespaces — What a process can see?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9WTufXpYJF8NIwTJJkimw.png" /><figcaption>namespace explanation</figcaption></figure><p>Namespace’s literal meaning is giving a process, a private view of global resources.</p><p>clone() — create a new process optionally with new namespaces<br>unshare() — move current process to a new namespace<br>setns() — joining in some existing namespace</p><p>ls -l /proc/self/ns will show current process’s namespaces and identities and lsns will show the list of the machine’s namespaces. ex: if two processes have same net namespace number then it means they would be sharing same nework namespace. Namespaces are of 8 types:-</p><ol><li>Mount namespace — CLONE_NEWNS</li></ol><p>it provides a different mount table. ex: inside container /workspace if we change the mount it will not change host’s mount table.</p><p>2. PID namespace — CLONE_NEWPID</p><p>It isolates the process IDs. A process’s ID on host could be 48213 but inside the container it can be 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6dSKStVIN3WBGlMXhOj5g.png" /><figcaption>PIDs isolation using namespaces</figcaption></figure><p>Important: inside the namespace, first process gets PID 1 and PID 1 responsibilities are:-</p><ul><li>Adopting the orphan processes</li><li>reaping the child processes by using wait()</li><li>handling the signals</li></ul><p>If zombie processes are not cleaned then they could accumulate. That’s why in docker docker run --init ubuntu:24.04 runs a small init process, usually tini , runs on PID 1 and it helps in reaping the orphan processes.</p><p>3. Network namespace — CLONE_NEWNET</p><p>It provides a different network stack with:-<br>- different IP addresses<br>- different network interfaces<br>- different routing tables (Based on the destination IP address of this packet, which interface should I send it out of, and who is the next gateway hop?)<br>- different ports</p><p>interestingly, 50 containers can use port 8080 in their network namespaces without any conflict.</p><p>4. UTS namespace — CLONE_NEWUTS</p><p>it isolates the hostname and NIS domain name.</p><pre>unshare --uts bash<br>hostname sandbox<br>hostname</pre><p>5. IPC namespace — CLONE_NEWIPC</p><p>it isolates the inter-process communication objects like Shared memory, Semaphore and Message queues which means container can not access IPC objects of the host freely.</p><p>6. User namespace — CLONE_NEWUSER</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8-1KE2TZDnqZm6Ub" /></figure><p>Let’s say container’s inner process has UID 0 which means he is the root inside the container but in host its UID could be 10000. <br>example mapping:-</p><pre>Container UID 0  → Host UID 100000<br>Container UID 1  → Host UID 100001<br>Container UID 2  → Host UID 100002</pre><p>basically, in container the process get root alike experience but is an unprivileged user on the host.</p><p>7. cgroup namespaces — CLONE_NEWCGROUP</p><p>this provides a restricted view of the cgroup tree in the container.</p><p>8. Time namespace — CLONE_NEWTIME</p><p>It isolates certain monotonic and boot-time clocks offsets.</p><h4><strong>What does namespaces doesn’t do ?</strong></h4><ul><li>doesn’t limit the CPU limit</li><li>doesn’t limit the memory</li><li>doesn’t block dangerous syscalls automatically</li><li>doesn’t provide a separate kernel</li></ul><p>So, namespaces decides what a process can see, but can’t decide how much resources it can consume or what it can request to the kernel</p><p>6. cgroups — How much resources a process can use ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yv1M_DcEJFbjZFa1" /><figcaption>cgroups usage</figcaption></figure><p>cgroups are control groups which controls how much resources a process can consume. ex:- if we give our AI agent a 512MB of memory with 1 CPU then we have to enforce the limits in the cgroups. It doesnt control one process but controls a whole group of the process including its child processes which shares the same budget.</p><p>cgroup v2 — instead of making everyone’s different hierarchy like cgroups old ones, this v2 makes a unified hierarchy like:-</p><pre>Location - /sys/fs/cgroup/<br><br>Inside container - <br><br>cat /sys/fs/cgroup/memory.max - maximum memory<br>cat /sys/fs/cgroup/memory.current - current memory usage<br>cat /sys/fs/cgroup/cpu.max - cpu quota<br>cat /sys/fs/cgroup/pids.max - maximum tasks</pre><p>6.1 Memory controller</p><p>ex:- docker run --memory=512m ubuntu:24.04 means container can use maximum of 512MB of memory. OOM (out of memory) errors you will see if resources usage is out of control like:-</p><pre>docker run --name oomtest \<br>  --memory=64m \<br>  --memory-swap=64m \<br>  python:3.12-slim \<br>  python -c &quot;x = bytearray(200 * 1024 * 1024)&quot;</pre><p>This will try to allocate 200MB of memory given 64MB is the limit.</p><p>6.2 CPU controller</p><p>ex: docker run --cpus=1 ubuntu:24.04 means container would get one maximum equivalent CPU time. Now, lets assume agent has used its CPU quota and then kernel wouldn’t schedule that process again and this is called CPU throttling. cat /sys/fs/cgroup/cpu.stat will give you nr_throttled and throttled_usec</p><p>6.3 PIDs controller</p><p>ex: docker run --pids-limit=128 ubuntu:24.04 means container can create maximum 128 tasks and in Linux threads are also counted and this protects the process (agent in our case) from fork bomb.</p><p>fork bomb:- :(){ :|:&amp; };: recursively keep on spawning new processes and without limits the machine could go unresponsive.</p><p>6.10 IO controller</p><ul><li>io.max — Disk write/read bandwidth or IOPS’s maximum limit</li><li>io.weight — relative priority when Disk contention occurs</li></ul><p>ex use case: some malicious ai agent run might make disk so busy that other users workloads will become too slow.</p><p>6.5 What cgroups do not limit?</p><pre>-----------------------------------------------------------<br>Resource                  | Alternative control            |<br>--------------------------| -------------------------------<br>Disk space                | Filesystem quota / bounded volume<br>Wall-clock execution time | Go context.WithTimeout<br>Captured stdout/stderr    | Application-level output cap<br>Open file descriptors     | ulimit / RLIMIT_NOFILE<br>-----------------------------------------------------------</pre><p>ex: ulimit -n shows the maximum file descriptors limit. in docker we use--ulimit nofile=1024:1024</p><p>7. seccomp — which system calls are allowed ?</p><p>As you know user program can not access the kernel memory directly and to talk with kernel he has to use system calls. ex: openat(), read(), write(), execve(), clone(), mount() . Every system call executes some kernel code, if kernel has some vulnerabilities then syscall can trigger that part and exploit it.</p><p>That’s why seccomp’s purpose is to make sure Process has certain selected system calls allowed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/0*745uam2D0_QvRL-f" /><figcaption>seccomp BPF program filtering</figcaption></figure><pre>-----------------------------------------------------------------<br>Action                    | Meaning                              |<br>--------------------------| -------------------------------------<br>SECCOMP_RET_ALLOW         | Syscall allow<br>SECCOMP_RET_ERRNO         | Error return<br>SECCOMP_RET_KILL_PROCESS  | Process kill<br>SECCOMP_RET_TRAP SIGSYS   | signal<br>SECCOMP_RET_USER_NOTIF    | decision taken using User-space supervisor<br>------------------------------------------------------------------</pre><p>Important properties:-</p><ol><li>Filters after getting installed, can not be removed</li><li>Child processes inherits the filters</li><li>Filter can see syscall number and argument’s raw register values</li><li>Filter can’t inspect file path string safely</li></ol><p><em>What about the last point?</em></p><p>openat(dirfd, &quot;/etc/shadow&quot;, flags); seccomp doesnt get actual path’s string, it gets memory pointer and that memory can be changed by some different thread and this problem is called TOCTOU race. That is why to restrict the filepaths filesystem mounts or LSMs are being used, not seccomps.</p><p><strong>Docker default seccomp</strong></p><p>docker applies the default profile and its a allowlist approach:- selected syscalls allowed and dangerous calls block. examples of restricted sys calls:-</p><pre>-----------------------------------------------------------------<br>SysCall                   | Purpose                              |<br>--------------------------| -------------------------------------<br>mount                     | Filesystem mount<br>umount2                   | Unmount<br>reboot                    | System reboot<br>init_module               | Kernel module load<br>delete_module             | Kernel module remove<br>keyctl                    | Kernel keyring access<br>bpf                       | BPF operations<br>ptrace                    | Process tracing/debugging<br>kexec_load                | New kernel load<br>------------------------------------------------------------------</pre><p>Note:-</p><ol><li>Docker’s default seccomp profile shouldn’t be disabled without a strong reason.</li><li>Capabilities decides what powers a process can have, seccomp decides what operations a process can use in the kernel. Both are different security layers</li></ol><p>In the next part we would look at sections like LSM, no_new_privs, Docker internal working, OCI, Docker architecture and much more….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bb8a53a69a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Unix-Style Process Pipeline in C++]]></title>
            <link>https://medium.com/@SinghDevHub/creating-a-unix-style-process-pipeline-in-c-1196163f4a16?source=rss-5e40f9f854c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1196163f4a16</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[unix]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[SinghDevHub]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 12:18:41 GMT</pubDate>
            <atom:updated>2024-04-28T12:18:41.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4tMFh6GNL_LgNoRXhHIh-A.png" /><figcaption>Interprocess communication using Pipes</figcaption></figure><h3><strong>Processes communication</strong></h3><p>Whenever we run a program or a set of instructions that program becomes a process right? But aren’t processes runs in an isolated environment? Yes, processes usually runs in an isolated environment after the resources allocation.</p><p>But what if one process needs to communicate with any other running process? How they can do it? One of the way is using pipes. I am sure that you must have seen commands like cat main.txt | grep hello which gives us all the lines having a hello word in it. But what exactly | mean here?</p><p>It means that output of cat main.txt will be redirected to the input of grep hello process. But do you know that implementation of Pipes is really simple yet very interesting.</p><p>Today we will be implementing exactly that in C++ using system calls from which you can learn a lot.</p><h3>System Calls</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Is9SZtmofqsv3esr.png" /><figcaption>source:- GeeksForGeeks</figcaption></figure><p>There are two modes:- User &amp; Kernel mode. Whenever we run our applications they usually runs in user mode and don’t have direct access to the Hardware. To get access to the resources one needs to switch to kernel mode.</p><p>This is where System calls like mkdir(), getcwd() comes into the picture which runs in the kernel mode and can give us the underlying resource’s details. System calls are provided via System call interface to the user’s applications. And today we will be using system calls which are the lowest calls possible to invoke from a user’s application running inside user mode.</p><h3>stdin, stdout, stderr</h3><p>In unix-like OS like Linux, MacOS, We have streams like input stream (stdin), output stream (stdout) and error stream (stderr). By default terminal is connected to stdout which prints any data on the stream.</p><p>Standard streams can be represented by file descriptors. <br>for ex: file descriptor value 0 is for stdin, 1 for stdout, 2 for stderr. Now, we will be writing a program which will simulate cat main.cpp | grep hello behaviour.</p><h3>Implementation</h3><pre>#include &lt;iostream&gt;<br>#include &lt;unistd.h&gt;<br><br>void pipeline(const char* process1, const char* process2) {<br>    int fd[2];<br>    pipe(fd);<br>    if (fork() != 0) { // parent process<br>        close(fd[0]); // Close the read end of the pipe<br>        dup2(fd[1], STDOUT_FILENO); // Redirect standard output to the write end of the pipe<br>        close(fd[1]); // Close the write end of the pipe<br><br>        // Execute process1<br>        execlp(&quot;/bin/cat&quot;, &quot;cat&quot;, &quot;main.cpp&quot;, nullptr);<br>        std::cerr &lt;&lt; &quot;Failed to execute &quot; &lt;&lt; process1 &lt;&lt; std::endl;<br>    } else {<br>        close(fd[1]); // Close the write end of the pipe<br>        dup2(fd[0], STDIN_FILENO); // Redirect standard input to the read end of the pipe<br>        close(fd[0]); // Close the read end of the pipe<br><br>        // Execute process2<br>        execlp(&quot;/usr/bin/grep&quot;, &quot;grep&quot;, &quot;hello&quot;, nullptr);<br>        std::cerr &lt;&lt; &quot;Failed to execute &quot; &lt;&lt; process2 &lt;&lt; std::endl;<br>    }<br>}<br><br>int main() {<br>    pipeline(&quot;cat main.cpp&quot;, &quot;grep hello&quot;);<br>    return 0;<br>}</pre><p><strong>Let’s go through the code (via visualisation):-</strong></p><ul><li>We have a pipeline(char* process1, char* process2)function which accepts arguments as process to run.</li><li>Although, we didn’t use process1 and process2 but they are passed if you want to make pipeline() function generic. Apart from running hard coded commands like cat main.cpp</li><li>We create array with 2 file descriptors to represent stdin and stdout</li><li>we then pipe(fd) which will attach file descriptors to the pipe as:-</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fa5yMy8ZtpmLcujDItId1Q.png" /><figcaption>refer to fd[1] and fd[0] connections only as of now</figcaption></figure><ul><li>Now we have two processes after fork(). fork()!=0 means parent process but otherwise it is the child process.</li><li>After the fork child will have the same exact snapshot of the parent which means same file descriptors child have.</li><li>Now, when running the parent, it is closing fd[0], the read end of the pipe which is not needed for running cat main.cpp as we dont want to print this to the terminal or anywhere yet</li><li>after that fd[1] is referenced to stdout which means any program ran by parent process will be sent to stdout (fd[1])</li><li>After this we close the fd[1] and run cat main.cpp which produces its output to write end of the pipe</li><li>After this in child process which closes the write end of the pipe (fd[1]) as it doesn’t need any write end</li><li>Then it reads from the stdin which is referenced from fd[0] read end of the pipe via dup() system call</li><li>as fd[0] ← → fd[1] are connected thus output of fd[1] (stdout) from cat main.cpp goes in the input of grep hello fd[0] (stdin) and thus finally output of execlp(&quot;usr/bin/grep&quot;, &quot;grep&quot;, &quot;hello&quot;, nullptr) goes to stdout which is no more referenced to fd[1], and thus it prints the results to the terminal.</li></ul><h3>Running the program</h3><ul><li>compiling the program</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iIxzqdnaEz9CPaBpFZy5Hw.png" /><figcaption>compiling and making an executable using g++</figcaption></figure><ul><li>running the program and it prints the lines containing “hello” world</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ln6Abm-0Auzpo-ikVXl2Bw.png" /><figcaption>running the program</figcaption></figure><p><em>THANKS, I hope you learnt how system calls works and uses file descriptors, standard input-output streams.</em></p><p><strong>👏 Give us a clap and follow to motivate us more :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1196163f4a16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Python, Langchain and OpenAI API: Building a datascience service to extract any text from…]]></title>
            <link>https://blog.gopenai.com/python-langchain-and-openai-api-building-a-datascience-service-to-extract-any-text-from-6936b129feb0?source=rss-5e40f9f854c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6936b129feb0</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[SinghDevHub]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 07:27:21 GMT</pubDate>
            <atom:updated>2024-04-30T15:51:37.452Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Python, Langchain and OpenAI API: Building a datascience service to extract any text from messages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6JwZxjXJQkfcZtoM.png" /><figcaption>Our buddies for today :)</figcaption></figure><p>Today we are gonna make a micro service called <a href="https://github.com/singhdevhub-lovepreet/dsService">ds-service</a> which takes messages from our app and extract data from that message and publishes that data to kafka so that other services can consume. This service is responsible for extracting expenses from our Bank sms but can be modified in your use case also.</p><p>For ex: we got a SMS from our app to our service:-<br><em>“INR 294.99 spent on ICICI Bank Card XX7003 on 23-Apr-24 at TW Coffee Kora. Avl Lmt: INR 43,266.15. To dispute,call 18002662/SMS BLOCK 7003 to 9215676766”</em></p><p>and ds-service will categorise it to schema like below and publishes to kafka:-</p><pre>{<br>  &quot;amount&quot;: 294.99,<br>  &quot;merchant&quot;: TW Coffee Kora,<br>  &quot;currency&quot;: INR<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pTxTsq-ZQp0GqhwJN5Odg.png" /><figcaption>getting message and extracting data and producing to kafka</figcaption></figure><h3>Getting started with setting up our service in Python</h3><p><strong>Install Python 3</strong></p><p>First install Python3 and make sure you are able to run python --version or python3 --version command in your terminal, which indicates that python has been installed successfully in your system.</p><p><strong>Setup a Virtual environment</strong></p><p>We should always make an virtual environment first incase you want to work/make services in Python. Virtual environments help us in isolating dependencies installation and version management from other projects in our computer running on Python and might be using same dependencies with different versions.</p><p>Below are the commands to setup our initial setup for the project:-</p><pre>cd ~<br>cd Desktop/<br>mkdir dsService<br>cd dsService<br>python -m venv dsenv #It will create a virtual env of name dsenv<br>code . # Opens up your VS code or open this folder in any other IDE<br>source dsenv/bin/activate # activates your virtual env in the same <br># terminal session of your IDE in which you typed the command                                                    INT ✘  dsenv 🐍  10:13:40 PM   </pre><p><strong>Project directories structure</strong></p><p>We are following here a src/app directory structure where following files are made</p><pre>dsenv # our virtual env directory created by running above commands<br>src<br>|<br>--app<br>  |<br>  -- &quot;__init__.py&quot;<br>  -- &quot;config.py&quot;<br>  |<br>  service<br>  |  |<br>  |  -- &quot;Expense.py&quot;<br>  |  -- &quot;llmService.py&quot;<br>  |  -- &quot;messageService.py&quot;<br>  |<br>  utils<br>    |<br>    -- &quot;messageUtils.py&quot;<br></pre><p>Whole code can be found at this Github repo <a href="https://github.com/singhdevhub-lovepreet/dsService/tree/add/langChain">link</a>.</p><p><strong>Implementing a sample to tell our LLM model that what kind of response it needs to give (Expense.py)</strong></p><pre>from typing import Optional<br>from langchain_mistralai import ChatMistralAI<br>from langchain_core.pydantic_v1 import BaseModel, Field<br><br>class Expense(BaseModel):<br>        &quot;&quot;&quot;Information about a transaction made on any Card&quot;&quot;&quot;<br>        amount: Optional[str] = Field(title=&quot;expense&quot;, description=&quot;Expense made on the transaction&quot;)<br>        merchant: Optional[str] = Field(title=&quot;merchant&quot;, description=&quot;Marchant name whom the transaction has been made&quot;)<br>        currency: Optional[str] = Field(title=&quot;currency&quot;, description=&quot;currency of the transaction&quot;)</pre><ul><li>Here, we are defining three attributes:- amount, merchant, currency and giving description for the LLM to understand them.</li></ul><p><strong>Defining LLM service to initialize the Model and give inputs</strong></p><pre>from typing import Optional<br>import os<br>from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder<br>from langchain_core.pydantic_v1 import BaseModel, Field<br>from langchain_openai import ChatOpenAI<br>from langchain_mistralai import ChatMistralAI<br>from service.Expense import Expense<br>from langchain_core.utils.function_calling import convert_to_openai_tool<br><br>class LLMService:<br>    def __init__(self):<br>        self.prompt = ChatPromptTemplate.from_messages(<br>        [<br>            (<br>                &quot;system&quot;,<br>                &quot;You are an expert extraction algorithm. &quot;<br>                &quot;Only extract relevant information from the text. &quot;<br>                &quot;If you do not know the value of an attribute asked to extract, &quot;<br>                &quot;return null for the attribute&#39;s value.&quot;,<br>            ),<br>            (&quot;human&quot;, &quot;{text}&quot;)<br>        ]<br>        )<br>        self.apiKey = os.getenv(&#39;OPENAI_API_KEY&#39;)<br>        self.llm = ChatMistralAI(api_key=self.apiKey, model=&quot;mistral-large-latest&quot;, temperature=0)<br>        self.runnable = self.prompt | self.llm.with_structured_output(schema=Expense)<br><br>    def runLLM(self, message):<br>        return self.runnable.invoke({&quot;text&quot;:message})</pre><ul><li>Here, we are telling system first that what you are supposed to do</li><li>Then getting apiKey that you can obtain from ChatMistralAI official website after logging in and set an env variable ( export OPEN_API_KEY=ABCDEFGHIJKL )</li><li>You can use any LLM here, for ex: ChatGPT 3.5, we ChatMistralAI’s mistral-large-latest LLM</li></ul><p><strong>Implementing messages util class</strong></p><pre>import re<br><br>class MessagesUtil:<br>    def isBankSms(self, message):<br>        words_to_search = [&quot;spent&quot;, &quot;bank&quot;, &quot;card&quot;]<br>        pattern = r&#39;\b(?:&#39; + &#39;|&#39;.join(re.escape(word) for word in words_to_search) + r&#39;)\b&#39;<br>        return bool(re.search(pattern, message, flags=re.IGNORECASE))</pre><ul><li>It checks if the given message is a valid message by checking if it contains any of the words from [“spent”, “bank”, “card”].</li><li>Because sending every message to LLM and wasting our tokens doesn’t make sense. So, an extra layer of validation can be used where one can check if it is a valid SMS then categorize from the LLM.</li></ul><p><strong>Implementing our main message service:-</strong></p><pre>from utils.messagesUtil import MessagesUtil<br>from service.llmService import LLMService<br><br>class MessageService:<br>    def __init__(self):<br>        self.messageUtil = MessagesUtil()<br>        self.llmService = LLMService()<br>    <br>    def process_message(self, message):<br>        if self.messageUtil.isBankSms(message):<br>            return self.llmService.runLLM(message)<br>        else:<br>            return None</pre><p>You can run the server using flask run --debug and hit the endpoint</p><pre>curl --location &#39;http://127.0.0.1:8000/v1/ds/message&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--header &#39;Cookie: JSESSIONID=5C49870A3856D9D5D8F79EB885D7CC2E&#39; \<br>--data &#39;{<br>    &quot;message&quot;: &quot;You spent Rs.120 on ICICI bank card for starbucks coffee&quot;<br>}&#39;</pre><p>It categorised it as:-</p><pre>Expense(amount:&#39;120&#39;, currency:&#39;rs&#39;, merchant:&#39;starbucks coffee&#39;)</pre><p><strong><em>🫸🫷A clap will motivate us, A follow will boost our confidence. THANKS</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6936b129feb0" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/python-langchain-and-openai-api-building-a-datascience-service-to-extract-any-text-from-6936b129feb0">🚀 Python, Langchain and OpenAI API: Building a datascience service to extract any text from…</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Gateways: Whats and Hows with implementation]]></title>
            <link>https://medium.com/@SinghDevHub/api-gateways-whats-and-hows-with-implementation-563d9f371edb?source=rss-5e40f9f854c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/563d9f371edb</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[SinghDevHub]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 19:47:23 GMT</pubDate>
            <atom:updated>2024-04-17T19:48:09.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KCnK5qSKRHqGZIc_" /><figcaption>Photo by <a href="https://unsplash.com/@walkator?utm_source=medium&amp;utm_medium=referral">Walkator</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>✅ When we deal with micro services architecture, we often end up building some number of services and those services we run on different ports. Because we can’t use the same port multiple times in the same machine 🥲</p><p>So, When your app/website calls any service it will hit the IP address of that machine in which your service is running and will fetch the info 🥱</p><h4>Let’s see an example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cPO8403hdg0pebwAQ3wmAQ.png" /></figure><p>In this case our app wants to check if</p><ul><li>user is authenticated or logged in properly (using auth micro-service)</li><li>then it tries to fetch the user details like name, profile pic etc (from the user service)</li><li>and then it checks the payment status of the user.</li></ul><p>So, to do this app needs to call different API endpoints with base url let’s say <strong>13.127.80.110:9019/authService/checkUserAuth?userId=abna1-ak411</strong></p><p>and similarly for user service and payment service the base url will remain same (<strong>IP_address:port/api_end_point</strong>)</p><ul><li>where <strong>IP_address</strong> will be the public IP of the machine in which our service’s docker containers are running</li><li>and <strong>port</strong> is the port exposed by that docker container</li><li>and <strong>api_end_point </strong>is the endpoint specific to different services.</li></ul><h4>🚀 Isn’t this tiresome, there should be some easy way. Isn’t it</h4><p><strong>Here is where our saviour comes into the picture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*B8_xl_dZPNre03HR.jpg" /></figure><h3>API GATEWAYS, wohooo 🎉</h3><p>API gateways in simple terms are nothing but a gate that is a centralized place for all the clients to make any request to any of the service. So, clients don’t have to change the baseUrl everytime (port) or url mapping can be done inside this API Gateway only.</p><p><em>At the End, API gateway is itself a program (service) that will run in a machine (or managed by any cloud provider like AWS).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9AbMk7Mz6RGt36RfWI_rw.png" /></figure><p><strong>🚀 Before moving to API gateways functionalities and implementing it, let’s see a real world scenario that How exactly things travel….</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*omYJlf7eLsufHrg-ldzQWQ.png" /></figure><ul><li>Let’s say a client makes a request to https://<em>singhdevhub.com </em>and this request needs to have some IP address to travel to the right server</li><li>So, request goes to DNS first and in case of static files response directly comes from the CDN itself (CDN stands for content delivery network and it can serve static files effectively like images, HTML, CSS etc)</li><li>But if it is not a static file for which the request is, then it travels to the API gateway. Now this API gateway could be self managed like we showed a docker container running inside our virtual machine earlier or a managed service by any cloud provider like AWS, GCP etc</li><li>Now, API gateway has some functionality (that we’ll see further) and it redirects the request and sends the response.</li></ul><h3>😎 Now, Let’s say what API Gateway can do</h3><h4>API Traffic Management</h4><p>API gateway routes incoming requests to different services depending on the request path, query params and headers. It also allows proper distribution of the load between target endpoints.</p><h4>Protocol Translation</h4><p>It can translate protocol easily like from HTTPS to HTTP. When app is requesting our gateway it should use secure protocoal like HTTPS and our internal services which are not exposed to the outer world could be requested with HTTP only</p><h4>Caching and Load balancing</h4><p>In API Gateway itself, one can use its caching which is to cache the most accessed response and as stated before api gateway is responsible for load balancing too if one wanted.</p><h4>API security and Prevention from DDOS attacks</h4><p>API Gateways are more secure as compared to exposing all service’s apis to the outer world (from our machine point of view) as it can carry authentication validations and also it can limit the requests from a source which prevents any kind of DDOS attacks. DDOS attack stands Distributed Denial of Service, which means sending so many requests or overloading a server until it becomes unhealthy.</p><h3>📌 Implementing Kong as an API Gateway for our Auth and User Service</h3><p>Kong documentation can be found at:- <a href="https://docs.konghq.com/gateway/3.6.x/get-started/">Kong’s official site</a></p><p>We have implemented few services in Spring boot which are Auth service and User service. You can clone the master branches if interested to deploy them in docker containers as:-</p><p><a href="https://github.com/singhdevhub-lovepreet/authservice">AuthService</a>, <a href="https://github.com/singhdevhub-lovepreet/userservice">UserService</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4z25PswbDZRQeIpwtYOYQ.png" /></figure><p>What we want to do (refer to the above fig):-</p><ul><li>We want to run docker containers of our auth-service and user-service and setup their APIs in kong.</li><li>So that whenever someone calls kong (our API gateway) then kong can call user/auth service internally.</li><li><em>Note:- 9810:9810 is the port mapping, which means 9810 is the port to use in a docker network to be used by other containers and 9810 is exposed for the outer world too who wants to request this container</em></li><li>In other words it means:- (outerWorldPort:dockerNetworkPort)</li><li><em>Note:- every container like auth, user-service and kong service they by default will run under docker network like bridge network that you can see using </em><em>docker network ls</em> Containers can communicate with each other using container’s IP if they are in the same docker network (either default or a custom network made by you)</li></ul><p>✨ Now, to spin up the containers we make a docker compose file which is nothing but a config file telling docker how to spin up the container.</p><ul><li>Making a docker compose file named “expensetrackerapp.yml”</li></ul><pre>version: &#39;3&#39;<br><br>services:<br>  zookeeper:<br>    image: confluentinc/cp-zookeeper:7.4.4<br>    environment:<br>      ZOOKEEPER_CLIENT_PORT: 2181<br>      ZOOKEEPER_TICK_TIME: 2000<br>    ports:<br>      - 2181:2181<br>  <br>  kafka:<br>    image: confluentinc/cp-kafka:7.4.4<br>    depends_on:<br>      - zookeeper<br>    ports:<br>      - 9092:9092<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://13.127.99.104:9092<br>      KAFKA_LISTENERS: PLAINTEXT://:9092<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT<br>      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>  <br>  mysql:<br>    image: mysql:8.3.0<br>    container_name: mysql-8.3.0<br>    restart: always<br>    environment:<br>      MYSQL_USER: test<br>      MYSQL_ROOT_USER: root<br>      MYSQL_PASSWORD: &#39;password&#39;<br>      MYSQL_ROOT_PASSWORD: &#39;password&#39;<br>    ports:<br>      - &#39;3306:3306&#39;<br>    expose:<br>      - &#39;3306&#39;<br>    volumes:<br>      - mysql-db:/var/lib/mysql<br>  <br>  user-service:<br>    image: user-service<br>    container_name: user-service<br>    ports:<br>      - &#39;9810:9810&#39;<br>    depends_on:<br>      - kafka<br>      - mysql<br><br>  auth-service:<br>    image: auth-service<br>    container_name: auth-service<br>    ports:<br>      - &#39;9898:9898&#39;<br>    depends_on:<br>      - kafka<br>      - mysql<br><br>volumes:<br>  mysql-db:<br>    driver: local</pre><p>📍 As, our services require kafka, zookeeper and mysql so that should start first, hence `depends_on` is mentioned. Images like “ image: user-service” &amp; “ image: user-service” are built using jars (refer to the optional section below to see how to make docker images from jars).</p><p>— — — — — — — —</p><p># [Optional] How to make a Docker Image of a spring boot application</p><ul><li>Run ./gradlew clean buildwhich will build a jar in build/libs/xyz.jar that you can move to your Virtual machine (VPS) and using that jar (assuming name of the jar is xyz.jar) you can make an image</li><li>to copy from your local machine to your virtual machine you can use command like</li></ul><pre>scp -i ~/.ssh/aws_lightsail.cer /Users/lovepreetsingh/Desktop/ExpenseTracker/AuthService/app/build/libs/app.jar  ubuntu@13.127.99.104:~/</pre><ul><li>now ssh into your VM, and make a dockerfile like</li></ul><pre>FROM amazoncorretto:21-alpine-jdk<br>MAINTAINER SinghDevHub<br>COPY app.jar auth-service.jar<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;/auth-service.jar&quot;]</pre><ul><li>It will make an image of name auth-service</li></ul><p>— — — — — — — —</p><p>Now, to make a kong config we can make folder like</p><pre>docker<br>|<br>|<br>---&gt; config<br>|   |<br>|   |    <br>|   ---&gt; kong-config.yml<br>|<br>|<br>---&gt; kong-compose.yml</pre><ul><li>kong-config.yml</li></ul><pre>_format_version: &quot;2.1&quot;<br><br>services:<br>- name: auth-service<br>  url: http://172.20.0.5:9898<br>  routes:<br>  - name: sign-up<br>    paths:<br>    - /auth/v1/signup<br><br>- name: user-service<br>  url: http://172.20.0.6:9810<br>  routes:<br>    - name: get-user<br>      paths:<br>      - /user/v1/getUser</pre><ul><li>kong-compose.yml</li></ul><pre>version: &#39;3.3&#39;<br><br>services:<br>  kong:<br>    image: kong<br>    volumes:<br>      - &quot;./config:/usr/local/kong/declarative&quot;<br>    environment:<br>      KONG_DATABASE: off<br>      KONG_DECLARATIVE_CONFIG: /usr/local/kong/declarative/kong-config.yml<br>      KONG_PROXY_ACCESS_LOG: /dev/stdout<br>      KONG_ADMIN_ACCESS_LOG: /dev/stdout<br>      KONG_PROXY_ERROR_LOG: /dev/stderr<br>      KONG_ADMIN_ERROR_LOG: /dev/stderr<br>      KONG_ADMIN_LISTEN: 0.0.0.0:8001, 0.0.0.0:8444 ssl<br>      KONG_LOG_LEVEL: debug<br>      KONG_PLUGINS: bundled<br>    ports:<br>      - &quot;8005:8000/tcp&quot;<br>      - &quot;127.0.0.1:7990:8001/tcp&quot;<br>      - &quot;8443:8443/tcp&quot;<br>      - &quot;127.0.0.1:8444:8444/tcp&quot;</pre><p>Process to start docker containers and use kong:-</p><ul><li>start services using docker compose -f expensetrackerapp.yml up -d</li><li>now start kong using docker compose -f kong-compose.yml up -d</li><li>Note:- in kong-config.yml ips of user-service and auth service (say <a href="http://172.20.0.5/">http://172.20.0.5</a>) are found using docker inspect &lt;container-id&gt; | grep IPAddress</li><li>Now to hit an API you have to hit your_vm_ip:kong_port/rest_api_path</li><li>for ex:</li></ul><pre>curl --location --request GET &#39;https://13.127.99.104:8443/user/v1/getUser&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--header &#39;Cookie: JSESSIONID=32ABCDEF406GHIJKLE9C78C65EDB67&#39; \<br>--data-raw &#39;{<br>    &quot;user_id&quot;:&quot;6034a397-e502-4997-a7a4-0d1ddbd68a25&quot;,<br>    &quot;username&quot;: &quot;lovepreetsingh&quot;,<br>    &quot;password&quot;: &quot;sinagh#1123&quot;,<br>    &quot;first_name&quot;: &quot;lovepreet&quot;,<br>    &quot;phone_number&quot;: 1112233455,<br>    &quot;last_name&quot;: &quot;singh&quot;,<br>    &quot;email&quot;: &quot;abc@gmail.com&quot;<br>}&#39;</pre><p><strong><em>Here, you go. For more you can refer to our Youtube channel:- </em></strong><a href="https://www.youtube.com/@SinghDevHub"><strong><em>Link</em></strong></a><strong><em> (Language:- Hindi 🇮🇳)</em></strong></p><p>THANKS, Give a clap, and follow for more……</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=563d9f371edb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>