123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246 |
- <?php
- /*
- * This file is part of Composer.
- *
- * (c) Nils Adermann <naderman@naderman.de>
- * Jordi Boggiano <j.boggiano@seld.be>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
- namespace Composer\Util;
- use Composer\Config;
- use Composer\IO\IOInterface;
- use Composer\Downloader\TransportException;
- /**
- * @author Jordi Boggiano <j.boggiano@seld.be>
- */
- class AuthHelper
- {
- protected $io;
- protected $config;
- public function __construct(IOInterface $io, Config $config)
- {
- $this->io = $io;
- $this->config = $config;
- }
- /**
- * @param string $origin
- * @param string|bool $storeAuth
- */
- public function storeAuth($origin, $storeAuth)
- {
- $store = false;
- $configSource = $this->config->getAuthConfigSource();
- if ($storeAuth === true) {
- $store = $configSource;
- } elseif ($storeAuth === 'prompt') {
- $answer = $this->io->askAndValidate(
- 'Do you want to store credentials for '.$origin.' in '.$configSource->getName().' ? [Yn] ',
- function ($value) {
- $input = strtolower(substr(trim($value), 0, 1));
- if (in_array($input, array('y','n'))) {
- return $input;
- }
- throw new \RuntimeException('Please answer (y)es or (n)o');
- },
- null,
- 'y'
- );
- if ($answer === 'y') {
- $store = $configSource;
- }
- }
- if ($store) {
- $store->addConfigSetting(
- 'http-basic.'.$origin,
- $this->io->getAuthentication($origin)
- );
- }
- }
- /**
- * @param string $url
- * @param string $origin
- * @param int $statusCode HTTP status code that triggered this call
- * @param string|null $reason a message/description explaining why this was called
- * @param string[] $headers
- * @return array|null containing retry (bool) and storeAuth (string|bool) keys, if retry is true the request should be
- * retried, if storeAuth is true then on a successful retry the authentication should be persisted to auth.json
- */
- public function promptAuthIfNeeded($url, $origin, $statusCode, $reason = null, $headers = array())
- {
- $storeAuth = false;
- $retry = false;
- if (in_array($origin, $this->config->get('github-domains'), true)) {
- $gitHubUtil = new GitHub($this->io, $this->config, null);
- $message = "\n";
- $rateLimited = $gitHubUtil->isRateLimited($headers);
- if ($rateLimited) {
- $rateLimit = $gitHubUtil->getRateLimit($headers);
- if ($this->io->hasAuthentication($origin)) {
- $message = 'Review your configured GitHub OAuth token or enter a new one to go over the API rate limit.';
- } else {
- $message = 'Create a GitHub OAuth token to go over the API rate limit.';
- }
- $message = sprintf(
- 'GitHub API limit (%d calls/hr) is exhausted, could not fetch '.$url.'. '.$message.' You can also wait until %s for the rate limit to reset.',
- $rateLimit['limit'],
- $rateLimit['reset']
- )."\n";
- } else {
- $message .= 'Could not fetch '.$url.', please ';
- if ($this->io->hasAuthentication($origin)) {
- $message .= 'review your configured GitHub OAuth token or enter a new one to access private repos';
- } else {
- $message .= 'create a GitHub OAuth token to access private repos';
- }
- }
- if (!$gitHubUtil->authorizeOAuth($origin)
- && (!$this->io->isInteractive() || !$gitHubUtil->authorizeOAuthInteractively($origin, $message))
- ) {
- throw new TransportException('Could not authenticate against '.$origin, 401);
- }
- } elseif (in_array($origin, $this->config->get('gitlab-domains'), true)) {
- $message = "\n".'Could not fetch '.$url.', enter your ' . $origin . ' credentials ' .($statusCode === 401 ? 'to access private repos' : 'to go over the API rate limit');
- $gitLabUtil = new GitLab($this->io, $this->config, null);
- if ($this->io->hasAuthentication($origin) && ($auth = $this->io->getAuthentication($origin)) && $auth['password'] === 'private-token') {
- throw new TransportException("Invalid credentials for '" . $url . "', aborting.", $statusCode);
- }
- if (!$gitLabUtil->authorizeOAuth($origin)
- && (!$this->io->isInteractive() || !$gitLabUtil->authorizeOAuthInteractively(parse_url($url, PHP_URL_SCHEME), $origin, $message))
- ) {
- throw new TransportException('Could not authenticate against '.$origin, 401);
- }
- } elseif ($origin === 'bitbucket.org') {
- $askForOAuthToken = true;
- if ($this->io->hasAuthentication($origin)) {
- $auth = $this->io->getAuthentication($origin);
- if ($auth['username'] !== 'x-token-auth') {
- $bitbucketUtil = new Bitbucket($this->io, $this->config);
- $accessToken = $bitbucketUtil->requestToken($origin, $auth['username'], $auth['password']);
- if (!empty($accessToken)) {
- $this->io->setAuthentication($origin, 'x-token-auth', $accessToken);
- $askForOAuthToken = false;
- }
- } else {
- throw new TransportException('Could not authenticate against ' . $origin, 401);
- }
- }
- if ($askForOAuthToken) {
- $message = "\n".'Could not fetch ' . $url . ', please create a bitbucket OAuth token to ' . (($statusCode === 401 || $statusCode === 403) ? 'access private repos' : 'go over the API rate limit');
- $bitBucketUtil = new Bitbucket($this->io, $this->config);
- if (! $bitBucketUtil->authorizeOAuth($origin)
- && (! $this->io->isInteractive() || !$bitBucketUtil->authorizeOAuthInteractively($origin, $message))
- ) {
- throw new TransportException('Could not authenticate against ' . $origin, 401);
- }
- }
- } else {
- // 404s are only handled for github
- if ($statusCode === 404) {
- return;
- }
- // fail if the console is not interactive
- if (!$this->io->isInteractive()) {
- if ($statusCode === 401) {
- $message = "The '" . $url . "' URL required authentication.\nYou must be using the interactive console to authenticate";
- }
- if ($statusCode === 403) {
- $message = "The '" . $url . "' URL could not be accessed: " . $reason;
- }
- throw new TransportException($message, $statusCode);
- }
- // fail if we already have auth
- if ($this->io->hasAuthentication($origin)) {
- throw new TransportException("Invalid credentials for '" . $url . "', aborting.", $statusCode);
- }
- $this->io->writeError(' Authentication required (<info>'.parse_url($url, PHP_URL_HOST).'</info>):');
- $username = $this->io->ask(' Username: ');
- $password = $this->io->askAndHideAnswer(' Password: ');
- $this->io->setAuthentication($origin, $username, $password);
- $storeAuth = $this->config->get('store-auths');
- }
- $retry = true;
- return array('retry' => $retry, 'storeAuth' => $storeAuth);
- }
- /**
- * @param array $headers
- * @param string $origin
- * @param string $url
- * @return array updated headers array
- */
- public function addAuthenticationHeader(array $headers, $origin, $url)
- {
- if ($this->io->hasAuthentication($origin)) {
- $auth = $this->io->getAuthentication($origin);
- if ('github.com' === $origin && 'x-oauth-basic' === $auth['password']) {
- $headers[] = 'Authorization: token '.$auth['username'];
- } elseif (in_array($origin, $this->config->get('gitlab-domains'), true)) {
- if ($auth['password'] === 'oauth2') {
- $headers[] = 'Authorization: Bearer '.$auth['username'];
- } elseif ($auth['password'] === 'private-token') {
- $headers[] = 'PRIVATE-TOKEN: '.$auth['username'];
- }
- } elseif (
- 'bitbucket.org' === $origin
- && $url !== Bitbucket::OAUTH2_ACCESS_TOKEN_URL
- && 'x-token-auth' === $auth['username']
- ) {
- if (!$this->isPublicBitBucketDownload($url)) {
- $headers[] = 'Authorization: Bearer ' . $auth['password'];
- }
- } else {
- $authStr = base64_encode($auth['username'] . ':' . $auth['password']);
- $headers[] = 'Authorization: Basic '.$authStr;
- }
- }
- return $headers;
- }
- /**
- * @link https://github.com/composer/composer/issues/5584
- *
- * @param string $urlToBitBucketFile URL to a file at bitbucket.org.
- *
- * @return bool Whether the given URL is a public BitBucket download which requires no authentication.
- */
- public function isPublicBitBucketDownload($urlToBitBucketFile)
- {
- $domain = parse_url($urlToBitBucketFile, PHP_URL_HOST);
- if (strpos($domain, 'bitbucket.org') === false) {
- // Bitbucket downloads are hosted on amazonaws.
- // We do not need to authenticate there at all
- return true;
- }
- $path = parse_url($urlToBitBucketFile, PHP_URL_PATH);
- // Path for a public download follows this pattern /{user}/{repo}/downloads/{whatever}
- // {@link https://blog.bitbucket.org/2009/04/12/new-feature-downloads/}
- $pathParts = explode('/', $path);
- return count($pathParts) >= 4 && $pathParts[3] == 'downloads';
- }
- }
|