This repository was archived by the owner on Jul 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathauthserver.go
248 lines (214 loc) · 7.61 KB
/
authserver.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
// Package authserver models an OAuth 2.0 Authorization Server
package authserver
import (
"errors"
"net/http"
"net/url"
"strings"
"github.com/golang/groupcache/singleflight"
"go.uber.org/zap"
"github.com/ibm-cloud-security/app-identity-and-access-adapter/adapter/authserver/keyset"
cstmErrs "github.com/ibm-cloud-security/app-identity-and-access-adapter/adapter/errors"
"github.com/ibm-cloud-security/app-identity-and-access-adapter/adapter/networking"
)
const (
clientPostSecret = "client_secret_post"
//clientPostBasic = "client_basic_post"
)
// DiscoveryConfig encapsulates the discovery endpoint configuration
type DiscoveryConfig struct {
DiscoveryURL string
Issuer string `json:"issuer"`
AuthURL string `json:"authorization_endpoint"`
TokenURL string `json:"token_endpoint"`
JwksURL string `json:"jwks_uri"`
UserInfoURL string `json:"userinfo_endpoint"`
}
// TokenResponse models an OAuth 2.0 /Value endpoint response
type TokenResponse struct {
// The OAuth 2.0 Access Value
AccessToken string `json:"access_token"`
// The OIDC ID Value
IdentityToken string `json:"id_token"`
// The OAuth 2.0 Refresh Value
RefreshToken string `json:"refresh_token"`
// The token expiration time
ExpiresIn int `json:"expires_in"`
}
// AuthorizationServerService represents an authorization server instance
type AuthorizationServerService interface {
JwksEndpoint() string
TokenEndpoint() string
AuthorizationEndpoint() string
UserInfoEndpoint() string
KeySet() keyset.KeySet
SetKeySet(keyset.KeySet)
GetTokens(authnMethod string, clientID string, clientSecret string, authorizationCode string, redirectURI string, refreshToken string) (*TokenResponse, error)
}
// RemoteService represents a remote authentication server
// Configuration is loaded asynchronously from the discovery endpoint
type RemoteService struct {
DiscoveryConfig
discoveryURL string
jwks keyset.KeySet
httpclient *networking.HTTPClient
requestGroup singleflight.Group
initialized bool
}
// New creates a RemoteService returning a AuthorizationServerService interface
func New(discoveryEndpoint string) AuthorizationServerService {
s := &RemoteService{
httpclient: networking.New(),
discoveryURL: discoveryEndpoint,
jwks: nil,
initialized: false,
}
err := s.initialize()
if err != nil {
zap.L().Debug("Initialization from discovery endpoint failed. Will retry later.", zap.String("url", discoveryEndpoint))
return s
}
zap.L().Debug("Initialized discovery configuration successfully", zap.String("url", discoveryEndpoint))
return s
}
// KeySet returns the instance's keyset or nil if none is available
func (s *RemoteService) KeySet() keyset.KeySet {
_ = s.initialize()
// If s.JwksURL contains an URL, make sure we return a KeySet with that URL
// That fixes the problem when SetKeySet() is used to set a KeySet with
// an empty JWKS URL while we already know the proper JWKS URL from the discovery
if s.JwksURL != "" && (s.jwks == nil || s.jwks.PublicKeyURL() == "") {
s.jwks = keyset.New(s.JwksURL, s.httpclient)
}
return s.jwks
}
// SetKeySet stores a JWKs in the OAuth server
func (s *RemoteService) SetKeySet(jwks keyset.KeySet) {
s.jwks = jwks
}
// JwksEndpoint returns the /publicKeys endpoint of the OAuth server
func (s *RemoteService) JwksEndpoint() string {
_ = s.initialize()
return s.JwksURL
}
// TokenEndpoint returns the /token endpoint of the OAuth server
func (s *RemoteService) TokenEndpoint() string {
_ = s.initialize()
return s.TokenURL
}
// AuthorizationEndpoint returns the /authorization endpoint of the OAuth server
func (s *RemoteService) AuthorizationEndpoint() string {
_ = s.initialize()
return s.AuthURL
}
// UserInfoEndpoint returns the /userinfo endpoint of the OAuth server
func (s *RemoteService) UserInfoEndpoint() string {
_ = s.initialize()
return s.UserInfoURL
}
// GetTokens performs a request to the token endpoint
func (s *RemoteService) GetTokens(authnMethod string, clientID string, clientSecret string, authorizationCode string, redirectURI string, refreshToken string) (*TokenResponse, error) {
_ = s.initialize()
form := url.Values{}
if refreshToken != "" {
form.Add("grant_type", "refresh_token")
form.Add("refresh_token", refreshToken)
} else {
form.Add("grant_type", "authorization_code")
form.Add("code", authorizationCode)
form.Add("redirect_uri", redirectURI)
}
if authnMethod == clientPostSecret {
form.Add("client_id", clientID)
form.Add("client_secret", clientSecret)
}
// Create request
req, err := http.NewRequest("POST", s.TokenURL, strings.NewReader(form.Encode()))
if err != nil {
zap.L().Warn("Could not serialize HTTP request", zap.Error(err))
return nil, err
}
// All other methods will default to client_post_basic
if authnMethod != clientPostSecret {
req.SetBasicAuth(clientID, clientSecret)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
tokenResponse := new(TokenResponse)
oa2Err := new(cstmErrs.OAuthError)
if res, err := s.httpclient.Do(req, tokenResponse, oa2Err); err != nil {
zap.L().Info("Failed to retrieve tokens", zap.Error(err))
return nil, err
} else if res.StatusCode != http.StatusOK {
zap.L().Info("Failed to retrieve tokens", zap.Error(oa2Err))
return nil, oa2Err
}
return tokenResponse, nil
}
// initialize attempts to load the Client configuration from the discovery endpoint
func (s *RemoteService) initialize() error {
if s.initialized {
return nil
}
// Retrieve configuration from .well-known endpoint.
// RequestGroup will prevent multiple calls to the discovery url from
// taking place at once. All threads coming into this call will wait for
// a single response, which can then be processed
_, err := s.requestGroup.Do(s.discoveryURL, func() (interface{}, error) {
if s.initialized {
return http.StatusOK, nil
}
return s.loadDiscoveryEndpoint()
})
if err != nil {
zap.L().Debug("Could not sync discovery endpoint", zap.String("url", s.discoveryURL), zap.Error(err))
return err
}
return nil
}
// loadDiscoveryEndpoint loads the configuration from the discovery endpoint
func (s *RemoteService) loadDiscoveryEndpoint() (interface{}, error) {
req, err := http.NewRequest("GET", s.discoveryURL, nil)
if err != nil {
zap.L().Debug("Could not sync discovery endpoint", zap.String("url", s.discoveryURL), zap.Error(err))
return nil, err
}
config := new(DiscoveryConfig)
config.DiscoveryURL = s.discoveryURL
oa2Err := new(cstmErrs.OAuthError)
if res, err := s.httpclient.Do(req, config, oa2Err); err != nil {
zap.L().Debug("Could not sync discovery endpoint", zap.String("url", s.discoveryURL), zap.Error(err))
return nil, err
} else if res.StatusCode != http.StatusOK {
zap.L().Debug("Could not sync discovery endpoint", zap.String("url", s.discoveryURL), zap.Error(oa2Err))
return nil, oa2Err
}
s.DiscoveryConfig = *config
s.initialized = true
return http.StatusOK, nil
}
// OK validates the result from a discovery configuration
func (c *DiscoveryConfig) OK() error {
if c.Issuer == "" {
return errors.New("invalid discovery config: missing `issuer`")
}
if c.JwksURL == "" {
return errors.New("invalid discovery config: missing `jwks_uri`")
}
if c.AuthURL == "" {
return errors.New("invalid discovery config: missing `authorization_endpoint`")
}
if c.TokenURL == "" {
return errors.New("invalid discovery config: missing `token_endpoint`")
}
if c.UserInfoURL == "" {
return errors.New("invalid discovery config: missing `userinfo_endpoint`")
}
return nil
}
// OK validates a TokenResponse
func (r *TokenResponse) OK() error {
if r.AccessToken == "" {
return errors.New("invalid token endpoint response: access_token does not exist")
}
return nil
}