summaryrefslogtreecommitdiff
path: root/app/controllers/register.go
blob: 312daaed43b2d15e6e93b2bac9eb8932c39d952f (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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
package controllers

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"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 (
	registerError = promauto.NewCounterVec(prometheus.CounterOpts{
		Namespace: "ssh_proxy",
		Name:      "register_error",
		Help:      "Total number of errors during registration",
	}, []string{"type"})
	registerSuccess = promauto.NewCounter(prometheus.CounterOpts{
		Namespace: "ssh_proxy",
		Name:      "register_success",
		Help:      "Total number of successful registrations",
	})
)

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

func (a *RegisterController[T]) validateRequest(ctx context.Context, u *models.User, code string) (*models.AuthSession, error) {
	if code == "" {
		return nil, fmt.Errorf("Code not passed in request")
	}

	authSession, err := a.AuthSessions.GetByUserCode(ctx, code)
	if err != nil {
		registerError.With(prometheus.Labels{"type": "no_user_for_code"}).Inc()
		return nil, fmt.Errorf("No auth session exists")
	}

	if time.Now().After(authSession.Expires) {
		registerError.With(prometheus.Labels{"type": "session_expired"}).Inc()
		return nil, fmt.Errorf("Session is expired")
	}

	if !authSession.IsRegistration {
		registerError.With(prometheus.Labels{"type": "incorrect_session_type"}).Inc()
		return nil, fmt.Errorf("Session is not an invitation to register")
	}

	if authSession.UserId != u.Username {
		registerError.With(prometheus.Labels{"type": "username_mismatch"}).Inc()
		return nil, fmt.Errorf("Session not valid for this user")
	}

	return authSession, nil
}

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

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

	if _, err := a.validateRequest(ctx, user, c.QueryParam("code")); err != nil {
		a.Logger.Errorf("Error creating registration request: %s", err)
		return c.NoContent(http.StatusNotFound)
	}

	request, sessionData, err := a.Webauthn.BeginRegistration(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 *RegisterController[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)
		return c.NoContent(http.StatusNotFound)
	}

	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.validateRequest(ctx, user, code.Code)
	if err != nil {
		a.Logger.Errorf("Error finishing register request: %s", err)
		return c.NoContent(http.StatusNotFound)
	}

	// Delete before anything else to avoid allowing double use of an auth
	// session in case of other errors
	if err := a.AuthSessions.Delete(ctx, authSession); err != nil {
		a.Logger.Errorf("Error deleting auth session: %s", err)
		registerError.With(prometheus.Labels{"type": "db_delete_session"}).Inc()
		return c.NoContent(http.StatusInternalServerError)
	}

	response, err := protocol.ParseCredentialCreationResponseBody(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)
	}

	credential, err := a.Webauthn.CreateCredential(user, *s.WebauthnSession, response)
	if err != nil {
		a.Logger.Errorf("Error creating credential: %s", err)
		return c.NoContent(http.StatusBadRequest)
	}

	user.Fido2Credentials = append(user.Fido2Credentials, *credential)

	if err := a.Users.Upsert(ctx, user); err != nil {
		a.Logger.Errorf("Error saving user: %s", err)
		return c.NoContent(http.StatusInternalServerError)
	}

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