From a85743b00cba95549823920d53bb5bbec5a66454 Mon Sep 17 00:00:00 2001 From: Anant Prakash Date: Sat, 3 Mar 2018 21:34:30 +0000 Subject: [PATCH 1/2] Login: Add Token based authentication Signed-off-by: Anant Prakash --- .../dendrite/clientapi/routing/login.go | 160 +++++++++++++----- 1 file changed, 114 insertions(+), 46 deletions(-) diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/login.go b/src/github.com/matrix-org/dendrite/clientapi/routing/login.go index f48261ab2..2112fa2a9 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/login.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/login.go @@ -15,6 +15,7 @@ package routing import ( + "database/sql" "net/http" "strings" @@ -28,6 +29,14 @@ import ( "github.com/matrix-org/util" ) +type loginType string + +// https://matrix.org/docs/spec/client_server/r0.3.0.html#login +const ( + PasswordBased loginType = "m.login.password" + TokenBased loginType = "m.login.token" +) + type loginFlows struct { Flows []flow `json:"flows"` } @@ -37,10 +46,15 @@ type flow struct { Stages []string `json:"stages"` } -type passwordRequest struct { - User string `json:"user"` - Password string `json:"password"` - InitialDisplayName *string `json:"initial_device_display_name"` +type loginRequest struct { + Type loginType `json:"type"` + User string `json:"user"` + Medium string `json:"medium"` + Address string `json:"address"` + Password string `json:"password"` + Token string `json:"token"` + DeviceID string `json:"device_id"` + InitialDisplayName *string `json:"initial_device_display_name"` } type loginResponse struct { @@ -50,25 +64,112 @@ type loginResponse struct { DeviceID string `json:"device_id"` } -func passwordLogin() loginFlows { +func defaultPasswordLogin() loginFlows { f := loginFlows{} - s := flow{"m.login.password", []string{"m.login.password"}} + s := flow{string(PasswordBased), []string{string(PasswordBased)}} f.Flows = append(f.Flows, s) return f } +func handlePasswordLogin( + r loginRequest, accountDB *accounts.Database, deviceDB *devices.Database, + req *http.Request, cfg config.Dendrite) *util.JSONResponse { + + localpart := r.User + acc, err := accountDB.GetAccountByPassword(req.Context(), localpart, r.Password) + + if err != nil { + // Technically we could tell them if the user does not exist by checking if err == sql.ErrNoRows + // but that would leak the existence of the user. + return &util.JSONResponse{ + Code: 403, + JSON: jsonerror.Forbidden("username or password was incorrect, or the account does not exist"), + } + } + + token, err := auth.GenerateAccessToken() + if err != nil { + httputil.LogThenError(req, err) + } + + // TODO: Use the device ID in the request + dev, err := deviceDB.CreateDevice( + req.Context(), acc.Localpart, nil, token, r.InitialDisplayName, + ) + if err != nil { + return &util.JSONResponse{ + Code: 500, + JSON: jsonerror.Unknown("failed to create device: " + err.Error()), + } + } + + return &util.JSONResponse{ + Code: 200, + JSON: loginResponse{ + UserID: dev.UserID, + AccessToken: dev.AccessToken, + HomeServer: cfg.Matrix.ServerName, + DeviceID: dev.ID, + }, + } +} + +func handleTokenLogin( + r loginRequest, deviceDB *devices.Database, + req *http.Request, cfg config.Dendrite) *util.JSONResponse { + if r.Token == "" { + return &util.JSONResponse{ + Code: 401, + JSON: jsonerror.MissingToken("missing access token"), + } + } + + dev, err := deviceDB.GetDeviceByAccessToken(req.Context(), r.Token) + if err != nil { + if err == sql.ErrNoRows { + return &util.JSONResponse{ + Code: 401, + JSON: jsonerror.UnknownToken("Unknown token"), + } + } + return &util.JSONResponse{ + Code: 401, + JSON: jsonerror.Unknown("Unexpected Server error occurred"), + } + } + + if dev.ID != r.DeviceID { + // The access token specified in the request was generated for a + // different device. + return &util.JSONResponse{ + Code: 403, + JSON: jsonerror.Forbidden("The access token was generated for a different device."), + } + } + + return &util.JSONResponse{ + Code: 200, + JSON: loginResponse{ + UserID: dev.UserID, + AccessToken: dev.AccessToken, + HomeServer: cfg.Matrix.ServerName, + DeviceID: dev.ID, + }, + } +} + // Login implements GET and POST /login func Login( req *http.Request, accountDB *accounts.Database, deviceDB *devices.Database, cfg config.Dendrite, ) util.JSONResponse { - if req.Method == "GET" { // TODO: support other forms of login other than password, depending on config options + if req.Method == "GET" { return util.JSONResponse{ Code: 200, - JSON: passwordLogin(), + JSON: defaultPasswordLogin(), } } else if req.Method == "POST" { - var r passwordRequest + var r loginRequest resErr := httputil.UnmarshalJSONRequest(req, &r) if resErr != nil { return *resErr @@ -82,12 +183,10 @@ func Login( util.GetLogger(req.Context()).WithField("user", r.User).Info("Processing login request") - // r.User can either be a user ID or just the localpart... or other things maybe. - localpart := r.User if strings.HasPrefix(r.User, "@") { var domain gomatrixserverlib.ServerName var err error - localpart, domain, err = gomatrixserverlib.SplitID('@', r.User) + _, domain, err = gomatrixserverlib.SplitID('@', r.User) if err != nil { return util.JSONResponse{ Code: 400, @@ -103,41 +202,10 @@ func Login( } } - acc, err := accountDB.GetAccountByPassword(req.Context(), localpart, r.Password) - if err != nil { - // Technically we could tell them if the user does not exist by checking if err == sql.ErrNoRows - // but that would leak the existence of the user. - return util.JSONResponse{ - Code: 403, - JSON: jsonerror.Forbidden("username or password was incorrect, or the account does not exist"), - } - } - - token, err := auth.GenerateAccessToken() - if err != nil { - httputil.LogThenError(req, err) - } - - // TODO: Use the device ID in the request - dev, err := deviceDB.CreateDevice( - req.Context(), acc.Localpart, nil, token, r.InitialDisplayName, - ) - if err != nil { - return util.JSONResponse{ - Code: 500, - JSON: jsonerror.Unknown("failed to create device: " + err.Error()), - } - } - - return util.JSONResponse{ - Code: 200, - JSON: loginResponse{ - UserID: dev.UserID, - AccessToken: dev.AccessToken, - HomeServer: cfg.Matrix.ServerName, - DeviceID: dev.ID, - }, + if r.Type == PasswordBased { + return *handleTokenLogin(r, deviceDB, req, cfg) } + return *handlePasswordLogin(r, accountDB, deviceDB, req, cfg) } return util.JSONResponse{ Code: 405, From 5a461f9071d916316a756bedc594de666dff1d33 Mon Sep 17 00:00:00 2001 From: Anant Prakash Date: Sun, 4 Mar 2018 18:17:02 +0530 Subject: [PATCH 2/2] Address PR comments Signed-off-by: Anant Prakash --- .../clientapi/auth/authtypes/loginrequest.go | 26 ++++++ .../clientapi/auth/authtypes/loginresponse.go | 26 ++++++ .../clientapi/auth/authtypes/logintypes.go | 2 + .../dendrite/clientapi/routing/login.go | 87 ++++++++----------- 4 files changed, 90 insertions(+), 51 deletions(-) create mode 100644 src/github.com/matrix-org/dendrite/clientapi/auth/authtypes/loginrequest.go create mode 100644 src/github.com/matrix-org/dendrite/clientapi/auth/authtypes/loginresponse.go diff --git a/src/github.com/matrix-org/dendrite/clientapi/auth/authtypes/loginrequest.go b/src/github.com/matrix-org/dendrite/clientapi/auth/authtypes/loginrequest.go new file mode 100644 index 000000000..f8c898062 --- /dev/null +++ b/src/github.com/matrix-org/dendrite/clientapi/auth/authtypes/loginrequest.go @@ -0,0 +1,26 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package authtypes + +// LoginRequest represents the request sent by the client +// https://matrix.org/docs/spec/client_server/r0.3.0.html#post-matrix-client-r0-login +type LoginRequest struct { + Type LoginType `json:"type"` + User string `json:"user"` + Medium string `json:"medium"` + Address string `json:"address"` + Password string `json:"password"` + Token string `json:"token"` + DeviceID string `json:"device_id"` + InitialDisplayName *string `json:"initial_device_display_name"` +} diff --git a/src/github.com/matrix-org/dendrite/clientapi/auth/authtypes/loginresponse.go b/src/github.com/matrix-org/dendrite/clientapi/auth/authtypes/loginresponse.go new file mode 100644 index 000000000..61dc01c3b --- /dev/null +++ b/src/github.com/matrix-org/dendrite/clientapi/auth/authtypes/loginresponse.go @@ -0,0 +1,26 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package authtypes + +import ( + "github.com/matrix-org/gomatrixserverlib" +) + +// LoginResponse represents the response received by the client +// https://matrix.org/docs/spec/client_server/r0.3.0.html#post-matrix-client-r0-login +type LoginResponse struct { + UserID string `json:"user_id"` + AccessToken string `json:"access_token"` + HomeServer gomatrixserverlib.ServerName `json:"home_server"` + DeviceID string `json:"device_id"` +} diff --git a/src/github.com/matrix-org/dendrite/clientapi/auth/authtypes/logintypes.go b/src/github.com/matrix-org/dendrite/clientapi/auth/authtypes/logintypes.go index 087e45043..5e07ce5f9 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/auth/authtypes/logintypes.go +++ b/src/github.com/matrix-org/dendrite/clientapi/auth/authtypes/logintypes.go @@ -9,4 +9,6 @@ const ( LoginTypeSharedSecret = "org.matrix.login.shared_secret" LoginTypeRecaptcha = "m.login.recaptcha" LoginTypeApplicationService = "m.login.application_service" + LoginTypePassword = "m.login.password" + LoginTypeToken = "m.login.token" ) diff --git a/src/github.com/matrix-org/dendrite/clientapi/routing/login.go b/src/github.com/matrix-org/dendrite/clientapi/routing/login.go index 2112fa2a9..a4432fe13 100644 --- a/src/github.com/matrix-org/dendrite/clientapi/routing/login.go +++ b/src/github.com/matrix-org/dendrite/clientapi/routing/login.go @@ -20,6 +20,7 @@ import ( "strings" "github.com/matrix-org/dendrite/clientapi/auth" + "github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/storage/accounts" "github.com/matrix-org/dendrite/clientapi/auth/storage/devices" "github.com/matrix-org/dendrite/clientapi/httputil" @@ -29,14 +30,6 @@ import ( "github.com/matrix-org/util" ) -type loginType string - -// https://matrix.org/docs/spec/client_server/r0.3.0.html#login -const ( - PasswordBased loginType = "m.login.password" - TokenBased loginType = "m.login.token" -) - type loginFlows struct { Flows []flow `json:"flows"` } @@ -46,42 +39,23 @@ type flow struct { Stages []string `json:"stages"` } -type loginRequest struct { - Type loginType `json:"type"` - User string `json:"user"` - Medium string `json:"medium"` - Address string `json:"address"` - Password string `json:"password"` - Token string `json:"token"` - DeviceID string `json:"device_id"` - InitialDisplayName *string `json:"initial_device_display_name"` -} - -type loginResponse struct { - UserID string `json:"user_id"` - AccessToken string `json:"access_token"` - HomeServer gomatrixserverlib.ServerName `json:"home_server"` - DeviceID string `json:"device_id"` -} - func defaultPasswordLogin() loginFlows { f := loginFlows{} - s := flow{string(PasswordBased), []string{string(PasswordBased)}} + s := flow{string(authtypes.LoginTypePassword), []string{string(authtypes.LoginTypePassword)}} f.Flows = append(f.Flows, s) return f } func handlePasswordLogin( - r loginRequest, accountDB *accounts.Database, deviceDB *devices.Database, - req *http.Request, cfg config.Dendrite) *util.JSONResponse { + r authtypes.LoginRequest, localpart string, accountDB *accounts.Database, + deviceDB *devices.Database, req *http.Request, cfg config.Dendrite) util.JSONResponse { - localpart := r.User acc, err := accountDB.GetAccountByPassword(req.Context(), localpart, r.Password) if err != nil { // Technically we could tell them if the user does not exist by checking if err == sql.ErrNoRows // but that would leak the existence of the user. - return &util.JSONResponse{ + return util.JSONResponse{ Code: 403, JSON: jsonerror.Forbidden("username or password was incorrect, or the account does not exist"), } @@ -97,15 +71,15 @@ func handlePasswordLogin( req.Context(), acc.Localpart, nil, token, r.InitialDisplayName, ) if err != nil { - return &util.JSONResponse{ + return util.JSONResponse{ Code: 500, JSON: jsonerror.Unknown("failed to create device: " + err.Error()), } } - return &util.JSONResponse{ + return util.JSONResponse{ Code: 200, - JSON: loginResponse{ + JSON: authtypes.LoginResponse{ UserID: dev.UserID, AccessToken: dev.AccessToken, HomeServer: cfg.Matrix.ServerName, @@ -115,41 +89,41 @@ func handlePasswordLogin( } func handleTokenLogin( - r loginRequest, deviceDB *devices.Database, - req *http.Request, cfg config.Dendrite) *util.JSONResponse { + r authtypes.LoginRequest, deviceDB *devices.Database, + req *http.Request, cfg config.Dendrite) util.JSONResponse { if r.Token == "" { - return &util.JSONResponse{ + return util.JSONResponse{ Code: 401, - JSON: jsonerror.MissingToken("missing access token"), + JSON: jsonerror.MissingToken("Missing access token"), } } dev, err := deviceDB.GetDeviceByAccessToken(req.Context(), r.Token) if err != nil { if err == sql.ErrNoRows { - return &util.JSONResponse{ + return util.JSONResponse{ Code: 401, JSON: jsonerror.UnknownToken("Unknown token"), } } - return &util.JSONResponse{ - Code: 401, - JSON: jsonerror.Unknown("Unexpected Server error occurred"), + return util.JSONResponse{ + Code: 500, + JSON: jsonerror.Unknown("Unexpected server error occurred"), } } if dev.ID != r.DeviceID { // The access token specified in the request was generated for a // different device. - return &util.JSONResponse{ + return util.JSONResponse{ Code: 403, - JSON: jsonerror.Forbidden("The access token was generated for a different device."), + JSON: jsonerror.Forbidden("Access token not valid for this device"), } } - return &util.JSONResponse{ + return util.JSONResponse{ Code: 200, - JSON: loginResponse{ + JSON: authtypes.LoginResponse{ UserID: dev.UserID, AccessToken: dev.AccessToken, HomeServer: cfg.Matrix.ServerName, @@ -169,7 +143,7 @@ func Login( JSON: defaultPasswordLogin(), } } else if req.Method == "POST" { - var r loginRequest + var r authtypes.LoginRequest resErr := httputil.UnmarshalJSONRequest(req, &r) if resErr != nil { return *resErr @@ -183,10 +157,13 @@ func Login( util.GetLogger(req.Context()).WithField("user", r.User).Info("Processing login request") + // r.User can either be a user ID or just the localpart... or other things maybe. + localpart := r.User + if strings.HasPrefix(r.User, "@") { var domain gomatrixserverlib.ServerName var err error - _, domain, err = gomatrixserverlib.SplitID('@', r.User) + localpart, domain, err = gomatrixserverlib.SplitID('@', r.User) if err != nil { return util.JSONResponse{ Code: 400, @@ -202,10 +179,18 @@ func Login( } } - if r.Type == PasswordBased { - return *handleTokenLogin(r, deviceDB, req, cfg) + switch r.Type { + case authtypes.LoginTypePassword: + return handlePasswordLogin(r, localpart, accountDB, deviceDB, req, cfg) + case authtypes.LoginTypeToken: + return handleTokenLogin(r, deviceDB, req, cfg) + default: + return util.JSONResponse{ + Code: 501, + JSON: jsonerror.Unknown("Unknown login type"), + } } - return *handlePasswordLogin(r, accountDB, deviceDB, req, cfg) + } return util.JSONResponse{ Code: 405,