Skip to content

Commit

Permalink
Diagnose command: Add GitHub OAuth token expiration date information
Browse files Browse the repository at this point in the history
GitHub's new fine-grained tokens have a cumpulsory expiration date, and their
classic tokens also support an expiration date.

https://github.blog/changelog/2021-07-26-expiration-options-for-personal-access-tokens/

This improves the `composer diagnose` command to display the expiration
date and time if it is provided by the response headers
(via `GitHub-Authentication-Token-Expiration`).

The `DateTime::createFromFormat` call is used to validate the expected date
format. It accounts for all the possible issued with the datetime extension
by catching `\Throwable` exceptions. This can be fine-tuned in the future
by narrowing the catched scopes to `\ValueError`, or the new granualar
[exceptions in PHP >= 8.3](https://php.watch/versions/8.3/datetime-exceptions)
  • Loading branch information
Ayesh committed Oct 26, 2023
1 parent c827c93 commit d748c32
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/Composer/Command/DiagnoseCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -327,11 +327,26 @@ private function checkGithubOauth(string $domain, string $token)
try {
$url = $domain === 'github.com' ? 'https://api.'.$domain.'/' : 'https://'.$domain.'/api/v3/';

$this->httpDownloader->get($url, [
$response = $this->httpDownloader->get($url, [
'retry-auth-failure' => false,
]);

return true;
$expiration = $response->getHeader('github-authentication-token-expiration');

if ($expiration === null) {
return '<info>OK</> <comment>does not expire</>';
}

try {
if (\DateTime::createFromFormat('Y-m-d h:i:s O', $expiration) !== false) {
return '<info>OK</> <comment>expires on '. $expiration .'</>';
}

return '<info>OK</> <comment>returned unexpected expiration date format</>';
}
catch (\Throwable $exception) {
return '<info>OK</> <comment>error parsing returned expiration date</>';
}
} catch (\Exception $e) {
if ($e instanceof TransportException && $e->getCode() === 401) {
return '<comment>The oauth token for '.$domain.' seems invalid, run "composer config --global --unset github-oauth.'.$domain.'" to remove it</comment>';
Expand Down

0 comments on commit d748c32

Please sign in to comment.