GitHub.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. if ($message) {
  70. $this->io->writeError($message);
  71. }
  72. $this->io->writeError(sprintf('A token will be created and stored in "%s", your password will never be stored', $this->config->getAuthConfigSource()->getName()));
  73. $this->io->writeError('To revoke access to this token you can visit https://github.com/settings/applications');
  74. $otp = null;
  75. $attemptCounter = 0;
  76. while ($attemptCounter++ < 5) {
  77. try {
  78. $response = $this->createToken($originUrl, $otp);
  79. } catch (TransportException $e) {
  80. // https://developer.github.com/v3/#authentication && https://developer.github.com/v3/auth/#working-with-two-factor-authentication
  81. // 401 is bad credentials, or missing otp code
  82. // 403 is max login attempts exceeded
  83. if (in_array($e->getCode(), array(403, 401))) {
  84. // in case of a 401, and authentication was previously provided
  85. if (401 === $e->getCode() && $this->io->hasAuthentication($originUrl)) {
  86. // check for the presence of otp headers and get otp code from user
  87. $otp = $this->checkTwoFactorAuthentication($e->getHeaders());
  88. // if given, retry creating a token using the user provided code
  89. if (null !== $otp) {
  90. continue;
  91. }
  92. }
  93. if (401 === $e->getCode()) {
  94. $this->io->writeError('Bad credentials.');
  95. } else {
  96. $this->io->writeError('Maximum number of login attempts exceeded. Please try again later.');
  97. }
  98. $this->io->writeError('You can also manually create a personal token at https://github.com/settings/applications');
  99. $this->io->writeError('Add it using "composer config github-oauth.github.com <token>"');
  100. continue;
  101. }
  102. throw $e;
  103. }
  104. $this->io->setAuthentication($originUrl, $response['token'], 'x-oauth-basic');
  105. $this->config->getConfigSource()->removeConfigSetting('github-oauth.'.$originUrl);
  106. // store value in user config
  107. $this->config->getAuthConfigSource()->addConfigSetting('github-oauth.'.$originUrl, $response['token']);
  108. return true;
  109. }
  110. throw new \RuntimeException("Invalid GitHub credentials 5 times in a row, aborting.");
  111. }
  112. private function createToken($originUrl, $otp = null)
  113. {
  114. if (null === $otp || !$this->io->hasAuthentication($originUrl)) {
  115. $username = $this->io->ask('Username: ');
  116. $password = $this->io->askAndHideAnswer('Password: ');
  117. $this->io->setAuthentication($originUrl, $username, $password);
  118. }
  119. $headers = array('Content-Type: application/json');
  120. if ($otp) {
  121. $headers[] = 'X-GitHub-OTP: ' . $otp;
  122. }
  123. $note = 'Composer';
  124. if ($this->config->get('github-expose-hostname') === true && 0 === $this->process->execute('hostname', $output)) {
  125. $note .= ' on ' . trim($output);
  126. }
  127. $note .= ' [' . date('YmdHis') . ']';
  128. $apiUrl = ('github.com' === $originUrl) ? 'api.github.com' : $originUrl . '/api/v3';
  129. $json = $this->remoteFilesystem->getContents($originUrl, 'https://'. $apiUrl . '/authorizations', false, array(
  130. 'retry-auth-failure' => false,
  131. 'http' => array(
  132. 'method' => 'POST',
  133. 'follow_location' => false,
  134. 'header' => $headers,
  135. 'content' => json_encode(array(
  136. 'scopes' => array('repo'),
  137. 'note' => $note,
  138. 'note_url' => 'https://getcomposer.org/',
  139. )),
  140. )
  141. ));
  142. $this->io->writeError('Token successfully created');
  143. return JsonFile::parseJson($json);
  144. }
  145. private function checkTwoFactorAuthentication(array $headers)
  146. {
  147. $headerNames = array_map(
  148. function ($header) {
  149. return strtolower(strstr($header, ':', true));
  150. },
  151. $headers
  152. );
  153. if (false !== ($key = array_search('x-github-otp', $headerNames))) {
  154. list($required, $method) = array_map('trim', explode(';', substr(strstr($headers[$key], ':'), 1)));
  155. if ('required' === $required) {
  156. $this->io->writeError('Two-factor Authentication');
  157. if ('app' === $method) {
  158. $this->io->writeError('Open the two-factor authentication app on your device to view your authentication code and verify your identity.');
  159. }
  160. if ('sms' === $method) {
  161. $this->io->writeError('You have been sent an SMS message with an authentication code to verify your identity.');
  162. }
  163. return $this->io->ask('Authentication Code: ');
  164. }
  165. }
  166. return null;
  167. }
  168. }