summaryrefslogtreecommitdiff
path: root/app/controllers/login.go
blob: f59789fe1033a079de87f2f1132ee3a83b9dfe19 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package controllers

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"time"

	"code.crute.us/mcrute/golib/echo/session"
	"code.crute.us/mcrute/ssh-proxy/app"
	"code.crute.us/mcrute/ssh-proxy/app/models"
	"github.com/go-webauthn/webauthn/protocol"
	"github.com/go-webauthn/webauthn/webauthn"
	"github.com/labstack/echo/v4"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
)

var (
	loginError = promauto.NewCounterVec(prometheus.CounterOpts{
		Namespace: "ssh_proxy",
		Name:      "login_error",
		Help:      "Total number of errors during login operation",
	}, []string{"type"})
	loginSuccess = promauto.NewCounter(prometheus.CounterOpts{
		Namespace: "ssh_proxy",
		Name:      "login_success",
		Help:      "Total number of successful logins",
	})
)

type LoginController[T app.AppSession] struct {
	Logger            echo.Logger
	Sessions          session.Store[T]
	Users             models.UserStore
	AuthSessions      models.AuthSessionStore
	Webauthn          *webauthn.WebAuthn
	SessionExpiration time.Duration
}

func (a *LoginController[T]) HandleStart(c echo.Context) error {
	user, err := a.Users.Get(c.Request().Context(), c.Param("username"))
	if err != nil {
		a.Logger.Errorf("Error getting user: %s", err)
		return c.NoContent(http.StatusNotFound)
	}

	request, sessionData, err := a.Webauthn.BeginLogin(user)
	if err != nil {
		a.Logger.Errorf("Error creating webauthn request: %s", err)
		return c.NoContent(http.StatusInternalServerError)
	}

	session := a.Sessions.Get(c)
	s := session.Self()
	s.WebauthnSession = sessionData
	a.Sessions.Update(c, session)

	return c.JSON(http.StatusOK, request)
}

func (a *LoginController[T]) HandleFinish(c echo.Context) error {
	ctx := c.Request().Context()

	body, err := io.ReadAll(c.Request().Body)
	if err != nil {
		a.Logger.Errorf("Error reading request body:", err)
		return c.NoContent(http.StatusInternalServerError)
	}

	user, err := a.Users.Get(ctx, c.Param("username"))
	if err != nil {
		a.Logger.Errorf("Error getting user: %s", err)
		loginError.With(prometheus.Labels{"type": "no_user"}).Inc()
		return c.NoContent(http.StatusNotFound)
	}

	response, err := protocol.ParseCredentialRequestResponseBody(bytes.NewBuffer(body))
	if err != nil {
		a.Logger.Errorf("Error parsing credential response: %s", err)
		return c.NoContent(http.StatusBadRequest)
	}

	session := a.Sessions.Get(c)
	s := session.Self()

	if s.WebauthnSession == nil {
		a.Logger.Errorf("Webauthn session is not set")
		return c.NoContent(http.StatusBadRequest)
	}

	if _, err := a.Webauthn.ValidateLogin(user, *s.WebauthnSession, response); err != nil {
		a.Logger.Errorf("Error validating login: %s", err)
		loginError.With(prometheus.Labels{"type": "webauthn_invalid"}).Inc()
		return c.NoContent(http.StatusBadRequest)
	}

	// Don't check the clone warning or the auth count because these are
	// meaningless for Passkeys since they are synced across devices
	// (presumably securely). This would only matter for hard tokens like
	// Yubikeys and since we're also allowing Passkey support there is no
	// need to be more strict for that class of device.

	var code struct {
		Code string `json:"code"`
	}
	if err := json.Unmarshal(body, &code); err != nil {
		a.Logger.Errorf("Error decoding json body")
		return c.NoContent(http.StatusBadRequest)
	}

	authSession, err := a.AuthSessions.GetByUserCode(ctx, code.Code)
	if err != nil {
		a.Logger.Errorf("No auth session exists")
		loginError.With(prometheus.Labels{"type": "no_session_for_code"}).Inc()
		return c.NoContent(http.StatusUnauthorized)
	}

	if authSession.AccessCode != "" {
		a.Logger.Errorf("Session is already authenticated")
		loginError.With(prometheus.Labels{"type": "already_authenticated"}).Inc()
		return c.NoContent(http.StatusUnauthorized)
	}

	authSession.GenerateAccessCode()
	authSession.UserId = user.Username
	authSession.Expires = time.Now().Add(a.SessionExpiration)

	if err := a.AuthSessions.Upsert(ctx, authSession); err != nil {
		a.Logger.Errorf("Error saving auth session")
		return c.NoContent(http.StatusInternalServerError)
	}

	loginSuccess.Inc()
	return c.NoContent(http.StatusOK)
}