-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathauthcode.go
More file actions
269 lines (247 loc) · 7.83 KB
/
authcode.go
File metadata and controls
269 lines (247 loc) · 7.83 KB
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package oidfed
import (
"crypto"
"encoding/json"
"io"
"net/http"
"net/url"
"time"
"github.com/google/uuid"
"github.com/lestrrat-go/jwx/v3/jwa"
"github.com/lestrrat-go/jwx/v3/jws"
"github.com/pkg/errors"
"github.com/go-oidfed/lib/apimodel"
"github.com/go-oidfed/lib/internal"
"github.com/go-oidfed/lib/jwx"
"github.com/go-oidfed/lib/oidfedconst"
)
// OIDCErrorResponse is the error response of an oidc provider
type OIDCErrorResponse struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description,omitempty"`
}
// OIDCTokenResponse is the token response of an oidc provider
type OIDCTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scopes string `json:"scope"`
IDToken string `json:"id_token"`
Extra map[string]any `json:"-"`
}
// UnmarshalJSON implements the json.Unmarshaler interface
func (res *OIDCTokenResponse) UnmarshalJSON(data []byte) error {
type oidcTokenResponse OIDCTokenResponse
r := oidcTokenResponse(*res)
extra, err := unmarshalWithExtra(data, &r)
if err != nil {
return err
}
r.Extra = extra
*res = OIDCTokenResponse(r)
return nil
}
// RequestObjectProducer is a generator for signed request objects
type RequestObjectProducer struct {
EntityID string
lifetime time.Duration
signer jwx.VersatileSigner
}
// NewRequestObjectProducer creates a new RequestObjectProducer with the passed properties
func NewRequestObjectProducer(
entityID string, multiSigner jwx.VersatileSigner, lifetime time.Duration,
) *RequestObjectProducer {
return &RequestObjectProducer{
EntityID: entityID,
lifetime: lifetime,
signer: multiSigner,
}
}
// RequestObject generates a signed request object jwt from the passed requestValues
func (rop RequestObjectProducer) RequestObject(requestValues map[string]any, headers jws.Headers, alg ...string) (
[]byte, error,
) {
if requestValues == nil {
return nil, errors.New("request must contain 'aud' claim with OPs issuer identifier url")
}
if _, audFound := requestValues["aud"]; !audFound {
return nil, errors.New("request must contain 'aud' claim with OPs issuer identifier url")
}
requestValues["iss"] = rop.EntityID
requestValues["client_id"] = rop.EntityID
delete(requestValues, "sub")
delete(requestValues, "client_secret")
if _, jtiFound := requestValues["jti"]; !jtiFound {
jti, err := uuid.NewRandom()
if err != nil {
return nil, errors.Wrap(err, "could not create jti")
}
requestValues["jti"] = jti.String()
}
now := time.Now()
requestValues["iat"] = now.Unix()
requestValues["exp"] = now.Add(rop.lifetime).Unix()
j, err := json.Marshal(requestValues)
if err != nil {
return nil, errors.Wrap(err, "could not marshal request object into JWT")
}
return rop.signPayload(j, headers, alg...)
}
func (rop RequestObjectProducer) signPayload(data []byte, headers jws.Headers, algs ...string) ([]byte, error) {
var signer crypto.Signer
var alg jwa.SignatureAlgorithm
if len(algs) == 0 {
signer, alg = rop.signer.DefaultSigner()
} else {
signer, alg = rop.signer.Signer(algs...)
}
if signer == nil {
return nil, errors.New("no compatible signing key")
}
return jwx.SignPayload(data, alg, signer, headers)
}
// ClientAssertion creates a new signed client assertion jwt for the passed audience
func (rop RequestObjectProducer) ClientAssertion(aud string, alg ...string) ([]byte, error) {
now := time.Now()
assertionValues := map[string]any{
"iss": rop.EntityID,
"sub": rop.EntityID,
"iat": now.Unix(),
"exp": now.Add(rop.lifetime).Unix(),
"aud": aud,
}
jti, err := uuid.NewRandom()
if err != nil {
return nil, errors.Wrap(err, "could not create jti")
}
assertionValues["jti"] = jti.String()
j, err := json.Marshal(assertionValues)
if err != nil {
return nil, errors.Wrap(err, "could not marshal client assertion into JWT")
}
return rop.signPayload(j, nil, alg...)
}
// GetAuthorizationURL creates an authorization url
func (f FederationLeaf) GetAuthorizationURL(
issuer, redirectURI, state, scope string, additionalParams url.Values,
) (string, error) {
resolved, err := DefaultMetadataResolver.ResolveResponsePayload(
apimodel.ResolveRequest{
Subject: issuer,
TrustAnchor: f.TrustAnchors.EntityIDs(),
EntityTypes: []string{oidfedconst.EntityTypeOpenIDProvider},
},
)
if err != nil {
return "", errors.Wrap(err, "get authorization url: could not resolve OP metadata")
}
if resolved.Metadata == nil {
return "", errors.New("get authorization url: OP metadata not found")
}
opMetadata := resolved.Metadata.OpenIDProvider
requestParams := map[string]any{}
for k, v := range additionalParams {
if len(v) == 1 {
requestParams[k] = v[0]
} else {
requestParams[k] = v
}
}
requestParams["aud"] = opMetadata.Issuer
requestParams["redirect_uri"] = redirectURI
requestParams["state"] = state
requestParams["response_type"] = "code"
requestParams["scope"] = scope
var headers jws.Headers
var heavyRequest bool
if f.RequestURIGenerator != nil && opMetadata.RequestURIParameterSupported && len(resolved.TrustChain) > 0 {
ownResolved, err := DefaultMetadataResolver.ResolveResponsePayload(
apimodel.ResolveRequest{
Subject: f.EntityID,
TrustAnchor: []string{resolved.TrustAnchor},
EntityTypes: []string{oidfedconst.EntityTypeOpenIDRelyingParty},
},
)
if err != nil {
internal.WithError(err).Error("explicit client registration: could not resolve own trust chain")
} else if len(ownResolved.TrustChain) > 0 {
_ = headers.Set("trust_chain", ownResolved.TrustChain)
_ = headers.Set("peer_trust_chain", resolved.TrustChain)
heavyRequest = true
}
}
requestObject, err := f.oidcROProducer.RequestObject(
requestParams, headers, opMetadata.RequestObjectSigningAlgValuesSupported...,
)
if err != nil {
return "", errors.Wrap(err, "could not create request object")
}
u, err := url.Parse(opMetadata.AuthorizationEndpoint)
if err != nil {
return "", errors.Wrap(err, "could not parse authorization endpoint")
}
q := url.Values{}
if heavyRequest {
requestURI, err := f.RequestURIGenerator(requestObject)
if err != nil {
return "", errors.Wrap(err, "could not generate request uri")
}
q.Set("request_uri", requestURI)
} else {
q.Set("request", string(requestObject))
}
q.Set("client_id", f.EntityID)
q.Set("response_type", "code")
q.Set("redirect_uri", redirectURI)
q.Set("scope", scope)
u.RawQuery = q.Encode()
return u.String(), nil
}
// CodeExchange performs an oidc code exchange it creates the mytoken and stores it in the database
func (f FederationLeaf) CodeExchange(
issuer, code, redirectURI string,
additionalParameter url.Values,
) (*OIDCTokenResponse, *OIDCErrorResponse, error) {
opMetadata, err := f.ResolveOPMetadata(issuer)
if err != nil {
return nil, nil, err
}
params := additionalParameter
if params == nil {
params = url.Values{}
}
params.Set("grant_type", "authorization_code")
params.Set("code", code)
params.Set("redirect_uri", redirectURI)
params.Set("client_id", f.EntityID)
clientAssertion, err := f.oidcROProducer.ClientAssertion(
opMetadata.TokenEndpoint,
opMetadata.TokenEndpointAuthSigningAlgValuesSupported...,
)
if err != nil {
return nil, nil, err
}
params.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
params.Set("client_assertion", string(clientAssertion))
res, err := http.PostForm(opMetadata.TokenEndpoint, params)
if err != nil {
return nil, nil, err
}
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, nil, err
}
var errRes OIDCErrorResponse
var tokenRes OIDCTokenResponse
if err = json.Unmarshal(body, &errRes); err != nil {
return nil, nil, err
}
if errRes.Error != "" {
return nil, &errRes, nil
}
if err = json.Unmarshal(body, &tokenRes); err != nil {
return nil, nil, err
}
return &tokenRes, nil, nil
}