forked from xmidt-org/webpa-common
-
Notifications
You must be signed in to change notification settings - Fork 0
/
issueHandler.go
315 lines (259 loc) · 8.47 KB
/
issueHandler.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package main
import (
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"github.com/SermoDigital/jose/crypto"
"github.com/SermoDigital/jose/jws"
"github.com/SermoDigital/jose/jwt"
"github.com/gorilla/schema"
"io/ioutil"
"net/http"
"strconv"
"time"
)
const (
KeyIDVariableName = "kid"
DefaultExpireDuration = time.Duration(24 * time.Hour)
DefaultNotBeforeDuration = time.Duration(1 * time.Hour)
)
var (
ErrorMissingKeyID = errors.New("A kid parameter is required")
zeroTime = time.Time{}
defaultSigningMethod crypto.SigningMethod = crypto.SigningMethodRS256
supportedSigningMethods = map[string]crypto.SigningMethod{
defaultSigningMethod.Alg(): defaultSigningMethod,
crypto.SigningMethodRS384.Alg(): crypto.SigningMethodRS384,
crypto.SigningMethodRS512.Alg(): crypto.SigningMethodRS512,
}
supportedNumericDateLayouts = []string{
time.RFC3339,
time.RFC822,
time.RFC822Z,
}
// zeroNumericDate is a singleton value indicating a blank value
zeroNumericDate = NumericDate{}
)
// NumericDate represents a JWT NumericDate as specified in:
// https://tools.ietf.org/html/rfc7519#section-2
//
// A number of formats for numeric dates are allowed, and each
// is converted appropriately:
//
// (1) An int64 value, which is interpreted as the exact value to use
// (2) A valid time.Duration, which is added to time.Now() to compute the value
// (3) An absolute date specified in RFC33399 or RFC822 formates. See the time package for details.
type NumericDate struct {
duration time.Duration
absolute time.Time
}
func (nd *NumericDate) UnmarshalText(raw []byte) error {
if len(raw) == 0 {
*nd = zeroNumericDate
return nil
}
text := string(raw)
if value, err := strconv.ParseInt(text, 10, 64); err == nil {
*nd = NumericDate{duration: 0, absolute: time.Unix(value, 0)}
return nil
}
if duration, err := time.ParseDuration(text); err == nil {
*nd = NumericDate{duration: duration, absolute: zeroTime}
return nil
}
for _, layout := range supportedNumericDateLayouts {
if value, err := time.Parse(layout, text); err == nil {
*nd = NumericDate{duration: 0, absolute: value}
return nil
}
}
return fmt.Errorf("Unparseable datetime: %s", text)
}
// IsZero tests whether this NumericDate is blank, as would be the case when
// the original request assigns a value to the empty string. This is useful to
// have the server generate a default value appropriate for the field.
func (nd *NumericDate) IsZero() bool {
return nd.duration == 0 && nd.absolute.IsZero()
}
// Compute calculates the time.Time value given a point in time
// assumed to be "now". Use of this level of indirection allows a
// single time value to be used in all calculations when issuing JWTs.
func (nd *NumericDate) Compute(now time.Time) time.Time {
if nd.duration != 0 {
return now.Add(nd.duration)
}
return nd.absolute
}
// SigningMethod is a custom type which holds the alg value.
type SigningMethod struct {
crypto.SigningMethod
}
func (s *SigningMethod) UnmarshalText(raw []byte) error {
if len(raw) == 0 {
*s = SigningMethod{defaultSigningMethod}
return nil
}
text := string(raw)
value, ok := supportedSigningMethods[text]
if ok {
*s = SigningMethod{value}
return nil
}
return fmt.Errorf("Unsupported algorithm: %s", text)
}
// IssueRequest contains the information necessary for issuing a JWS.
// Any custom claims must be transmitted separately.
type IssueRequest struct {
Now time.Time `schema:"-"`
KeyID string `schema:"kid"`
Algorithm *SigningMethod `schema:"alg"`
Expires *NumericDate `schema:"exp"`
NotBefore *NumericDate `schema:"nbf"`
JWTID *string `schema:"jti"`
Subject string `schema:"sub"`
Audience *[]string `schema:"aud"`
}
func (ir *IssueRequest) SigningMethod() crypto.SigningMethod {
if ir.Algorithm != nil {
return ir.Algorithm.SigningMethod
}
return defaultSigningMethod
}
// AddToHeader adds the appropriate header information from this issue request
func (ir *IssueRequest) AddToHeader(header map[string]interface{}) error {
// right now, we just add the kid
header[KeyIDVariableName] = ir.KeyID
return nil
}
// AddToClaims takes the various parts of this issue request and formats them
// appropriately into a supplied jwt.Claims object.
func (ir *IssueRequest) AddToClaims(claims jwt.Claims) error {
claims.SetIssuedAt(ir.Now)
if ir.Expires != nil {
if ir.Expires.IsZero() {
claims.SetExpiration(ir.Now.Add(DefaultExpireDuration))
} else {
claims.SetExpiration(ir.Expires.Compute(ir.Now))
}
}
if ir.NotBefore != nil {
if ir.NotBefore.IsZero() {
claims.SetNotBefore(ir.Now.Add(DefaultNotBeforeDuration))
} else {
claims.SetNotBefore(ir.NotBefore.Compute(ir.Now))
}
}
if ir.JWTID != nil {
jti := *ir.JWTID
if len(jti) == 0 {
// generate a type 4 UUID
buffer := make([]byte, 16)
if _, err := rand.Read(buffer); err != nil {
return err
}
buffer[6] = (buffer[6] | 0x40) & 0x4F
buffer[8] = (buffer[8] | 0x80) & 0x8F
// dashes are just noise!
jti = fmt.Sprintf("%X", buffer)
}
claims.SetJWTID(jti)
}
if len(ir.Subject) > 0 {
claims.SetSubject(ir.Subject)
}
if ir.Audience != nil {
claims.SetAudience((*ir.Audience)...)
}
return nil
}
func NewIssueRequest(decoder *schema.Decoder, source map[string][]string) (*IssueRequest, error) {
issueRequest := &IssueRequest{}
if err := decoder.Decode(issueRequest, source); err != nil {
return nil, err
}
if len(issueRequest.KeyID) == 0 {
return nil, ErrorMissingKeyID
}
issueRequest.Now = time.Now()
return issueRequest, nil
}
// IssueHandler issues JWS tokens
type IssueHandler struct {
BasicHandler
issuer string
decoder *schema.Decoder
}
// issue handles all the common logic for issuing a JWS token
func (handler *IssueHandler) issue(response http.ResponseWriter, issueRequest *IssueRequest, claims jwt.Claims) {
issueKey, ok := handler.keyStore.PrivateKey(issueRequest.KeyID)
if !ok {
handler.httpError(response, http.StatusBadRequest, fmt.Sprintf("No such key: %s", issueRequest.KeyID))
return
}
if claims == nil {
claims = make(jwt.Claims)
}
issuedJWT := jws.NewJWT(jws.Claims(claims), issueRequest.SigningMethod())
if err := issueRequest.AddToClaims(issuedJWT.Claims()); err != nil {
handler.httpError(response, http.StatusInternalServerError, err.Error())
return
}
issuedJWT.Claims().SetIssuer(handler.issuer)
issuedJWS := issuedJWT.(jws.JWS)
if err := issueRequest.AddToHeader(issuedJWS.Protected()); err != nil {
handler.httpError(response, http.StatusInternalServerError, err.Error())
return
}
compact, err := issuedJWS.Compact(issueKey)
if err != nil {
handler.httpError(response, http.StatusInternalServerError, err.Error())
return
}
response.Header().Set("Content-Type", "application/jwt")
response.Write(compact)
}
// SimpleIssue handles requests with no body, appropriate for simple use cases.
func (handler *IssueHandler) SimpleIssue(response http.ResponseWriter, request *http.Request) {
if err := request.ParseForm(); err != nil {
handler.httpError(response, http.StatusBadRequest, err.Error())
return
}
issueRequest, err := NewIssueRequest(handler.decoder, request.Form)
if err != nil {
handler.httpError(response, http.StatusBadRequest, err.Error())
return
}
handler.issue(response, issueRequest, nil)
}
// IssueUsingBody accepts a JSON claims document, to which it then adds all the standard
// claims mentioned in request parameters, e.g. exp. It then uses the merged claims
// in an issued JWS.
func (handler *IssueHandler) IssueUsingBody(response http.ResponseWriter, request *http.Request) {
if err := request.ParseForm(); err != nil {
handler.httpError(response, http.StatusBadRequest, err.Error())
return
}
issueRequest, err := NewIssueRequest(handler.decoder, request.Form)
if err != nil {
handler.httpError(response, http.StatusBadRequest, err.Error())
return
}
// this variant reads the claims directly from the request body
claims := make(jwt.Claims)
if request.Body != nil {
body, err := ioutil.ReadAll(request.Body)
if err != nil {
handler.httpError(response, http.StatusBadRequest, fmt.Sprintf("Unable to read request body: %s", err))
return
}
if len(body) > 0 {
// we don't want to uses the Claims unmarshalling logic, as that assumes base64
if err := json.Unmarshal(body, (*map[string]interface{})(&claims)); err != nil {
handler.httpError(response, http.StatusBadRequest, fmt.Sprintf("Unable to parse JSON in request body: %s", err))
return
}
}
}
handler.issue(response, issueRequest, claims)
}