lib: Fix the function for getting SA token

The script is run as root so by default it
can't use user credentials when building
locally. Using folder name in /home to
find username to use. By default, there's
only one folder in /home inside chroot.

BUG=b/322380986
TEST=presubmit
RELEASE_NOTE=None

Change-Id: I612f3f49c4082206b85d5ad65ce3469bf24edccf
diff --git a/lib/gs.py b/lib/gs.py
index 3fd2fc9..f6f1545 100644
--- a/lib/gs.py
+++ b/lib/gs.py
@@ -1814,14 +1814,39 @@
         """
         with open(self._PRIVATE_SA_NAME_FILE, "r", encoding="utf-8") as file:
             mirror_sa = file.read()
-
-        # Cannot run with "check=True" because it will firstly assume running in
-        # a GCE VM. If building locally, the command will erorr out with
-        # "check=True" though developers can impersonate the service account.
-        result = subprocess.run([self._MIRROR_SA_TOKEN_BIN, "-sa", mirror_sa])
-        if result.stderr:
-            raise GSContextException(
-                f"failed to get private mirror SA token, err: {result.stderr}"
+        try:
+            result = subprocess.run(
+                [self._MIRROR_SA_TOKEN_BIN, "-sa", mirror_sa],
+                capture_output=True,
+                text=True,
+                check=True,
+            )
+        except subprocess.CalledProcessError:
+            # Running as root only works in GCE VMs.
+            # Need to use user credential when running locally.
+            home_dir = "/home"
+            folders = [
+                name
+                for name in os.listdir(home_dir)
+                if os.path.isdir(os.path.join(home_dir, name))
+            ]
+            user = folders[0]
+            print(
+                f"Using credentials of user '{user}' to "
+                "fetch service account token."
+            )
+            result = subprocess.run(
+                [
+                    "sudo",
+                    "-u",
+                    user,
+                    self._MIRROR_SA_TOKEN_BIN,
+                    "-sa",
+                    mirror_sa,
+                ],
+                capture_output=True,
+                text=True,
+                check=True,
             )
         return result.stdout