Reland "scripts: build_image: Disable network access"

This is a reland of commit c88eba3b61ce26a2a8cf2102997f43d2ba6964a8

Specify preserve_env so that the envvars we need get passed along for
re-execution.

Original change's description:
> scripts: build_image: Disable network access
>
> Call ReExecuteWithNamespace for build_image to disable network access
> by enabling the network namespace as the root user.
>
> BUG=b:233635037
> TEST=CQ
>
> Cq-Depend: chromium:3710502
> Change-Id: I60db80499fa4341782e1a3916dfa6cbd87b08394
> Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/chromite/+/3836499
> Tested-by: Cindy Lin <xcl@google.com>
> Commit-Queue: Cindy Lin <xcl@google.com>
> Reviewed-by: Mike Frysinger <vapier@chromium.org>

BUG=b:233635037
TEST=cros tryjob {release,full,factory}, manual verification of envvars, CQ

Cq-Depend: chromium:3880985
Change-Id: Id6a61fed57429c3e4f50a86adbfebcbe71ca3500
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/chromite/+/3869174
Tested-by: Cindy Lin <xcl@google.com>
Reviewed-by: Ram Chandrasekar <rchandrasekar@google.com>
Commit-Queue: Cindy Lin <xcl@google.com>
diff --git a/scripts/build_api.py b/scripts/build_api.py
index e292c58..70e8a4e 100644
--- a/scripts/build_api.py
+++ b/scripts/build_api.py
@@ -15,6 +15,7 @@
 from chromite.api.gen.chromite.api import build_api_config_pb2
 from chromite.lib import commandline
 from chromite.lib import cros_build_lib
+from chromite.lib import namespaces
 from chromite.utils import matching
 
 
@@ -164,6 +165,13 @@
     router = router_lib.GetRouter()
     opts = _ParseArgs(argv, router)
 
+    # For build_image, make sure we run with network disabled to prevent leakage.
+    if (
+        cros_build_lib.IsInsideChroot()
+        and opts.service_method == "chromite.api.ImageService/Create"
+    ):
+        namespaces.ReExecuteWithNamespace(sys.argv, preserve_env=True)
+
     # We currently don't have any APIs that want to access stdin, so rebind.
     sys.stdin = open(os.devnull, "r")  # pylint: disable=consider-using-with
     os.dup2(sys.stdin.fileno(), 0)