| 1 |
// Copyright (c) 2016 VMware, Inc. All Rights Reserved. |
| 2 |
// |
| 3 |
// This product is licensed to you under the Apache License, Version 2.0 (the "License"). |
| 4 |
// You may not use this product except in compliance with the License. |
| 5 |
// |
| 6 |
// This product may include a number of subcomponents with separate copyright notices and |
| 7 |
// license terms. Your use of these subcomponents is subject to the terms and conditions |
| 8 |
// of the subcomponent's license, as noted in the LICENSE file. |
| 9 |
|
| 10 |
package lightwave |
| 11 |
|
| 12 |
import ( |
| 13 |
"crypto/tls" |
| 14 |
"crypto/x509" |
| 15 |
"encoding/json" |
| 16 |
"encoding/pem" |
| 17 |
"fmt" |
| 18 |
"io/ioutil" |
| 19 |
"log" |
| 20 |
"net/http" |
| 21 |
"net/url" |
| 22 |
"strings" |
| 23 |
) |
| 24 |
|
| 25 |
const tokenScope string = "openid offline_access" |
| 26 |
|
| 27 |
type OIDCClient struct { |
| 28 |
httpClient *http.Client |
| 29 |
logger *log.Logger |
| 30 |
|
| 31 |
Endpoint string |
| 32 |
Options *OIDCClientOptions |
| 33 |
} |
| 34 |
|
| 35 |
type OIDCClientOptions struct { |
| 36 |
// Whether or not to ignore any TLS errors when talking to photon, |
| 37 |
// false by default. |
| 38 |
IgnoreCertificate bool |
| 39 |
|
| 40 |
// List of root CA's to use for server validation |
| 41 |
// nil by default. |
| 42 |
RootCAs *x509.CertPool |
| 43 |
|
| 44 |
// The scope values to use when requesting tokens |
| 45 |
TokenScope string |
| 46 |
} |
| 47 |
|
| 48 |
func NewOIDCClient(endpoint string, options *OIDCClientOptions, logger *log.Logger) (c *OIDCClient) { |
| 49 |
if logger == nil { |
| 50 |
logger = log.New(ioutil.Discard, "", log.LstdFlags) |
| 51 |
} |
| 52 |
|
| 53 |
options = buildOptions(options) |
| 54 |
tr := &http.Transport{ |
| 55 |
TLSClientConfig: &tls.Config{ |
| 56 |
InsecureSkipVerify: options.IgnoreCertificate, |
| 57 |
RootCAs: options.RootCAs}, |
| 58 |
} |
| 59 |
|
| 60 |
c = &OIDCClient{ |
| 61 |
httpClient: &http.Client{Transport: tr}, |
| 62 |
logger: logger, |
| 63 |
|
| 64 |
Endpoint: strings.TrimRight(endpoint, "/"), |
| 65 |
Options: options, |
| 66 |
} |
| 67 |
return |
| 68 |
} |
| 69 |
|
| 70 |
func buildOptions(options *OIDCClientOptions) (result *OIDCClientOptions) { |
| 71 |
result = &OIDCClientOptions{ |
| 72 |
TokenScope: tokenScope, |
| 73 |
} |
| 74 |
|
| 75 |
if options == nil { |
| 76 |
return |
| 77 |
} |
| 78 |
|
| 79 |
result.IgnoreCertificate = options.IgnoreCertificate |
| 80 |
|
| 81 |
if options.RootCAs != nil { |
| 82 |
result.RootCAs = options.RootCAs |
| 83 |
} |
| 84 |
|
| 85 |
if options.TokenScope != "" { |
| 86 |
result.TokenScope = options.TokenScope |
| 87 |
} |
| 88 |
|
| 89 |
return |
| 90 |
} |
| 91 |
|
| 92 |
func (client *OIDCClient) buildUrl(path string) (url string) { |
| 93 |
return fmt.Sprintf("%s%s", client.Endpoint, path) |
| 94 |
} |
| 95 |
|
| 96 |
// Cert download helper |
| 97 |
|
| 98 |
const certDownloadPath string = "/afd/vecs/ssl" |
| 99 |
|
| 100 |
type lightWaveCert struct { |
| 101 |
Value string `json:"encoded"` |
| 102 |
} |
| 103 |
|
| 104 |
func (client *OIDCClient) GetRootCerts() (certList []*x509.Certificate, err error) { |
| 105 |
// turn TLS verification off for |
| 106 |
originalTr := client.httpClient.Transport |
| 107 |
defer client.setTransport(originalTr) |
| 108 |
|
| 109 |
tr := &http.Transport{ |
| 110 |
TLSClientConfig: &tls.Config{ |
| 111 |
InsecureSkipVerify: true, |
| 112 |
}, |
| 113 |
} |
| 114 |
client.setTransport(tr) |
| 115 |
|
| 116 |
// get the certs |
| 117 |
resp, err := client.httpClient.Get(client.buildUrl(certDownloadPath)) |
| 118 |
if err != nil { |
| 119 |
return |
| 120 |
} |
| 121 |
defer resp.Body.Close() |
| 122 |
if resp.StatusCode != 200 { |
| 123 |
err = fmt.Errorf("Unexpected error retrieving auth server certs: %v %s", resp.StatusCode, resp.Status) |
| 124 |
return |
| 125 |
} |
| 126 |
|
| 127 |
// parse the certs |
| 128 |
certsData := &[]lightWaveCert{} |
| 129 |
err = json.NewDecoder(resp.Body).Decode(certsData) |
| 130 |
if err != nil { |
| 131 |
return |
| 132 |
} |
| 133 |
|
| 134 |
certList = make([]*x509.Certificate, len(*certsData)) |
| 135 |
for idx, cert := range *certsData { |
| 136 |
block, _ := pem.Decode([]byte(cert.Value)) |
| 137 |
if block == nil { |
| 138 |
err = fmt.Errorf("Unexpected response format: %v", certsData) |
| 139 |
return nil, err |
| 140 |
} |
| 141 |
|
| 142 |
decodedCert, err := x509.ParseCertificate(block.Bytes) |
| 143 |
if err != nil { |
| 144 |
return nil, err |
| 145 |
} |
| 146 |
|
| 147 |
certList[idx] = decodedCert |
| 148 |
} |
| 149 |
|
| 150 |
return |
| 151 |
} |
| 152 |
|
| 153 |
func (client *OIDCClient) setTransport(tr http.RoundTripper) { |
| 154 |
client.httpClient.Transport = tr |
| 155 |
} |
| 156 |
|
| 157 |
// Toke request helpers |
| 158 |
|
| 159 |
const tokenPath string = "/openidconnect/token" |
| 160 |
const passwordGrantFormatString = "grant_type=password&username=%s&password=%s&scope=%s" |
| 161 |
const refreshTokenGrantFormatString = "grant_type=refresh_token&refresh_token=%s" |
| 162 |
const clientGrantFormatString = "grant_type=password&username=%s&password=%s&scope=%s&client_id=%s" |
| 163 |
|
| 164 |
type OIDCTokenResponse struct { |
| 165 |
AccessToken string `json:"access_token"` |
| 166 |
ExpiresIn int `json:"expires_in"` |
| 167 |
RefreshToken string `json:"refresh_token,omitempty"` |
| 168 |
IdToken string `json:"id_token"` |
| 169 |
TokenType string `json:"token_type"` |
| 170 |
} |
| 171 |
|
| 172 |
func (client *OIDCClient) GetTokenByPasswordGrant(username string, password string) (tokens *OIDCTokenResponse, err error) { |
| 173 |
username = url.QueryEscape(username) |
| 174 |
password = url.QueryEscape(password) |
| 175 |
body := fmt.Sprintf(passwordGrantFormatString, username, password, client.Options.TokenScope) |
| 176 |
return client.getToken(body) |
| 177 |
} |
| 178 |
|
| 179 |
func (client *OIDCClient) GetClientTokenByPasswordGrant(username string, password string, clientID string) (tokens *OIDCTokenResponse, err error) { |
| 180 |
username = url.QueryEscape(username) |
| 181 |
password = url.QueryEscape(password) |
| 182 |
clientID = url.QueryEscape(clientID) |
| 183 |
body := fmt.Sprintf(clientGrantFormatString, username, password, client.Options.TokenScope, clientID) |
| 184 |
return client.getToken(body) |
| 185 |
} |
| 186 |
|
| 187 |
func (client *OIDCClient) GetTokenByRefreshTokenGrant(refreshToken string) (tokens *OIDCTokenResponse, err error) { |
| 188 |
body := fmt.Sprintf(refreshTokenGrantFormatString, refreshToken) |
| 189 |
return client.getToken(body) |
| 190 |
} |
| 191 |
|
| 192 |
func (client *OIDCClient) getToken(body string) (tokens *OIDCTokenResponse, err error) { |
| 193 |
request, err := http.NewRequest("POST", client.buildUrl(tokenPath), strings.NewReader(body)) |
| 194 |
if err != nil { |
| 195 |
return nil, err |
| 196 |
} |
| 197 |
request.Header.Add("Content-Type", "application/x-www-form-urlencoded") |
| 198 |
|
| 199 |
resp, err := client.httpClient.Do(request) |
| 200 |
if err != nil { |
| 201 |
return nil, err |
| 202 |
} |
| 203 |
defer resp.Body.Close() |
| 204 |
|
| 205 |
err = client.checkResponse(resp) |
| 206 |
if err != nil { |
| 207 |
return nil, err |
| 208 |
} |
| 209 |
|
| 210 |
tokens = &OIDCTokenResponse{} |
| 211 |
err = json.NewDecoder(resp.Body).Decode(tokens) |
| 212 |
if err != nil { |
| 213 |
return nil, err |
| 214 |
} |
| 215 |
|
| 216 |
return |
| 217 |
} |
| 218 |
|
| 219 |
type OIDCError struct { |
| 220 |
Code string `json:"error"` |
| 221 |
Message string `json:"error_description"` |
| 222 |
} |
| 223 |
|
| 224 |
func (e OIDCError) Error() string { |
| 225 |
return fmt.Sprintf("%v: %v", e.Code, e.Message) |
| 226 |
} |
| 227 |
|
| 228 |
func (client *OIDCClient) checkResponse(response *http.Response) (err error) { |
| 229 |
if response.StatusCode/100 == 2 { |
| 230 |
return |
| 231 |
} |
| 232 |
|
| 233 |
respBody, readErr := ioutil.ReadAll(response.Body) |
| 234 |
if err != nil { |
| 235 |
return fmt.Errorf( |
| 236 |
"Status: %v, Body: %v [%v]", response.Status, string(respBody[:]), readErr) |
| 237 |
} |
| 238 |
|
| 239 |
var oidcErr OIDCError |
| 240 |
err = json.Unmarshal(respBody, &oidcErr) |
| 241 |
if err != nil { |
| 242 |
return fmt.Errorf( |
| 243 |
"Status: %v, Body: %v [%v]", response.Status, string(respBody[:]), readErr) |
| 244 |
} |
| 245 |
|
| 246 |
return oidcErr |
| 247 |
} |