1
0

Add 2fa for authentification (#383)

Fix user tests

Add swagger docs

Fix lint

Add totp check when logging in

Make totp enrollment work

Add migration for totp table

go mod vendor

Add routes for totp routes

Add route handler for totp routes

Add basic implementation to enroll a user in totp

Co-authored-by: kolaente <k@knt.li>
Reviewed-on: https://kolaente.dev/vikunja/api/pulls/383
This commit is contained in:
konrad
2020-04-17 19:25:35 +00:00
parent 1dca8e96a7
commit 24904585a2
47 changed files with 3220 additions and 12 deletions

View File

@ -41,5 +41,4 @@ func init() {
return tx.DropTables(list20200322214624{})
},
})
}

View File

@ -0,0 +1,47 @@
// Vikunja is a to-do list application to facilitate your life.
// Copyright 2018-2020 Vikunja and contributors. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package migration
import (
"src.techknowlogick.com/xormigrate"
"xorm.io/xorm"
)
type totp20200417175201 struct {
ID int64 `xorm:"int(11) autoincr not null unique pk" json:"-"`
UserID int64 `xorm:"int(11) not null" json:"-"`
Secret string `xorm:"varchar(20) not null" json:"secret"`
Enabled bool `xorm:"null" json:"enabled"`
URL string `xorm:"text null" json:"url"`
}
func (t totp20200417175201) TableName() string {
return "totp"
}
func init() {
migrations = append(migrations, &xormigrate.Migration{
ID: "20200417175201",
Description: "Add totp table",
Migrate: func(tx *xorm.Engine) error {
return tx.Sync2(totp20200417175201{})
},
Rollback: func(tx *xorm.Engine) error {
return tx.DropTables(totp20200417175201{})
},
})
}

View File

