From fe5feeea22a639a4835724cf42b337773b54d83c Mon Sep 17 00:00:00 2001 From: kmcknight Date: Thu, 25 Feb 2021 17:17:25 -0800 Subject: Implement Push Auth support for 2FA verification When `2fa_verify` command is executed: - A user is asked to enter OTP - A blocking call for push auth is performed Then: - If the push auth request fails, the user is still able to enter OTP - If OTP is invalid, the `2fa_verify` command ends the execution - If OTP is valid or push auth request succeeded, then the user is successfully authenticated - If 30 seconds passed while no OTP or Push have been provided, then the `2fa_verify` command ends the execution --- .../command/twofactorverify/twofactorverify.go | 122 ++++++++++++++-- .../twofactorverify/twofactorverify_test.go | 121 ---------------- .../twofactorverify/twofactorverifymanual_test.go | 154 +++++++++++++++++++++ .../twofactorverify/twofactorverifypush_test.go | 144 +++++++++++++++++++ 4 files changed, 406 insertions(+), 135 deletions(-) delete mode 100644 internal/command/twofactorverify/twofactorverify_test.go create mode 100644 internal/command/twofactorverify/twofactorverifymanual_test.go create mode 100644 internal/command/twofactorverify/twofactorverifypush_test.go (limited to 'internal/command') diff --git a/internal/command/twofactorverify/twofactorverify.go b/internal/command/twofactorverify/twofactorverify.go index a0a952c..1043bfb 100644 --- a/internal/command/twofactorverify/twofactorverify.go +++ b/internal/command/twofactorverify/twofactorverify.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "io" + "time" "gitlab.com/gitlab-org/labkit/log" @@ -15,23 +16,96 @@ import ( type Command struct { Config *config.Config + Client *twofactorverify.Client Args *commandargs.Shell ReadWriter *readwriter.ReadWriter } +type Result struct { + Error error + Status string + Success bool +} + func (c *Command) Execute(ctx context.Context) error { ctxlog := log.ContextLogger(ctx) - ctxlog.Info("twofactorverify: execute: waiting for user input") - otp := c.getOTP(ctx) - ctxlog.Info("twofactorverify: execute: verifying entered OTP") - err := c.verifyOTP(ctx, otp) + // config.GetHTTPClient isn't thread-safe so save Client in struct for concurrency + // workaround until #518 is fixed + var err error + c.Client, err = twofactorverify.NewClient(c.Config) + if err != nil { ctxlog.WithError(err).Error("twofactorverify: execute: OTP verification failed") return err } - ctxlog.WithError(err).Info("twofactorverify: execute: OTP verified") + // Create timeout context + // TODO: make timeout configurable + const ctxTimeout = 30 + timeoutCtx, cancelTimeout := context.WithTimeout(ctx, ctxTimeout*time.Second) + defer cancelTimeout() + + // Background push notification with timeout + pushauth := make(chan Result) + go func() { + defer close(pushauth) + ctxlog.Info("twofactorverify: execute: waiting for push auth") + status, success, err := c.pushAuth(timeoutCtx) + ctxlog.WithError(err).Info("twofactorverify: execute: push auth verified") + + select { + case <-timeoutCtx.Done(): // push cancelled by manual OTP + // skip writing to channel + ctxlog.Info("twofactorverify: execute: push auth cancelled") + default: + pushauth <- Result{Error: err, Status: status, Success: success} + } + }() + + // Also allow manual OTP entry while waiting for push, with same timeout as push + verify := make(chan Result) + go func() { + defer close(verify) + ctxlog.Info("twofactorverify: execute: waiting for user input") + answer := "" + answer = c.getOTP(timeoutCtx) + ctxlog.Info("twofactorverify: execute: user input received") + + select { + case <-timeoutCtx.Done(): // manual OTP cancelled by push + // skip writing to channel + ctxlog.Info("twofactorverify: execute: verify cancelled") + default: + ctxlog.Info("twofactorverify: execute: verifying entered OTP") + status, success, err := c.verifyOTP(timeoutCtx, answer) + ctxlog.WithError(err).Info("twofactorverify: execute: OTP verified") + verify <- Result{Error: err, Status: status, Success: success} + } + }() + + for { + select { + case res := <-verify: + if res.Status == "" { + // channel closed; don't print anything + } else { + fmt.Fprint(c.ReadWriter.Out, res.Status) + return nil + } + case res := <-pushauth: + if res.Status == "" { + // channel closed; don't print anything + } else { + fmt.Fprint(c.ReadWriter.Out, res.Status) + return nil + } + case <-timeoutCtx.Done(): // push timed out + fmt.Fprint(c.ReadWriter.Out, "\nOTP verification timed out\n") + return nil + } + } + return nil } @@ -49,18 +123,38 @@ func (c *Command) getOTP(ctx context.Context) string { return answer } -func (c *Command) verifyOTP(ctx context.Context, otp string) error { - client, err := twofactorverify.NewClient(c.Config) - if err != nil { - return err +func (c *Command) verifyOTP(ctx context.Context, otp string) (status string, success bool, err error) { + reason := "" + + success, reason, err = c.Client.VerifyOTP(ctx, c.Args, otp) + if success { + status = fmt.Sprintf("\nOTP validation successful. Git operations are now allowed.\n") + } else { + if err != nil { + status = fmt.Sprintf("\nOTP validation failed.\n%v\n", err) + } else { + status = fmt.Sprintf("\nOTP validation failed.\n%v\n", reason) + } } - err = client.VerifyOTP(ctx, c.Args, otp) - if err == nil { - fmt.Fprint(c.ReadWriter.Out, "\nOTP validation successful. Git operations are now allowed.\n") + err = nil + + return +} + +func (c *Command) pushAuth(ctx context.Context) (status string, success bool, err error) { + reason := "" + + success, reason, err = c.Client.PushAuth(ctx, c.Args) + if success { + status = fmt.Sprintf("\nPush OTP validation successful. Git operations are now allowed.\n") } else { - fmt.Fprintf(c.ReadWriter.Out, "\nOTP validation failed.\n%v\n", err) + if err != nil { + status = fmt.Sprintf("\nPush OTP validation failed.\n%v\n", err) + } else { + status = fmt.Sprintf("\nPush OTP validation failed.\n%v\n", reason) + } } - return nil + return } diff --git a/internal/command/twofactorverify/twofactorverify_test.go b/internal/command/twofactorverify/twofactorverify_test.go deleted file mode 100644 index 4b0b1c9..0000000 --- a/internal/command/twofactorverify/twofactorverify_test.go +++ /dev/null @@ -1,121 +0,0 @@ -package twofactorverify - -import ( - "bytes" - "context" - "encoding/json" - "io" - "net/http" - "testing" - - "github.com/stretchr/testify/require" - - "gitlab.com/gitlab-org/gitlab-shell/v14/client/testserver" - "gitlab.com/gitlab-org/gitlab-shell/v14/internal/command/commandargs" - "gitlab.com/gitlab-org/gitlab-shell/v14/internal/command/readwriter" - "gitlab.com/gitlab-org/gitlab-shell/v14/internal/config" - "gitlab.com/gitlab-org/gitlab-shell/v14/internal/gitlabnet/twofactorverify" -) - -func setup(t *testing.T) []testserver.TestRequestHandler { - requests := []testserver.TestRequestHandler{ - { - Path: "/api/v4/internal/two_factor_otp_check", - Handler: func(w http.ResponseWriter, r *http.Request) { - b, err := io.ReadAll(r.Body) - defer r.Body.Close() - - require.NoError(t, err) - - var requestBody *twofactorverify.RequestBody - require.NoError(t, json.Unmarshal(b, &requestBody)) - - switch requestBody.KeyId { - case "1": - body := map[string]interface{}{ - "success": true, - } - json.NewEncoder(w).Encode(body) - case "error": - body := map[string]interface{}{ - "success": false, - "message": "error message", - } - require.NoError(t, json.NewEncoder(w).Encode(body)) - case "broken": - w.WriteHeader(http.StatusInternalServerError) - } - }, - }, - } - - return requests -} - -const ( - question = "OTP: \n" - errorHeader = "OTP validation failed.\n" -) - -func TestExecute(t *testing.T) { - requests := setup(t) - - url := testserver.StartSocketHttpServer(t, requests) - - testCases := []struct { - desc string - arguments *commandargs.Shell - answer string - expectedOutput string - }{ - { - desc: "With a known key id", - arguments: &commandargs.Shell{GitlabKeyId: "1"}, - answer: "123456\n", - expectedOutput: question + - "OTP validation successful. Git operations are now allowed.\n", - }, - { - desc: "With bad response", - arguments: &commandargs.Shell{GitlabKeyId: "-1"}, - answer: "123456\n", - expectedOutput: question + errorHeader + "Parsing failed\n", - }, - { - desc: "With API returns an error", - arguments: &commandargs.Shell{GitlabKeyId: "error"}, - answer: "yes\n", - expectedOutput: question + errorHeader + "error message\n", - }, - { - desc: "With API fails", - arguments: &commandargs.Shell{GitlabKeyId: "broken"}, - answer: "yes\n", - expectedOutput: question + errorHeader + "Internal API error (500)\n", - }, - { - desc: "With missing arguments", - arguments: &commandargs.Shell{}, - answer: "yes\n", - expectedOutput: question + errorHeader + "who='' is invalid\n", - }, - } - - for _, tc := range testCases { - t.Run(tc.desc, func(t *testing.T) { - output := &bytes.Buffer{} - input := bytes.NewBufferString(tc.answer) - - cmd := &Command{ - Config: &config.Config{GitlabUrl: url}, - Args: tc.arguments, - ReadWriter: &readwriter.ReadWriter{Out: output, In: input}, - } - - err := cmd.Execute(context.Background()) - - require.NoError(t, err) - require.Equal(t, tc.expectedOutput, output.String()) - }) - } -} diff --git a/internal/command/twofactorverify/twofactorverifymanual_test.go b/internal/command/twofactorverify/twofactorverifymanual_test.go new file mode 100644 index 0000000..59db281 --- /dev/null +++ b/internal/command/twofactorverify/twofactorverifymanual_test.go @@ -0,0 +1,154 @@ +package twofactorverify + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "gitlab.com/gitlab-org/gitlab-shell/v14/client/testserver" + "gitlab.com/gitlab-org/gitlab-shell/v14/internal/command/commandargs" + "gitlab.com/gitlab-org/gitlab-shell/v14/internal/command/readwriter" + "gitlab.com/gitlab-org/gitlab-shell/v14/internal/config" + "gitlab.com/gitlab-org/gitlab-shell/v14/internal/gitlabnet/twofactorverify" +) + +func setupManual(t *testing.T) []testserver.TestRequestHandler { + requests := []testserver.TestRequestHandler{ + { + Path: "/api/v4/internal/two_factor_manual_otp_check", + Handler: func(w http.ResponseWriter, r *http.Request) { + b, err := io.ReadAll(r.Body) + defer r.Body.Close() + + require.NoError(t, err) + + var requestBody *twofactorverify.RequestBody + require.NoError(t, json.Unmarshal(b, &requestBody)) + + var body map[string]interface{} + switch requestBody.KeyId { + case "1": + body = map[string]interface{}{ + "success": true, + } + json.NewEncoder(w).Encode(body) + case "error": + body = map[string]interface{}{ + "success": false, + "message": "error message", + } + require.NoError(t, json.NewEncoder(w).Encode(body)) + case "broken": + w.WriteHeader(http.StatusInternalServerError) + } + }, + }, + { + Path: "/api/v4/internal/two_factor_push_otp_check", + Handler: func(w http.ResponseWriter, r *http.Request) { + b, err := io.ReadAll(r.Body) + defer r.Body.Close() + + require.NoError(t, err) + + var requestBody *twofactorverify.RequestBody + require.NoError(t, json.Unmarshal(b, &requestBody)) + + time.Sleep(5 * time.Second) + + var body map[string]interface{} + switch requestBody.KeyId { + case "1": + body = map[string]interface{}{ + "success": true, + } + json.NewEncoder(w).Encode(body) + case "error": + body = map[string]interface{}{ + "success": false, + "message": "error message", + } + require.NoError(t, json.NewEncoder(w).Encode(body)) + case "broken": + w.WriteHeader(http.StatusInternalServerError) + default: + body = map[string]interface{}{ + "success": true, + "message": "default message", + } + json.NewEncoder(w).Encode(body) + } + }, + }, + } + + return requests +} + +const ( + manualQuestion = "OTP: \n" + manualErrorHeader = "OTP validation failed.\n" +) + +func TestExecuteManual(t *testing.T) { + requests := setupManual(t) + + url := testserver.StartSocketHttpServer(t, requests) + + testCases := []struct { + desc string + arguments *commandargs.Shell + answer string + expectedOutput string + }{ + { + desc: "With a known key id", + arguments: &commandargs.Shell{GitlabKeyId: "1"}, + answer: "123456\n", + expectedOutput: manualQuestion + "OTP validation successful. Git operations are now allowed.\n", + }, + { + desc: "With bad response", + arguments: &commandargs.Shell{GitlabKeyId: "-1"}, + answer: "123456\n", + expectedOutput: manualQuestion + manualErrorHeader + "Parsing failed\n", + }, + { + desc: "With API returns an error", + arguments: &commandargs.Shell{GitlabKeyId: "error"}, + answer: "yes\n", + expectedOutput: manualQuestion + manualErrorHeader + "error message\n", + }, + { + desc: "With API fails", + arguments: &commandargs.Shell{GitlabKeyId: "broken"}, + answer: "yes\n", + expectedOutput: manualQuestion + manualErrorHeader + "Internal API error (500)\n", + }, + } + + for _, tc := range testCases { + t.Run(tc.desc, func(t *testing.T) { + output := &bytes.Buffer{} + + input := bytes.NewBufferString(tc.answer) + + cmd := &Command{ + Config: &config.Config{GitlabUrl: url}, + Args: tc.arguments, + ReadWriter: &readwriter.ReadWriter{Out: output, In: input}, + } + + err := cmd.Execute(context.Background()) + + require.NoError(t, err) + require.Equal(t, tc.expectedOutput, output.String()) + }) + } +} diff --git a/internal/command/twofactorverify/twofactorverifypush_test.go b/internal/command/twofactorverify/twofactorverifypush_test.go new file mode 100644 index 0000000..4b58cc5 --- /dev/null +++ b/internal/command/twofactorverify/twofactorverifypush_test.go @@ -0,0 +1,144 @@ +package twofactorverify + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "gitlab.com/gitlab-org/gitlab-shell/v14/client/testserver" + "gitlab.com/gitlab-org/gitlab-shell/v14/internal/command/commandargs" + "gitlab.com/gitlab-org/gitlab-shell/v14/internal/command/readwriter" + "gitlab.com/gitlab-org/gitlab-shell/v14/internal/config" + "gitlab.com/gitlab-org/gitlab-shell/v14/internal/gitlabnet/twofactorverify" +) + +func setupPush(t *testing.T) []testserver.TestRequestHandler { + requests := []testserver.TestRequestHandler{ + { + Path: "/api/v4/internal/two_factor_push_otp_check", + Handler: func(w http.ResponseWriter, r *http.Request) { + b, err := io.ReadAll(r.Body) + defer r.Body.Close() + + require.NoError(t, err) + + var requestBody *twofactorverify.RequestBody + require.NoError(t, json.Unmarshal(b, &requestBody)) + + var body map[string]interface{} + switch requestBody.KeyId { + case "1": + body = map[string]interface{}{ + "success": true, + } + json.NewEncoder(w).Encode(body) + case "error": + body = map[string]interface{}{ + "success": false, + "message": "error message", + } + require.NoError(t, json.NewEncoder(w).Encode(body)) + case "broken": + w.WriteHeader(http.StatusInternalServerError) + } + }, + }, + { + Path: "/api/v4/internal/two_factor_manual_otp_check", + Handler: func(w http.ResponseWriter, r *http.Request) { + b, err := io.ReadAll(r.Body) + defer r.Body.Close() + + require.NoError(t, err) + + var requestBody *twofactorverify.RequestBody + require.NoError(t, json.Unmarshal(b, &requestBody)) + + time.Sleep(20 * time.Second) + + var body map[string]interface{} + switch requestBody.KeyId { + case "1": + body = map[string]interface{}{ + "success": true, + } + json.NewEncoder(w).Encode(body) + case "error": + body = map[string]interface{}{ + "success": false, + "message": "error message", + } + require.NoError(t, json.NewEncoder(w).Encode(body)) + case "broken": + w.WriteHeader(http.StatusInternalServerError) + } + }, + }, + } + + return requests +} + +const ( + pushQuestion = "OTP: \n" + pushErrorHeader = "Push OTP validation failed.\n" +) + +func TestExecutePush(t *testing.T) { + requests := setupPush(t) + + url := testserver.StartSocketHttpServer(t, requests) + + testCases := []struct { + desc string + arguments *commandargs.Shell + answer string + expectedOutput string + }{ + { + desc: "When push is provided", + arguments: &commandargs.Shell{GitlabKeyId: "1"}, + answer: "", + expectedOutput: pushQuestion + "Push OTP validation successful. Git operations are now allowed.\n", + }, + { + desc: "With API returns an error", + arguments: &commandargs.Shell{GitlabKeyId: "error"}, + answer: "", + expectedOutput: pushQuestion + pushErrorHeader + "error message\n", + }, + { + desc: "With API fails", + arguments: &commandargs.Shell{GitlabKeyId: "broken"}, + answer: "", + expectedOutput: pushQuestion + pushErrorHeader + "Internal API error (500)\n", + }, + } + + for _, tc := range testCases { + t.Run(tc.desc, func(t *testing.T) { + output := &bytes.Buffer{} + + var input io.Reader + // make input wait for push auth tests + input, _ = io.Pipe() + + cmd := &Command{ + Config: &config.Config{GitlabUrl: url}, + Args: tc.arguments, + ReadWriter: &readwriter.ReadWriter{Out: output, In: input}, + } + + err := cmd.Execute(context.Background()) + + require.NoError(t, err) + require.Equal(t, tc.expectedOutput, output.String()) + }) + } +} -- cgit v1.2.1