-
Notifications
You must be signed in to change notification settings - Fork 560
/
auth.go
198 lines (164 loc) · 4.34 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package auth
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"github.com/adrg/xdg"
"github.com/pkg/browser"
"github.com/rs/zerolog/log"
"golang.org/x/oauth2"
)
const (
authDomain = "auth.dagger.cloud"
callbackPort = 38932
)
var credentialsFile = filepath.Join(xdg.ConfigHome, "dagger", "credentials.json")
var authConfig = &oauth2.Config{
// https://manage.auth0.com/dashboard/us/dagger-io/applications/brEY7u4SEoFypOgYBdYMs32b4ShRVIEv/settings
ClientID: "brEY7u4SEoFypOgYBdYMs32b4ShRVIEv",
RedirectURL: fmt.Sprintf("http://localhost:%d/callback", callbackPort),
Scopes: []string{"openid", "offline_access"},
Endpoint: oauth2.Endpoint{
AuthStyle: oauth2.AuthStyleInParams,
AuthURL: "https://" + authDomain + "/authorize",
TokenURL: "https://" + authDomain + "/oauth/token",
},
}
// Login logs the user in and stores the credentials for later use.
// Interactive messages are printed to w.
func Login(ctx context.Context) error {
lg := log.Ctx(ctx)
lg.Info().Msg("logging in to " + authDomain)
// oauth2 localhost handler
requestCh := make(chan *http.Request)
m := http.NewServeMux()
// since Login could be called multiple times, only register /callback once
m.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
if oauthError := r.URL.Query().Get("error"); oauthError != "" {
message := r.URL.Query().Get("error_description")
fmt.Fprintf(w, `
<html>
<head>
<script>window.close()</script>
<body>
%s
</body>
</html>
`, message)
} else {
fmt.Fprint(w, `
<html>
<head>
<script>window.location.href="https://dagger.cloud/auth-success"</script>
<body>
</body>
</html>
`)
}
requestCh <- r
})
srv := &http.Server{ //nolint: gosec
Addr: fmt.Sprintf("localhost:%d", callbackPort),
Handler: m,
}
go func() {
err := srv.ListenAndServe()
if err != http.ErrServerClosed {
lg.Fatal().Err(err).Msg("auth server failed")
}
}()
defer srv.Shutdown(ctx)
// Generate random state
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
return fmt.Errorf("rand: %w", err)
}
state := hex.EncodeToString(b)
tokenURL := authConfig.AuthCodeURL(state)
lg.Info().Msgf("opening %s", tokenURL)
if err := browser.OpenURL(tokenURL); err != nil {
lg.Warn().Err(err).Msg("could not open browser; please follow the above URL manually")
}
var req *http.Request
select {
case req = <-requestCh:
case <-ctx.Done():
lg.Info().Msg("giving up")
return nil
}
responseState := req.URL.Query().Get("state")
if state != responseState {
return fmt.Errorf("corrupted login challenge (%q != %q)", state, responseState)
}
if oauthError := req.URL.Query().Get("error"); oauthError != "" {
description := req.URL.Query().Get("error_description")
return fmt.Errorf("authentication error: %s (%s)", oauthError, description)
}
token, err := authConfig.Exchange(ctx, req.URL.Query().Get("code"))
if err != nil {
return err
}
return saveCredentials(token)
}
// Logout deletes the client credentials
func Logout() error {
err := os.Remove(credentialsFile)
if os.IsNotExist(err) {
return nil
}
return err
}
func TokenSource(ctx context.Context) oauth2.TokenSource {
return loginTokenSource{ctx}
}
// loginTokenSource is a TokenSource that will re-login if a token is not available or cannot be refreshed.
type loginTokenSource struct {
ctx context.Context
}
func (src loginTokenSource) Token() (*oauth2.Token, error) {
token, err := loadCredentials()
if err != nil {
if err := Login(src.ctx); err != nil {
return nil, err
}
return src.Token()
}
token, err = authConfig.TokenSource(src.ctx, token).Token()
if err != nil {
if err := Login(src.ctx); err != nil {
return nil, err
}
return src.Token()
}
return token, nil
}
func loadCredentials() (*oauth2.Token, error) {
data, err := os.ReadFile(credentialsFile)
if err != nil {
return nil, err
}
token := &oauth2.Token{}
if err := json.Unmarshal(data, token); err != nil {
return nil, err
}
return token, nil
}
func saveCredentials(token *oauth2.Token) error {
data, err := json.Marshal(token)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(credentialsFile), 0o755); err != nil {
return err
}
if err := os.WriteFile(credentialsFile, data, 0o600); err != nil {
return err
}
return nil
}