GitHub.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Util;
  12. use Composer\IO\IOInterface;
  13. use Composer\Config;
  14. use Composer\Downloader\TransportException;
  15. use Composer\Json\JsonFile;
  16. /**
  17. * @author Jordi Boggiano <j.boggiano@seld.be>
  18. */
  19. class GitHub
  20. {
  21. protected $io;
  22. protected $config;
  23. protected $process;
  24. protected $remoteFilesystem;
  25. /**
  26. * Constructor.
  27. *
  28. * @param IOInterface $io The IO instance
  29. * @param Config $config The composer configuration
  30. * @param ProcessExecutor $process Process instance, injectable for mocking
  31. * @param RemoteFilesystem $remoteFilesystem Remote Filesystem, injectable for mocking
  32. */
  33. public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, RemoteFilesystem $remoteFilesystem = null)
  34. {
  35. $this->io = $io;
  36. $this->config = $config;
  37. $this->process = $process ?: new ProcessExecutor;
  38. $this->remoteFilesystem = $remoteFilesystem ?: new RemoteFilesystem($io, $config);
  39. }
  40. /**
  41. * Attempts to authorize a GitHub domain via OAuth
  42. *
  43. * @param string $originUrl The host this GitHub instance is located at
  44. * @return bool true on success
  45. */
  46. public function authorizeOAuth($originUrl)
  47. {
  48. if (!in_array($originUrl, $this->config->get('github-domains'))) {
  49. return false;
  50. }
  51. // if available use token from git config
  52. if (0 === $this->process->execute('git config github.accesstoken', $output)) {
  53. $this->io->setAuthentication($originUrl, trim($output), 'x-oauth-basic');
  54. return true;
  55. }
  56. return false;
  57. }
  58. /**
  59. * Authorizes a GitHub domain interactively via OAuth
  60. *
  61. * @param string $originUrl The host this GitHub instance is located at
  62. * @param string $message The reason this authorization is required
  63. * @throws \RuntimeException
  64. * @throws TransportException|\Exception
  65. * @return bool true on success
  66. */
  67. public function authorizeOAuthInteractively($originUrl, $message = null)
  68. {
  69. $attemptCounter = 0;
  70. $apiUrl = ('github.com' === $originUrl) ? 'api.github.com' : $originUrl . '/api/v3';
  71. if ($message) {
  72. $this->io->write($message);
  73. }
  74. $this->io->write('The credentials will be swapped for an OAuth token stored in '.$this->config->getAuthConfigSource()->getName().', your password will not be stored');
  75. $this->io->write('To revoke access to this token you can visit https://github.com/settings/applications');
  76. while ($attemptCounter++ < 5) {
  77. try {
  78. if (empty($otp) || !$this->io->hasAuthentication($originUrl)) {
  79. $username = $this->io->ask('Username: ');
  80. $password = $this->io->askAndHideAnswer('Password: ');
  81. $otp = null;
  82. $this->io->setAuthentication($originUrl, $username, $password);
  83. }
  84. // build up OAuth app name
  85. $appName = 'Composer';
  86. if ($this->config->get('github-expose-hostname') === true && 0 === $this->process->execute('hostname', $output)) {
  87. $appName .= ' on ' . trim($output);
  88. } else {
  89. $appName .= ' [' . date('YmdHis') . ']';
  90. }
  91. $headers = array();
  92. if ($otp) {
  93. $headers = array('X-GitHub-OTP: ' . $otp);
  94. }
  95. // try retrieving an existing token with the same name
  96. $contents = null;
  97. $auths = JsonFile::parseJson($this->remoteFilesystem->getContents($originUrl, 'https://'. $apiUrl . '/authorizations', false, array(
  98. 'retry-auth-failure' => false,
  99. 'http' => array(
  100. 'header' => $headers
  101. )
  102. )));
  103. foreach ($auths as $auth) {
  104. if (
  105. isset($auth['app']['name'])
  106. && 0 === strpos($auth['app']['name'], $appName)
  107. && $auth['app']['url'] === 'https://getcomposer.org/'
  108. ) {
  109. $this->io->write('An existing OAuth token for Composer is present and will be reused');
  110. $contents['token'] = $auth['token'];
  111. break;
  112. }
  113. }
  114. // no existing token, create one
  115. if (empty($contents['token'])) {
  116. $headers[] = 'Content-Type: application/json';
  117. $contents = JsonFile::parseJson($this->remoteFilesystem->getContents($originUrl, 'https://'. $apiUrl . '/authorizations', false, array(
  118. 'retry-auth-failure' => false,
  119. 'http' => array(
  120. 'method' => 'POST',
  121. 'follow_location' => false,
  122. 'header' => $headers,
  123. 'content' => json_encode(array(
  124. 'scopes' => array('repo'),
  125. 'note' => $appName,
  126. 'note_url' => 'https://getcomposer.org/',
  127. )),
  128. )
  129. )));
  130. $this->io->write('Token successfully created');
  131. }
  132. } catch (TransportException $e) {
  133. if (in_array($e->getCode(), array(403, 401))) {
  134. // 401 when authentication was supplied, handle 2FA if required.
  135. if ($this->io->hasAuthentication($originUrl)) {
  136. $headerNames = array_map(function ($header) {
  137. return strtolower(strstr($header, ':', true));
  138. }, $e->getHeaders());
  139. if ($key = array_search('x-github-otp', $headerNames)) {
  140. $headers = $e->getHeaders();
  141. list($required, $method) = array_map('trim', explode(';', substr(strstr($headers[$key], ':'), 1)));
  142. if ('required' === $required) {
  143. $this->io->write('Two-factor Authentication');
  144. if ('app' === $method) {
  145. $this->io->write('Open the two-factor authentication app on your device to view your authentication code and verify your identity.');
  146. }
  147. if ('sms' === $method) {
  148. $this->io->write('You have been sent an SMS message with an authentication code to verify your identity.');
  149. }
  150. $otp = $this->io->ask('Authentication Code: ');
  151. continue;
  152. }
  153. }
  154. }
  155. $this->io->write('Invalid credentials.');
  156. continue;
  157. }
  158. throw $e;
  159. }
  160. $this->io->setAuthentication($originUrl, $contents['token'], 'x-oauth-basic');
  161. // store value in user config
  162. $this->config->getConfigSource()->removeConfigSetting('github-oauth.'.$originUrl);
  163. $this->config->getAuthConfigSource()->addConfigSetting('github-oauth.'.$originUrl, $contents['token']);
  164. return true;
  165. }
  166. throw new \RuntimeException("Invalid GitHub credentials 5 times in a row, aborting.");
  167. }
  168. }