This repository has been archived by the owner on Feb 13, 2024. It is now read-only.
forked from onetwentyseven-dev/apigw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
156 lines (118 loc) · 3.89 KB
/
auth.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
package apigw
import (
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/aws/aws-lambda-go/events"
"github.com/lestrrat-go/jwx/jwk"
"github.com/lestrrat-go/jwx/jwt"
)
type OpenIDConfiguration struct {
JWKSURI string `json:"jwks_uri"`
}
func fetchOpenIDConfiguration(client *http.Client, tenant string) (*OpenIDConfiguration, error) {
tenant = strings.TrimSuffix(tenant, "/")
endpoint := fmt.Sprintf("%s/.well-known/openid-configuration", tenant)
request, err := http.NewRequest(http.MethodGet, endpoint, nil)
if err != nil {
return nil, fmt.Errorf("failed to build request to openid-configration endpoint: %w", err)
}
response, err := client.Do(request)
if err != nil {
return nil, fmt.Errorf("failed to execute request to openid-configration endpoint: %w", err)
}
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code received from the openid-configration endpoint %s: %w", endpoint, err)
}
defer response.Body.Close()
var openIDConfiguration = new(OpenIDConfiguration)
err = json.NewDecoder(response.Body).Decode(openIDConfiguration)
if err != nil {
return nil, fmt.Errorf("failed to decode openid-configration: %w", err)
}
return openIDConfiguration, nil
}
func fetchJWKS(client *http.Client, tenant string) (jwk.Set, error) {
openIDConfiguration, err := fetchOpenIDConfiguration(client, tenant)
if err != nil {
return nil, err
}
request, err := http.NewRequest(http.MethodGet, openIDConfiguration.JWKSURI, nil)
if err != nil {
return nil, fmt.Errorf("failed to build request to jwks-uri %s: %w", openIDConfiguration.JWKSURI, err)
}
response, err := client.Do(request)
if err != nil {
return nil, fmt.Errorf("failed to execute request to jwks-uri %s: %w", openIDConfiguration.JWKSURI, err)
}
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code received from the jwks-uri %s: %w", openIDConfiguration.JWKSURI, err)
}
defer response.Body.Close()
data, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("failed to read jwks: %w", err)
}
set, err := jwk.Parse(data)
if err != nil {
return nil, fmt.Errorf("failed to parse data to jwks: %w", err)
}
return set, nil
}
func Auth(client *http.Client, tenant, clientID, audience string) (Middleware, error) {
jwks, err := fetchJWKS(client, tenant)
if err != nil {
return nil, fmt.Errorf("failed to initialize jwks: %w", err)
}
return func(next Handler) Handler {
return func(ctx context.Context, event events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
authorization := event.Headers["authorization"]
if authorization == "" {
return &events.APIGatewayProxyResponse{
StatusCode: http.StatusUnauthorized,
}, nil
}
if strings.HasPrefix(strings.ToLower(authorization), `bearer `) {
authorization = strings.TrimPrefix(authorization, `bearer `)
authorization = strings.TrimPrefix(authorization, `Bearer `)
}
token, err := jwt.ParseString(
authorization,
jwt.WithKeySet(jwks),
jwt.WithIssuer(tenant),
jwt.WithClock(jwt.ClockFunc(time.Now().UTC)),
jwt.WithClaimValue("azp", audience),
)
if err != nil {
return RespondError(http.StatusUnauthorized, "", nil, nil)
}
ctx = context.WithValue(ctx, UserContextKey, token)
return next(ctx, event)
}
}, nil
}
func UserIDFromContext(ctx context.Context) (string, error) {
token, err := TokenFromContext(ctx)
if err != nil {
return "", err
}
cliams := token.PrivateClaims()
emailIface, ok := cliams["https://email"]
if !ok {
return "", fmt.Errorf("required key email missing from claims")
}
email, ok := emailIface.(string)
if !ok {
return "", fmt.Errorf("key email is %T expected string", emailIface)
}
md5Hash := md5.New()
md5Hash.Write([]byte(email))
hash := md5Hash.Sum(nil)
return hex.EncodeToString(hash), nil
}