This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
/
resource_server.go
120 lines (99 loc) · 3.36 KB
/
resource_server.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
package authzserver
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"mime"
"net/http"
"net/url"
"strings"
"k8s.io/apimachinery/pkg/util/sets"
"github.com/flyteorg/flytestdlib/config"
"github.com/coreos/go-oidc"
authConfig "github.com/flyteorg/flyteadmin/auth/config"
"github.com/flyteorg/flyteadmin/auth/interfaces"
"github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/service"
"golang.org/x/oauth2"
)
// ResourceServer authorizes access requests issued by an external Authorization Server.
type ResourceServer struct {
signatureVerifier oidc.KeySet
allowedAudience []string
}
func (r ResourceServer) ValidateAccessToken(ctx context.Context, expectedAudience, tokenStr string) (interfaces.IdentityContext, error) {
raw, err := r.signatureVerifier.VerifySignature(ctx, tokenStr)
if err != nil {
return nil, err
}
claimsRaw := map[string]interface{}{}
if err = json.Unmarshal(raw, &claimsRaw); err != nil {
return nil, fmt.Errorf("failed to unmarshal user info claim into UserInfo type. Error: %w", err)
}
return verifyClaims(sets.NewString(append(r.allowedAudience, expectedAudience)...), claimsRaw)
}
func doRequest(ctx context.Context, req *http.Request) (*http.Response, error) {
client := http.DefaultClient
if c, ok := ctx.Value(oauth2.HTTPClient).(*http.Client); ok {
client = c
}
return client.Do(req.WithContext(ctx))
}
func unmarshalResp(r *http.Response, body []byte, v interface{}) error {
err := json.Unmarshal(body, &v)
if err == nil {
return nil
}
ct := r.Header.Get("Content-Type")
mediaType, _, parseErr := mime.ParseMediaType(ct)
if parseErr == nil && mediaType == "application/json" {
return fmt.Errorf("got Content-Type = application/json, but could not unmarshal as JSON: %v", err)
}
return fmt.Errorf("expected Content-Type = application/json, got %q: %v", ct, err)
}
func getJwksForIssuer(ctx context.Context, issuerBaseURL url.URL, customMetadataURL url.URL) (keySet oidc.KeySet, err error) {
issuerBaseURL.Path = strings.TrimSuffix(issuerBaseURL.Path, "/") + "/"
var wellKnown *url.URL
if len(customMetadataURL.String()) > 0 {
wellKnown = issuerBaseURL.ResolveReference(&customMetadataURL)
} else {
wellKnown = issuerBaseURL.ResolveReference(oauth2MetadataEndpoint)
}
req, err := http.NewRequest(http.MethodGet, wellKnown.String(), nil)
if err != nil {
return nil, err
}
resp, err := doRequest(ctx, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("unable to read response body: %v", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %s", resp.Status, body)
}
p := &service.OAuth2MetadataResponse{}
err = unmarshalResp(resp, body, &p)
if err != nil {
return nil, fmt.Errorf("failed to decode provider discovery object: %v", err)
}
return oidc.NewRemoteKeySet(ctx, p.JwksUri), nil
}
// NewOAuth2ResourceServer initializes a new OAuth2ResourceServer.
func NewOAuth2ResourceServer(ctx context.Context, cfg authConfig.ExternalAuthorizationServer, fallbackBaseURL config.URL) (ResourceServer, error) {
u := cfg.BaseURL
if len(u.String()) == 0 {
u = fallbackBaseURL
}
verifier, err := getJwksForIssuer(ctx, u.URL, cfg.MetadataEndpointURL.URL)
if err != nil {
return ResourceServer{}, err
}
return ResourceServer{
signatureVerifier: verifier,
allowedAudience: cfg.AllowedAudience,
}, nil
}