/
appauth.go
208 lines (188 loc) · 5.34 KB
/
appauth.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
199
200
201
202
203
204
205
206
207
208
// Package userauth implements the OAuth2 native app authorization
// described in rfc8252. This helps CLI client to get access token.
//
// It uses loopback device and by default uses any free port according
// to https://datatracker.ietf.org/doc/html/rfc8252#section-7.3
//
// To configure this, you'll need to add a couple of redirect URLs
// like http://127.0.0.1:<your-port> into the okta application sign-in redirect URIs.
// And use WithLocalServerBindAddress to configure the context to
// only uses ports list from your assigned list.
package appauth
import (
"context"
"fmt"
"log"
"net/http"
"time"
"golang.org/x/oauth2"
"golang.org/x/sync/errgroup"
"github.com/int128/oauth2cli"
"github.com/int128/oauth2cli/oauth2params"
"github.com/tiewei/otoken/pkg/openid"
"github.com/tiewei/otoken/pkg/types"
)
// Option configures optional field for TokenSource,
// it's an interface with private function, hence can
// only be created within the pkg.
type Option interface {
apply(*TokenSource)
}
type option struct {
applyFunc func(*TokenSource)
}
func (o option) apply(s *TokenSource) {
o.applyFunc(s)
}
// UseURLOpener sets URL opener for tokensource
func UseURLOpener(o types.URLOpener) Option {
return &option{applyFunc: func(s *TokenSource) {
s.opener = o
}}
}
// UseHTTPClient sets http client used to make http requests.
func UseHTTPClient(c *http.Client) Option {
return &option{applyFunc: func(s *TokenSource) {
s.client = c
}}
}
// Timeout sets additional timeout for the token polling process.
func Timeout(t time.Duration) Option {
return &option{applyFunc: func(s *TokenSource) {
s.timeout = t
}}
}
// UseBindAddress provides a way to bind local server on pre-configured addresses.
//
// The RFC8252 requires port to be any port when using loopback interface redirection,
// hence the default behavior is using first free port and 127.0.0.1 address
// https://datatracker.ietf.org/doc/html/rfc8252#section-7.3
//
// In case running it in container, it will need to bind on 0.0.0.0 or other addresses.
func UseBindAddress(addresses []string) Option {
return &option{applyFunc: func(s *TokenSource) {
s.bindAddresses = addresses
}}
}
// UseRedirectHostname provides a way to set redirect hostname.
//
// The RFC8252 requires 127.0.0.1 address to for safety reason.
// You can set this if your provider does not accept 127.0.0.1
func UseRedirectHostname(hostname string) Option {
return &option{applyFunc: func(s *TokenSource) {
s.redirectHostname = hostname
}}
}
type TokenSource struct {
authEndpoint string
tokenEndpoint string
clientID string
scopes []string
clientSecret string
usePKCE bool
client *http.Client
opener types.URLOpener
bindAddresses []string
timeout time.Duration
redirectHostname string
}
var _ oauth2.TokenSource = &TokenSource{}
func NewPKCE(authEndpoint string, tokenEndpoint string, clientID string, scopes []string, opts ...Option) *TokenSource {
s := &TokenSource{
authEndpoint: authEndpoint,
tokenEndpoint: tokenEndpoint,
clientID: clientID,
usePKCE: true,
scopes: openid.EnsureOpenIDScope(scopes),
client: http.DefaultClient,
opener: types.BrowserOpener,
redirectHostname: "127.0.0.1",
}
for _, op := range opts {
if op != nil {
op.apply(s)
}
}
return s
}
func NewImplicit(authEndpoint string, tokenEndpoint string, clientID string, clientSecret string, scopes []string, opts ...Option) *TokenSource {
s := &TokenSource{
authEndpoint: authEndpoint,
tokenEndpoint: tokenEndpoint,
clientID: clientID,
clientSecret: clientSecret,
scopes: openid.EnsureOpenIDScope(scopes),
client: http.DefaultClient,
opener: types.BrowserOpener,
redirectHostname: "127.0.0.1",
}
for _, op := range opts {
if op != nil {
op.apply(s)
}
}
return s
}
func (s *TokenSource) Token() (*oauth2.Token, error) {
oauth2Cfg := oauth2.Config{
ClientID: s.clientID,
ClientSecret: s.clientSecret,
Scopes: s.scopes,
Endpoint: oauth2.Endpoint{
TokenURL: s.tokenEndpoint,
AuthURL: s.authEndpoint,
},
}
readyChan := make(chan string, 1)
config := oauth2cli.Config{
OAuth2Config: oauth2Cfg,
LocalServerReadyChan: readyChan,
RedirectURLHostname: s.redirectHostname,
}
if len(s.bindAddresses) > 0 {
config.LocalServerBindAddress = s.bindAddresses
}
if s.usePKCE {
pkce, err := oauth2params.NewPKCE()
if err != nil {
return nil, err
}
config.AuthCodeOptions = pkce.AuthCodeOptions()
config.TokenRequestOptions = pkce.TokenRequestOptions()
}
ctx := context.Background()
if s.timeout > 0 {
var cancelFunc context.CancelFunc
ctx, cancelFunc = context.WithTimeout(ctx, s.timeout)
defer cancelFunc()
}
if s.client != nil {
ctx = context.WithValue(ctx, oauth2.HTTPClient, s.client)
}
var eg errgroup.Group
var token *oauth2.Token
eg.Go(func() error {
select {
case url, ok := <-readyChan:
if !ok {
return nil
}
s.opener(url)
return nil
case <-ctx.Done():
return fmt.Errorf("cancelled while waiting for the local server: %w", ctx.Err())
}
})
eg.Go(func() error {
var err error
token, err = oauth2cli.GetToken(ctx, config)
if err != nil {
return fmt.Errorf("could not get a token: %w", err)
}
return nil
})
if err := eg.Wait(); err != nil {
log.Printf("authorization error: %s", err)
}
return token, nil
}