@ -39,6 +39,7 @@ type Token struct {
// @Param credentials body user.UserLogin true "The login credentials"
// @Success 200 {object} v1.Token
// @Failure 400 {object} models.Message "Invalid user password model."
// @Failure 412 {object} models.Message "Invalid totp passcode."
// @Failure 403 {object} models.Message "Invalid username or password."
// @Router /login [post]
func Login(c echo.Context) error {
@ -53,6 +54,21 @@ func Login(c echo.Context) error {
return handler.HandleHTTPError(err, c)
}
totpEnabled, err := user2.TOTPEnabledForUser(user)
if err != nil {
return handler.HandleHTTPError(err, c)
}
if totpEnabled {
_, err = user2.ValidateTOTPPasscode(&user2.TOTPPasscode{
User: user,
Passcode: u.TOTPPasscode,
})
if err != nil {
return handler.HandleHTTPError(err, c)
}
}
// Create token
t, err := NewUserJWTAuthtoken(user)
if err != nil {

View File

@ -0,0 +1,124 @@
// Vikunja is a to-do list application to facilitate your life.
// Copyright 2018-2020 Vikunja and contributors. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package v1
import (
"bytes"
"code.vikunja.io/api/pkg/log"
"code.vikunja.io/api/pkg/models"
"code.vikunja.io/api/pkg/user"
"code.vikunja.io/web/handler"
"fmt"
"github.com/labstack/echo/v4"
"image/jpeg"
"net/http"
)
// UserTOTPEnroll is the handler to enroll a user into totp
// @Summary Enroll a user into totp
// @Description Creates an initial setup for the user in the db. After this step, the user needs to verify they have a working totp setup with the "enable totp" endpoint.
// @tags user
// @Accept json
// @Produce json
// @Security JWTKeyAuth
// @Success 200 {object} user.TOTP
// @Failure 400 {object} code.vikunja.io/web.HTTPError "Something's invalid."
// @Failure 404 {object} code.vikunja.io/web.HTTPError "User does not exist."
// @Failure 500 {object} models.Message "Internal server error."
// @Router /user/settings/totp/enroll [post]
func UserTOTPEnroll(c echo.Context) error {
u, err := user.GetCurrentUser(c)
if err != nil {
return handler.HandleHTTPError(err, c)
}
t, err := user.EnrollTOTP(u)
if err != nil {
return handler.HandleHTTPError(err, c)
}
return c.JSON(http.StatusOK, t)
}
// UserTOTPEnable is the handler to enable totp for a user
// @Summary Enable a previously enrolled totp setting.
// @Description Enables a previously enrolled totp setting by providing a totp passcode.
// @tags user
// @Accept json
// @Produce json
// @Param totp body user.TOTPPasscode true "The totp passcode."
// @Security JWTKeyAuth
// @Success 200 {object} models.Message "Successfully enabled"
// @Failure 400 {object} code.vikunja.io/web.HTTPError "Something's invalid."
// @Failure 404 {object} code.vikunja.io/web.HTTPError "User does not exist."
// @Failure 412 {object} code.vikunja.io/web.HTTPError "TOTP is not enrolled."
// @Failure 500 {object} models.Message "Internal server error."
// @Router /user/settings/totp/enable [post]
func UserTOTPEnable(c echo.Context) error {
u, err := user.GetCurrentUser(c)
if err != nil {
return handler.HandleHTTPError(err, c)
}
passcode := &user.TOTPPasscode{
User: u,
}
if err := c.Bind(passcode); err != nil {
log.Debugf("Invalid model error. Internal error was: %s", err.Error())
if he, is := err.(*echo.HTTPError); is {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid model provided. Error was: %s", he.Message))
}
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid model provided."))
}
err = user.EnableTOTP(passcode)
if err != nil {
return handler.HandleHTTPError(err, c)
}
return c.JSON(http.StatusOK, models.Message{Message: "TOTP was enabled successfully."})
}
// UserTOTPQrCode is the handler to show a qr code to enroll the user into totp
// @Summary Totp QR Code
// @Description Returns a qr code for easier setup at end user's devices.
// @tags user
// @Accept json
// @Produce json
// @Security JWTKeyAuth
// @Success 200 {} string "The qr code as jpeg image"
// @Failure 500 {object} models.Message "Internal server error."
// @Router /user/settings/totp/qrcode [get]
func UserTOTPQrCode(c echo.Context) error {
u, err := user.GetCurrentUser(c)
if err != nil {
return handler.HandleHTTPError(err, c)
}
qrcode, err := user.GetTOTPQrCodeForUser(u)
if err != nil {
return handler.HandleHTTPError(err, c)
}
buff := &bytes.Buffer{}
err = jpeg.Encode(buff, qrcode, nil)
if err != nil {
return handler.HandleHTTPError(err, c)
}
return c.Blob(http.StatusOK, "image/jpeg", buff.Bytes())
}

View File

@ -202,11 +202,16 @@ func registerAPIRoutes(a *echo.Group) {
a.POST("/tokenTest", apiv1.CheckToken)
// User stuff
a.GET("/user", apiv1.UserShow)
a.POST("/user/password", apiv1.UserChangePassword)
a.GET("/users", apiv1.UserList)
a.POST("/user/token", apiv1.RenewToken)
a.POST("/user/settings/email", apiv1.UpdateUserEmail)
u := a.Group("/user")
u.GET("", apiv1.UserShow)
u.POST("/password", apiv1.UserChangePassword)
u.GET("s", apiv1.UserList)
u.POST("/token", apiv1.RenewToken)
u.POST("/settings/email", apiv1.UpdateUserEmail)
u.POST("/settings/totp/enroll", apiv1.UserTOTPEnroll)
u.POST("/settings/totp/enable", apiv1.UserTOTPEnable)
u.GET("/settings/totp/qrcode", apiv1.UserTOTPQrCode)
listHandler := &handler.WebHandler{
EmptyStruct: func() handler.CObject {

View File

@ -46,5 +46,6 @@ func InitDB() (err error) {
func GetTables() []interface{} {
return []interface{}{
&User{},
&TOTP{},
}
}

View File

@ -289,3 +289,80 @@ const ErrCodeEmptyOldPassword = 1014
func (err ErrEmptyOldPassword) HTTPError() web.HTTPError {
return web.HTTPError{HTTPCode: http.StatusPreconditionFailed, Code: ErrCodeEmptyOldPassword, Message: "Please specify old password."}
}
// ErrTOTPAlreadyEnabled represents a "TOTPAlreadyEnabled" kind of error.
type ErrTOTPAlreadyEnabled struct{}
// IsErrTOTPAlreadyEnabled checks if an error is a ErrTOTPAlreadyEnabled.
func IsErrTOTPAlreadyEnabled(err error) bool {
_, ok := err.(ErrTOTPAlreadyEnabled)
return ok
}
func (err ErrTOTPAlreadyEnabled) Error() string {
return fmt.Sprintf("Totp is already enabled for this user")
}
// ErrCodeTOTPAlreadyEnabled holds the unique world-error code of this error
const ErrCodeTOTPAlreadyEnabled = 1015
// HTTPError holds the http error description
func (err ErrTOTPAlreadyEnabled) HTTPError() web.HTTPError {
return web.HTTPError{
HTTPCode: http.StatusPreconditionFailed,
Code: ErrCodeTOTPAlreadyEnabled,
Message: "Totp is already enabled for this user, but not activated.",
}
}
// ErrTOTPNotEnabled represents a "TOTPNotEnabled" kind of error.
type ErrTOTPNotEnabled struct{}
// IsErrTOTPNotEnabled checks if an error is a ErrTOTPNotEnabled.
func IsErrTOTPNotEnabled(err error) bool {
_, ok := err.(ErrTOTPNotEnabled)
return ok
}
func (err ErrTOTPNotEnabled) Error() string {
return fmt.Sprintf("Totp is not enabled for this user")
}
// ErrCodeTOTPNotEnabled holds the unique world-error code of this error
const ErrCodeTOTPNotEnabled = 1016
// HTTPError holds the http error description
func (err ErrTOTPNotEnabled) HTTPError() web.HTTPError {
return web.HTTPError{
HTTPCode: http.StatusPreconditionFailed,
Code: ErrCodeTOTPNotEnabled,
Message: "Totp is not enabled for this user.",
}
}
// ErrInvalidTOTPPasscode represents a "InvalidTOTPPasscode" kind of error.
type ErrInvalidTOTPPasscode struct {
Passcode string
}
// IsErrInvalidTOTPPasscode checks if an error is a ErrInvalidTOTPPasscode.
func IsErrInvalidTOTPPasscode(err error) bool {
_, ok := err.(ErrInvalidTOTPPasscode)
return ok
}
func (err ErrInvalidTOTPPasscode) Error() string {
return fmt.Sprintf("Invalid totp passcode")
}
// ErrCodeInvalidTOTPPasscode holds the unique world-error code of this error
const ErrCodeInvalidTOTPPasscode = 1017
// HTTPError holds the http error description
func (err ErrInvalidTOTPPasscode) HTTPError() web.HTTPError {
return web.HTTPError{
HTTPCode: http.StatusPreconditionFailed,
Code: ErrCodeInvalidTOTPPasscode,
Message: "Invalid totp passcode.",
}
}

133
pkg/user/totp.go Normal file
View File

@ -0,0 +1,133 @@
// Vikunja is a to-do list application to facilitate your life.
// Copyright 2018-2020 Vikunja and contributors. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package user
import (
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
"image"
)
// TOTP holds a user's totp setting in the database.
type TOTP struct {
ID int64 `xorm:"int(11) autoincr not null unique pk" json:"-"`
UserID int64 `xorm:"int(11) not null" json:"-"`
Secret string `xorm:"varchar(20) not null" json:"secret"`
// The totp entry will only be enabled after the user verified they have a working totp setup.
Enabled bool `xorm:"null" json:"enabled"`
// The totp url used to be able to enroll the user later
URL string `xorm:"text null" json:"url"`
}
// TableName holds the table name for totp secrets
func (T *TOTP) TableName() string {
return "totp"
}
// TOTPPasscode is used to validate a users totp passcode
type TOTPPasscode struct {
User *User `json:"-"`
Passcode string `json:"passcode"`
}
// TOTPEnabledForUser checks if totp is enabled for a user - not if it is activated, use getTOTPForUser to check that.
func TOTPEnabledForUser(user *User) (bool, error) {
return x.Where("user_id = ?", user.ID).Exist(&TOTP{})
}
func getTOTPForUser(user *User) (t *TOTP, err error) {
t = &TOTP{}
exists, err := x.Where("user_id = ?", user.ID).Get(t)
if err != nil {
return
}
if !exists {
return nil, ErrTOTPNotEnabled{}
}
return
}
// EnrollTOTP creates a new TOTP entry for the user - it does not enable it yet.
func EnrollTOTP(user *User) (t *TOTP, err error) {
isEnrolled, err := x.Where("user_id = ?", user.ID).Exist(&TOTP{})
if err != nil {
return
}
if isEnrolled {
return nil, ErrTOTPAlreadyEnabled{}
}
key, err := totp.Generate(totp.GenerateOpts{
Issuer: "Vikunja",
AccountName: user.Username,
})
if err != nil {
return
}
t = &TOTP{
UserID: user.ID,
Secret: key.Secret(),
Enabled: false,
URL: key.URL(),
}
_, err = x.Insert(t)
return
}
// EnableTOTP enables totp for a user. The provided passcode is used to verify the user has a working totp setup.
func EnableTOTP(passcode *TOTPPasscode) (err error) {
t, err := ValidateTOTPPasscode(passcode)
if err != nil {
return
}
_, err = x.
Where("id = ?", t.ID).
Cols("enabled").
Update(&TOTP{Enabled: true})
return
}
// ValidateTOTPPasscode validated totp codes of users.
func ValidateTOTPPasscode(passcode *TOTPPasscode) (t *TOTP, err error) {
t, err = getTOTPForUser(passcode.User)
if err != nil {
return
}
if !totp.Validate(passcode.Passcode, t.Secret) {
return nil, ErrInvalidTOTPPasscode{Passcode: passcode.Passcode}
}
return
}
// GetTOTPQrCodeForUser returns a qrcode for a user's totp setting
func GetTOTPQrCodeForUser(user *User) (qrcode image.Image, err error) {
t, err := getTOTPForUser(user)
if err != nil {
return
}
key, err := otp.NewKeyFromURL(t.URL)
if err != nil {
return
}
return key.Image(300, 300)
}

View File

@ -37,6 +37,8 @@ type Login struct {
Username string `json:"username"`
// The password for the user.
Password string `json:"password"`
// The totp passcode of a user. Only needs to be provided when enabled.
TOTPPasscode string `json:"totp_passcode"`
}
// User holds information about an user

View File

@ -147,36 +147,36 @@ func TestGetUser(t *testing.T) {
func TestCheckUserCredentials(t *testing.T) {
t.Run("normal", func(t *testing.T) {
db.LoadAndAssertFixtures(t)
_, err := CheckUserCredentials(&Login{"user1", "1234"})
_, err := CheckUserCredentials(&Login{Username: "user1", Password: "1234"})
assert.NoError(t, err)
})
t.Run("unverified email", func(t *testing.T) {
db.LoadAndAssertFixtures(t)
_, err := CheckUserCredentials(&Login{"user5", "1234"})
_, err := CheckUserCredentials(&Login{Username: "user5", Password: "1234"})
assert.Error(t, err)
assert.True(t, IsErrEmailNotConfirmed(err))
})
t.Run("wrong password", func(t *testing.T) {
db.LoadAndAssertFixtures(t)
_, err := CheckUserCredentials(&Login{"user1", "12345"})
_, err := CheckUserCredentials(&Login{Username: "user1", Password: "12345"})
assert.Error(t, err)
assert.True(t, IsErrWrongUsernameOrPassword(err))
})
t.Run("nonexistant user", func(t *testing.T) {
db.LoadAndAssertFixtures(t)
_, err := CheckUserCredentials(&Login{"dfstestuu", "1234"})
_, err := CheckUserCredentials(&Login{Username: "dfstestuu", Password: "1234"})
assert.Error(t, err)
assert.True(t, IsErrWrongUsernameOrPassword(err))
})
t.Run("empty password", func(t *testing.T) {
db.LoadAndAssertFixtures(t)
_, err := CheckUserCredentials(&Login{"user1", ""})
_, err := CheckUserCredentials(&Login{Username: "user1"})
assert.Error(t, err)
assert.True(t, IsErrNoUsernamePassword(err))
})
t.Run("empty username", func(t *testing.T) {
db.LoadAndAssertFixtures(t)
_, err := CheckUserCredentials(&Login{"", "1234"})
_, err := CheckUserCredentials(&Login{Password: "1234"})
assert.Error(t, err)
assert.True(t, IsErrNoUsernamePassword(err))
})