-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
181 lines (145 loc) · 3.63 KB
/
auth.go
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package cmd
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"runtime"
"github.com/gomicro/align/config"
"github.com/gomicro/trust"
"github.com/spf13/cobra"
"golang.org/x/oauth2"
)
var (
reapprove bool
clientID string
clientSecret string
)
func init() {
authCmd.Flags().BoolVarP(&reapprove, "force", "f", false, "force align to reauth")
}
var authCmd = &cobra.Command{
Use: "auth",
Short: "auth with github",
Long: `authorize align against github`,
RunE: authFunc,
}
const (
state = "9292a768-34bf-4002-8a69-8ace5302709d"
)
func authFunc(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if clientID == "" || clientSecret == "" {
return fmt.Errorf("client id and secret must be baked into the binary, and are not present")
}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return err
}
port := listener.Addr().(*net.TCPAddr).Port
pool := trust.New()
certs, err := pool.CACerts()
if err != nil {
return fmt.Errorf("failed to create cert pool: %w", err)
}
httpClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: certs,
MinVersion: tls.VersionTLS12,
},
},
}
ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient)
conf := &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
Scopes: []string{"repo"},
Endpoint: oauth2.Endpoint{
AuthURL: "https://github.com/login/oauth/authorize",
TokenURL: "https://github.com/login/oauth/access_token",
},
RedirectURL: fmt.Sprintf("http://localhost:%v/auth", port),
}
token := make(chan string)
go startServer(ctx, listener, conf, token)
var opts []oauth2.AuthCodeOption
if reapprove {
opts = []oauth2.AuthCodeOption{oauth2.AccessTypeOffline, oauth2.ApprovalForce}
} else {
opts = []oauth2.AuthCodeOption{oauth2.AccessTypeOffline}
}
url := conf.AuthCodeURL(state, opts...)
err = openBrowser(url)
if err != nil {
return err
}
tkn := <-token
close(token)
c, err := config.ParseFromFile()
if err != nil {
return err
}
c.Github.Token = tkn
err = c.WriteFile()
if err != nil {
return err
}
return nil
}
func startServer(ctx context.Context, listener net.Listener, conf *oauth2.Config, token chan string) {
http.HandleFunc("/auth", authHandler(ctx, conf, token))
srv := &http.Server{}
go func() {
<-ctx.Done()
err := srv.Shutdown(ctx)
if err != nil {
fmt.Printf("Error shutting down server: %v", err.Error())
os.Exit(1)
}
}()
err := srv.Serve(listener)
if err != nil {
fmt.Printf("Error: %v", err.Error())
os.Exit(1)
}
}
func authHandler(ctx context.Context, conf *oauth2.Config, token chan string) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
code := req.URL.Query().Get("code")
rstate := req.URL.Query().Get("state")
if rstate != state {
fmt.Println("bad response from oauth server")
os.Exit(1)
}
tok, err := conf.Exchange(ctx, code)
if err != nil {
fmt.Printf("errored exchanging token: %v", err.Error())
os.Exit(1)
}
body := `<html>
<body>
<h1>Config file updated, you can close this window.</h1>
</body>
</html>`
w.WriteHeader(http.StatusOK)
w.Write([]byte(body)) //nolint
token <- tok.AccessToken
}
}
func openBrowser(url string) error {
switch runtime.GOOS {
case "linux":
return exec.Command("xdg-open", url).Start()
case "windows":
return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
return exec.Command("open", url).Start()
default:
return fmt.Errorf("unsupported platform")
}
}