diff --git a/coderd/userauth.go b/coderd/userauth.go index 9d86b8e758885..ded162b29a97d 100644 --- a/coderd/userauth.go +++ b/coderd/userauth.go @@ -133,7 +133,18 @@ func (api *API) postLogin(rw http.ResponseWriter, r *http.Request) { // @Success 200 {object} codersdk.Response // @Router /users/logout [post] func (api *API) postLogout(rw http.ResponseWriter, r *http.Request) { - ctx := r.Context() + var ( + ctx = r.Context() + auditor = api.Auditor.Load() + aReq, commitAudit = audit.InitRequest[database.APIKey](rw, &audit.RequestParams{ + Audit: *auditor, + Log: api.Logger, + Request: r, + Action: database.AuditActionLogout, + }) + ) + defer commitAudit() + // Get a blank token cookie. cookie := &http.Cookie{ // MaxAge < 0 means to delete the cookie now. @@ -145,6 +156,8 @@ func (api *API) postLogout(rw http.ResponseWriter, r *http.Request) { // Delete the session token from database. apiKey := httpmw.APIKey(r) + aReq.Old = apiKey + err := api.Database.DeleteAPIKeyByID(ctx, apiKey.ID) if err != nil { httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ @@ -198,6 +211,8 @@ func (api *API) postLogout(rw http.ResponseWriter, r *http.Request) { } } + aReq.New = database.APIKey{} + httpapi.Write(ctx, rw, http.StatusOK, codersdk.Response{ Message: "Logged out!", }) diff --git a/coderd/users_test.go b/coderd/users_test.go index d4b8d8b5dca40..7bebba908e0ce 100644 --- a/coderd/users_test.go +++ b/coderd/users_test.go @@ -327,9 +327,12 @@ func TestPostLogout(t *testing.T) { // Checks that the cookie is cleared and the API Key is deleted from the database. t.Run("Logout", func(t *testing.T) { t.Parallel() + auditor := audit.NewMock() + client := coderdtest.New(t, &coderdtest.Options{Auditor: auditor}) + numLogs := len(auditor.AuditLogs) - client := coderdtest.New(t, nil) admin := coderdtest.CreateFirstUser(t, client) + numLogs++ // add an audit log for login ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong) defer cancel() @@ -343,10 +346,15 @@ func TestPostLogout(t *testing.T) { require.NoError(t, err, "Server URL should parse successfully") res, err := client.Request(ctx, http.MethodPost, fullURL.String(), nil) + numLogs++ // add an audit log for logout + require.NoError(t, err, "/logout request should succeed") res.Body.Close() require.Equal(t, http.StatusOK, res.StatusCode) + require.Len(t, auditor.AuditLogs, numLogs) + require.Equal(t, database.AuditActionLogout, auditor.AuditLogs[numLogs-1].Action) + cookies := res.Cookies() var found bool