Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/__init__.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/_version.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/heartbeat.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/patch.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/plugin.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/tokens.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/utils.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/__init__.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/__main__.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/_version.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/actions.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/adapters.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/cli.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/client.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/config.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/device_flow.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/exceptions.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/handlers.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/panel.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/repo.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/token.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/utils.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__init__.pyAdded+12
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/__init__.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/auth_handler.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/conda_api.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/conda_token.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/condarc.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/config.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/entrypoint.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/plugins.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/repo_config.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/auth_handler.pyAdded+165
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/conda_api.pyAdded+27
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/conda_token.pyAdded+152
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/condarc.pyAdded+93
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/config.pyAdded+152
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/entrypoint.pyAdded+8
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/plugins.pyAdded+52
- data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/repo_config.pyAdded+549
- data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/__init__.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/__main__.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/cli.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__init__.pyAdded+27
- data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/__init__.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/alias.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/detect.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/microarchitecture.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/schema.cpython-313.pycAdded
- data/miniconda3/lib/python3.13/site-packages/archspec/cpu/alias.pyAdded+87
123456789101112"""This module provides conda plugins.
Since conda is not a strict dependency of `anaconda-auth`, the modules here shouldNOT be imported outside of this module. This package is declared as the plugin entrypointinside `pyproject.toml` such that it will be imported and, if conda is installed, theplugin definitions will be imported. However, if conda is not installed, no plugins areimported into the runtime.
As a result, we do not have to spread conditional imports everywhere, but we do need tobe careful that only the single top-level import of this subpackage is performed.
"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165"""Defines an auth handler to inject an Authorization header into each request.
Tokens are assumed to be installed onto a user's system via a separate CLI command.
"""
from functools import lru_cachefrom typing import Anyfrom typing import Optionalfrom urllib.parse import urlparse
from conda import CondaErrorfrom conda.plugins.types import ChannelAuthBasefrom requests import PreparedRequestfrom requests import Response
from anaconda_auth._conda import repo_configfrom anaconda_auth._conda.config import TOKEN_DOMAIN_MAPfrom anaconda_auth.config import AnacondaAuthConfigfrom anaconda_auth.exceptions import TokenNotFoundErrorfrom anaconda_auth.token import TokenInfo
URI_PREFIX = "/repo/"
class AnacondaAuthError(CondaError): """ A generic error to raise that is a subclass of CondaError so we don't trigger the unhandled exception traceback. """
class AnacondaAuthHandler(ChannelAuthBase): @staticmethod def _load_token_from_keyring(url: str) -> Optional[str]: """Attempt to load an appropriate token from the keyring.
We parse the requested URL, extract what may be an organization ID, and first attempt to load the token for that specific organization. If that fails, we then simply return the first token in the keyring (since this is in all likelihood one of the default channels ('main', 'r', etc.).
If no token can be found in the keyring, we return None, which means that the token will attempt to be read from via conda-token instead.
""" parsed_url = urlparse(url) channel_domain = parsed_url.netloc.lower() if channel_domain in TOKEN_DOMAIN_MAP: token_domain, is_unified, _ = TOKEN_DOMAIN_MAP[channel_domain] else: token_domain, is_unified = channel_domain, False
try: token_info = TokenInfo.load(token_domain) except TokenNotFoundError: # Fallback to conda-token if the token is not found in the keyring return None
# Check configuration to use unified api key, # otherwise continue and attempt to utilize repo token if api_key := token_info.api_key: if is_unified: return api_key try: config = AnacondaAuthConfig(domain=token_domain) if config.use_unified_repo_api_key: return api_key except Exception: pass
path = parsed_url.path if path.startswith(URI_PREFIX): path = path[len(URI_PREFIX) :] maybe_org, _, _ = path.partition("/")
# First we attempt to return an organization-specific token try: return token_info.get_repo_token(maybe_org) except TokenNotFoundError: pass
# Return the first one, assuming this is not an org-specific channel try: return token_info.repo_tokens[0].token except IndexError: pass
return None
@staticmethod def _load_token_via_conda_token(url: str) -> Optional[str]: domain = urlparse(url).netloc.lower() # Try to load the token via conda-token if that is installed if repo_config is not None: tokens = repo_config.token_list() for token_url, token in tokens.items(): token_netloc = urlparse(token_url).netloc if token_netloc.lower() == domain and token is not None: return token return None
@lru_cache def _load_token(self, url: str) -> Optional[str]: """Load the appropriate token based on URL matching.
First, attempts to load from the keyring. If that fails, we attempt to load the legacy repo token via conda-token.
Cached for performance.
Args: url: The URL for the request.
Returns: The token, if it can be loaded. None, otherwise.
"""
# First, we try to load the token from the keyring. If it is not found, we fall through if token := self._load_token_from_keyring(url): return token elif token := self._load_token_via_conda_token(url): return token return None
def handle_missing_token(self, response: Response, **_: Any) -> Response: """Raise a nice error message if the authentication token is missing.""" if response.status_code in {401, 403}: raise AnacondaAuthError( f"Token not found for {self.channel_name}. Please install token with " "`anaconda token install`." ) return response
def handle_invalid_token(self, response: Response, **_: Any) -> Response: """Raise a nice error message if the authentication token is invalid (not missing).""" if response.status_code in {401, 403}: raise AnacondaAuthError( f"Received authentication error ({response.status_code}) when " f"accessing {self.channel_name}. " "If your token is invalid or expired, please re-install with " "`anaconda token install`." ) return response
def __call__(self, request: PreparedRequest) -> PreparedRequest: """Inject the token as an Authorization header on each request.""" try: token = self._load_token(request.url) except Exception: # TODO(mattkram): We need to be very resilient about exceptions here for now token = None
if not token: request.register_hook("response", self.handle_missing_token) return request
request.register_hook("response", self.handle_invalid_token) config = AnacondaAuthConfig() if config.use_unified_repo_api_key: request.headers["Authorization"] = f"Bearer {token}" else: request.headers["Authorization"] = f"token {token}"
return request123456789101112131415161718192021222324252627# This is a minimal reimplementation of the deprecated conda.cli.python_api# module. It uses the subprocess module to duplicate the fullest extent of# the run_command functionality needed for tests. But most of the internal# uses of run_command do not require this overhead and are better served# working in process. So when subprocess is needed, we do this:# from anaconda_auth._conda.conda_api import Commands, run_command# and when it is not needed, we do this:# from anaconda_auth._conda.conda_api import Commands# from conda.cli.main import main as run_command
import subprocess
class Commands: CLEAN = "clean" CONFIG = "config" INSTALL = "install" LIST = "list" REMOVE = "remove" SEARCH = "search"
def run_command(*args, use_exception_handler=False): # type: ignore args = ("python", "-m", "conda") + args proc = subprocess.run(args, capture_output=True, text=True) return proc.stdout, proc.stderr, proc.returncode123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152"""CLI for conda-token."""
from __future__ import annotations
import osimport sysfrom argparse import ArgumentParserfrom argparse import Namespace
from anaconda_auth import __version__from anaconda_auth._conda import repo_config
def token_list(args: Namespace) -> int: """Default function for list subparser.""" tokens = { k: v for k, v in repo_config.token_list().items() if k == repo_config.REPO_URL } if not tokens: print( f"No tokens have been configured for {repo_config.REPO_URL}", file=sys.stderr, ) return 1
for url, token in tokens.items(): print(url, token)
return 0
def token_set(args: Namespace) -> int: try: repo_config.validate_token(args.token, no_ssl_verify=args.no_ssl_verify) except repo_config.CondaTokenError as e: print(e, file=sys.stderr) return 1
repo_config.token_set( args.token, args.system, args.env, args.file, args.include_archive_channels, args.no_ssl_verify, args.enable_signature_verification, force=args.force_config_condarc, ) print("Success! Your token was validated and Conda has been configured.") return 0
def token_remove(args: Namespace) -> int: repo_config.token_remove() return 0
def condarc_path_args(parser: ArgumentParser) -> None: """Add condarc path arguments.""" config_file_location_group = parser.add_argument_group( "Config File Location Selection", f"Without one of these flags, the user config file at '{repo_config.escaped_user_rc_path}' is used.", ) location = config_file_location_group.add_mutually_exclusive_group() location.add_argument( "--system", action="store_true", help=f"Write to the system .condarc file at '{repo_config.escaped_user_rc_path}'.", ) location.add_argument( "--env", action="store_true", help=( f"Write to the active conda environment .condarc file ({os.getenv('CONDA_PREFIX', '<no active environment>').replace('%', '%%')}). " f"If no environment is active, write to the user config file ({repo_config.escaped_user_rc_path})." ), ) location.add_argument("--file", action="store", help="Write to the given file.")
def cli(argv: list[str] | None = None) -> int: parser = ArgumentParser( "conda-token", usage="conda token", description="Configure token access for Anaconda Commercial Edition", )
parser.add_argument( "-V", "--version", action="version", help="Show the conda-token version number and exit.", version=f"conda-token {__version__}", )
subparser = parser.add_subparsers(help="Token commands")
subparser_list = subparser.add_parser("list", help="List token if configured.") subparser_list.set_defaults(func=token_list)
subparser_remove = subparser.add_parser( "remove", help="Remove token and revert default_channels." ) condarc_path_args(subparser_remove) subparser_remove.set_defaults(func=token_remove)
subparser_set = subparser.add_parser( "set", help="Set your token and configure default_channels." ) subparser_set.add_argument("token", help="Your token.") subparser_set.add_argument( "--include-archive-channels", choices=repo_config.ARCHIVE_CHANNELS, help="Add archived channels to default_channels. " "\nAvailable channels are mro, mro-archive, free, and pro.", nargs="+", default=None, metavar="CHANNEL_NAME", ) subparser_set.add_argument( "--no-ssl-verify", help="Force disabling SSL verification. " "By default conda-token will respect your " "ssl_verify flag in your Conda settings. " "Using this flag will add ssl_verify: false " "to your .condarc file. If not already set.", action="store_true", ) subparser_set.add_argument( "--enable-signature-verification", action="store_true", help="Enable Conda package signature verification. Default is off.", ) subparser_set.add_argument( "--force-config-condarc", action="store_true", help="Force configuration of .condarc", ) condarc_path_args(subparser_set) subparser_set.set_defaults(func=token_set)
if len(sys.argv) == 1: sys.argv.append("--help")
args = parser.parse_args(argv) return args.func(args)
if __name__ == "__main__": cli(sys.argv[1:])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293from __future__ import annotations
from pathlib import Pathfrom typing import Any
from ruamel.yaml import YAMLfrom ruamel.yaml import YAMLError
from anaconda_cli_base import console
DEFAULT_CONDARC_PATH = Path("~/.condarc").expanduser()
yaml = YAML()
class CondaRCError(Exception): pass
class CondaRC: def __init__(self, condarc_path: Path | None = None): """ Initializes the CondaRC object by attempting to open and load the contents of the condarc file found in the user's home directory. """ self.condarc_path = condarc_path or DEFAULT_CONDARC_PATH self._loaded_yaml: dict[str, Any] = {} self.load()
@property def _backup_condarc_path(self) -> Path: return self.condarc_path.with_suffix(".bak")
def load(self, path: Path | None = None) -> None: path = path or self.condarc_path try: path.touch() with path.open("r") as fp: contents = fp.read() except OSError as exc: raise CondaRCError(f"Could not open condarc file: {exc}")
try: self._loaded_yaml = yaml.load(contents) or {} except YAMLError as exc: raise CondaRCError(f"Could not parse condarc: {exc}")
def update_channel_settings( self, channel: str, auth_type: str, username: str | None = None ) -> None: """ Update the condarc file's "channel_settings" section """ if username is None: updated_settings = {"channel": channel, "auth": auth_type} else: updated_settings = { "channel": channel, "auth": auth_type, "username": username, }
channel_settings = self._loaded_yaml.get("channel_settings", []) or []
# Filter out the existing channel's entry if it's there filter_settings = [ settings for settings in channel_settings if settings.get("channel") != channel ]
# Add the updated settings map filter_settings.append(updated_settings)
self._loaded_yaml["channel_settings"] = filter_settings
def restore(self) -> None: console.print(f"Restoring config from {self._backup_condarc_path}") self.load(self._backup_condarc_path) self.save()
def backup(self) -> None: console.print(f"Backing up config to {self._backup_condarc_path}") self.save(self._backup_condarc_path)
def save(self, path: Path | None = None) -> None: """Save the condarc file""" path = path or self.condarc_path try: with path.open("w") as fp: yaml.dump(self._loaded_yaml, fp) except OSError as exc: raise CondaRCError(f"Could not save file: {exc}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152"""Configuration manager for the conda plugin.
This file is used as a central location to manage global configurationsettings and deliver them to the locations where they are needed, includingother modules and YAML configuration files. It is designed to be callable asa standalone script or as a module. It can install a conda configuration filein the prefix, and to verify its existence and expected behavioral impact.These functions are both used by the conda recipe itself.
It is imperative that this module not include any other anaconda_auth importsso that it can be run during the conda build process"""
import sysfrom pathlib import Pathfrom typing import Anyfrom typing import Dictfrom typing import Listfrom typing import NamedTuplefrom typing import Setfrom typing import Union
__all__ = []
PREFIX_CONDARC_PATH = Path(sys.prefix) / "condarc.d" / "anaconda-auth.yml"
# This list is now serving THREE purposes. The keys are used in the conda# plugin module to determine which hosts should be hardcoded to use# anaconda-auth for authentication. The values are used to provide the# keyring domain where the legacy token will be stored, as well as# whether or not the destination should receive a proper API key.# Finally, the list is used to generate the master anaconda-auth.yml# configuration for conda.class TokenDomainSetting(NamedTuple): token_domain: str default_use_unified_api_key: bool = True autoconfigure_conda_channel_settings: bool = False
TOKEN_DOMAIN_MAP = { "repo.continuum.io": TokenDomainSetting("anaconda.com"), "repo.anaconda.com": TokenDomainSetting("anaconda.com"), "repo.anaconda.cloud": TokenDomainSetting("anaconda.com", False, True),}
def _dictify(channel_settings: List[Dict[str, str]]) -> Dict[str, str]: """ Extract the authentication information for each channel for better comparison with expectations. """ return {c["channel"]: c.get("auth", "") for c in channel_settings}
def _assert_settings( context: Any, expected: Dict[str, str], filtered: bool = False) -> None: """ Compare just the channel authentication information for each channel with the expectation, with order independence """ found = _dictify(context.channel_settings) if filtered: found = {k: v for k, v in expected.items() if k in expected} assert found == expected, f"{found=}, {expected=}"
def _build_channel_settings( include_defaults: bool = True, include_sites: bool = True) -> List[Dict[str, str]]: hosts: Set[str] = set() if include_defaults: hosts.update( repo_domain for repo_domain, settings in TOKEN_DOMAIN_MAP.items() if settings.autoconfigure_conda_channel_settings ) if include_sites: # We are delaying this import so this file can be run standalone from anaconda_auth.config import AnacondaAuthSitesConfig
hosts.update(s.domain for s in AnacondaAuthSitesConfig().sites.root.values()) return [{"channel": f"https://{host}/*", "auth": "anaconda-auth"} for host in hosts]
def _build_channel_yaml( include_defaults: bool = True, include_sites: bool = True) -> str: settings = _build_channel_settings(include_defaults, include_sites) # Hand-construct the YAML so we can avoid a library dependency, and # easily include the warning comment. lines = [ "# DO NOT EDIT THIS FILE.", "# This file was generated automatically for anaconda-auth.", ] lines.append("channel_settings:") for record in settings: pfx = "- " for key, value in record.items(): lines.append(f'{pfx}{key}: "{value}"') pfx = " " if not settings: lines[-1] += " []" lines.append("") return "\n".join(lines)
def _write_channel_settings( fpath: Union[Path, str], include_defaults: bool = True, include_sites: bool = True, overwrite: bool = False,) -> None: with Path(fpath).open(mode="w" if overwrite else "x") as fp: fp.write(_build_channel_yaml(include_defaults, include_sites))
def _write_condarc_d_settings(overwrite: bool = False) -> None: PREFIX_CONDARC_PATH.parent.mkdir(parents=True, exist_ok=True) _write_channel_settings( PREFIX_CONDARC_PATH, include_sites=False, overwrite=overwrite )
def _verify_channel_settings(filtered: bool = True) -> None: from conda.base.context import context
context.__init__() expected = _build_channel_settings(include_sites=False) _assert_settings(context, _dictify(expected), filtered=filtered)
if __name__ == "__main__": import sys
invalid = [ x for x in sys.argv[1:] if x not in ("--install", "--verify", "--overwrite") ] if len(sys.argv) == 1 or invalid: print( f"Usage: {sys.argv[0]} [--install] [--verify] [--overwrite]", file=sys.stderr, ) if invalid: print(f"Invalid option(s): {' '.join(invalid)}", file=sys.stderr) sys.exit(1) if "--install" in sys.argv: _write_condarc_d_settings(overwrite="--overwrite" in sys.argv) if "--verify" in sys.argv: _verify_channel_settings()12345678# The plugin entrypoints are loaded via this module as specified in pyproject.toml# We do this to be very conservative and catch potential import errors without surfacing to users.# Plugins were first introduced in conda=22.11.0# The ChannelAuthBase class was introduced in conda=23.7.0try: from anaconda_auth._conda.plugins import * # noqa: F403except ImportError: pass12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Definitions for conda plugins.
This file should not be imported directly, but instead the parent package willconditionally import it in case conda is not installed in the user's environment.
"""
from typing import Iterablefrom typing import Optional
from conda import pluginsfrom conda.plugins.types import CondaAuthHandlerfrom conda.plugins.types import CondaSubcommand
from anaconda_auth._conda.auth_handler import AnacondaAuthHandlerfrom anaconda_auth._conda.conda_token import cli
__all__ = ["conda_subcommands", "conda_auth_handlers"]
def _cli_wrapper(argv: Optional[list[str]] = None) -> int: # type: ignore # If argv is empty tuple, we need to set it back to None return cli(argv=argv or None)
@plugins.hookimpldef conda_subcommands() -> Iterable[CondaSubcommand]: """Defines subcommands into conda itself (not `anaconda` CLI).""" yield CondaSubcommand( name="token", summary="Set repository access token and configure default_channels", action=_cli_wrapper, # type: ignore )
@plugins.hookimpldef conda_auth_handlers() -> Iterable[CondaAuthHandler]: """Defines the auth handler that can be used for specific channels.
The following shows an example for how to configure a specific channel inside .condarc:
```yaml channel_settings: - channel: https://repo.anaconda.cloud/* auth: anaconda-auth ```
""" yield CondaAuthHandler( name="anaconda-auth", handler=AnacondaAuthHandler, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549"""Configure Conda to use Anaconda Commercial Edition."""
from __future__ import annotations
import contextlibimport ioimport jsonimport osimport sysimport warningsfrom os.path import abspathfrom os.path import expanduserfrom os.path import joinfrom typing import Anyfrom urllib.parse import urljoin
import condaimport conda.gateways.logging # noqa: F401from conda.base import context as context_modulefrom conda.cli import main as conda_mainfrom conda.exceptions import CondaKeyErrorfrom conda.gateways.anaconda_client import read_binstar_tokensfrom conda.gateways.anaconda_client import remove_binstar_tokenfrom conda.gateways.anaconda_client import set_binstar_tokenfrom conda.gateways.connection.session import CondaSessionfrom conda.models.channel import Channelfrom packaging import versionfrom rich.prompt import Confirm
from anaconda_auth._conda.conda_api import Commandsfrom anaconda_auth._conda.condarc import CondaRCfrom anaconda_auth._conda.config import _build_channel_settingsfrom anaconda_cli_base import console
CONDA_VERSION = version.parse(conda.__version__)
REPO_URL = os.getenv("CONDA_TOKEN_REPO_URL", "https://repo.anaconda.cloud/repo/")MAIN_CHANNEL = "main"ACTIVE_CHANNELS = ["r", "msys2"]ARCHIVE_CHANNELS = ["free", "mro-archive", "pro"]
user_rc_path = abspath(expanduser("~/.condarc"))escaped_user_rc_path = user_rc_path.replace("%", "%%")escaped_sys_rc_path = abspath(join(sys.prefix, ".condarc")).replace("%", "%%")
def run_command(*args: Any, **kwargs: Any) -> int: with warnings.catch_warnings(): # Ignore PendingDeprecationWarning from any other plugins invoked when calling conda warnings.simplefilter("ignore", PendingDeprecationWarning) return conda_main(*args, **kwargs)
class CondaTokenError(RuntimeError): pass
class CondaVersionWarning(UserWarning): pass
def _get_condarc_args( condarc_system: bool = False, condarc_env: bool = False, condarc_file: str | None = None,) -> list[str]: """Construct conda CLI args related to condarc location.""" config_args = []
if condarc_system: config_args.append("--system") elif condarc_env: config_args.append("--env") elif condarc_file: config_args.append(f"--file={condarc_file}")
return config_args
def can_restore_free_channel() -> bool: # restore_free_channel was removed in conda 25.9.0 return CONDA_VERSION >= version.parse("4.7.0") and CONDA_VERSION < version.parse( "25.9.0" )
def clean_index() -> None: """Runs conda clean -i.
It is important to remove index cache when changing the condarc to ensure that the downloaded repodata is correct. """ run_command(Commands.CLEAN, "-i", "-y", "-q")
def validate_token(token: str, no_ssl_verify: bool = False) -> None: """Checks that token can be used with the repository."""
# Force ssl_verify: false if no_ssl_verify: context_module.context.ssl_verify = False # type: ignore
# Use CondaSession to be compatible with ssl_verify: truststore # https://conda.io/projects/conda/en/latest/user-guide/configuration/settings.html#ssl-verify-ssl-verification # Clear metaclass cache to create new session checking ssl_verify if hasattr(CondaSession, "cache_clear"): # not present in conda < January 2024 CondaSession.cache_clear() else: # what cache_clear() does try: CondaSession._thread_local.sessions.clear() # type: ignore except AttributeError: # AttributeError: thread's session cache has not been initialized pass
session = CondaSession()
# Ensure the index cache is cleaned first clean_index()
channel = Channel(urljoin(REPO_URL, "main/noarch/repodata.json")) channel.token = token token_url = str(channel.url(with_credentials=True))
r = session.head(token_url, verify=session.verify) if r.status_code != 200: raise CondaTokenError( "The token could not be validated. Please check that you have typed it correctly." )
def configure_plugin(should_set_default_channels: bool = False) -> None: """Configure the user's .condarc file with the anaconda-auth plugin.
We install the auth-handler plugin by writing the "channel_settings" key and associate all premium repo channels with this auth handler.
""" settings = _build_channel_settings(include_defaults=False) if not settings: return condarc = CondaRC() condarc.backup() for s in settings: condarc.update_channel_settings(s["channel"], s["auth"], username=None) condarc.save()
def enable_extra_safety_checks( condarc_system: bool = False, condarc_env: bool = False, condarc_file: str | None = None,) -> None: """Enable package signature verification.
This will set extra_safety_checks: True and signing_metadata_url_base in the CondaRC file. """ if CONDA_VERSION < version.parse("4.10.1"): warnings.warn( "You need upgrade to at least Conda version 4.10.1 to enable package signature verification.", CondaVersionWarning, ) return
condarc_file_args = _get_condarc_args( condarc_system=condarc_system, condarc_env=condarc_env, condarc_file=condarc_file, )
safety_check_args = ["--set", "extra_safety_checks", "true"] safety_check_args.extend(condarc_file_args) run_command(Commands.CONFIG, *safety_check_args)
metadata_url_args = ["--set", "signing_metadata_url_base", REPO_URL.rstrip("/")] metadata_url_args.extend(condarc_file_args) run_command(Commands.CONFIG, *metadata_url_args)
def disable_extra_safety_checks( condarc_system: bool = False, condarc_env: bool = False, condarc_file: str | None = None,) -> None: """Disable package signature verification.
This will set extra_safety_checks: false and remove signing_metadata_url_base in the CondaRC file. """
if CONDA_VERSION < version.parse("4.10.1"): return
condarc_file_args = _get_condarc_args( condarc_system=condarc_system, condarc_env=condarc_env, condarc_file=condarc_file, )
safety_check_args = ["--set", "extra_safety_checks", "false"] safety_check_args.extend(condarc_file_args) try: run_command(Commands.CONFIG, *safety_check_args) except CondaKeyError: pass
metadata_url_args = ["--remove-key", "signing_metadata_url_base"] metadata_url_args.extend(condarc_file_args) try: run_command(Commands.CONFIG, *metadata_url_args) except CondaKeyError: pass
def _set_add_anaconda_token( condarc_system: bool = False, condarc_env: bool = False, condarc_file: str | None = None,) -> None: """Run conda config --set add_anaconda_token true.
Setting this parameter to true ensures that the token is used when making requests to the repository. """ config_args = ["--set", "add_anaconda_token", "true"]
condarc_file_args = _get_condarc_args( condarc_system=condarc_system, condarc_env=condarc_env, condarc_file=condarc_file, ) config_args.extend(condarc_file_args)
run_command(Commands.CONFIG, *config_args)
def _set_ssl_verify_false( condarc_system: bool = False, condarc_env: bool = False, condarc_file: str | None = None,) -> None: """Run conda config --set ssl_verify false.
Setting this parameter to false disables all SSL verification for conda activities """ config_args = ["--set", "ssl_verify", "false"]
condarc_file_args = _get_condarc_args( condarc_system=condarc_system, condarc_env=condarc_env, condarc_file=condarc_file, ) config_args.extend(condarc_file_args)
run_command(Commands.CONFIG, *config_args)
def _unset_restore_free_channel( condarc_system: bool = False, condarc_env: bool = False, condarc_file: str | None = None,) -> None: """Runs conda config --set restore_free_channel false.
The free channel is provided by Commercial Edition as and should be added directly.""" config_args = ["--set", "restore_free_channel", "false"]
condarc_file_args = _get_condarc_args( condarc_system=condarc_system, condarc_env=condarc_env, condarc_file=condarc_file, ) config_args.extend(condarc_file_args)
run_command(Commands.CONFIG, *config_args, use_exception_handler=True)
def _set_channel( channel: str, prepend: bool = True, condarc_system: bool = False, condarc_env: bool = False, condarc_file: str | None = None,) -> None: """Adds a named Commercial Edition channel to default_channels.""" channel_url = urljoin(REPO_URL, channel)
config_args = [ "--prepend" if prepend else "--append", "default_channels", channel_url, ]
condarc_file_args = _get_condarc_args( condarc_system=condarc_system, condarc_env=condarc_env, condarc_file=condarc_file, ) config_args.extend(condarc_file_args)
run_command(Commands.CONFIG, *config_args)
def _get_from_condarc( key: str, default: Any = None, condarc_system: bool = False, condarc_env: bool = False, condarc_file: str | None = None,) -> Any: """Retrieve the existing default_channels from the user's `.condarc` file.
If the user does not have a "default_channels" section, an empty list is returned.
""" config_args = ["--get", key, "--json"]
condarc_file_args = _get_condarc_args( condarc_system=condarc_system, condarc_env=condarc_env, condarc_file=condarc_file, ) config_args.extend(condarc_file_args)
# Capture the JSON output from stdout string_io = io.StringIO() with contextlib.redirect_stdout(string_io): run_command(Commands.CONFIG, *config_args)
try: result = json.loads(string_io.getvalue()) except json.JSONDecodeError: result = {}
return result.get("get", {}).get(key, default)
def _get_default_channels( condarc_system: bool = False, condarc_env: bool = False, condarc_file: str | None = None,) -> list[str]: """Retrieve the existing default_channels from the user's `.condarc` file.
If the user does not have a "default_channels" section, an empty list is returned.
""" return _get_from_condarc( "default_channels", default=[], condarc_system=condarc_system, condarc_env=condarc_env, condarc_file=condarc_file, )
def _remove_default_channels( condarc_system: bool = False, condarc_env: bool = False, condarc_file: str | None = None,) -> None: """Runs conda config --remove-key default_channels
It is best to remove the default_channels in case they are not set at the default values before configuring Commercial Edition. """ config_args = ["--remove-key", "default_channels"]
condarc_file_args = _get_condarc_args( condarc_system=condarc_system, condarc_env=condarc_env, condarc_file=condarc_file, ) config_args.extend(condarc_file_args)
# We suppress a CondaKeyError below to prevent logging an internal conda error # to the terminal. err_io = io.StringIO() with contextlib.redirect_stderr(err_io): try: run_command(Commands.CONFIG, *config_args) except CondaKeyError: pass
err_string = err_io.getvalue() if "CondaKeyError" not in err_string.strip(): print(err_string, file=sys.stderr)
def _prompt_to_set_default_channels() -> bool: """Prompt the user for whether they would like to set their default channels.""" existing_default_channels = _get_default_channels() if existing_default_channels: console.print("Existing default channels found:") for c in existing_default_channels: console.print(f"- {c}") console.print( "This action will override the existing default_channels setting." ) else: console.print("Prepared to set default channels in .condarc.")
return Confirm.ask("Proceed?", default=False)
def configure_default_channels( condarc_system: bool = False, condarc_env: bool = False, condarc_file: str | None = None, include_archive_channels: list[str] | None = None, force: bool = False,) -> None: """Configure the default_channels to utilize only Commercial Edition.
This function performs the following actions 1. unset default_channels if it exists in the condarc 2. unset restore_free_channel if it exists in the condarc 3. Add the main, r, and msys2 channels to default_channels 4. Optionally add any of the archive channels: free, pro, mro, mro-archive """ console.print("Configuring your [cyan].condarc[/cyan] file")
existing_default_channels = _get_default_channels()
existing_default_channels_short_names = [ c.removeprefix(REPO_URL) for c in existing_default_channels ] if set(existing_default_channels_short_names) == set( [MAIN_CHANNEL] + ACTIVE_CHANNELS ): console.print("Default channels already configured, nothing to do.") return
if not (force or _prompt_to_set_default_channels()): return
_remove_default_channels(condarc_system, condarc_env, condarc_file)
if can_restore_free_channel() and _get_from_condarc( "restore_free_channel", condarc_system=condarc_system, condarc_env=condarc_env, condarc_file=condarc_file, ): _unset_restore_free_channel(condarc_system, condarc_env, condarc_file)
_set_channel( MAIN_CHANNEL, prepend=True, condarc_system=condarc_system, condarc_env=condarc_env, condarc_file=condarc_file, )
for c in ACTIVE_CHANNELS: _set_channel( c, prepend=False, condarc_system=condarc_system, condarc_env=condarc_env, condarc_file=condarc_file, )
if include_archive_channels is None: return
for c in include_archive_channels: if c in ARCHIVE_CHANNELS: _set_channel( c, prepend=False, condarc_system=condarc_system, condarc_env=condarc_env, condarc_file=condarc_file, ) else: raise ValueError( f"The archive channel {c} is not one of {', '.join(ARCHIVE_CHANNELS)}" )
def token_list() -> dict[str, str]: """Return a dictionary of tokens for all configured repository urls.
Note that this function will return tokens configured for non-Commercial Edition urls.""" return read_binstar_tokens()
def token_remove( system: bool = False, env: bool = False, file: str | None = None) -> None: """Completely remove the Commercial Edition token and default_channels.
This function performs three actions. 1. Remove the token 2. Remove the custom default_channels in the condarc 3. Disable package signature verification 4. Run conda clean -i """ remove_binstar_token(REPO_URL) _remove_default_channels(system, env, file) disable_extra_safety_checks(system, env, file) clean_index()
def token_set( token: str, system: bool = False, env: bool = False, file: str | None = None, include_archive_channels: list[str] | None = None, no_ssl_verify: bool = False, enable_signature_verification: bool = False, force: bool = False,) -> None: """Set the Commercial Edition token and configure default_channels.
This function performs 4 actions. 1. Remove previous Commercial Edition token if present. 2. Add token. 3. Configure default_channels in the condarc file. 4. Optionally enable Conda package signature verification 5. Run conda clean -i """ remove_binstar_token(REPO_URL)
set_binstar_token(REPO_URL, token) _set_add_anaconda_token(system, env, file)
if no_ssl_verify: _set_ssl_verify_false(system, env, file)
if enable_signature_verification: enable_extra_safety_checks(system, env, file)
configure_default_channels(system, env, file, include_archive_channels, force=force) clean_index()123456789101112131415161718192021222324252627# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other# Archspec Project Developers. See the top-level COPYRIGHT file for details.## SPDX-License-Identifier: (Apache-2.0 OR MIT)"""The "cpu" package permits to query and compare differentCPU microarchitectures."""from .detect import brand_string, hostfrom .microarchitecture import ( TARGETS, InvalidCompilerVersion, Microarchitecture, UnsupportedMicroarchitecture, generic_microarchitecture, version_components,)
__all__ = [ "brand_string", "host", "TARGETS", "InvalidCompilerVersion", "Microarchitecture", "UnsupportedMicroarchitecture", "generic_microarchitecture", "version_components",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other# Archspec Project Developers. See the top-level COPYRIGHT file for details.## SPDX-License-Identifier: (Apache-2.0 OR MIT)"""Aliases for microarchitecture features."""from .schema import TARGETS_JSON, LazyDictionary
_FEATURE_ALIAS_PREDICATE = {}
class FeatureAliasTest: """A test that must be passed for a feature alias to succeed.
Args: rules (dict): dictionary of rules to be met. Each key must be a valid alias predicate """
# pylint: disable=too-few-public-methods def __init__(self, rules): self.rules = rules self.predicates = [] for name, args in rules.items(): self.predicates.append(_FEATURE_ALIAS_PREDICATE[name](args))
def __call__(self, microarchitecture): return all(feature_test(microarchitecture) for feature_test in self.predicates)
def _feature_aliases(): """Returns the dictionary of all defined feature aliases.""" json_data = TARGETS_JSON["feature_aliases"] aliases = {} for alias, rules in json_data.items(): aliases[alias] = FeatureAliasTest(rules) return aliases
FEATURE_ALIASES = LazyDictionary(_feature_aliases)
def alias_predicate(func): """Decorator to register a predicate that can be used to evaluate feature aliases. """ name = func.__name__
# Check we didn't register anything else with the same name if name in _FEATURE_ALIAS_PREDICATE: msg = f'the alias predicate "{name}" already exists' raise KeyError(msg)
_FEATURE_ALIAS_PREDICATE[name] = func
return func
@alias_predicatedef reason(_): """This predicate returns always True and it's there to allow writing a documentation string in the JSON file to explain why an alias is needed. """ return lambda x: True
@alias_predicatedef any_of(list_of_features): """Returns a predicate that is True if any of the feature in the list is in the microarchitecture being tested, False otherwise. """
def _impl(microarchitecture): return any(x in microarchitecture for x in list_of_features)
return _impl
@alias_predicatedef families(list_of_families): """Returns a predicate that is True if the architecture family of the microarchitecture being tested is in the list, False otherwise. """
def _impl(microarchitecture): return str(microarchitecture.family) in list_of_families
return _impldata/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/__init__.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/_version.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/heartbeat.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/patch.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/plugin.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/tokens.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/utils.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/__init__.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/__main__.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/_version.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/actions.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/adapters.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/cli.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/client.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/config.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/device_flow.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/exceptions.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/handlers.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/panel.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/repo.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/token.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/utils.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__init__.pyAdded+12
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/__init__.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/auth_handler.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/conda_api.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/conda_token.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/condarc.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/config.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/entrypoint.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/plugins.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/repo_config.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/auth_handler.pyAdded+165
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/conda_api.pyAdded+27
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/conda_token.pyAdded+152
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/condarc.pyAdded+93
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/config.pyAdded+152
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/entrypoint.pyAdded+8
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/plugins.pyAdded+52
data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/repo_config.pyAdded+549
data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/__init__.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/__main__.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/cli.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__init__.pyAdded+27
data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/__init__.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/alias.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/detect.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/microarchitecture.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/schema.cpython-313.pycAdded
data/miniconda3/lib/python3.13/site-packages/archspec/cpu/alias.pyAdded+87