// Package raxidentity is for internal and public identity/cloud/global auth package raxidentity import ( "bytes" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net/http" "strconv" "strings" "time" "github.com/julienschmidt/httprouter" log "github.com/sirupsen/logrus" "github.rackspace.com/gorax/tools/lagger" "github.rackspace.com/gorax/webutil" ) const ( internalAPI = "https://identity-internal.api.rackspacecloud.com/v2.0/tokens" internalStagingAPI = "https://staging.identity-internal.api.rackspacecloud.com/v2.0/tokens" internalURL = "https://identity-internal.api.rackspacecloud.com" internalURLStg = "https://staging.identity-internal.api.rackspacecloud.com" publicAPI = "https://identity.api.rackspacecloud.com/v2.0/tokens" publicStagingAPI = "https://staging.identity-internal.api.rackspacecloud.com/v2.0/tokens" ) type ( /* RaxCloudAuth is the main structure for our access information type RaxCloudAuth struct { Access struct { Token struct { ID string `json:"id"` Expire time.Time `json:"expires"` AuthBy []string `json:"RAX-AUTH:authenticatedBy"` } `json:"token"` User struct { ID string `json:"id"` Roles []struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` } `json:"roles"` } `json:"user"` ServiceCatalog []struct { Name string `json:"name"` Type string `json:"type"` EndPoints []struct { Region string `json:"region"` TenantID string `json:"tenantId"` PublicURL string `json:"publicURL,omitempty"` InternalURL string `json:"internalURL,omitempty"` } `json:"endpoints"` } `json:"serviceCatalog"` } `json:"access"` } */ Client struct { Access access `json:"access"` URL string } access struct { Token Token `json:"token"` User User `json:"user"` ServiceCatalog []ServiceCatalog `json:"serviceCatalog"` } Token struct { ID string `json:"id"` Expire time.Time `json:"expires"` AuthBy []string `json:"RAX-AUTH:authenticatedBy"` } User struct { RAXAuth string `json:"RAX-AUTH:defaultRegion"` Name string `json:"name"` ID string `json:"id"` Roles []Role `json:"roles"` } Role struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` ServiceId string `json:"serviceId"` } ServiceCatalog struct { Name string `json:"name"` Type string `json:"type"` EndPoints []EndPoint `json:"endpoints"` } EndPoint struct { Region string `json:"region"` TenantID string `json:"tenantId"` PublicURL string `json:"publicURL,omitempty"` InternalURL string `json:"internalURL,omitempty"` } cloudAuth struct { Auth *auth `json:"auth"` } auth struct { RAXAUTHDOM *authDom `json:"RAX-AUTH:domain,omitempty"` Credentials *authCredentials `json:"passwordCredentials,omitempty"` RSACredentials *rsaCredentials `json:"RAX-AUTH:rsaCredentials,omitempty"` } authDom struct { Name string `json:"name"` } authCredentials struct { User *string `json:"username,omitempty"` Pass *string `json:"password,omitempty"` } rsaCredentials struct { Username string `json:"username,omitempty"` TokenKey string `json:"tokenKey,omitempty"` } ImpersonatePayload struct { RAXAUTH struct { User struct { Username string `json:"username"` } `json:"user"` ExpireIn int `json:"expire-in-seconds"` } `json:"RAX-AUTH:impersonation"` } ) // PublicAuth is a top level function that authenticates against the public Cloud instance func PublicAuth(user, password string) (*Client, error) { return newClient(user, password, false, false) } // InternalAuth is a top level function that authenticates against the public Cloud instance func InternalAuth(user, password string, staging bool) (*Client, error) { return newClient(user, password, true, staging) } // InternalMustAuth is a top level function that authenticates against the public Cloud instance func InternalMustAuth(user, password string, staging bool) *Client { t, err := newClient(user, password, true, staging) if err != nil { panic(err) } return t } func InternalRSAAuth(user, rsa string, staging bool) (Client, error) { var ar Client var u string if staging { u = internalStagingAPI } else { u = internalAPI } log.WithField("URL", u).Debug("URL In Use") rd := authDom{ Name: "Rackspace", } au := auth{ RAXAUTHDOM: &rd, RSACredentials: &rsaCredentials{ Username: strings.Trim(user, "\n"), TokenKey: rsa, }, } a := cloudAuth{ Auth: &au, } jsonStr, err := json.Marshal(a) if err != nil { return ar, err } log.WithField("payload", string(jsonStr)).Debug("Payload to send") req, err := http.NewRequest("POST", u, bytes.NewBuffer(jsonStr)) req.Header.Set("Content-Type", "application/json") client := &http.Client{} log.Debug("Sending request to API") resp, err := client.Do(req) if err != nil { return ar, err } defer resp.Body.Close() log.Debug("Decoding Response") body, _ := ioutil.ReadAll(resp.Body) if err := json.Unmarshal(body, &ar); err != nil { return ar, err } if resp.StatusCode != 200 { log.WithFields(log.Fields{ "StatusCode": resp.StatusCode, "Status": resp.Status, }).Debug("Error received.") return ar, errors.New(resp.Status) } return ar, nil } func InternalStagingAuth(user, password string) (*Client, error) { return newClient(user, password, true, true) } func newClient(user, password string, internal, staging bool) (*Client, error) { a, err := json.Marshal(&cloudAuth{ Auth: &auth{ RAXAUTHDOM: func() *authDom { if !internal { return nil } return &authDom{ Name: "Rackspace", } }(), Credentials: &authCredentials{ User: &user, Pass: &password, }, }, }) if err != nil { return nil, err } var u string if internal { u = internalPath(staging) } else { u = publicPath(staging) } res, code, err := webutil.JSONPost(a, u, nil, false) if err != nil { return nil, err } if code != 200 { info := make(map[string]interface{}) if err := json.Unmarshal(res, &info); err != nil { return nil, err } var s string for i, e := range info { // loop over it, just in case there's more than one, but typically this will only be something like {"unauthorized": { "code": 401, "message": "unauthorized"}} s = s + fmt.Sprintf("%v: %v", i, e) } return nil, fmt.Errorf("error: %s", s) } var rca Client if err := json.Unmarshal(res, &rca); err != nil { return nil, err } rca.URL = u return &rca, nil } // APIKey returns the Identity Auth token func (r *Client) APIKey() string { return r.Access.Token.ID } // Validate returns true if the token is still valid, false if not func (r *Client) ValidateInternal(staging bool) bool { req := new(http.Request) var err error client := &http.Client{} req, err = http.NewRequest("GET", internalPath(staging)+"/"+r.Access.Token.ID, nil) if err != nil { log.Println(err) return false } // Add our token in to the request req.Header.Set("X-Auth-Token", r.Access.Token.ID) res, err := client.Do(req) if err != nil { log.Println(err) return false } defer res.Body.Close() // if 200 OK, the token is valid. Any other response indicates an error or invalid token if res.StatusCode == 200 { return true } return false } // ValidateInternalToken returns the token information if it is a valid token or returns an error. func ValidateInternalToken(token string, staging bool) (*Client, error) { headers := make(map[string]string) headers["X-Auth-Token"] = token data, code, err := webutil.JSONGetClose(internalPath(staging)+"/"+token, headers, false) if err != nil { return nil, err } if code != 200 { return nil, fmt.Errorf("received Error Code: %d", code) } ra := new(Client) ra.URL = internalPath(staging) if err = json.Unmarshal(data, ra); err != nil { return nil, err } return ra, nil } // ValidateExternalToken returns the token information if it is a valid token or returns an error. func ValidateExternalToken(token string, staging bool) (*Client, error) { headers := make(map[string]string) headers["X-Auth-Token"] = token data, code, err := webutil.JSONGetClose(publicPath(staging)+"/"+token, headers, false) if err != nil { return nil, err } if code != 200 { return nil, fmt.Errorf("received Error Code: %d", code) } ra := new(Client) ra.URL = publicPath(staging) if err = json.Unmarshal(data, ra); err != nil { return nil, err } return ra, nil } func internalPath(staging bool) string { if staging { return internalStagingAPI } return internalAPI } func publicPath(staging bool) string { if staging { return publicStagingAPI } return publicAPI } // Revoke the token (i.e. logout) func Revoke(token string, internal bool, staging bool) { var u string if internal { u = internalPath(staging) } else { u = publicPath(staging) } client := &http.Client{} req, _ := http.NewRequest("DELETE", u, nil) req.Header.Add("X-Auth-Token", token) r, _ := client.Do(req) defer r.Body.Close() } // Impersonate returns an impersonation token for the given account func Impersonate(account int, token string) (string, error) { u := "https://identity-internal.api.rackspacecloud.com/v2.0/RAX-AUTH/impersonation-tokens" var data ImpersonatePayload data.RAXAUTH.User.Username = fmt.Sprintf("hybrid%s", strconv.Itoa(account)) data.RAXAUTH.ExpireIn = 60 jsonData, err := json.Marshal(data) if err != nil { return "", err } client := &http.Client{} req, err := http.NewRequest("POST", u, bytes.NewBuffer(jsonData)) if err != nil { return "", err } req.Header.Add("X-Auth-Token", token) req.Header.Add("Content-Type", "application/json") r, err := client.Do(req) if err != nil { return "", err } defer r.Body.Close() if r.StatusCode != 200 { return "", fmt.Errorf("error: %v", r.StatusCode) } ident, err := decodeIdentity(r.Body) if err != nil { return "", err } return ident.Access.Token.ID, nil } func decodeIdentity(r io.Reader) (i *Client, err error) { i = new(Client) err = json.NewDecoder(r).Decode(i) return } type IdentityAuth struct { Log *lagger.NSILogger Staging bool Internal bool } // Auth method will take an initialized IdentityAuth structure and use the struct to // auth against the correct endpoint func (i *IdentityAuth) Auth(h httprouter.Handle) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { xauth := r.Header.Get("X-Auth-Token") if xauth == "" { i.Log.Error(i.Log.WebLog(r, "not_yet_authed", "raxidentity/Auth() X-Auth-Token does not exist")) http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } var ( t *Client err error ) if i.Internal { t, err = ValidateInternalToken(xauth, i.Staging) if err != nil { i.Log.Error(i.Log.WebLog(r, "unauthed", "raxidentity/Auth/ValidateInternalToken() Invalid token.")) http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } } else { t, err = ValidateExternalToken(xauth, i.Staging) if err != nil { i.Log.Error(i.Log.WebLog(r, "unauthed", "raxidentity/Auth/ValidateExternalToken() Invalid token.")) http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } } r.Header.Set("UserID", t.Access.User.Name) h(w, r, ps) return } } func Assert(saml2P string, staging bool) (Client, error) { var ( response Client headers = map[string]string{ "Content-Type": "application/xml", "Accept": "application/json", } url = func() string { if staging { return internalURLStg } return internalURL }() ) req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/v2.0/RAX-AUTH/federation/saml/auth", url), strings.NewReader(saml2P)) if err != nil { return response, fmt.Errorf("Assert:http.NewRequest:%s", err) } for k, v := range headers { req.Header.Set(k, v) } res, err := http.DefaultClient.Do(req) if err != nil { return response, fmt.Errorf("Assert:Client.Do:%s", err) } if res != nil { // Note: We use a func to error check defer as opposed to using // defer res.Body.Close(), which will never return an error. defer func() { if defErr := res.Body.Close(); defErr != nil { err = fmt.Errorf("%s:%s", defErr, err) } }() } if err = json.NewDecoder(res.Body).Decode(&response); err != nil { return response, fmt.Errorf("Assert:json.Decode:%s: %s", res.Status, err) } return response, nil }