2018-09-21 13:54:48 +03:00
package github
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"os"
2018-09-21 19:23:46 +03:00
"regexp"
2019-11-19 23:12:10 +03:00
"sort"
2019-05-24 22:04:25 +03:00
"strconv"
2018-09-21 13:54:48 +03:00
"strings"
"time"
2019-11-26 21:46:50 +03:00
text "github.com/MichaelMure/go-term-text"
2019-05-29 21:49:55 +03:00
"github.com/pkg/errors"
2019-05-24 22:04:25 +03:00
2018-09-21 19:23:46 +03:00
"github.com/MichaelMure/git-bug/bridge/core"
2019-12-08 23:15:06 +03:00
"github.com/MichaelMure/git-bug/bridge/core/auth"
"github.com/MichaelMure/git-bug/cache"
2019-11-23 21:20:32 +03:00
"github.com/MichaelMure/git-bug/entity"
2019-12-26 00:55:53 +03:00
"github.com/MichaelMure/git-bug/identity"
2020-01-08 00:06:42 +03:00
"github.com/MichaelMure/git-bug/input"
2018-09-21 19:23:46 +03:00
"github.com/MichaelMure/git-bug/repository"
2019-11-26 21:46:50 +03:00
"github.com/MichaelMure/git-bug/util/colors"
2018-09-21 13:54:48 +03:00
)
2019-04-27 02:15:02 +03:00
const (
2019-06-17 00:02:59 +03:00
target = "github"
2019-04-27 02:15:02 +03:00
githubV3Url = "https://api.github.com"
2019-05-24 22:04:25 +03:00
keyOwner = "owner"
2019-04-27 02:15:02 +03:00
keyProject = "project"
2019-05-24 22:04:25 +03:00
2019-05-26 13:47:01 +03:00
defaultTimeout = 60 * time . Second
2019-04-27 02:15:02 +03:00
)
2018-09-21 19:23:46 +03:00
2019-05-24 22:04:25 +03:00
var (
2019-05-29 21:49:55 +03:00
ErrBadProjectURL = errors . New ( "bad project url" )
2019-05-24 22:04:25 +03:00
)
2018-09-21 13:54:48 +03:00
2019-12-08 23:15:06 +03:00
func ( g * Github ) Configure ( repo * cache . RepoCache , params core . BridgeParams ) ( core . Configuration , error ) {
2019-12-10 22:30:29 +03:00
if params . BaseURL != "" {
fmt . Println ( "warning: --base-url is ineffective for a Github bridge" )
}
2019-05-24 22:04:25 +03:00
conf := make ( core . Configuration )
var err error
2019-12-08 23:15:06 +03:00
if ( params . CredPrefix != "" || params . TokenRaw != "" ) &&
2019-08-23 12:09:03 +03:00
( params . URL == "" && ( params . Project == "" || params . Owner == "" ) ) {
2019-08-21 15:24:48 +03:00
return nil , fmt . Errorf ( "you must provide a project URL or Owner/Name to configure this bridge with a token" )
}
2019-11-26 21:46:50 +03:00
var owner string
var project string
2019-12-08 23:15:06 +03:00
2019-05-25 16:56:52 +03:00
// getting owner and project name
2019-11-26 21:46:50 +03:00
switch {
case params . Owner != "" && params . Project != "" :
2019-05-25 18:27:25 +03:00
// first try to use params if both or project and owner are provided
2019-05-24 22:04:25 +03:00
owner = params . Owner
project = params . Project
2019-11-26 21:46:50 +03:00
case params . URL != "" :
2019-05-25 18:27:25 +03:00
// try to parse params URL and extract owner and project
2019-05-29 21:49:55 +03:00
owner , project , err = splitURL ( params . URL )
2019-05-24 22:04:25 +03:00
if err != nil {
return nil , err
}
2019-11-26 21:46:50 +03:00
default :
2019-05-25 18:27:25 +03:00
// terminal prompt
2019-12-08 23:15:06 +03:00
owner , project , err = promptURL ( repo )
2019-05-24 22:04:25 +03:00
if err != nil {
return nil , err
}
2018-09-21 13:54:48 +03:00
}
2019-05-24 22:04:25 +03:00
// validate project owner
ok , err := validateUsername ( owner )
2018-09-21 13:54:48 +03:00
if err != nil {
return nil , err
}
2019-05-24 22:04:25 +03:00
if ! ok {
return nil , fmt . Errorf ( "invalid parameter owner: %v" , owner )
2018-09-21 13:54:48 +03:00
}
2019-12-08 23:15:06 +03:00
user , err := repo . GetUserIdentity ( )
2019-12-26 00:55:53 +03:00
if err != nil && err != identity . ErrNoIdentitySet {
2019-12-08 23:15:06 +03:00
return nil , err
2019-11-23 21:20:32 +03:00
}
2019-12-26 00:55:53 +03:00
// default to a "to be filled" user Id if we don't have a valid one yet
userId := auth . DefaultUserId
if user != nil {
userId = user . Id ( )
}
2019-12-08 23:15:06 +03:00
var cred auth . Credential
switch {
case params . CredPrefix != "" :
cred , err = auth . LoadWithPrefix ( repo , params . CredPrefix )
2018-09-21 19:23:46 +03:00
if err != nil {
return nil , err
2018-09-21 13:54:48 +03:00
}
2019-12-26 00:55:53 +03:00
if user != nil && cred . UserId ( ) != user . Id ( ) {
2019-12-08 23:15:06 +03:00
return nil , fmt . Errorf ( "selected credential don't match the user" )
}
case params . TokenRaw != "" :
2019-12-26 00:55:53 +03:00
cred = auth . NewToken ( userId , params . TokenRaw , target )
2019-12-08 23:15:06 +03:00
default :
2019-12-26 00:55:53 +03:00
cred , err = promptTokenOptions ( repo , userId , owner , project )
2019-11-23 21:20:32 +03:00
if err != nil {
return nil , err
}
2019-12-08 23:15:06 +03:00
}
token , ok := cred . ( * auth . Token )
if ! ok {
return nil , fmt . Errorf ( "the Github bridge only handle token credentials" )
2018-09-21 13:54:48 +03:00
}
2019-05-25 16:20:30 +03:00
// verify access to the repository with token
2019-12-08 23:15:06 +03:00
ok , err = validateProject ( owner , project , token )
2019-05-24 22:04:25 +03:00
if err != nil {
return nil , err
}
if ! ok {
2019-06-05 01:45:34 +03:00
return nil , fmt . Errorf ( "project doesn't exist or authentication token has an incorrect scope" )
2019-05-24 22:04:25 +03:00
}
2019-11-10 19:48:13 +03:00
conf [ core . ConfigKeyTarget ] = target
2019-05-24 22:04:25 +03:00
conf [ keyOwner ] = owner
conf [ keyProject ] = project
2018-09-21 13:54:48 +03:00
2019-08-21 15:24:48 +03:00
err = g . ValidateConfig ( conf )
if err != nil {
return nil , err
}
2019-12-08 23:15:06 +03:00
// don't forget to store the now known valid token
if ! auth . IdExist ( repo , cred . ID ( ) ) {
err = auth . Store ( repo , cred )
if err != nil {
return nil , err
}
}
2019-05-24 22:04:25 +03:00
return conf , nil
2018-09-21 13:54:48 +03:00
}
2018-09-24 18:21:24 +03:00
func ( * Github ) ValidateConfig ( conf core . Configuration ) error {
2019-11-10 19:48:13 +03:00
if v , ok := conf [ core . ConfigKeyTarget ] ; ! ok {
return fmt . Errorf ( "missing %s key" , core . ConfigKeyTarget )
2019-06-17 00:02:59 +03:00
} else if v != target {
return fmt . Errorf ( "unexpected target name: %v" , v )
2019-06-15 03:33:06 +03:00
}
2019-05-24 22:04:25 +03:00
if _ , ok := conf [ keyOwner ] ; ! ok {
return fmt . Errorf ( "missing %s key" , keyOwner )
2018-09-24 18:21:24 +03:00
}
if _ , ok := conf [ keyProject ] ; ! ok {
return fmt . Errorf ( "missing %s key" , keyProject )
}
return nil
}
2019-05-24 22:04:25 +03:00
func requestToken ( note , username , password string , scope string ) ( * http . Response , error ) {
return requestTokenWith2FA ( note , username , password , "" , scope )
2018-09-21 15:38:44 +03:00
}
2019-05-24 22:04:25 +03:00
func requestTokenWith2FA ( note , username , password , otpCode string , scope string ) ( * http . Response , error ) {
2018-09-21 15:38:44 +03:00
url := fmt . Sprintf ( "%s/authorizations" , githubV3Url )
params := struct {
Scopes [ ] string ` json:"scopes" `
Note string ` json:"note" `
Fingerprint string ` json:"fingerprint" `
} {
2019-05-24 22:04:25 +03:00
Scopes : [ ] string { scope } ,
2018-09-21 15:38:44 +03:00
Note : note ,
Fingerprint : randomFingerprint ( ) ,
}
data , err := json . Marshal ( params )
if err != nil {
return nil , err
}
req , err := http . NewRequest ( "POST" , url , bytes . NewBuffer ( data ) )
if err != nil {
return nil , err
}
req . SetBasicAuth ( username , password )
req . Header . Set ( "Content-Type" , "application/json" )
if otpCode != "" {
req . Header . Set ( "X-GitHub-OTP" , otpCode )
}
2019-05-24 22:04:25 +03:00
client := & http . Client {
Timeout : defaultTimeout ,
}
2018-09-21 15:38:44 +03:00
return client . Do ( req )
}
2018-09-21 19:23:46 +03:00
func decodeBody ( body io . ReadCloser ) ( string , error ) {
2018-09-21 13:54:48 +03:00
data , _ := ioutil . ReadAll ( body )
aux := struct {
Token string ` json:"token" `
} { }
err := json . Unmarshal ( data , & aux )
if err != nil {
2018-09-21 19:23:46 +03:00
return "" , err
}
if aux . Token == "" {
return "" , fmt . Errorf ( "no token found in response: %s" , string ( data ) )
2018-09-21 13:54:48 +03:00
}
2018-09-21 19:23:46 +03:00
return aux . Token , nil
2018-09-21 13:54:48 +03:00
}
func randomFingerprint ( ) string {
// Doesn't have to be crypto secure, it's just to avoid token collision
rand . Seed ( time . Now ( ) . UnixNano ( ) )
var letterRunes = [ ] rune ( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" )
b := make ( [ ] rune , 32 )
for i := range b {
b [ i ] = letterRunes [ rand . Intn ( len ( letterRunes ) ) ]
}
return string ( b )
}
2019-12-08 23:15:06 +03:00
func promptTokenOptions ( repo repository . RepoConfig , userId entity . Id , owner , project string ) ( auth . Credential , error ) {
2019-05-25 16:20:30 +03:00
for {
2019-12-08 23:15:06 +03:00
creds , err := auth . List ( repo , auth . WithUserId ( userId ) , auth . WithTarget ( target ) )
2019-11-23 21:20:32 +03:00
if err != nil {
return nil , err
}
2019-05-25 16:20:30 +03:00
fmt . Println ( )
2019-11-26 22:45:32 +03:00
fmt . Println ( "[1]: enter my token" )
2019-06-05 02:42:36 +03:00
fmt . Println ( "[2]: interactive token creation" )
2019-11-24 16:38:44 +03:00
2019-12-08 23:15:06 +03:00
if len ( creds ) > 0 {
sort . Sort ( auth . ById ( creds ) )
2019-11-26 21:46:50 +03:00
fmt . Println ( )
fmt . Println ( "Existing tokens for Github:" )
2019-12-08 23:15:06 +03:00
for i , cred := range creds {
token := cred . ( * auth . Token )
fmt . Printf ( "[%d]: %s => %s (%s)\n" ,
i + 3 ,
colors . Cyan ( token . ID ( ) . Human ( ) ) ,
colors . Red ( text . TruncateMax ( token . Value , 10 ) ) ,
token . CreateTime ( ) . Format ( time . RFC822 ) ,
)
2019-11-23 21:20:32 +03:00
}
}
2019-11-26 21:46:50 +03:00
fmt . Println ( )
2019-05-25 16:20:30 +03:00
fmt . Print ( "Select option: " )
line , err := bufio . NewReader ( os . Stdin ) . ReadString ( '\n' )
fmt . Println ( )
if err != nil {
2019-11-23 21:20:32 +03:00
return nil , err
2019-05-25 16:20:30 +03:00
}
2019-11-25 17:08:48 +03:00
line = strings . TrimSpace ( line )
2019-05-25 16:20:30 +03:00
index , err := strconv . Atoi ( line )
2019-12-08 23:15:06 +03:00
if err != nil || index < 1 || index > len ( creds ) + 2 {
2019-05-25 16:20:30 +03:00
fmt . Println ( "invalid input" )
continue
}
2019-11-24 16:38:44 +03:00
switch index {
case 1 :
2019-12-08 23:15:06 +03:00
value , err := promptToken ( )
2019-11-23 21:20:32 +03:00
if err != nil {
return nil , err
}
2019-12-08 23:15:06 +03:00
return auth . NewToken ( userId , value , target ) , nil
2019-11-24 16:38:44 +03:00
case 2 :
2019-12-08 23:15:06 +03:00
value , err := loginAndRequestToken ( owner , project )
2019-11-23 21:20:32 +03:00
if err != nil {
return nil , err
}
2019-12-08 23:15:06 +03:00
return auth . NewToken ( userId , value , target ) , nil
2019-11-24 16:38:44 +03:00
default :
2019-12-08 23:15:06 +03:00
return creds [ index - 3 ] , nil
2019-05-25 16:20:30 +03:00
}
2019-11-23 21:20:32 +03:00
}
}
2019-05-25 16:20:30 +03:00
func promptToken ( ) ( string , error ) {
2019-05-26 18:35:39 +03:00
fmt . Println ( "You can generate a new token by visiting https://github.com/settings/tokens." )
fmt . Println ( "Choose 'Generate new token' and set the necessary access scope for your repository." )
fmt . Println ( )
fmt . Println ( "The access scope depend on the type of repository." )
fmt . Println ( "Public:" )
2019-05-29 21:49:55 +03:00
fmt . Println ( " - 'public_repo': to be able to read public repositories" )
2019-05-26 18:35:39 +03:00
fmt . Println ( "Private:" )
2019-05-29 21:49:55 +03:00
fmt . Println ( " - 'repo' : to be able to read private repositories" )
2019-05-26 18:35:39 +03:00
fmt . Println ( )
2019-06-05 02:42:36 +03:00
re , err := regexp . Compile ( ` ^[a-zA-Z0-9] { 40} ` )
if err != nil {
panic ( "regexp compile:" + err . Error ( ) )
}
2020-01-08 00:06:42 +03:00
validator := func ( name string , value string ) ( complaint string , err error ) {
if re . MatchString ( value ) {
return "" , nil
2019-05-25 16:20:30 +03:00
}
2020-01-08 00:06:42 +03:00
return "token has incorrect format" , nil
2019-05-25 16:20:30 +03:00
}
2020-01-08 00:06:42 +03:00
return input . Prompt ( "Enter token" , "token" , "" , input . Required , validator )
2019-05-25 16:20:30 +03:00
}
func loginAndRequestToken ( owner , project string ) ( string , error ) {
2019-11-26 21:46:50 +03:00
fmt . Println ( "git-bug will now generate an access token in your Github profile. Your credential are not stored and are only used to generate the token. The token is stored in the global git config." )
2019-05-25 16:20:30 +03:00
fmt . Println ( )
2019-05-26 13:47:01 +03:00
fmt . Println ( "The access scope depend on the type of repository." )
fmt . Println ( "Public:" )
2019-05-29 21:49:55 +03:00
fmt . Println ( " - 'public_repo': to be able to read public repositories" )
2019-05-26 13:47:01 +03:00
fmt . Println ( "Private:" )
2019-05-29 21:49:55 +03:00
fmt . Println ( " - 'repo' : to be able to read private repositories" )
2019-05-25 16:20:30 +03:00
fmt . Println ( )
// prompt project visibility to know the token scope needed for the repository
2020-01-08 00:06:42 +03:00
i , err := input . PromptChoice ( "repository visibility" , [ ] string { "public" , "private" } )
2019-05-25 16:20:30 +03:00
if err != nil {
return "" , err
}
2020-01-08 00:06:42 +03:00
isPublic := i == 0
2019-05-25 16:20:30 +03:00
username , err := promptUsername ( )
if err != nil {
return "" , err
}
2020-01-08 00:06:42 +03:00
password , err := input . PromptPassword ( "Password" , "password" , input . Required )
2019-05-25 16:20:30 +03:00
if err != nil {
return "" , err
}
var scope string
if isPublic {
2019-05-29 21:49:55 +03:00
// public_repo is requested to be able to read public repositories
scope = "public_repo"
2019-05-25 16:20:30 +03:00
} else {
// 'repo' is request to be able to read private repositories
// /!\ token will have read/write rights on every private repository you have access to
scope = "repo"
}
// Attempt to authenticate and create a token
note := fmt . Sprintf ( "git-bug - %s/%s" , owner , project )
resp , err := requestToken ( note , username , password , scope )
if err != nil {
return "" , err
}
defer resp . Body . Close ( )
// Handle 2FA is needed
OTPHeader := resp . Header . Get ( "X-GitHub-OTP" )
if resp . StatusCode == http . StatusUnauthorized && OTPHeader != "" {
2020-01-08 00:06:42 +03:00
otpCode , err := input . PromptPassword ( "Two-factor authentication code" , "code" , input . Required )
2019-05-25 16:20:30 +03:00
if err != nil {
return "" , err
}
2020-01-08 00:06:42 +03:00
resp , err = requestTokenWith2FA ( note , login , password , otpCode , scope )
2019-05-25 16:20:30 +03:00
if err != nil {
return "" , err
}
defer resp . Body . Close ( )
}
if resp . StatusCode == http . StatusCreated {
2019-05-26 13:47:01 +03:00
return decodeBody ( resp . Body )
2019-05-25 16:20:30 +03:00
}
b , _ := ioutil . ReadAll ( resp . Body )
return "" , fmt . Errorf ( "error creating token %v: %v" , resp . StatusCode , string ( b ) )
}
2019-12-08 23:15:06 +03:00
func promptURL ( repo repository . RepoCommon ) ( string , string , error ) {
// remote suggestions
remotes , err := repo . GetRemotes ( )
if err != nil {
return "" , "" , err
}
2019-05-27 21:26:36 +03:00
validRemotes := getValidGithubRemoteURLs ( remotes )
2019-05-25 16:20:30 +03:00
if len ( validRemotes ) > 0 {
for {
fmt . Println ( "\nDetected projects:" )
// print valid remote github urls
for i , remote := range validRemotes {
fmt . Printf ( "[%d]: %v\n" , i + 1 , remote )
}
fmt . Printf ( "\n[0]: Another project\n\n" )
fmt . Printf ( "Select option: " )
line , err := bufio . NewReader ( os . Stdin ) . ReadString ( '\n' )
if err != nil {
return "" , "" , err
}
2019-11-25 17:08:48 +03:00
line = strings . TrimSpace ( line )
2019-05-25 16:20:30 +03:00
index , err := strconv . Atoi ( line )
2019-07-23 18:20:42 +03:00
if err != nil || index < 0 || index > len ( validRemotes ) {
2019-05-25 16:20:30 +03:00
fmt . Println ( "invalid input" )
continue
}
// if user want to enter another project url break this loop
if index == 0 {
break
}
// get owner and project with index
2019-05-29 21:49:55 +03:00
owner , project , _ := splitURL ( validRemotes [ index - 1 ] )
2019-05-25 16:20:30 +03:00
return owner , project , nil
}
}
// manually enter github url
2018-09-21 19:23:46 +03:00
for {
2018-09-24 16:25:15 +03:00
fmt . Print ( "Github project URL: " )
2018-09-21 19:23:46 +03:00
line , err := bufio . NewReader ( os . Stdin ) . ReadString ( '\n' )
if err != nil {
return "" , "" , err
}
2019-11-25 17:08:48 +03:00
line = strings . TrimSpace ( line )
2018-09-21 19:23:46 +03:00
if line == "" {
fmt . Println ( "URL is empty" )
continue
}
2019-05-25 16:20:30 +03:00
// get owner and project from url
2019-05-29 21:49:55 +03:00
owner , project , err := splitURL ( line )
2018-09-21 19:23:46 +03:00
if err != nil {
fmt . Println ( err )
continue
}
2019-05-25 16:20:30 +03:00
return owner , project , nil
2018-09-21 19:23:46 +03:00
}
}
2019-05-29 21:49:55 +03:00
// splitURL extract the owner and project from a github repository URL. It will remove the
// '.git' extension from the URL before parsing it.
// Note that Github removes the '.git' extension from projects names at their creation
func splitURL ( url string ) ( owner string , project string , err error ) {
2019-05-26 18:35:39 +03:00
cleanURL := strings . TrimSuffix ( url , ".git" )
2019-05-29 21:49:55 +03:00
re , err := regexp . Compile ( ` github\.com[/:]([a-zA-Z0-9\-_]+)/([a-zA-Z0-9\-_.]+) ` )
if err != nil {
2019-05-30 13:50:21 +03:00
panic ( "regexp compile:" + err . Error ( ) )
2019-05-29 21:49:55 +03:00
}
res := re . FindStringSubmatch ( cleanURL )
2018-09-21 19:23:46 +03:00
if res == nil {
2019-05-29 21:49:55 +03:00
return "" , "" , ErrBadProjectURL
2019-05-25 16:20:30 +03:00
}
2019-05-29 21:49:55 +03:00
owner = res [ 1 ]
project = res [ 2 ]
2019-06-05 01:45:34 +03:00
return
2019-05-25 16:20:30 +03:00
}
2019-05-27 21:26:36 +03:00
func getValidGithubRemoteURLs ( remotes map [ string ] string ) [ ] string {
2019-05-25 16:20:30 +03:00
urls := make ( [ ] string , 0 , len ( remotes ) )
for _ , url := range remotes {
// split url can work again with shortURL
2019-05-29 21:49:55 +03:00
owner , project , err := splitURL ( url )
2019-05-25 16:20:30 +03:00
if err == nil {
2019-05-29 21:49:55 +03:00
shortURL := fmt . Sprintf ( "%s/%s/%s" , "github.com" , owner , project )
2019-05-25 16:20:30 +03:00
urls = append ( urls , shortURL )
}
2018-09-21 13:54:48 +03:00
}
2019-11-19 23:12:10 +03:00
sort . Strings ( urls )
2019-05-25 16:20:30 +03:00
return urls
2018-09-21 13:54:48 +03:00
}
func validateUsername ( username string ) ( bool , error ) {
url := fmt . Sprintf ( "%s/users/%s" , githubV3Url , username )
2019-05-29 21:49:55 +03:00
client := & http . Client {
Timeout : defaultTimeout ,
}
resp , err := client . Get ( url )
2018-09-21 13:54:48 +03:00
if err != nil {
return false , err
}
err = resp . Body . Close ( )
if err != nil {
return false , err
}
return resp . StatusCode == http . StatusOK , nil
}
2019-12-08 23:15:06 +03:00
func validateProject ( owner , project string , token * auth . Token ) ( bool , error ) {
2019-05-24 22:04:25 +03:00
url := fmt . Sprintf ( "%s/repos/%s/%s" , githubV3Url , owner , project )
req , err := http . NewRequest ( "GET" , url , nil )
if err != nil {
return false , err
}
2019-05-25 16:20:30 +03:00
// need the token for private repositories
2019-12-08 23:15:06 +03:00
req . Header . Set ( "Authorization" , fmt . Sprintf ( "token %s" , token . Value ) )
2019-05-24 22:04:25 +03:00
client := & http . Client {
Timeout : defaultTimeout ,
}
resp , err := client . Do ( req )
if err != nil {
return false , err
}
err = resp . Body . Close ( )
if err != nil {
return false , err
}
return resp . StatusCode == http . StatusOK , nil
}