pax_global_header00006660000000000000000000000064141420354570014517gustar00rootroot0000000000000052 comment=e95b1f769f024df070f2fa9f610d0d78acc2f96e golang-github-juju-usso-1.0.1/000077500000000000000000000000001414203545700162075ustar00rootroot00000000000000golang-github-juju-usso-1.0.1/.travis.yml000066400000000000000000000002051414203545700203150ustar00rootroot00000000000000language: go go_import_path: "github.com/juju/usso" go: - "1.11.x" - "1.12.x" - "1.13.x" script: GO111MODULE=on go test ./... golang-github-juju-usso-1.0.1/LICENSE000066400000000000000000000211151414203545700172140ustar00rootroot00000000000000Copyright © 2015 Canonical Inc. This software is licensed under the LGPLv3, included below. As a special exception to the GNU Lesser General Public License version 3 ("LGPL3"), the copyright holders of this Library give you permission to convey to a third party a Combined Work that links statically or dynamically to this Library without providing any Minimal Corresponding Source or Minimal Application Code as set out in 4d or providing the installation information set out in section 4e, provided that you comply with the other provisions of LGPL3 and provided that you meet, for the Application the terms and conditions of the license(s) which apply to the Application. Except as stated in this special exception, the provisions of LGPL3 will continue to comply in full to this Library. If you modify this Library, you may apply this exception to your version of this Library, but you are not obliged to do so. If you do not wish to do so, delete this exception statement from your version. This exception does not (and cannot) modify any license terms which apply to the Application, with which you must still comply. GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. golang-github-juju-usso-1.0.1/README000066400000000000000000000000001414203545700170550ustar00rootroot00000000000000golang-github-juju-usso-1.0.1/go.mod000066400000000000000000000002521414203545700173140ustar00rootroot00000000000000module github.com/juju/usso require ( github.com/frankban/quicktest v1.5.0 github.com/yohcop/openid-go v1.0.0 gopkg.in/errgo.v1 v1.0.0 gopkg.in/macaroon.v2 v2.1.0 ) golang-github-juju-usso-1.0.1/go.sum000066400000000000000000000047141414203545700173500ustar00rootroot00000000000000github.com/frankban/quicktest v1.0.0/go.mod h1:R98jIehRai+d1/3Hv2//jOVCTJhW1VBavT6B6CuGq2k= github.com/frankban/quicktest v1.5.0 h1:Tb4jWdSpdjKzTUicPnY61PZxKbDoGa7ABbrReT3gQVY= github.com/frankban/quicktest v1.5.0/go.mod h1:jaStnuzAqU1AJdCO0l53JDCJrVDKcS03DbaAcR7Ks/o= github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/yohcop/openid-go v1.0.0 h1:EciJ7ZLETHR3wOtxBvKXx9RV6eyHZpCaSZ1inbBaUXE= github.com/yohcop/openid-go v1.0.0/go.mod h1:/408xiwkeItSPJZSTPF7+VtZxPkPrRRpRNK2vjGh6yI= golang.org/x/crypto v0.0.0-20180723164146-c126467f60eb/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/net v0.0.0-20190522155817-f3200d17e092 h1:4QSRKanuywn15aTZvI/mIDEgPQpswuFndXpOj3rKEco= golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v1 v1.0.0 h1:n+7XfCyygBFb8sEjg6692xjC6Us50TFRO54+xYUEwjE= gopkg.in/errgo.v1 v1.0.0/go.mod h1:CxwszS/Xz1C49Ucd2i6Zil5UToP1EmyrFhKaMVbg1mk= gopkg.in/macaroon.v2 v2.1.0 h1:HZcsjBCzq9t0eBPMKqTN/uSN6JOm78ZJ2INbqcBQOUI= gopkg.in/macaroon.v2 v2.1.0/go.mod h1:OUb+TQP/OP0WOerC2Jp/3CwhIKyIa9kQjuc7H24e6/o= golang-github-juju-usso-1.0.1/oauth.go000066400000000000000000000076431414203545700176700ustar00rootroot00000000000000// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENSE file for details. package usso import ( "crypto/hmac" "crypto/sha1" "encoding/base64" "fmt" "math/rand" "net/http" "net/url" "strconv" "time" ) // Initialize the random generator. func init() { rand.Seed(time.Now().UTC().UnixNano()) } // Create a timestamp used in authorization header. func timestamp() string { return strconv.Itoa(int(time.Now().Unix())) } // Create a nonce used in authorization header. func nonce() string { return strconv.Itoa(rand.Intn(100000000)) } // Contains the oauth data to perform a request. type SSOData struct { ConsumerKey string `json:"consumer_key"` ConsumerSecret string `json:"consumer_secret"` Realm string `json:"realm"` TokenKey string `json:"token_key"` TokenName string `json:"token_name"` TokenSecret string `json:"token_secret"` } type RequestParameters struct { HTTPMethod string BaseURL string Params url.Values Nonce string Timestamp string SignatureMethod SignatureMethod } type SignatureMethod interface { Name() string Signature( ssodata *SSOData, rp *RequestParameters) (string, error) } type PLAINTEXT struct{} // Return the name of the signature method, used to compose the // Authentication Header. func (PLAINTEXT) Name() string { return "PLAINTEXT" } // Calculate the oaut_signature part of the Authentication Header. func (PLAINTEXT) Signature( ssodata *SSOData, rp *RequestParameters) (string, error) { return fmt.Sprintf( `%s&%s`, ssodata.ConsumerSecret, ssodata.TokenSecret), nil } type HMACSHA1 struct{} // Return the name of the signature method, used to compose the // Authentication Header. func (HMACSHA1) Name() string { return "HMAC-SHA1" } // Calculate the oaut_signature part of the Authentication Header. func (HMACSHA1) Signature( ssodata *SSOData, rp *RequestParameters) (string, error) { baseUrl, err := NormalizeURL(rp.BaseURL) if err != nil { return "", err } query := url.Values{} for k, v := range rp.Params { query[k] = v } query.Set("oauth_consumer_key", ssodata.ConsumerKey) query.Set("oauth_nonce", rp.Nonce) query.Set("oauth_signature_method", string(rp.SignatureMethod.Name())) query.Set("oauth_timestamp", rp.Timestamp) query.Set("oauth_token", ssodata.TokenKey) query.Set("oauth_version", "1.0") params, err := NormalizeParameters(query) if err != nil { return "", err } baseString := fmt.Sprintf("%s&%s&%s", rp.HTTPMethod, escape(baseUrl), escape(params), ) hashfun := hmac.New(sha1.New, []byte( ssodata.ConsumerSecret+"&"+ssodata.TokenSecret)) hashfun.Write([]byte(baseString)) rawsignature := hashfun.Sum(nil) base64signature := make( []byte, base64.StdEncoding.EncodedLen(len(rawsignature))) base64.StdEncoding.Encode(base64signature, rawsignature) return string(base64signature), nil } // Sign the provided request. func (ssodata *SSOData) GetAuthorizationHeader( rp *RequestParameters) (string, error) { if rp.Nonce == "" { rp.Nonce = nonce() } if rp.Timestamp == "" { rp.Timestamp = timestamp() } signature, err := rp.SignatureMethod.Signature(ssodata, rp) if err != nil { return "", err } auth := fmt.Sprintf( `OAuth realm="%s", `+ `oauth_consumer_key="%s", `+ `oauth_token="%s", `+ `oauth_signature_method="%s", `+ `oauth_signature="%s", `+ `oauth_timestamp="%s", `+ `oauth_nonce="%s", `+ `oauth_version="1.0"`, url.QueryEscape(ssodata.Realm), url.QueryEscape(ssodata.ConsumerKey), url.QueryEscape(ssodata.TokenKey), rp.SignatureMethod.Name(), signature, url.QueryEscape(rp.Timestamp), url.QueryEscape(rp.Nonce)) return auth, nil } // Sign the provided request. func (ssodata *SSOData) SignRequest( rp *RequestParameters, req *http.Request) error { auth, error := ssodata.GetAuthorizationHeader(rp) if req.Header == nil { req.Header = make(map[string][]string) } req.Header.Add("Authorization", auth) return error } golang-github-juju-usso-1.0.1/oauth_test.go000066400000000000000000000056021414203545700207200ustar00rootroot00000000000000// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENSE file for details. package usso import ( "net/http" "net/url" "testing" qt "github.com/frankban/quicktest" ) func defaults(c *qt.C) (SSOData, RequestParameters, *http.Request) { baseUrl := "https://localhost" ssodata := SSOData{ ConsumerKey: consumerKey, ConsumerSecret: consumerSecret, Realm: realm, TokenKey: tokenKey, TokenName: tokenName, TokenSecret: tokenSecret, } rp := RequestParameters{ BaseURL: "https://localhost", HTTPMethod: "GET", Nonce: "10888885", Timestamp: "1358853126", } req, err := http.NewRequest("GET", baseUrl, nil) c.Assert(err, qt.Equals, nil) return ssodata, rp, req } // It is possible to sign a request with oauth_signature_method = PLAINTEXT func TestSignRequestPlainText(t *testing.T) { c := qt.New(t) ssodata, rp, req := defaults(c) rp.SignatureMethod = PLAINTEXT{} err := ssodata.SignRequest(&rp, req) c.Assert(err, qt.Equals, nil) authHeader := req.Header.Get("Authorization") c.Assert(authHeader, qt.Matches, `^OAuth.*`) c.Assert(authHeader, qt.Matches, `.*realm="API".*`) c.Assert(authHeader, qt.Matches, `.*oauth_consumer_key="`+url.QueryEscape(ssodata.ConsumerKey)+`".*`) c.Assert(authHeader, qt.Matches, `.*oauth_token="`+url.QueryEscape(ssodata.TokenKey)+`".*`) c.Assert(authHeader, qt.Matches, `.*oauth_signature="`+url.QueryEscape(ssodata.ConsumerSecret)+`&`+url.QueryEscape(ssodata.TokenSecret)+`.*`) } // It is possible to sign a request with oauth_signature_method = SHA1 func TestSignRequestSHA1(t *testing.T) { c := qt.New(t) ssodata, rp, req := defaults(c) rp.SignatureMethod = HMACSHA1{} err := ssodata.SignRequest(&rp, req) c.Assert(err, qt.Equals, nil) authHeader := req.Header.Get("Authorization") c.Assert(authHeader, qt.Matches, `^OAuth.*`) c.Assert(authHeader, qt.Matches, `.*realm="API".*`) c.Assert(authHeader, qt.Matches, `.*oauth_consumer_key="`+url.QueryEscape(ssodata.ConsumerKey)+`".*`) c.Assert(authHeader, qt.Matches, `.*oauth_token="`+url.QueryEscape(ssodata.TokenKey)+`".*`) c.Assert(authHeader, qt.Matches, `.*oauth_signature="`+"amJnYeek4G9ObTgTiE2y6cwTyPg="+`.*`) } func TestSignRequestSHA1WithParams(t *testing.T) { c := qt.New(t) ssodata, rp, req := defaults(c) rp.SignatureMethod = HMACSHA1{} rp.Params = url.Values{ "a": []string{"B", "A"}, "z": []string{""}, } err := ssodata.SignRequest(&rp, req) c.Assert(err, qt.Equals, nil) authHeader := req.Header.Get("Authorization") c.Assert(authHeader, qt.Matches, `^OAuth.*`) c.Assert(authHeader, qt.Matches, `.*realm="API".*`) c.Assert(authHeader, qt.Matches, `.*oauth_consumer_key="`+url.QueryEscape(ssodata.ConsumerKey)+`".*`) c.Assert(authHeader, qt.Matches, `.*oauth_token="`+url.QueryEscape(ssodata.TokenKey)+`".*`) c.Assert(authHeader, qt.Matches, `.*oauth_signature="`+"a/PwZ4HMX0FptNA4KRFl1jIqlOg="+`.*`) } golang-github-juju-usso-1.0.1/openid/000077500000000000000000000000001414203545700174655ustar00rootroot00000000000000golang-github-juju-usso-1.0.1/openid/example/000077500000000000000000000000001414203545700211205ustar00rootroot00000000000000golang-github-juju-usso-1.0.1/openid/example/main.go000066400000000000000000000052671414203545700224050ustar00rootroot00000000000000// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENSE file for details. // Example web application that performs an OpenID login to Ubuntu SSO. // When making a request to the host it redirects you to Ubuntu SSO to // log in. If there are any teams specified by the -teams flag, // membership information for those teams will be requested with the // login. If any fields are specified by the -optional or -required // flags, then these values will be requested with the log in. package main import ( "flag" "fmt" "html/template" "log" "net/http" "os" "strings" "github.com/juju/usso" "github.com/juju/usso/openid" ) var ( caveatID = flag.String("caveatid", "", "`caveat ID` of a third-party caveat addressed to login.ubuntu.com") optional = flag.String("optional", "", "comma separated list of optional simple registration `fields`.") required = flag.String("required", "", "comma separated list of required simple registration `fields`.") teams = flag.String("teams", "", "comma separated list of `teams` to request membership of.") ) var client = openid.NewClient(usso.ProductionUbuntuSSOServer, nil, nil) func main() { flag.Parse() http.Handle("/", http.HandlerFunc(openID)) err := http.ListenAndServe("localhost:8080", nil) fmt.Fprintf(os.Stderr, "%s", err) } func openID(w http.ResponseWriter, r *http.Request) { r.ParseForm() url := *r.URL url.Scheme = "http" url.Host = "localhost:8080" if r.Form.Get("openid.ns") == "" { req := openid.Request{ ReturnTo: url.String(), Teams: strings.FieldsFunc(*teams, isComma), SRegRequired: strings.FieldsFunc(*required, isComma), SRegOptional: strings.FieldsFunc(*optional, isComma), CaveatID: *caveatID, } url := client.RedirectURL(&req) http.Redirect(w, r, url, http.StatusFound) return } resp, err := client.Verify(url.String()) w.Header().Set("ContentType", "text/html") if err != nil { w.WriteHeader(http.StatusBadRequest) errorTemplate.Execute(w, err) return } if err := loginTemplate.Execute(w, resp); err != nil { log.Println(err) } } func isComma(c rune) bool { return c == ',' } var errorTemplate = template.Must(template.New("failure").Parse(` Login Error {{.}} `)) var loginTemplate = template.Must(template.New("success").Parse(` Login Success {{if .Teams}} {{end}}{{range $k, $v := .SReg}} {{end}}{{if .Discharge}} {{end}}
Claimed ID{{.ID}}
Teams{{.Teams}}
{{$k}}{{$v}}
Discharge{{printf "%s" .Discharge.MarshalJSON}}
`)) golang-github-juju-usso-1.0.1/openid/export_test.go000066400000000000000000000002031414203545700223670ustar00rootroot00000000000000// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENSE file for details. package openid var Verify = &verify golang-github-juju-usso-1.0.1/openid/openid.go000066400000000000000000000221511414203545700212730ustar00rootroot00000000000000// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENSE file for details. // Package openid contains functions to help log-in to Ubuntu SSO using // OpenID 2.0. package openid import ( "net/url" "strings" "github.com/yohcop/openid-go" "gopkg.in/errgo.v1" macaroon "gopkg.in/macaroon.v2" "github.com/juju/usso" ) const ( // These standard simple registration fields are supported by // Ubuntu SSO. SRegNickname = "nickname" SRegEmail = "email" SRegFullName = "fullname" SRegPostcode = "postcode" SRegCountry = "country" SRegLanguage = "language" SRegTimezone = "timezone" // These non-standard simple registration fields are supported by // Ubuntu SSO. SRegAddress1 = "x_address1" SRegAddress2 = "x_address2" SRegCity = "x_city" SRegProvince = "x_province" SRegPhone = "x_phone" ) const ( nsSReg = "http://openid.net/extensions/sreg/1.1" nsTeams = "http://ns.launchpad.net/2007/openid-teams" nsMacaroon = "http://ns.login.ubuntu.com/2016/openid-macaroon" ) var ( // ErrCancel is the error cause returned by Client.Verify when a // login request has been cancelled. ErrCancel = errgo.New("login cancelled") ) // OpenIDError represents an error response from an OpenID server. See // http://openid.net/specs/openid-authentication-2_0.html#rfc.section.5.2.3 // for details. type OpenIDError struct { // Message contains the "openid.error" field from the response. Message string // Contact contains the "openid.contact" field from the response. Contact string // Reference contains the "openid.reference" field from the // response. Reference string } // Error implements error.Error. func (e *OpenIDError) Error() string { return e.Message } // NonceStore is the NonceStore type from github.com/yohcop/openid-go. It // is replicated here for the convenience of clients. type NonceStore interface { openid.NonceStore } // DiscoveryCache is the DiscoveryCache type from // github.com/yohcop/openid-go. It is replicated here for the convenience // of clients. type DiscoveryCache interface { openid.DiscoveryCache } // Client is an OpenID client that provides OpenID login for a specific // Ubuntu SSO server. type Client struct { // Server holds the Ubuntu SSO server that OpenID requests will // be made against. Server usso.UbuntuSSOServer // NonceStore contains the NonceStore used to verify the OpenID // responses have not been previously processed. NonceStore NonceStore // DiscoveryCache contains a DiscoveryCache to use when verifying // OpenID responses. DiscoveryCache DiscoveryCache } // NewClient creates a new Client for the specified Ubuntu SSO server. If // ns is nil then a new in-memory NonceStore will be created. If dc is // nil then a DiscoveryCache derived from the server wil be used. func NewClient(s usso.UbuntuSSOServer, ns NonceStore, dc DiscoveryCache) *Client { if ns == nil { ns = openid.NewSimpleNonceStore() } if dc == nil { dc = ussoDiscoveryCache{s} } return &Client{ Server: s, NonceStore: ns, DiscoveryCache: dc, } } // Request contains the paramaters for an UbuntuSSO OpenID login request. type Request struct { // ReturnTo contains the callback address for the service, this is // where the login response will come. ReturnTo string // Realm contains the realm that the user is logging into. See // http://openid.net/specs/openid-authentication-2_0.html#realms // for details. Realm string // Teams contains a list of launchpad teams to query membership // of for the logged in user. Teams []string // SRegRequired contains a list of simple registration fields // that are required by the service. SRegRequired []string // SRegOptional contains a list of simple registration fields // that are optional, but requested by the service. SRegOptional []string // CaveatID contains the caveat ID of a third-party macaroon // caveat addressed to the identity server. CaveatID string } // RedirectURL creates an OpenID login request addressed to c.Server. func (c *Client) RedirectURL(r *Request) string { v := url.Values{ "openid.ns": {"http://specs.openid.net/auth/2.0"}, "openid.mode": {"checkid_setup"}, "openid.claimed_id": {"http://specs.openid.net/auth/2.0/identifier_select"}, "openid.identity": {"http://specs.openid.net/auth/2.0/identifier_select"}, "openid.return_to": {r.ReturnTo}, } if r.Realm != "" { v.Set("openid.realm", r.Realm) } if len(r.Teams) > 0 { v.Set("openid.ns.lp", nsTeams) v.Set("openid.lp.query_membership", strings.Join(r.Teams, ",")) } if len(r.SRegRequired) > 0 { v.Set("openid.ns.sreg", nsSReg) v.Set("openid.sreg.required", strings.Join(r.SRegRequired, ",")) } if len(r.SRegOptional) > 0 { v.Set("openid.ns.sreg", nsSReg) v.Set("openid.sreg.optional", strings.Join(r.SRegOptional, ",")) } if r.CaveatID != "" { v.Set("openid.ns.macaroon", nsMacaroon) v.Set("openid.macaroon.caveat_id", r.CaveatID) } return c.Server.OpenIDURL() + "?" + v.Encode() } // Response contains the values returned from Ubuntu SSO after a // successful login. type Response struct { // ID contains the claimed_id of the logged in user. This will // always be present in a successful login. ID string // Teams contains any launchpad teams that were specified in the // OpenID response. Teams []string // SReg contains any simple registration fields are // were provided in the OpenID response. SReg map[string]string // Discharge contains the discharge macaroon returned // from the identity provider if a CaveatID was supplied in the // request. Discharge *macaroon.Macaroon } // verify is used to perform the OpenID verification of the login // response. This is declared as a variable so it can be overridden for // testing. var verify = openid.Verify // Verify processes a positive assertion from Ubuntu SSO. If the // verification is successful any parameters asserted by Ubuntu SSO will // be set in the Response. If the OpenID response reports that the login // was cancelled then an error will be returned with a cause of // ErrCancel. If the OpenID response reports an error occurred then an // error of type *OpenIDError will be returned. func (c *Client) Verify(requestURL string) (*Response, error) { u, err := url.ParseRequestURI(requestURL) if err != nil { return nil, err } v := u.Query() switch mode := v.Get("openid.mode"); mode { case "error": return nil, &OpenIDError{ Message: v.Get("openid.error"), Contact: v.Get("openid.contact"), Reference: v.Get("openid.reference"), } case "cancel": return nil, ErrCancel default: return nil, errgo.Newf("unrecognised mode %q", mode) case "id_res": } if endpoint := v.Get("openid.op_endpoint"); endpoint != c.Server.OpenIDURL() { return nil, errgo.Newf("OpenID response from unexpected endpoint %q", endpoint) } // Verify the openid response. id, err := verify(requestURL, c.DiscoveryCache, c.NonceStore) if err != nil { return nil, err } r := Response{ ID: id, } // check for extensions in the response. signed := strings.Split(v.Get("openid.signed"), ",") if v.Get("openid.ns.lp") == nsTeams && contains(signed, "lp.is_member") { r.Teams = strings.Split(v.Get("openid.lp.is_member"), ",") } if v.Get("openid.ns.sreg") == nsSReg { for k := range v { if !strings.HasPrefix(k, "openid.sreg.") { continue } if !contains(signed, k[len("openid."):]) { continue } if r.SReg == nil { r.SReg = make(map[string]string) } r.SReg[k[len("openid.sreg."):]] = v.Get(k) } } if v.Get("openid.ns.macaroon") == nsMacaroon && contains(signed, "macaroon.discharge") { // If the discharge macaroon does not parse still complete the login. r.Discharge, _ = decodeMacaroon(v.Get("openid.macaroon.discharge")) } return &r, nil } func decodeMacaroon(v string) (*macaroon.Macaroon, error) { var m macaroon.Macaroon buf, err := macaroon.Base64Decode([]byte(v)) if err != nil { return nil, errgo.Mask(err) } if err := m.UnmarshalBinary(buf); err != nil { return nil, errgo.Mask(err) } return &m, nil } // contains finds whether ss contains s. func contains(ss []string, s string) bool { for _, t := range ss { if t == s { return true } } return false } // ussoDiscoveryCache is a DiscoveryCache that generates the cached // information based on the behaviour of Ubuntu SSO. type ussoDiscoveryCache struct { server usso.UbuntuSSOServer } // Put implements DiscoveryCache.Put, it does nothing. func (dc ussoDiscoveryCache) Put(id string, info openid.DiscoveredInfo) { } // Get implements DiscoveryCache.Get by returning Ubuntu SSO specific // values when the id has a prefix matching the Ubuntu SSO server's login // URL. The generated data uses id as both the local ID and the claimed // ID, and the server's OpenID endpoint. func (dc ussoDiscoveryCache) Get(id string) openid.DiscoveredInfo { if !strings.HasPrefix(id, dc.server.LoginURL()) { return nil } return discoveredInfo{ id: id, endpoint: dc.server.OpenIDURL(), } } type discoveredInfo struct { id string endpoint string } func (d discoveredInfo) OpEndpoint() string { return d.endpoint } func (d discoveredInfo) OpLocalID() string { return d.id } func (d discoveredInfo) ClaimedID() string { return d.id } golang-github-juju-usso-1.0.1/openid/openid_test.go000066400000000000000000000433331414203545700223370ustar00rootroot00000000000000// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENSE file for details. package openid_test import ( "errors" "net/url" "testing" qt "github.com/frankban/quicktest" yopenid "github.com/yohcop/openid-go" "gopkg.in/errgo.v1" macaroon "gopkg.in/macaroon.v2" "github.com/juju/usso" "github.com/juju/usso/openid" ) type openidSuite struct { } var redirectURLTests = []struct { about string server usso.UbuntuSSOServer request *openid.Request expect string }{{ about: "production-with-only-return_to", server: usso.ProductionUbuntuSSOServer, request: &openid.Request{ ReturnTo: "http://return.to", }, expect: "https://login.ubuntu.com/+openid?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=checkid_setup&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.return_to=http://return.to", }, { about: "staging-with-only-return_to", server: usso.StagingUbuntuSSOServer, request: &openid.Request{ ReturnTo: "http://return.to", }, expect: "https://login.staging.ubuntu.com/+openid?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=checkid_setup&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.return_to=http://return.to", }, { about: "with-realm", server: usso.ProductionUbuntuSSOServer, request: &openid.Request{ ReturnTo: "http://return.to/abcdef", Realm: "http://return.to", }, expect: "https://login.ubuntu.com/+openid?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=checkid_setup&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.return_to=http://return.to/abcdef&openid.realm=http://return.to", }, { about: "with-teams", server: usso.ProductionUbuntuSSOServer, request: &openid.Request{ ReturnTo: "http://return.to", Teams: []string{"team1", "team2"}, }, expect: "https://login.ubuntu.com/+openid?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=checkid_setup&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.return_to=http://return.to&openid.ns.lp=http://ns.launchpad.net/2007/openid-teams&openid.lp.query_membership=team1,team2", }, { about: "with sreg.required", server: usso.ProductionUbuntuSSOServer, request: &openid.Request{ ReturnTo: "http://return.to", SRegRequired: []string{openid.SRegEmail, openid.SRegProvince}, }, expect: "https://login.ubuntu.com/+openid?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=checkid_setup&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.return_to=http://return.to&openid.ns.sreg=http://openid.net/extensions/sreg/1.1&openid.sreg.required=email,x_province", }, { about: "with-sreg.optional", server: usso.ProductionUbuntuSSOServer, request: &openid.Request{ ReturnTo: "http://return.to", SRegOptional: []string{openid.SRegNickname, openid.SRegCity}, }, expect: "https://login.ubuntu.com/+openid?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=checkid_setup&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.return_to=http://return.to&openid.ns.sreg=http://openid.net/extensions/sreg/1.1&openid.sreg.optional=nickname,x_city", }, { about: "with-sreg", server: usso.ProductionUbuntuSSOServer, request: &openid.Request{ ReturnTo: "http://return.to", SRegRequired: []string{openid.SRegEmail, openid.SRegProvince}, SRegOptional: []string{openid.SRegNickname, openid.SRegCity}, }, expect: "https://login.ubuntu.com/+openid?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=checkid_setup&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.return_to=http://return.to&openid.ns.sreg=http://openid.net/extensions/sreg/1.1&openid.sreg.required=email,x_province&openid.sreg.optional=nickname,x_city", }, { about: "with-caveat", server: usso.ProductionUbuntuSSOServer, request: &openid.Request{ ReturnTo: "http://return.to", CaveatID: `{"secret": "squirrel", "version": 1}`, }, expect: `https://login.ubuntu.com/+openid?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=checkid_setup&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.return_to=http://return.to&openid.ns.macaroon=http://ns.login.ubuntu.com/2016/openid-macaroon&openid.macaroon.caveat_id={"secret": "squirrel", "version": 1}`, }} func TestRedirectURL(t *testing.T) { c := qt.New(t) for _, test := range redirectURLTests { c.Run(test.about, func(c *qt.C) { client := openid.NewClient(test.server, nil, nil) u, err := url.Parse(client.RedirectURL(test.request)) c.Assert(err, qt.Equals, nil) expectURL, err := url.Parse(test.expect) c.Assert(err, qt.Equals, nil) query := u.Query() expectQuery := expectURL.Query() c.Assert(query, qt.DeepEquals, expectQuery) u.RawQuery = "" expectURL.RawQuery = "" c.Assert(u, qt.DeepEquals, expectURL) }) } } var verifyTests = []struct { about string url string server usso.UbuntuSSOServer nonceStore yopenid.NonceStore discoveryCache yopenid.DiscoveryCache verifyF func(*qt.C, string, yopenid.DiscoveryCache, yopenid.NonceStore) (string, error) expectResponse *openid.Response expectError string expectErrorCause error }{{ about: "id only", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=id_res&openid.op_endpoint=https://login.ubuntu.com/%2Bopenid&openid.claimed_id=https://login.ubuntu.com/%2Bid/AAAAAA&openid.identity=https://login.ubuntu.com/%2Bid/AAAAAA&openid.return_to=http://return.to&openid.response_nonce=2005-05-15T17:11:51ZUNIQUE&openid.assoc_handle=1&openid.signed=op_endpoint,return_to,response_nonce,assoc_handle,claimed_id,identity&openid.sig=AAAA", server: usso.ProductionUbuntuSSOServer, verifyF: verifySuccess, expectResponse: &openid.Response{ ID: "https://login.ubuntu.com/+id/AAAAAA", }, }, { about: "teams", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=id_res&openid.op_endpoint=https://login.ubuntu.com/%2Bopenid&openid.claimed_id=https://login.ubuntu.com/%2Bid/AAAAAA&openid.identity=https://login.ubuntu.com/%2Bid/AAAAAA&openid.return_to=http://return.to&openid.response_nonce=2005-05-15T17:11:51ZUNIQUE&openid.assoc_handle=1&openid.signed=op_endpoint,return_to,response_nonce,assoc_handle,claimed_id,identity,lp.is_member&openid.sig=AAAA&openid.ns.lp=http://ns.launchpad.net/2007/openid-teams&openid.lp.is_member=team1,team2", server: usso.ProductionUbuntuSSOServer, verifyF: verifySuccess, expectResponse: &openid.Response{ ID: "https://login.ubuntu.com/+id/AAAAAA", Teams: []string{"team1", "team2"}, }, }, { about: "simple-registration", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=id_res&openid.op_endpoint=https://login.ubuntu.com/%2Bopenid&openid.claimed_id=https://login.ubuntu.com/%2Bid/AAAAAA&openid.identity=https://login.ubuntu.com/%2Bid/AAAAAA&openid.return_to=http://return.to&openid.response_nonce=2005-05-15T17:11:51ZUNIQUE&openid.assoc_handle=1&openid.signed=op_endpoint,return_to,response_nonce,assoc_handle,claimed_id,identity,sreg.email,sreg.fullname&openid.sig=AAAA&openid.ns.sreg=http://openid.net/extensions/sreg/1.1&openid.sreg.email=a@example.org&openid.sreg.fullname=A", server: usso.ProductionUbuntuSSOServer, verifyF: verifySuccess, expectResponse: &openid.Response{ ID: "https://login.ubuntu.com/+id/AAAAAA", SReg: map[string]string{ openid.SRegEmail: "a@example.org", openid.SRegFullName: "A", }, }, }, { about: "teams-not-signed", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=id_res&openid.op_endpoint=https://login.ubuntu.com/%2Bopenid&openid.claimed_id=https://login.ubuntu.com/%2Bid/AAAAAA&openid.identity=https://login.ubuntu.com/%2Bid/AAAAAA&openid.return_to=http://return.to&openid.response_nonce=2005-05-15T17:11:51ZUNIQUE&openid.assoc_handle=1&openid.signed=op_endpoint,return_to,response_nonce,assoc_handle,claimed_id,identity&openid.sig=AAAA&openid.ns.lp=http://ns.launchpad.net/2007/openid-teams&openid.lp.is_member=team1,team2", server: usso.ProductionUbuntuSSOServer, verifyF: verifySuccess, expectResponse: &openid.Response{ ID: "https://login.ubuntu.com/+id/AAAAAA", }, }, { about: "simple-registration-not-signed", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=id_res&openid.op_endpoint=https://login.ubuntu.com/%2Bopenid&openid.claimed_id=https://login.ubuntu.com/%2Bid/AAAAAA&openid.identity=https://login.ubuntu.com/%2Bid/AAAAAA&openid.return_to=http://return.to&openid.response_nonce=2005-05-15T17:11:51ZUNIQUE&openid.assoc_handle=1&openid.signed=op_endpoint,return_to,response_nonce,assoc_handle,claimed_id,identity&openid.sig=AAAA&openid.ns.sreg=http://openid.net/extensions/sreg/1.1&openid.sreg.email=a@example.org&openid.sreg.fullname=A", server: usso.ProductionUbuntuSSOServer, verifyF: verifySuccess, expectResponse: &openid.Response{ ID: "https://login.ubuntu.com/+id/AAAAAA", }, }, { about: "bad-url", url: "://return.to", server: usso.ProductionUbuntuSSOServer, verifyF: verifySuccess, expectError: "parse ://return.to: missing protocol scheme", }, { about: "unexpected-OP", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=id_res&openid.op_endpoint=https://login.ubuntu.com/%2Bopenid&openid.claimed_id=https://login.ubuntu.com/%2Bid/AAAAAA&openid.identity=https://login.ubuntu.com/%2Bid/AAAAAA&openid.return_to=http://return.to&openid.response_nonce=2005-05-15T17:11:51ZUNIQUE&openid.assoc_handle=1&openid.signed=op_endpoint,return_to,response_nonce,assoc_handle,claimed_id,identity&openid.sig=AAAA", server: usso.StagingUbuntuSSOServer, verifyF: verifySuccess, expectError: `OpenID response from unexpected endpoint "https://login.ubuntu.com/\+openid"`, }, { about: "verification-failure", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=id_res&openid.op_endpoint=https://login.ubuntu.com/%2Bopenid&openid.claimed_id=https://login.ubuntu.com/%2Bid/AAAAAA&openid.identity=https://login.ubuntu.com/%2Bid/AAAAAA&openid.return_to=http://return.to&openid.response_nonce=2005-05-15T17:11:51ZUNIQUE&openid.assoc_handle=1&openid.signed=op_endpoint,return_to,response_nonce,assoc_handle,claimed_id,identity&openid.sig=AAAA", server: usso.ProductionUbuntuSSOServer, verifyF: func(*qt.C, string, yopenid.DiscoveryCache, yopenid.NonceStore) (string, error) { return "", errors.New("TEST!") }, expectError: `TEST!`, }, { about: "uses-specified-NonceStore", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=id_res&openid.op_endpoint=https://login.ubuntu.com/%2Bopenid&openid.claimed_id=https://login.ubuntu.com/%2Bid/AAAAAA&openid.identity=https://login.ubuntu.com/%2Bid/AAAAAA&openid.return_to=http://return.to&openid.response_nonce=2005-05-15T17:11:51ZUNIQUE&openid.assoc_handle=1&openid.signed=op_endpoint,return_to,response_nonce,assoc_handle,claimed_id,identity&openid.sig=AAAA", server: usso.ProductionUbuntuSSOServer, nonceStore: testNonceStore, verifyF: func(c *qt.C, _ string, _ yopenid.DiscoveryCache, ns yopenid.NonceStore) (string, error) { c.Assert(ns, qt.Equals, testNonceStore) return "PASS", nil }, expectResponse: &openid.Response{ ID: "PASS", }, }, { about: "creates-server-specific-DiscoveryCache", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=id_res&openid.op_endpoint=https://login.ubuntu.com/%2Bopenid&openid.claimed_id=https://login.ubuntu.com/%2Bid/AAAAAA&openid.identity=https://login.ubuntu.com/%2Bid/AAAAAA&openid.return_to=http://return.to&openid.response_nonce=2005-05-15T17:11:51ZUNIQUE&openid.assoc_handle=1&openid.signed=op_endpoint,return_to,response_nonce,assoc_handle,claimed_id,identity&openid.sig=AAAA", server: usso.ProductionUbuntuSSOServer, verifyF: func(c *qt.C, _ string, dc yopenid.DiscoveryCache, _ yopenid.NonceStore) (string, error) { c.Assert(dc, qt.Not(qt.IsNil)) di := dc.Get("https://login.ubuntu.com/+id/AAAAAA") c.Assert(di, qt.Not(qt.IsNil)) c.Assert(di.ClaimedID(), qt.Equals, "https://login.ubuntu.com/+id/AAAAAA") c.Assert(di.OpLocalID(), qt.Equals, "https://login.ubuntu.com/+id/AAAAAA") c.Assert(di.OpEndpoint(), qt.Equals, "https://login.ubuntu.com/+openid") di = dc.Get("https://login.staging.ubuntu.com/+id/AAAAAA") c.Assert(di, qt.IsNil) return "PASS", nil }, expectResponse: &openid.Response{ ID: "PASS", }, }, { about: "cancel-response", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=cancel", verifyF: func(c *qt.C, _ string, _ yopenid.DiscoveryCache, _ yopenid.NonceStore) (string, error) { c.Fatalf("verify should not have been called") panic("unreachable") }, expectError: "login cancelled", expectErrorCause: openid.ErrCancel, }, { about: "bad-mode", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=bad", verifyF: func(c *qt.C, _ string, _ yopenid.DiscoveryCache, _ yopenid.NonceStore) (string, error) { c.Fatalf("verify should not have been called") panic("unreachable") }, expectError: `unrecognised mode "bad"`, }, { about: "openid-error", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=error&openid.error=test+message&openid.contact=test+contact&openid.reference=test+reference", verifyF: func(c *qt.C, _ string, _ yopenid.DiscoveryCache, _ yopenid.NonceStore) (string, error) { c.Fatalf("verify should not have been called") panic("unreachable") }, expectError: `test message`, expectErrorCause: &openid.OpenIDError{ Message: "test message", Contact: "test contact", Reference: "test reference", }, }, { about: "discharge", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=id_res&openid.op_endpoint=https://login.ubuntu.com/%2Bopenid&openid.claimed_id=https://login.ubuntu.com/%2Bid/AAAAAA&openid.identity=https://login.ubuntu.com/%2Bid/AAAAAA&openid.return_to=http://return.to&openid.response_nonce=2005-05-15T17:11:51ZUNIQUE&openid.assoc_handle=1&openid.signed=op_endpoint,return_to,response_nonce,assoc_handle,claimed_id,identity,macaroon.discharge&openid.sig=AAAA&openid.ns.macaroon=http://ns.login.ubuntu.com/2016/openid-macaroon&openid.macaroon.discharge=MDAwZWxvY2F0aW9uIAowMDE0aWRlbnRpZmllciBUZXN0CjAwMmZzaWduYXR1cmUgHF1XmyS2hpzHuObgmCBWFzpF7U0hFRuLnDsfkGLG9kAK", server: usso.ProductionUbuntuSSOServer, verifyF: verifySuccess, expectResponse: &openid.Response{ ID: "https://login.ubuntu.com/+id/AAAAAA", Discharge: testMacaroon, }, }, { about: "discharge-bad-base64", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=id_res&openid.op_endpoint=https://login.ubuntu.com/%2Bopenid&openid.claimed_id=https://login.ubuntu.com/%2Bid/AAAAAA&openid.identity=https://login.ubuntu.com/%2Bid/AAAAAA&openid.return_to=http://return.to&openid.response_nonce=2005-05-15T17:11:51ZUNIQUE&openid.assoc_handle=1&openid.signed=op_endpoint,return_to,response_nonce,assoc_handle,claimed_id,identity,macaroon.discharge&openid.sig=AAAA&openid.ns.macaroon=http://ns.login.ubuntu.com/2016/openid-macaroon&openid.macaroon.discharge=MDAwZWxvY2F0aW9uIAowMDE0aWRlbnRpZmllciBUZXN0CjAwMmZzaWduYXR1cmUgHF1XmyS2hpzHuObgmCBWFzpF7U0hFRuLnDsfkGLG9kA:", server: usso.ProductionUbuntuSSOServer, verifyF: verifySuccess, expectResponse: &openid.Response{ ID: "https://login.ubuntu.com/+id/AAAAAA", }, }, { about: "discharge-invalid-macaroon", url: "http://return.to?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=id_res&openid.op_endpoint=https://login.ubuntu.com/%2Bopenid&openid.claimed_id=https://login.ubuntu.com/%2Bid/AAAAAA&openid.identity=https://login.ubuntu.com/%2Bid/AAAAAA&openid.return_to=http://return.to&openid.response_nonce=2005-05-15T17:11:51ZUNIQUE&openid.assoc_handle=1&openid.signed=op_endpoint,return_to,response_nonce,assoc_handle,claimed_id,identity,macaroon.discharge&openid.sig=AAAA&openid.ns.macaroon=http://ns.login.ubuntu.com/2016/openid-macaroon&openid.macaroon.discharge=NDAwZWxvY2F0aW9uIAowMDE0aWRlbnRpZmllciBUZXN0CjAwMmZzaWduYXR1cmUgHF1XmyS2hpzHuObgmCBWFzpF7U0hFRuLnDsfkGLG9kAK", server: usso.ProductionUbuntuSSOServer, verifyF: verifySuccess, expectResponse: &openid.Response{ ID: "https://login.ubuntu.com/+id/AAAAAA", }, }} var testMacaroon = func() *macaroon.Macaroon { m, err := macaroon.New([]byte("A"), []byte("Test"), "", macaroon.V1) if err != nil { panic(err) } return m }() func TestVerify(t *testing.T) { c := qt.New(t) for _, test := range verifyTests { c.Run(test.about, func(c *qt.C) { *openid.Verify = func(s string, dc yopenid.DiscoveryCache, ns yopenid.NonceStore) (string, error) { return test.verifyF(c, s, dc, ns) } client := openid.NewClient(test.server, test.nonceStore, test.discoveryCache) r, err := client.Verify(test.url) if test.expectError != "" { c.Assert(err, qt.ErrorMatches, test.expectError) if test.expectErrorCause != nil { c.Assert(errgo.Cause(err), qt.DeepEquals, test.expectErrorCause) } return } c.Assert(err, qt.Equals, nil) c.Assert(r, qt.DeepEquals, test.expectResponse) }) } } func verifySuccess(_ *qt.C, s string, _ yopenid.DiscoveryCache, _ yopenid.NonceStore) (string, error) { u, err := url.Parse(s) if err != nil { return "", err } return u.Query().Get("openid.claimed_id"), nil } var testNonceStore = yopenid.NewSimpleNonceStore() golang-github-juju-usso-1.0.1/url.go000066400000000000000000000053501414203545700173430ustar00rootroot00000000000000// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENSE file for details. package usso import ( "fmt" "net/url" "sort" "strings" ) // Remove the standard ports from the URL. func normalizeHost(scheme, hostSpec string) string { standardPorts := map[string]string{ "http": "80", "https": "443", } hostParts := strings.Split(hostSpec, ":") if len(hostParts) == 2 && hostParts[1] == standardPorts[scheme] { // There's a port, but it's the default one. Leave it out. return hostParts[0] } return hostSpec } // Normalize the URL according to OAuth specs. func NormalizeURL(inputUrl string) (string, error) { parsedUrl, err := url.Parse(inputUrl) if err != nil { return "", err } host := normalizeHost(parsedUrl.Scheme, parsedUrl.Host) normalizedUrl := fmt.Sprintf( "%v://%v%v", parsedUrl.Scheme, host, parsedUrl.Path) return normalizedUrl, nil } type parameterSlice []parameter func (p parameterSlice) Len() int { return len(p) } func (p parameterSlice) Less(i, j int) bool { if p[i].key < p[j].key { return true } if p[i].key == p[j].key { return p[i].value < p[j].value } return false } func (p parameterSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p parameterSlice) String() string { ss := make([]string, len(p)) for i, param := range p { ss[i] = param.String() } return strings.Join(ss, "&") } type parameter struct { key, value string } func (p parameter) String() string { return fmt.Sprintf("%s=%s", p.key, p.value) } // Normalize the parameters in the query string according to // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2. // url.Values.Encode encoded the GET parameters in a consistent order we // do the encoding ourselves. func NormalizeParameters(parameters url.Values) (string, error) { var ps parameterSlice for k, vs := range parameters { if k == "oauth_signature" { continue } k = escape(k) for _, v := range vs { v = escape(v) ps = append(ps, parameter{k, v}) } } sort.Sort(ps) return ps.String(), nil } var escaped = [4]uint64{ 0xFC009FFFFFFFFFFF, 0xB800000178000001, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, } // escape percent encodes s as defined in // http://tools.ietf.org/html/rfc5849#section-3.6. // // Note: this is slightly different from the output of url.QueryEscape. func escape(s string) string { var count int for i := 0; i < len(s); i++ { if (escaped[s[i]>>6]>>(s[i]&0x3f))&1 == 1 { count++ } } if count == 0 { return s } buf := make([]byte, len(s)+2*count) j := 0 for i := 0; i < len(s); i++ { if (escaped[s[i]>>6]>>(s[i]&0x3f))&1 == 1 { buf[j] = '%' buf[j+1] = "0123456789ABCDEF"[s[i]>>4] buf[j+2] = "0123456789ABCDEF"[s[i]&0xf] j += 3 continue } buf[j] = s[i] j++ } return string(buf) } golang-github-juju-usso-1.0.1/url_test.go000066400000000000000000000163141414203545700204040ustar00rootroot00000000000000// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENSE file for details. package usso import ( "net/url" "testing" qt "github.com/frankban/quicktest" ) // When NormalizeURL() is passed a simple URL, it will make no changes // to it. func TestNormalizeURLReturnsBasicURL(t *testing.T) { c := qt.New(t) output, err := NormalizeURL("http://example.com/path") c.Check(err, qt.Equals, nil) c.Check(output, qt.Equals, "http://example.com/path") } // NormalizeURL() strips the ":80" from http:// URLs that contain it. func TestNormalizeURLStripsStandardHTTPPort(t *testing.T) { c := qt.New(t) output, err := NormalizeURL("http://example.com:80/path") c.Check(err, qt.Equals, nil) c.Check(output, qt.Equals, "http://example.com/path") } // NormalizeURL() strips the ":443" from https:// URLs that contain it. func TestNormalizeURLStripsStandardHTTPSPort(t *testing.T) { c := qt.New(t) output, err := NormalizeURL("https://example.com:443/path") c.Check(err, qt.Equals, nil) c.Check(output, qt.Equals, "https://example.com/path") } // NormalizeURL() does not remove non-standard ports from the URL. func TestNormalizeURLLeavesNonstandardPort(t *testing.T) { c := qt.New(t) output, err := NormalizeURL("http://example.com:8080/") c.Check(err, qt.Equals, nil) c.Check(output, qt.Equals, "http://example.com:8080/") } // NormalizeURL() strips the query string from URLs. func TestNormalizeURLStripsParameters(t *testing.T) { c := qt.New(t) output, err := NormalizeURL("http://example.com/path?query=value¶m=arg") c.Check(err, qt.Equals, nil) c.Check(output, qt.Equals, "http://example.com/path") } // NormalizeParameters() takes a url.Values instance and returns an // encoded key=value string containing the parameters in that instance. func TestNormalizeParametersReturnsParameters(t *testing.T) { c := qt.New(t) output, err := NormalizeParameters(url.Values{"param": []string{"value"}}) c.Check(err, qt.Equals, nil) c.Check(output, qt.Equals, "param=value") } // NormalizeParameters() encodes multiple key/value parameters as a // query string. func TestNormalizeParametersConcatenatesParameters(t *testing.T) { c := qt.New(t) output, err := NormalizeParameters( url.Values{"a": []string{"1"}, "b": []string{"2"}}) c.Check(err, qt.Equals, nil) c.Check(output, qt.Matches, "(a=1&b=2)") } // NormalizeParameters() escapes the parameters correctly when encoding // them as a query string. func TestNormalizeParametersEscapesParameters(t *testing.T) { c := qt.New(t) output, err := NormalizeParameters(url.Values{"a&b": []string{"1"}}) c.Check(err, qt.Equals, nil) c.Check(output, qt.Equals, "a%26b=1") } // If oauth_signature appears in the parameters passed to // NormalizeParameters(), it is omitted in the returned string as it does not // have to be included in the computation of the new oauth_signature. func TestNormalizeParametersOmitsOAuthSignature(t *testing.T) { c := qt.New(t) params := url.Values{ "a": []string{"1"}, "oauth_signature": []string{"foobarsplatszot"}, "z": []string{"26"}, } output, err := NormalizeParameters(params) c.Check(err, qt.Equals, nil) c.Check(output, qt.Matches, "(a=1&z=26)") } var escapeTests = map[string]string{ "\x00": "%00", "\x01": "%01", "\x02": "%02", "\x03": "%03", "\x04": "%04", "\x05": "%05", "\x06": "%06", "\x07": "%07", "\x08": "%08", "\x09": "%09", "\x0a": "%0A", "\x0b": "%0B", "\x0c": "%0C", "\x0d": "%0D", "\x0e": "%0E", "\x0f": "%0F", "\x10": "%10", "\x11": "%11", "\x12": "%12", "\x13": "%13", "\x14": "%14", "\x15": "%15", "\x16": "%16", "\x17": "%17", "\x18": "%18", "\x19": "%19", "\x1a": "%1A", "\x1b": "%1B", "\x1c": "%1C", "\x1d": "%1D", "\x1e": "%1E", "\x1f": "%1F", "\x20": "%20", "\x21": "%21", "\x22": "%22", "\x23": "%23", "\x24": "%24", "\x25": "%25", "\x26": "%26", "\x27": "%27", "\x28": "%28", "\x29": "%29", "\x2a": "%2A", "\x2b": "%2B", "\x2c": "%2C", "\x2d": "-", "\x2e": ".", "\x2f": "%2F", "\x30": "0", "\x31": "1", "\x32": "2", "\x33": "3", "\x34": "4", "\x35": "5", "\x36": "6", "\x37": "7", "\x38": "8", "\x39": "9", "\x3a": "%3A", "\x3b": "%3B", "\x3c": "%3C", "\x3d": "%3D", "\x3e": "%3E", "\x3f": "%3F", "\x40": "%40", "\x41": "A", "\x42": "B", "\x43": "C", "\x44": "D", "\x45": "E", "\x46": "F", "\x47": "G", "\x48": "H", "\x49": "I", "\x4a": "J", "\x4b": "K", "\x4c": "L", "\x4d": "M", "\x4e": "N", "\x4f": "O", "\x50": "P", "\x51": "Q", "\x52": "R", "\x53": "S", "\x54": "T", "\x55": "U", "\x56": "V", "\x57": "W", "\x58": "X", "\x59": "Y", "\x5a": "Z", "\x5b": "%5B", "\x5c": "%5C", "\x5d": "%5D", "\x5e": "%5E", "\x5f": "_", "\x60": "%60", "\x61": "a", "\x62": "b", "\x63": "c", "\x64": "d", "\x65": "e", "\x66": "f", "\x67": "g", "\x68": "h", "\x69": "i", "\x6a": "j", "\x6b": "k", "\x6c": "l", "\x6d": "m", "\x6e": "n", "\x6f": "o", "\x70": "p", "\x71": "q", "\x72": "r", "\x73": "s", "\x74": "t", "\x75": "u", "\x76": "v", "\x77": "w", "\x78": "x", "\x79": "y", "\x7a": "z", "\x7b": "%7B", "\x7c": "%7C", "\x7d": "%7D", "\x7e": "~", "\x7f": "%7F", "\x80": "%80", "\x81": "%81", "\x82": "%82", "\x83": "%83", "\x84": "%84", "\x85": "%85", "\x86": "%86", "\x87": "%87", "\x88": "%88", "\x89": "%89", "\x8a": "%8A", "\x8b": "%8B", "\x8c": "%8C", "\x8d": "%8D", "\x8e": "%8E", "\x8f": "%8F", "\x90": "%90", "\x91": "%91", "\x92": "%92", "\x93": "%93", "\x94": "%94", "\x95": "%95", "\x96": "%96", "\x97": "%97", "\x98": "%98", "\x99": "%99", "\x9a": "%9A", "\x9b": "%9B", "\x9c": "%9C", "\x9d": "%9D", "\x9e": "%9E", "\x9f": "%9F", "\xa0": "%A0", "\xa1": "%A1", "\xa2": "%A2", "\xa3": "%A3", "\xa4": "%A4", "\xa5": "%A5", "\xa6": "%A6", "\xa7": "%A7", "\xa8": "%A8", "\xa9": "%A9", "\xaa": "%AA", "\xab": "%AB", "\xac": "%AC", "\xad": "%AD", "\xae": "%AE", "\xaf": "%AF", "\xb0": "%B0", "\xb1": "%B1", "\xb2": "%B2", "\xb3": "%B3", "\xb4": "%B4", "\xb5": "%B5", "\xb6": "%B6", "\xb7": "%B7", "\xb8": "%B8", "\xb9": "%B9", "\xba": "%BA", "\xbb": "%BB", "\xbc": "%BC", "\xbd": "%BD", "\xbe": "%BE", "\xbf": "%BF", "\xc0": "%C0", "\xc1": "%C1", "\xc2": "%C2", "\xc3": "%C3", "\xc4": "%C4", "\xc5": "%C5", "\xc6": "%C6", "\xc7": "%C7", "\xc8": "%C8", "\xc9": "%C9", "\xca": "%CA", "\xcb": "%CB", "\xcc": "%CC", "\xcd": "%CD", "\xce": "%CE", "\xcf": "%CF", "\xd0": "%D0", "\xd1": "%D1", "\xd2": "%D2", "\xd3": "%D3", "\xd4": "%D4", "\xd5": "%D5", "\xd6": "%D6", "\xd7": "%D7", "\xd8": "%D8", "\xd9": "%D9", "\xda": "%DA", "\xdb": "%DB", "\xdc": "%DC", "\xdd": "%DD", "\xde": "%DE", "\xdf": "%DF", "\xe0": "%E0", "\xe1": "%E1", "\xe2": "%E2", "\xe3": "%E3", "\xe4": "%E4", "\xe5": "%E5", "\xe6": "%E6", "\xe7": "%E7", "\xe8": "%E8", "\xe9": "%E9", "\xea": "%EA", "\xeb": "%EB", "\xec": "%EC", "\xed": "%ED", "\xee": "%EE", "\xef": "%EF", "\xf0": "%F0", "\xf1": "%F1", "\xf2": "%F2", "\xf3": "%F3", "\xf4": "%F4", "\xf5": "%F5", "\xf6": "%F6", "\xf7": "%F7", "\xf8": "%F8", "\xf9": "%F9", "\xfa": "%FA", "\xfb": "%FB", "\xfc": "%FC", "\xfd": "%FD", "\xfe": "%FE", "\xff": "%FF", } func TestEscape(t *testing.T) { c := qt.New(t) for in, expected := range escapeTests { c.Assert(escape(in), qt.Equals, expected) } } golang-github-juju-usso-1.0.1/usso.go000066400000000000000000000160741414203545700175370ustar00rootroot00000000000000// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENSE file for details. package usso import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" ) type UbuntuSSOServer struct { baseUrl string tokenRegistrationUrl string } // tokenURL returns the URL where the Ubuntu SSO tokens can be requested. func (server UbuntuSSOServer) tokenURL() string { return server.baseUrl + "/api/v2/tokens/oauth" } // AccountURL returns the URL where the Ubuntu SSO account information can be // requested. func (server UbuntuSSOServer) AccountsURL() string { return server.baseUrl + "/api/v2/accounts/" } // TokenDetailURL returns the URL where the Ubuntu SSO token details can be // requested. func (server UbuntuSSOServer) TokenDetailsURL() string { return server.baseUrl + "/api/v2/tokens/oauth/" } // LoginURL returns the URL for the interactive login. func (server UbuntuSSOServer) LoginURL() string { return server.baseUrl } // OpenIDURL returns the URL of the OpenID login endpoint. func (server UbuntuSSOServer) OpenIDURL() string { return server.baseUrl + "/+openid" } // ProductionUbuntuSSOServer represents the production Ubuntu SSO server // located at https://login.ubuntu.com. var ProductionUbuntuSSOServer = UbuntuSSOServer{"https://login.ubuntu.com", "https://one.ubuntu.com/oauth/sso-finished-so-get-tokens/"} // StagingUbuntuSSOServer represents the staging Ubuntu SSO server located // at https://login.staging.ubuntu.com. Use it for testing. var StagingUbuntuSSOServer = UbuntuSSOServer{"https://login.staging.ubuntu.com", "https://one.staging.ubuntu.com/oauth/sso-finished-so-get-tokens/"} // Giving user credentials and token name, retrieves oauth credentials // for the users, the oauth credentials can be used later to sign // requests. If an error is returned from the identity server then it // will be of type *Error. func (server UbuntuSSOServer) GetToken(email string, password string, tokenName string) (*SSOData, error) { return server.GetTokenWithOTP(email, password, "", tokenName) } // GetTokenWithOTP retrieves an oauth token from the Ubuntu SSO server. // Using the user credentials including two-factor authentication and the // token name, an oauth token is retrieved that can later be used to sign // requests. If an error is returned from the identity server then it // will be of type *Error. If otp is blank then this is identical to // GetToken. func (server UbuntuSSOServer) GetTokenWithOTP(email, password, otp, tokenName string) (*SSOData, error) { credentials := map[string]string{ "email": email, "password": password, "token_name": tokenName, } if otp != "" { credentials["otp"] = otp } jsonCredentials, err := json.Marshal(credentials) if err != nil { return nil, err } response, err := http.Post( server.tokenURL(), "application/json", strings.NewReader(string(jsonCredentials))) if err != nil { return nil, err } defer response.Body.Close() if response.StatusCode != 200 && response.StatusCode != 201 { return nil, getError(response) } ssodata := SSOData{} body, err := ioutil.ReadAll(response.Body) if err != nil { return nil, err } err = json.Unmarshal(body, &ssodata) if err != nil { return nil, err } ssodata.Realm = "API" return &ssodata, nil } // Error represents an error message returned from Ubuntu SSO. type Error struct { Message string `json:"message"` Code string `json:"code,omitempty"` Extra map[string]interface{} `json:"extra,omitempty"` } // getError attempts to extract the most meaningful error that it can // from a response. func getError(resp *http.Response) *Error { var ssoError Error body, err := ioutil.ReadAll(resp.Body) if err != nil { ssoError.Code = resp.Status ssoError.Message = resp.Status return &ssoError } err = json.Unmarshal(body, &ssoError) if err != nil { // Attempt to pass the original error back in the best way possible ssoError.Code = resp.Status ssoError.Message = string(body) return &ssoError } return &ssoError } // Error implements error.Error. func (err *Error) Error() string { if len(err.Extra) == 0 { return err.Message } extra := make([]string, 0, len(err.Extra)) for k, v := range err.Extra { extra = append(extra, fmt.Sprintf("%s: %v", k, v)) } return fmt.Sprintf("%s (%s)", err.Message, strings.Join(extra, ", ")) } // Returns all the Ubuntu SSO information related to this account. func (server UbuntuSSOServer) GetAccounts(ssodata *SSOData) (string, error) { rp := RequestParameters{ BaseURL: server.AccountsURL() + ssodata.ConsumerKey, HTTPMethod: "GET", SignatureMethod: HMACSHA1{}} request, err := http.NewRequest(rp.HTTPMethod, rp.BaseURL, nil) if err != nil { return "", err } err = SignRequest(ssodata, &rp, request) if err != nil { return "", err } client := &http.Client{} response, err := client.Do(request) if err != nil { return "", err } body, err := ioutil.ReadAll(response.Body) if err != nil { return "", err } if response.StatusCode == 200 { return string(body), nil } else { var jsonMap map[string]interface{} err = json.Unmarshal(body, &jsonMap) // In theory, this should never happen. if err != nil { return "", fmt.Errorf("NO_JSON_RESPONSE") } code, ok := jsonMap["code"] if !ok { return "", fmt.Errorf("NO_CODE") } return "", fmt.Errorf("%v", code) } } // Given oauth credentials and a request, return it signed. func SignRequest( ssodata *SSOData, rp *RequestParameters, request *http.Request) error { return ssodata.SignRequest(rp, request) } // Given oauth credentials return a valid http authorization header. func GetAuthorizationHeader( ssodata *SSOData, rp *RequestParameters) (string, error) { header, err := ssodata.GetAuthorizationHeader(rp) return header, err } // Returns all the Ubuntu SSO information related to this token. func (server UbuntuSSOServer) GetTokenDetails(ssodata *SSOData) (string, error) { rp := RequestParameters{ BaseURL: server.TokenDetailsURL() + ssodata.TokenKey, HTTPMethod: "GET", SignatureMethod: HMACSHA1{}} request, err := http.NewRequest(rp.HTTPMethod, rp.BaseURL, nil) if err != nil { return "", err } err = SignRequest(ssodata, &rp, request) if err != nil { return "", err } client := &http.Client{} response, err := client.Do(request) if err != nil { return "", err } body, err := ioutil.ReadAll(response.Body) if err != nil { return "", err } if response.StatusCode == 200 { return string(body), nil } else { var jsonMap map[string]interface{} err = json.Unmarshal(body, &jsonMap) // due to bug #1285176, it is possible to get non json code in the response. if err != nil { return "", fmt.Errorf("INVALID_CREDENTIALS") } code, ok := jsonMap["code"] if !ok { return "", fmt.Errorf("NO_CODE") } return "", fmt.Errorf("%v", code) } } // Verify the validity of the token, abusing the API to get the token details. func (server UbuntuSSOServer) IsTokenValid(ssodata *SSOData) (bool, error) { details, err := server.GetTokenDetails(ssodata) if details != "" && err == nil { return true, nil } else { return false, err } } golang-github-juju-usso-1.0.1/usso_test.go000066400000000000000000000234241414203545700205730ustar00rootroot00000000000000// Copyright 2015 Canonical Ltd. // Licensed under the LGPLv3, see LICENSE file for details. package usso import ( "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" qt "github.com/frankban/quicktest" ) const ( tokenName = "foo" tokenKey = "abcs" tokenSecret = "mTBgLxtTRUdfqewqgrqsvxlijbMWkPBajgKcoZCrDwv" realm = "API" consumerKey = "rfyzhdQ" consumerSecret = "rwDkQkkdfdfdeAslkmmxAOjOAT" email = "foo@bar.com" password = "foobarpwd" otp = "000000" ) // TestProductionUbuntuSSOServerURLs tests the URLs of the production server. func TestProductionUbuntuSSOServerURLs(t *testing.T) { c := qt.New(t) tokenURL := ProductionUbuntuSSOServer.tokenURL() c.Assert(tokenURL, qt.Equals, "https://login.ubuntu.com/api/v2/tokens/oauth") } // TestStagingUbuntuSSOServerURLs tests the URLs of the staging server. func TestStagingUbuntuSSOServerURLs(t *testing.T) { c := qt.New(t) tokenURL := StagingUbuntuSSOServer.tokenURL() c.Assert(tokenURL, qt.Equals, "https://login.staging.ubuntu.com/api/v2/tokens/oauth") } type TestServer struct { *httptest.Server requestContent *string } // newTestServer http server to mock U1 SSO server. func newTestServer(response, tokenDetails string, code int) *TestServer { var requestContent string handler := func(w http.ResponseWriter, r *http.Request) { res, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } if strings.Contains(string(res), "WRONG") { http.Error(w, "404 page not found", http.StatusNotFound) } if r.URL.String() == "/api/v2/tokens/oauth" { requestContent = string(res) fmt.Fprint(w, response) return } if r.URL.String() == "/api/v2/tokens/oauth/abcs" { fmt.Fprint(w, tokenDetails) return } else { http.Error(w, "404 page not found", http.StatusNotFound) return } } server := httptest.NewServer(http.HandlerFunc(handler)) return &TestServer{server, &requestContent} } func TestGetTokenReturnsTokens(t *testing.T) { c := qt.New(t) // Simulate a valid Ubuntu SSO Server response. serverResponseData := map[string]string{ "date_updated": "2013-01-16 14:03:36", "date_created": "2013-01-16 14:03:36", "href": "/api/v2/tokens/" + tokenKey, "token_name": tokenName, "token_key": tokenKey, "token_secret": tokenSecret, "consumer_key": consumerKey, "consumer_secret": consumerSecret, } jsonServerResponseData, err := json.Marshal(serverResponseData) if err != nil { panic(err) } server := newTestServer(string(jsonServerResponseData), "{}", 200) var testSSOServer = &UbuntuSSOServer{server.URL, ""} defer server.Close() // The returned information is correct. ssodata, err := testSSOServer.GetToken(email, password, tokenName) c.Assert(err, qt.Equals, nil) expectedSSOData := &SSOData{ConsumerKey: consumerKey, ConsumerSecret: consumerSecret, Realm: realm, TokenKey: tokenKey, TokenSecret: tokenSecret, TokenName: tokenName} c.Assert(ssodata, qt.DeepEquals, expectedSSOData) // The request that the fake Ubuntu SSO Server has the credentials. credentials := map[string]string{ "email": email, "password": password, "token_name": tokenName, } expectedRequestContent, err := json.Marshal(credentials) if err != nil { panic(err) } c.Assert(*server.requestContent, qt.Equals, string(expectedRequestContent)) } // GetToken should return empty credentials and an error, if wrong account is provided. func TestGetTokenFails(t *testing.T) { c := qt.New(t) server := newTestServer("{}", "{}", 200) var testSSOServer = &UbuntuSSOServer{server.URL, ""} defer server.Close() ssodata, err := testSSOServer.GetToken(email, "WRONG", tokenName) c.Assert(err, qt.ErrorMatches, `404 page not found`+"\n"+`\{\}`) c.Assert(ssodata, qt.IsNil) } func TestGetTokenDetails(t *testing.T) { c := qt.New(t) // Simulate a valid Ubuntu SSO Server response. serverResponseData := map[string]string{ "date_updated": "2013-01-16 14:03:36", "date_created": "2013-01-16 14:03:36", "href": "/api/v2/tokens/" + tokenKey, "token_name": tokenName, "token_key": tokenKey, "consumer_key": consumerKey, } jsonServerResponseData, err := json.Marshal(serverResponseData) if err != nil { panic(err) } tokenDetails := map[string]string{ "token_name": tokenName, "date_updated": "2014-01-22T13:35:49.867", "token_key": tokenKey, "href": "/api/v2/tokens/oauth/JckChNpbXxPRmPkElLglSnqnjsnGseWJmNqTJCWfUtNBSsGtoG", "date_created": "2014-01-17T20:03:24.993", "consumer_key": consumerKey, } jsonTokenDetails, err := json.Marshal(tokenDetails) if err != nil { panic(err) } server := newTestServer(string(jsonServerResponseData), string(jsonTokenDetails), 200) var testSSOServer = &UbuntuSSOServer{server.URL, ""} defer server.Close() ssodata, err := testSSOServer.GetToken(email, password, tokenName) // The returned information is correct. token_details, err := testSSOServer.GetTokenDetails(ssodata) c.Assert(err, qt.IsNil) //The request that the fake Ubuntu SSO Server has the token details. c.Assert(token_details, qt.Equals, string(jsonTokenDetails)) } func TestGetTokenWithOTP(t *testing.T) { c := qt.New(t) // Simulate a valid Ubuntu SSO Server response. serverResponseData := map[string]string{ "date_updated": "2013-01-16 14:03:36", "date_created": "2013-01-16 14:03:36", "href": "/api/v2/tokens/" + tokenKey, "token_name": tokenName, "token_key": tokenKey, "token_secret": tokenSecret, "consumer_key": consumerKey, "consumer_secret": consumerSecret, } jsonServerResponseData, err := json.Marshal(serverResponseData) if err != nil { panic(err) } server := newTestServer(string(jsonServerResponseData), "{}", 200) var testSSOServer = &UbuntuSSOServer{server.URL, ""} defer server.Close() // The returned information is correct. ssodata, err := testSSOServer.GetTokenWithOTP(email, password, otp, tokenName) c.Assert(err, qt.IsNil) expectedSSOData := &SSOData{ConsumerKey: consumerKey, ConsumerSecret: consumerSecret, Realm: realm, TokenKey: tokenKey, TokenSecret: tokenSecret, TokenName: tokenName} c.Assert(ssodata, qt.DeepEquals, expectedSSOData) // The request that the fake Ubuntu SSO Server has the credentials. credentials := map[string]string{ "email": email, "password": password, "token_name": tokenName, "otp": otp, } expectedRequestContent, err := json.Marshal(credentials) c.Assert(err, qt.IsNil) c.Assert(*server.requestContent, qt.Equals, string(expectedRequestContent)) } func TestTokenValidity(t *testing.T) { c := qt.New(t) // Simulate a valid Ubuntu SSO Server response. serverResponseData := map[string]string{ "date_updated": "2013-01-16 14:03:36", "date_created": "2013-01-16 14:03:36", "href": "/api/v2/tokens/" + tokenKey, "token_name": tokenName, "token_key": tokenKey, "consumer_key": consumerKey, } jsonServerResponseData, err := json.Marshal(serverResponseData) if err != nil { panic(err) } tokenDetails := map[string]string{ "token_name": tokenName, "date_updated": "2014-01-22T13:35:49.867", "token_key": tokenKey, "href": "/api/v2/tokens/oauth/JckChNpbXxPRmPkElLglSnqnjsnGseWJmNqTJCWfUtNBSsGtoG", "date_created": "2014-01-17T20:03:24.993", "consumer_key": consumerKey, } jsonTokenDetails, err := json.Marshal(tokenDetails) if err != nil { panic(err) } server := newTestServer(string(jsonServerResponseData), string(jsonTokenDetails), 200) var testSSOServer = &UbuntuSSOServer{server.URL, ""} defer server.Close() ssodata, err := testSSOServer.GetToken(email, password, tokenName) // The returned information is correct. token_details, err := testSSOServer.GetTokenDetails(ssodata) c.Assert(err, qt.IsNil) //The request that the fake Ubuntu SSO Server has the token details. c.Assert(token_details, qt.Equals, string(jsonTokenDetails)) validity, err := testSSOServer.IsTokenValid(ssodata) c.Assert(validity, qt.Equals, true) } // Check invalid token func TestInvalidToken(t *testing.T) { c := qt.New(t) server := newTestServer("{}", "{}", 200) var testSSOServer = &UbuntuSSOServer{server.URL, ""} defer server.Close() ssodata := SSOData{"WRONG", "", "", "", "", ""} validity, err := testSSOServer.IsTokenValid(&ssodata) c.Assert(err, qt.ErrorMatches, `INVALID_CREDENTIALS`) c.Assert(validity, qt.Equals, false) } var getErrorTests = []struct { about string status string body io.Reader expectCode string expectError string }{{ about: "valid error", body: strings.NewReader(`{"message": "test error"}`), expectError: `test error`, }, { about: "valid error with code", body: strings.NewReader(`{"message": "test error", "code": "ERROR"}`), expectCode: "ERROR", expectError: `test error`, }, { about: "valid error with extra", body: strings.NewReader(`{"message": "test error", "extra": {"ext": "thing"}}`), expectError: `test error \(ext: thing\)`, }, { about: "bad json", status: "500 Internal Server Error", body: strings.NewReader(`{"message": "test error"`), expectCode: "500 Internal Server Error", expectError: `{"message": "test error"`, }, { about: "bad reader", status: "500 Internal Server Error", body: errorReader{fmt.Errorf("test read error")}, expectCode: "500 Internal Server Error", expectError: `500 Internal Server Error`, }} func TestGetError(t *testing.T) { c := qt.New(t) for i, test := range getErrorTests { c.Logf("%d. %s", i, test.about) resp := &http.Response{ Status: test.status, Body: ioutil.NopCloser(test.body), } err := getError(resp) c.Assert(err.Code, qt.Equals, test.expectCode) c.Assert(err, qt.ErrorMatches, test.expectError) } } type errorReader struct { Err error } func (r errorReader) Read(b []byte) (int, error) { return 0, r.Err }