about summary refs log tree commit diff
path: root/tools/ssh-key-to-forge/main.go
blob: efea3989dc8f8310b8e201c3e202718136f1d296 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main

import (
	"context"
	"encoding/base64"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/google/go-github/github"
	"github.com/tcnksm/go-gitconfig"
	"golang.org/x/crypto/ssh"
	"golang.org/x/oauth2"
)

var (
	defaultPublicKeyPath = filepath.Join(os.Getenv("HOME"), ".ssh", "id_rsa.pub")
)

func main() {
	sshkey := flag.String("ssh-key", defaultPublicKeyPath, "Path to the ssh public key to upload")

	flag.Parse()

	keyContent, keyTitle, err := readPublicKey(sshkey)
	if err != nil {
		log.Fatal(err)
	}

	keyToGitHub(keyContent, keyTitle)
}

// readPublicKey reads the public key, ensure it's in the proper
// format to prevent sending incorrect data, and returns the content
// of the key (the whole content) and the last field of the key that
// will be used as the title.
func readPublicKey(sshkey *string) (string, string, error) {
	// first, let's ensure it's a public key, so we don't upload
	// something incorrect.
	data, err := ioutil.ReadFile(*sshkey)
	if err != nil {
		return "", "", fmt.Errorf("failed to open %s: %v", *sshkey, err)
	}

	// we only want the content of the key to be parsed, not all the fields
	fields := strings.Fields(string(data))
	if len(fields) < 2 {
		return "", "", fmt.Errorf("not enough fields in public key %s (%d)", *sshkey, len(fields))
	}

	raw, err := base64.StdEncoding.DecodeString(fields[1])
	if err != nil {
		return "", "", fmt.Errorf("failed to read the second field in the public key %s: %v", *sshkey, err)
	}
	_, err = ssh.ParsePublicKey(raw)
	if err != nil {
		return "", "", fmt.Errorf("%s is not a valid public key: %v", *sshkey, err)
	}

	return strings.TrimSuffix(string(data), "\n"), fields[2], nil
}

// If the key does not exists already on GitHub, upload it, using the
// signature (last part of the key) as the title.
func keyToGitHub(keyContent, keyTitle string) {
	user, err := gitconfig.Global("github.user")
	if err != nil {
		fmt.Fprintf(os.Stderr, "github: failed to get the username: %v", err)
		return
	}

	token, err := gitconfig.Global("github.tokensshtoforge")
	if err != nil {
		fmt.Fprintf(os.Stderr, "github: failed to get the token: %v", err)
		return
	}

	ctx := context.Background()
	ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
	tc := oauth2.NewClient(ctx, ts)

	client := github.NewClient(tc)

	keys, _, err := client.Users.ListKeys(ctx, user, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "github: failed to get the list of existing keys: %v", err)
		return
	}

	skip := false
	for _, k := range keys {
		ghKey := *k.Key + " " + keyTitle
		c := strings.Compare(ghKey, keyContent)
		if c == 0 {
			skip = true
			break
		}
	}

	if !skip {
		key := github.Key{
			Key:   &keyContent,
			Title: &keyTitle,
		}
		_, _, err := client.Users.CreateKey(ctx, &key)
		if err != nil {
			fmt.Fprintf(os.Stderr, "github: failed to upload the ssh public key: %+v", err)
			return
		}
	}
}