You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@buildstream.apache.org by ak...@apache.org on 2023/10/19 15:28:35 UTC
[buildstream-plugins] 01/01: cargo: add support for authentication using .netrc
This is an automated email from the ASF dual-hosted git repository.
akitouni pushed a commit to branch abderrahim/cargo-netrc
in repository https://gitbox.apache.org/repos/asf/buildstream-plugins.git
commit 23bcd437988e066e169f7c840d41d56a3969a63b
Author: Abderrahim Kitouni <ab...@codethink.co.uk>
AuthorDate: Thu Oct 19 16:26:06 2023 +0100
cargo: add support for authentication using .netrc
This copies some code from downloadablefilesource.py in buildstream
---
src/buildstream_plugins/sources/_utils.py | 114 ++++++++++++++++++++++++++++++
src/buildstream_plugins/sources/cargo.py | 88 +++++++----------------
2 files changed, 140 insertions(+), 62 deletions(-)
diff --git a/src/buildstream_plugins/sources/_utils.py b/src/buildstream_plugins/sources/_utils.py
new file mode 100644
index 0000000..ea8ab77
--- /dev/null
+++ b/src/buildstream_plugins/sources/_utils.py
@@ -0,0 +1,114 @@
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+#
+# Mostly copied from downloadablefilesource.py in buildstream.
+#
+
+import contextlib
+import shutil
+import os
+import netrc
+import urllib.parse
+import urllib.request
+import urllib.error
+
+class _NetrcPasswordManager:
+ def __init__(self, netrc_config):
+ self.netrc = netrc_config
+
+ def add_password(self, realm, uri, user, passwd):
+ pass
+
+ def find_user_password(self, realm, authuri):
+ if not self.netrc:
+ return None, None
+ parts = urllib.parse.urlsplit(authuri)
+ entry = self.netrc.authenticators(parts.hostname)
+ if not entry:
+ return None, None
+ else:
+ login, _, password = entry
+ return login, password
+
+def _parse_netrc():
+ netrc_config = None
+ try:
+ netrc_config = netrc.netrc()
+ except (OSError, netrc.NetrcParseError):
+ # If the .netrc file was not found, FileNotFoundError will be
+ # raised, but OSError will be raised directly by the netrc package
+ # in the case that $HOME is not set.
+ #
+ # This will catch both cases.
+ pass
+
+ return netrc_config
+
+class _UrlOpenerCreator:
+ def __init__(self, netrc_config):
+ self.netrc_config = netrc_config
+
+ def get_url_opener(self):
+ if self.netrc_config:
+ netrc_pw_mgr = _NetrcPasswordManager(self.netrc_config)
+ http_auth = urllib.request.HTTPBasicAuthHandler(netrc_pw_mgr)
+ return urllib.request.build_opener(http_auth)
+ return urllib.request.build_opener()
+
+def download_file(url, etag, directory):
+ opener_creator = _UrlOpenerCreator(_parse_netrc())
+ opener = opener_creator.get_url_opener()
+ default_name = os.path.basename(url)
+ request = urllib.request.Request(url)
+ request.add_header("Accept", "*/*")
+ request.add_header("User-Agent", "BuildStream/2")
+
+ if etag is not None:
+ request.add_header("If-None-Match", etag)
+
+ try:
+ with contextlib.closing(opener.open(request)) as response:
+ info = response.info()
+
+ # some servers don't honor the 'If-None-Match' header
+ if etag and info["ETag"] == etag:
+ return None, None, None
+
+ etag = info["ETag"]
+ length = info.get("Content-Length")
+
+ filename = info.get_filename(default_name)
+ filename = os.path.basename(filename)
+ local_file = os.path.join(directory, filename)
+ with open(local_file, "wb") as dest:
+ shutil.copyfileobj(response, dest)
+
+ actual_length = dest.tell()
+ if length and actual_length < int(length):
+ raise ValueError(f"Partial file {actual_length}/{length}")
+
+ except urllib.error.HTTPError as e:
+ if e.code == 304:
+ # 304 Not Modified.
+ # Because we use etag only for matching ref, currently specified ref is what
+ # we would have downloaded.
+ return None, None, None
+
+ return None, None, str(e)
+ except (urllib.error.URLError, OSError, ValueError) as e:
+ # Note that urllib.request.Request in the try block may throw a
+ # ValueError for unknown url types, so we handle it here.
+ return None, None, str(e)
+
+ return local_file, etag, None
diff --git a/src/buildstream_plugins/sources/cargo.py b/src/buildstream_plugins/sources/cargo.py
index 09aef6f..a8e4905 100644
--- a/src/buildstream_plugins/sources/cargo.py
+++ b/src/buildstream_plugins/sources/cargo.py
@@ -60,13 +60,9 @@ See `built-in functionality doumentation
details on common configuration options for sources.
"""
-import contextlib
import json
import os.path
-import shutil
import tarfile
-import urllib.error
-import urllib.request
from urllib.parse import urljoin
# We prefer tomli that was put into standard library as tomllib
@@ -79,6 +75,8 @@ except ImportError:
from buildstream import Source, SourceFetcher, SourceError
from buildstream import utils
+from ._utils import download_file
+
# This automatically goes into .cargo/config
#
@@ -198,66 +196,32 @@ class Crate(SourceFetcher):
# (str): The sha256 checksum of the downloaded crate
#
def _download(self, url):
+ # We do not use etag in case what we have in cache is
+ # not matching ref in order to be able to recover from
+ # corrupted download.
+ if self.sha:
+ etag = self._get_etag(self.sha)
+ else:
+ etag = None
- try:
- with self.cargo.tempdir() as td:
- default_name = os.path.basename(url)
- request = urllib.request.Request(url)
- request.add_header("Accept", "*/*")
- request.add_header("User-Agent", "BuildStream/2")
-
- # We do not use etag in case what we have in cache is
- # not matching ref in order to be able to recover from
- # corrupted download.
- if self.sha:
- etag = self._get_etag(self.sha)
- if etag and self.is_cached():
- request.add_header("If-None-Match", etag)
-
- with contextlib.closing(urllib.request.urlopen(request)) as response:
- info = response.info()
-
- etag = info["ETag"] if "ETag" in info else None
-
- filename = info.get_filename(default_name)
- filename = os.path.basename(filename)
- local_file = os.path.join(td, filename)
- with open(local_file, "wb") as dest:
- shutil.copyfileobj(response, dest)
-
- # Make sure url-specific mirror dir exists.
- os.makedirs(self._get_mirror_dir(), exist_ok=True)
-
- # Store by sha256sum
- sha256 = utils.sha256sum(local_file)
- # Even if the file already exists, move the new file over.
- # In case the old file was corrupted somehow.
- os.rename(local_file, self._get_mirror_file(sha256))
-
- if etag:
- self._store_etag(sha256, etag)
- return sha256
-
- except urllib.error.HTTPError as e:
- if e.code == 304:
- # 304 Not Modified.
- # Because we use etag only for matching sha, currently specified sha is what
- # we would have downloaded.
- return self.sha
- raise SourceError(
- "{}: Error mirroring {}: {}".format(self, url, e),
- temporary=True,
- ) from e
+ with self.cargo.tempdir() as td:
+ local_file, etag, error = download_file(url, etag, td)
- except (
- urllib.error.URLError,
- urllib.error.ContentTooShortError,
- OSError,
- ) as e:
- raise SourceError(
- "{}: Error mirroring {}: {}".format(self, url, e),
- temporary=True,
- ) from e
+ if error:
+ raise SourceError("{}: Error mirroring {}: {}".format(self, url, error), temporary=True)
+
+ # Make sure url-specific mirror dir exists.
+ os.makedirs(self._get_mirror_dir(), exist_ok=True)
+
+ # Store by sha256sum
+ sha256 = utils.sha256sum(local_file)
+ # Even if the file already exists, move the new file over.
+ # In case the old file was corrupted somehow.
+ os.rename(local_file, self._get_mirror_file(sha256))
+
+ if etag:
+ self._store_etag(sha256, etag)
+ return sha256
# _get_url()
#