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
|
// Package auth handles Google OAuth2 for the CLI using a local loopback server
// to receive the authorization code.
package auth
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net"
"net/http"
"os/exec"
"runtime"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"git.onurgunduz.com/colabctl/internal/config"
)
// Scopes required to use the Drive API and the Colab runtime API.
// The colaboratory scope is mandatory; without it the /tun/m/assign
// endpoint returns 403 SCOPE_NOT_PERMITTED.
var scopes = []string{
"openid",
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/colaboratory",
"https://www.googleapis.com/auth/drive",
}
// oauthConfig builds an oauth2.Config from the supplied client credentials.
func oauthConfig(clientID, clientSecret, redirectURL string) *oauth2.Config {
return &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Scopes: scopes,
Endpoint: google.Endpoint,
}
}
// Login performs an interactive OAuth2 flow. It starts a temporary local HTTP
// server on a free port, opens the browser for the user, waits for the
// authorization code, exchanges it for tokens, and persists them to disk.
func Login(ctx context.Context, clientID, clientSecret string) error {
// Pick a free port on localhost.
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return fmt.Errorf("start local server: %w", err)
}
port := listener.Addr().(*net.TCPAddr).Port
redirectURL := fmt.Sprintf("http://127.0.0.1:%d/callback", port)
cfg := oauthConfig(clientID, clientSecret, redirectURL)
// Generate a random state value to guard against CSRF.
state, err := randomState()
if err != nil {
return err
}
authURL := cfg.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.ApprovalForce)
codeCh := make(chan string, 1)
errCh := make(chan error, 1)
mux := http.NewServeMux()
srv := &http.Server{Handler: mux}
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("state") != state {
http.Error(w, "state mismatch", http.StatusBadRequest)
errCh <- errors.New("oauth2 state mismatch; possible CSRF")
return
}
code := r.URL.Query().Get("code")
if code == "" {
msg := r.URL.Query().Get("error")
http.Error(w, "authorization denied", http.StatusBadRequest)
errCh <- fmt.Errorf("authorization denied: %s", msg)
return
}
fmt.Fprintln(w, "<html><body><h2>Authentication successful; you can close this tab.</h2></body></html>")
codeCh <- code
})
go func() {
if err := srv.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
errCh <- err
}
}()
fmt.Printf("Opening browser for authentication.\nIf the browser does not open, visit:\n\n %s\n\n", authURL)
openBrowser(authURL)
var code string
select {
case code = <-codeCh:
case err = <-errCh:
_ = srv.Shutdown(context.Background())
return err
case <-time.After(5 * time.Minute):
_ = srv.Shutdown(context.Background())
return errors.New("timed out waiting for authorization")
}
_ = srv.Shutdown(context.Background())
tok, err := cfg.Exchange(ctx, code)
if err != nil {
return fmt.Errorf("exchange code: %w", err)
}
return config.SaveToken(tok)
}
// TokenSource loads the stored token and wraps it in an auto-refreshing
// TokenSource. Returns an error if no token has been saved (i.e. the user has
// not yet run auth login).
func TokenSource(ctx context.Context, clientID, clientSecret string) (oauth2.TokenSource, error) {
tok, err := config.LoadToken()
if err != nil {
return nil, fmt.Errorf("not authenticated; run \"colabctl auth login\" first: %w", err)
}
cfg := oauthConfig(clientID, clientSecret, "")
return cfg.TokenSource(ctx, tok), nil
}
// Client returns an *http.Client backed by the stored token.
func Client(ctx context.Context, clientID, clientSecret string) (*http.Client, error) {
ts, err := TokenSource(ctx, clientID, clientSecret)
if err != nil {
return nil, err
}
return oauth2.NewClient(ctx, ts), nil
}
func randomState() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("generate state: %w", err)
}
return base64.URLEncoding.EncodeToString(b), nil
}
func openBrowser(url string) {
var cmd string
var args []string
switch runtime.GOOS {
case "darwin":
cmd = "open"
args = []string{url}
case "windows":
cmd = "rundll32"
args = []string{"url.dll,FileProtocolHandler", url}
default:
cmd = "xdg-open"
args = []string{url}
}
_ = exec.Command(cmd, args...).Start()
}
|