-
Notifications
You must be signed in to change notification settings - Fork 14
/
jwt.go
273 lines (231 loc) · 6.59 KB
/
jwt.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
package lib
import (
"crypto/ecdsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"strings"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/hashicorp/hcl/v2"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
"github.com/zclconf/go-cty/cty/function/stdlib"
acjwt "github.com/avenga/couper/accesscontrol/jwt"
"github.com/avenga/couper/config"
"github.com/avenga/couper/config/reader"
"github.com/avenga/couper/internal/seetie"
)
const FnJWTSign = "jwt_sign"
type JWTSigningConfig struct {
Claims config.Claims
Headers hcl.Expression
Key interface{}
SignatureAlgorithm string
TTL int64
}
func checkData(ttl, signatureAlgorithm string) (int64, acjwt.Algorithm, error) {
alg := acjwt.NewAlgorithm(signatureAlgorithm)
if alg == acjwt.AlgorithmUnknown {
return 0, alg, fmt.Errorf("algorithm is not supported")
}
if ttl != "0" {
dur, err := time.ParseDuration(ttl)
if err != nil {
return 0, alg, err
}
return int64(dur.Seconds()), alg, nil
}
return 0, alg, nil
}
func getKey(keyBytes []byte, signatureAlgorithm string) (interface{}, error) {
var (
key interface{}
parseErr error
)
key = keyBytes
if strings.HasPrefix(signatureAlgorithm, "RS") {
key, parseErr = jwt.ParseRSAPrivateKeyFromPEM(keyBytes)
} else if strings.HasPrefix(signatureAlgorithm, "ES") {
key, parseErr = parseECPrivateKeyFromPEM(keyBytes)
}
return key, parseErr
}
func NewJWTSigningConfigFromJWTSigningProfile(j *config.JWTSigningProfile, algCheckFunc func(alg acjwt.Algorithm) error) (*JWTSigningConfig, error) {
ttl, alg, err := checkData(j.TTL, j.SignatureAlgorithm)
if err != nil {
return nil, err
}
if algCheckFunc != nil {
if err = algCheckFunc(alg); err != nil {
return nil, err
}
}
keyBytes, err := reader.ReadFromAttrFile("jwt_signing_profile key", j.Key, j.KeyFile)
if err != nil {
return nil, err
}
key, err := getKey(keyBytes, j.SignatureAlgorithm)
if err != nil {
return nil, err
}
c := &JWTSigningConfig{
Claims: j.Claims,
Headers: j.Headers,
Key: key,
SignatureAlgorithm: j.SignatureAlgorithm,
TTL: ttl,
}
return c, nil
}
func NewJWTSigningConfigFromJWT(j *config.JWT) (*JWTSigningConfig, error) {
if j.SigningTTL == "" {
return nil, nil
}
ttl, alg, err := checkData(j.SigningTTL, j.SignatureAlgorithm)
if err != nil {
return nil, err
}
var signingKey, signingKeyFile string
if alg.IsHMAC() {
signingKey = j.Key
signingKeyFile = j.KeyFile
} else {
signingKey = j.SigningKey
signingKeyFile = j.SigningKeyFile
}
keyBytes, err := reader.ReadFromAttrFile("jwt signing key", signingKey, signingKeyFile)
if err != nil {
return nil, err
}
key, err := getKey(keyBytes, j.SignatureAlgorithm)
if err != nil {
return nil, err
}
c := &JWTSigningConfig{
Claims: j.Claims,
Key: key,
SignatureAlgorithm: j.SignatureAlgorithm,
TTL: ttl,
}
return c, nil
}
var NoOpJwtSignFunction = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "jwt_signing_profile_label",
Type: cty.String,
},
{
Name: "claims",
Type: cty.DynamicPseudoType,
},
},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, _ cty.Type) (ret cty.Value, err error) {
if len(args) > 0 {
return cty.StringVal(""), fmt.Errorf("missing jwt_signing_profile or jwt (with signing_ttl) block with referenced label %q", args[0].AsString())
}
return cty.StringVal(""), fmt.Errorf("missing jwt_signing_profile or jwt (with signing_ttl) definitions")
},
})
func NewJwtSignFunction(ctx *hcl.EvalContext, jwtSigningConfigs map[string]*JWTSigningConfig,
evalFn func(*hcl.EvalContext, hcl.Expression) (cty.Value, error)) function.Function {
return function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "jwt_signing_profile_label",
Type: cty.String,
},
{
Name: "claims",
Type: cty.DynamicPseudoType,
},
},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, _ cty.Type) (ret cty.Value, err error) {
label := args[0].AsString()
signingConfig, exist := jwtSigningConfigs[label]
if !exist {
return NoOpJwtSignFunction.Call(args)
}
var claims, argumentClaims, headers map[string]interface{}
if signingConfig.Headers != nil {
h, diags := evalFn(ctx, signingConfig.Headers)
if diags != nil {
return cty.StringVal(""), diags
}
headers = seetie.ValueToMap(h)
}
// get claims from signing profile
if signingConfig.Claims != nil {
v, diags := evalFn(ctx, signingConfig.Claims)
if diags != nil {
return cty.StringVal(""), err
}
claims = seetie.ValueToMap(v)
} else {
claims = make(map[string]interface{})
}
if signingConfig.TTL != 0 {
claims["exp"] = time.Now().Unix() + signingConfig.TTL
}
// get claims from function argument
jsonClaims, err := stdlib.JSONEncode(args[1])
if err != nil {
return cty.StringVal(""), err
}
err = json.Unmarshal([]byte(jsonClaims.AsString()), &argumentClaims)
if err != nil {
return cty.StringVal(""), err
}
for k, v := range argumentClaims {
claims[k] = v
}
tokenString, err := CreateJWT(signingConfig.SignatureAlgorithm, signingConfig.Key, claims, headers)
if err != nil {
return cty.StringVal(""), err
}
return cty.StringVal(tokenString), nil
},
})
}
func CreateJWT(signatureAlgorithm string, key interface{}, mapClaims jwt.MapClaims, headers map[string]interface{}) (string, error) {
signingMethod := jwt.GetSigningMethod(signatureAlgorithm)
if signingMethod == nil {
return "", fmt.Errorf("no signing method for given algorithm: %s", signatureAlgorithm)
}
if headers == nil {
headers = map[string]interface{}{}
}
if _, set := headers["typ"]; !set {
headers["typ"] = "JWT"
}
headers["alg"] = signingMethod.Alg()
// create token
token := &jwt.Token{Header: headers, Claims: mapClaims, Method: signingMethod}
// sign token
return token.SignedString(key)
}
func parseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) {
var err error
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, jwt.ErrKeyMustBePEMEncoded
}
// Parse the key
var parsedKey interface{}
if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil {
if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
return nil, err
}
}
var pkey *ecdsa.PrivateKey
var ok bool
if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok {
return nil, jwt.ErrNotECPrivateKey
}
return pkey, nil
}