Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: implement time-based OTP secret generator (#4973)
boojacke87f5129a285
diff --git a/backend/plugin/mfa/otp/otp.go b/backend/plugin/mfa/otp/otp.gonew file mode 100644index 0000000000..dabaf79c79--- /dev/null+++ b/backend/plugin/mfa/otp/otp.go@@ -0,0 +1,89 @@+// Package otp is the plugin for OTP Multi-Factor Authentication.+package otp++import (+ "strconv"+ "strings"+ "time"++ "github.com/pquerna/otp/totp"+)++const (+ // issuerName is the name of the issuer of the OTP token.+ issuerName = "Bytebase"+ // generateSecretPeriod is the period that we generate a new secret.+ generateSecretPeriod = 5 * time.Minute+)++// TimeBasedReader is a reader that returns the same value for the same timestamp.+type TimeBasedReader struct {+ reader *strings.Reader+}++// NewTimeBasedReader creates a new TimeBasedReader for the given timestamp.+func NewTimeBasedReader(timestamp time.Time) *TimeBasedReader {+ // Convert the timestamp to Unix time and divide by the secretMaxExpiredDuration.+ // We generate a new secret every 5 minutes. e.g. 15:00, 15:05+ formatedTimestampUnix := timestamp.Unix() / int64(generateSecretPeriod/time.Second)+ return &TimeBasedReader{+ reader: strings.NewReader(strconv.FormatInt(formatedTimestampUnix, 10)),+ }+}++func (r *TimeBasedReader) Read(p []byte) (int, error) {+ return r.reader.Read(p)+}++// GenerateSecret generates a secret for the given account name and timestamp.+func GenerateSecret(accountName string, timestamp time.Time) (string, error) {+ key, err := totp.Generate(totp.GenerateOpts{+ Issuer: issuerName,+ AccountName: accountName,+ Rand: NewTimeBasedReader(timestamp),+ })+ if err != nil {+ return "", err+ }+ return key.Secret(), nil+}++// GetValidSecrets returns a list of valid secrets for the given account name and timestamp.+func GetValidSecrets(accountName string, timestamp time.Time) ([]string, error) {+ var secrets []string+ // validTimestamps is a list of timestamps that are valid for the secret.+ // The secret is valid for 5 minutes. So we need to check the current timestamp and the timestamp 5 minutes ago.+ validTimestamps := []time.Time{timestamp, timestamp.Add(-1 * generateSecretPeriod)}+ for _, t := range validTimestamps {+ key, err := totp.Generate(totp.GenerateOpts{+ Issuer: issuerName,+ AccountName: accountName,+ Rand: NewTimeBasedReader(t),+ })+ if err != nil {+ return nil, err+ }+ secrets = append(secrets, key.Secret())+ }+ return secrets, nil+}++// ValidateWithCodeAndAccountName validates the given code against the given account name.+func ValidateWithCodeAndAccountName(code, accountName string) (bool, error) {+ validSecrets, err := GetValidSecrets(accountName, time.Now())+ if err != nil {+ return false, err+ }++ for _, secret := range validSecrets {+ if ValidateWithCodeAndSecret(code, secret) {+ return true, nil+ }+ }+ return false, nil+}++// ValidateWithCodeAndSecret validates the given code against the given secret.+func ValidateWithCodeAndSecret(code, secret string) bool {+ return totp.Validate(code, secret)+}diff --git a/backend/plugin/mfa/otp/otp_test.go b/backend/plugin/mfa/otp/otp_test.gonew file mode 100644index 0000000000..1318fa68ea--- /dev/null+++ b/backend/plugin/mfa/otp/otp_test.go@@ -0,0 +1,80 @@+package otp++import (+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "golang.org/x/exp/slices"+)++func TestGenerateTimeBasedSecret(t *testing.T) {+ currentTime := time.Now()+ accountName := "test-user"++ tests := []struct {+ name string+ generateTime time.Time+ validateTime time.Time+ isSecretExpired bool+ }{+ {+ name: "-5min",+ generateTime: currentTime,+ validateTime: currentTime.Add(-5 * time.Minute),+ isSecretExpired: true,+ },+ {+ name: "0",+ generateTime: currentTime,+ validateTime: currentTime,+ isSecretExpired: false,+ },+ {+ name: "20s",+ generateTime: currentTime,+ validateTime: currentTime.Add(20 * time.Second),+ isSecretExpired: false,+ },+ {+ name: "2min",+ generateTime: currentTime,+ validateTime: currentTime.Add(2 * time.Minute),+ isSecretExpired: false,+ },+ {+ name: "4min - 1s",+ generateTime: currentTime,+ validateTime: currentTime.Add(4*time.Minute - 1*time.Second),+ isSecretExpired: false,+ },+ {+ name: "5min - 1s",+ generateTime: currentTime,+ validateTime: currentTime.Add(5*time.Minute - 1*time.Second),+ isSecretExpired: false,+ },+ {+ name: "5min",+ generateTime: currentTime,+ validateTime: currentTime.Add(5 * time.Minute),+ isSecretExpired: false,+ },+ {+ name: "10min",+ generateTime: currentTime,+ validateTime: currentTime.Add(10 * time.Minute),+ isSecretExpired: true,+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ secret, err := GenerateSecret(accountName, test.generateTime)+ assert.NoError(t, err)+ validSecrets, err := GetValidSecrets(accountName, test.validateTime)+ assert.NoError(t, err)+ assert.Equal(t, test.isSecretExpired, !slices.Contains(validSecrets, secret))+ })+ }+}diff --git a/go.mod b/go.modindex 3544c9973d..06bf42c4ea 100644--- a/go.mod+++ b/go.mod@@ -61,6 +61,8 @@ require (gopkg.in/yaml.v3 v3.0.1)+require github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect+require (cloud.google.com/go v0.110.0 // indirectcloud.google.com/go/compute v1.18.0 // indirect@@ -159,6 +161,7 @@ require (github.com/pmezard/go-difflib v1.0.0 // indirectgithub.com/power-devops/perfstat v0.0.0-20220216144756-c35f1ee13d7c // indirectgithub.com/pquerna/cachecontrol v0.1.0 // indirect+ github.com/pquerna/otp v1.4.0github.com/prometheus/client_golang v1.13.0 // indirectgithub.com/prometheus/client_model v0.3.0 // indirectgithub.com/prometheus/common v0.37.0 // indirectdiff --git a/go.sum b/go.sumindex 123edef6ad..ff072bf5dc 100644--- a/go.sum+++ b/go.sum@@ -162,6 +162,8 @@ github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2ygithub.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4=github.com/boombuler/barcode v1.0.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=+github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI=+github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=github.com/bytebase/gh-ost v1.1.3-0.20220728080340-11d9c9027651 h1:NpoTuRY6Ckj37zTlEax/UTfvHCOdanI5/5dVCarOD18=github.com/bytebase/gh-ost v1.1.3-0.20220728080340-11d9c9027651/go.mod h1:/HsnX0+34LXVz3MxtZoW15GiwEOXz/PrEhutjb3icfE=github.com/bytebase/pg_query_go/v2 v2.0.0-20221123093650-17425d1d18b7 h1:RDN6UnjTq4HR4LKrN8Yav4XfwUoGRjTocvWmzGr6Usc=@@ -770,6 +772,8 @@ github.com/power-devops/perfstat v0.0.0-20220216144756-c35f1ee13d7c h1:NRoLoZvkBgithub.com/power-devops/perfstat v0.0.0-20220216144756-c35f1ee13d7c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=github.com/pquerna/cachecontrol v0.1.0 h1:yJMy84ti9h/+OEWa752kBTKv4XC30OtVVHYv/8cTqKc=github.com/pquerna/cachecontrol v0.1.0/go.mod h1:NrUG3Z7Rdu85UNR3vm7SOsl1nFIeSiQnrHV5K9mBcUI=+github.com/pquerna/otp v1.4.0 h1:wZvl1TIVxKRThZIBiwOOHOGP/1+nZyWBil9Y2XNEDzg=+github.com/pquerna/otp v1.4.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs=github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=