Make http_archive honor $HOME/.netrc

For http_archive and related rules, if no netrc file is specified,
but a file "$HOME/.netrc" exists (on non-Windows systems), read this
file to allow implicit authentication, the same way other programs
for downloading handle it.

Change-Id: I336421ad49ed75c673d1c78fd0575ddc78812064
PiperOrigin-RevId: 256677554
diff --git a/src/test/shell/bazel/skylark_repository_test.sh b/src/test/shell/bazel/skylark_repository_test.sh
index 2fd1ee3..bf4bc0e 100755
--- a/src/test/shell/bazel/skylark_repository_test.sh
+++ b/src/test/shell/bazel/skylark_repository_test.sh
@@ -1692,4 +1692,39 @@
       || fail "Expected success despite needing a file behind basic auth"
 }
 
+function test_implicit_netrc() {
+  mkdir x
+  echo 'exports_files(["file.txt"])' > x/BUILD
+  echo 'Hello World' > x/file.txt
+  tar cvf x.tar x
+  serve_file_auth x.tar
+
+  export HOME=`pwd`
+  cat > .netrc <<'EOF'
+machine 127.0.0.1
+login foo
+password bar
+EOF
+
+  mkdir main
+  cd main
+  cat > WORKSPACE <<EOF
+load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
+http_archive(
+  name="ext",
+  url = "http://127.0.0.1:$nc_port/x.tar",
+)
+EOF
+  cat > BUILD <<'EOF'
+genrule(
+  name = "it",
+  srcs = ["@ext//x:file.txt"],
+  outs = ["it.txt"],
+  cmd = "cp $< $@",
+)
+EOF
+  bazel build //:it \
+      || fail "Expected success despite needing a file behind basic auth"
+}
+
 run_suite "local repository tests"
diff --git a/tools/build_defs/repo/http.bzl b/tools/build_defs/repo/http.bzl
index 61df5ba..1d3d020 100644
--- a/tools/build_defs/repo/http.bzl
+++ b/tools/build_defs/repo/http.bzl
@@ -45,7 +45,15 @@
         netrc = read_netrc(ctx, ctx.attr.netrc)
         return use_netrc(netrc, urls)
 
-    # TODO: use ~/.netrc instead, if it exists and is readable
+    if "HOME" in ctx.os.environ:
+        if not ctx.os.name.startswith("windows"):
+            netrcfile = "%s/.netrc" % (ctx.os.environ["HOME"],)
+            if ctx.execute(["test", "-f", netrcfile]).return_code == 0:
+                netrc = read_netrc(ctx, netrcfile)
+                return use_netrc(netrc, urls)
+
+        # TODO: Search at a similarly canonical place for Windows as well
+
     return {}
 
 def _http_archive_impl(ctx):