1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
19 "gopkg.in/square/go-jose.v2"
20 "gopkg.in/square/go-jose.v2/jwt"
23 type OIDCProvider struct {
24 // expected token request
27 ValidClientSecret string
28 // desired response from token endpoint
30 AuthEmailVerified bool
32 AccessTokenPayload map[string]interface{}
34 PeopleAPIResponse map[string]interface{}
37 Issuer *httptest.Server
38 PeopleAPI *httptest.Server
42 func NewOIDCProvider(c *check.C) *OIDCProvider {
43 p := &OIDCProvider{c: c}
45 p.key, err = rsa.GenerateKey(rand.Reader, 2048)
46 c.Assert(err, check.IsNil)
47 p.Issuer = httptest.NewServer(http.HandlerFunc(p.serveOIDC))
48 p.PeopleAPI = httptest.NewServer(http.HandlerFunc(p.servePeopleAPI))
49 p.AccessTokenPayload = map[string]interface{}{"sub": "example"}
53 func (p *OIDCProvider) ValidAccessToken() string {
54 buf, _ := json.Marshal(p.AccessTokenPayload)
55 return p.fakeToken(buf)
58 func (p *OIDCProvider) serveOIDC(w http.ResponseWriter, req *http.Request) {
60 p.c.Logf("serveOIDC: got req: %s %s %s", req.Method, req.URL, req.Form)
61 w.Header().Set("Content-Type", "application/json")
63 case "/.well-known/openid-configuration":
64 json.NewEncoder(w).Encode(map[string]interface{}{
65 "issuer": p.Issuer.URL,
66 "authorization_endpoint": p.Issuer.URL + "/auth",
67 "token_endpoint": p.Issuer.URL + "/token",
68 "jwks_uri": p.Issuer.URL + "/jwks",
69 "userinfo_endpoint": p.Issuer.URL + "/userinfo",
72 var clientID, clientSecret string
73 auth, _ := base64.StdEncoding.DecodeString(strings.TrimPrefix(req.Header.Get("Authorization"), "Basic "))
74 authsplit := strings.Split(string(auth), ":")
75 if len(authsplit) == 2 {
76 clientID, _ = url.QueryUnescape(authsplit[0])
77 clientSecret, _ = url.QueryUnescape(authsplit[1])
79 if clientID != p.ValidClientID || clientSecret != p.ValidClientSecret {
80 p.c.Logf("OIDCProvider: expected (%q, %q) got (%q, %q)", p.ValidClientID, p.ValidClientSecret, clientID, clientSecret)
81 w.WriteHeader(http.StatusUnauthorized)
85 if req.Form.Get("code") != p.ValidCode || p.ValidCode == "" {
86 w.WriteHeader(http.StatusUnauthorized)
89 idToken, _ := json.Marshal(map[string]interface{}{
91 "aud": []string{clientID},
92 "sub": "fake-user-id",
93 "exp": time.Now().UTC().Add(time.Minute).Unix(),
94 "iat": time.Now().UTC().Unix(),
95 "nonce": "fake-nonce",
97 "email_verified": p.AuthEmailVerified,
99 "alt_verified": true, // for custom claim tests
100 "alt_email": "alt_email@example.com", // for custom claim tests
101 "alt_username": "desired-username", // for custom claim tests
103 json.NewEncoder(w).Encode(struct {
104 AccessToken string `json:"access_token"`
105 TokenType string `json:"token_type"`
106 RefreshToken string `json:"refresh_token"`
107 ExpiresIn int32 `json:"expires_in"`
108 IDToken string `json:"id_token"`
110 AccessToken: p.ValidAccessToken(),
112 RefreshToken: "test-refresh-token",
114 IDToken: p.fakeToken(idToken),
117 json.NewEncoder(w).Encode(jose.JSONWebKeySet{
118 Keys: []jose.JSONWebKey{
119 {Key: p.key.Public(), Algorithm: string(jose.RS256), KeyID: ""},
123 w.WriteHeader(http.StatusInternalServerError)
125 authhdr := req.Header.Get("Authorization")
126 if _, err := jwt.ParseSigned(strings.TrimPrefix(authhdr, "Bearer ")); err != nil {
127 p.c.Logf("OIDCProvider: bad auth %q", authhdr)
128 w.WriteHeader(http.StatusUnauthorized)
131 json.NewEncoder(w).Encode(map[string]interface{}{
132 "sub": "fake-user-id",
134 "given_name": p.AuthName,
136 "alt_username": "desired-username",
137 "email": p.AuthEmail,
138 "email_verified": p.AuthEmailVerified,
141 w.WriteHeader(http.StatusNotFound)
145 func (p *OIDCProvider) servePeopleAPI(w http.ResponseWriter, req *http.Request) {
147 p.c.Logf("servePeopleAPI: got req: %s %s %s", req.Method, req.URL, req.Form)
148 w.Header().Set("Content-Type", "application/json")
149 switch req.URL.Path {
150 case "/v1/people/me":
151 if f := req.Form.Get("personFields"); f != "emailAddresses,names" {
152 w.WriteHeader(http.StatusBadRequest)
155 json.NewEncoder(w).Encode(p.PeopleAPIResponse)
157 w.WriteHeader(http.StatusNotFound)
161 func (p *OIDCProvider) fakeToken(payload []byte) string {
162 signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: p.key}, nil)
167 object, err := signer.Sign(payload)
172 t, err := object.CompactSerialize()
177 p.c.Logf("fakeToken(%q) == %q", payload, t)