A continuation of HomeBox the inventory and organization system built for the Home User
feat: logout all devices option
Matthew Kilgore49895ec68551
diff --git a/backend/app/api/handlers/v1/v1_ctrl_auth.go b/backend/app/api/handlers/v1/v1_ctrl_auth.goindex 2989daa6..1d530eb8 100644--- a/backend/app/api/handlers/v1/v1_ctrl_auth.go+++ b/backend/app/api/handlers/v1/v1_ctrl_auth.go@@ -353,6 +353,41 @@ func (ctrl *V1Controller) HandleAuthLogout() errchain.HandlerFunc {}}+// HandleAuthLogoutAll godoc+//+// @Summary Log Out Of All Sessions+// @Description Revokes every session token for the authenticated user across all+// @Description devices, including the current one. Use this to invalidate a session+// @Description token that may have been leaked or stolen. API keys are stored+// @Description separately and are not affected; revoke them from the API keys page.+// @Tags Authentication+// @Success 204+// @Router /v1/users/logout/all [POST]+// @Security Bearer+func (ctrl *V1Controller) HandleAuthLogoutAll() errchain.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) error {+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleAuthLogoutAll")+ defer span.End()++ auth := services.NewContext(spanCtx)+ span.SetAttributes(attribute.String("user.id", auth.UID.String()))++ revoked, err := ctrl.svc.User.LogoutAll(spanCtx, auth.UID)+ if err != nil {+ recordCtrlSpanError(span, err)+ span.SetAttributes(attribute.String("logout_all.outcome", "delete_failed"))+ return validate.NewRequestError(err, http.StatusInternalServerError)+ }++ span.SetAttributes(+ attribute.Int("logout_all.sessions_revoked", revoked),+ attribute.String("logout_all.outcome", "success"),+ )+ ctrl.unsetCookies(w, noPort(r.Host))+ return server.JSON(w, http.StatusNoContent, nil)+ }+}+// HandleAuthRefresh godoc//// @Summary User Token Refreshdiff --git a/backend/app/api/routes.go b/backend/app/api/routes.goindex d2d11ed2..fcf272c2 100644--- a/backend/app/api/routes.go+++ b/backend/app/api/routes.go@@ -113,6 +113,7 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllRr.Get("/users/self/settings", chain.ToHandlerFunc(v1Ctrl.HandleUserSelfSettingsGet(), userMW...))r.Put("/users/self/settings", chain.ToHandlerFunc(v1Ctrl.HandleUserSelfSettingsUpdate(), userMW...))r.Post("/users/logout", chain.ToHandlerFunc(v1Ctrl.HandleAuthLogout(), userMW...))+ r.Post("/users/logout/all", chain.ToHandlerFunc(v1Ctrl.HandleAuthLogoutAll(), userMW...))r.Get("/users/refresh", chain.ToHandlerFunc(v1Ctrl.HandleAuthRefresh(), userMW...))r.Put("/users/self/change-password", chain.ToHandlerFunc(v1Ctrl.HandleUserSelfChangePassword(), userMW...))diff --git a/backend/app/api/static/docs/docs.go b/backend/app/api/static/docs/docs.goindex 332ed531..1b5b917c 100644--- a/backend/app/api/static/docs/docs.go+++ b/backend/app/api/static/docs/docs.go@@ -2804,6 +2804,25 @@ const docTemplate = `{}}},+ "/v1/users/logout/all": {+ "post": {+ "security": [+ {+ "Bearer": []+ }+ ],+ "description": "Revokes every session token for the authenticated user across all\ndevices, including the current one. Use this to invalidate a session\ntoken that may have been leaked or stolen. API keys are stored\nseparately and are not affected; revoke them from the API keys page.",+ "tags": [+ "Authentication"+ ],+ "summary": "Log Out Of All Sessions",+ "responses": {+ "204": {+ "description": "No Content"+ }+ }+ }+ },"/v1/users/refresh": {"get": {"security": [diff --git a/backend/app/api/static/docs/openapi-3.json b/backend/app/api/static/docs/openapi-3.jsonindex c541111a..72148253 100644--- a/backend/app/api/static/docs/openapi-3.json+++ b/backend/app/api/static/docs/openapi-3.json@@ -3017,6 +3017,25 @@}}},+ "/v1/users/logout/all": {+ "post": {+ "security": [+ {+ "Bearer": []+ }+ ],+ "description": "Revokes every session token for the authenticated user across all\ndevices, including the current one. Use this to invalidate a session\ntoken that may have been leaked or stolen. API keys are stored\nseparately and are not affected; revoke them from the API keys page.",+ "tags": [+ "Authentication"+ ],+ "summary": "Log Out Of All Sessions",+ "responses": {+ "204": {+ "description": "No Content"+ }+ }+ }+ },"/v1/users/refresh": {"get": {"security": [diff --git a/backend/app/api/static/docs/openapi-3.yaml b/backend/app/api/static/docs/openapi-3.yamlindex 9b0ce92c..79246bbd 100644--- a/backend/app/api/static/docs/openapi-3.yaml+++ b/backend/app/api/static/docs/openapi-3.yaml@@ -1797,6 +1797,21 @@ paths:responses:"204":description: No Content+ /v1/users/logout/all:+ post:+ security:+ - Bearer: []+ description: |-+ Revokes every session token for the authenticated user across all+ devices, including the current one. Use this to invalidate a session+ token that may have been leaked or stolen. API keys are stored+ separately and are not affected; revoke them from the API keys page.+ tags:+ - Authentication+ summary: Log Out Of All Sessions+ responses:+ "204":+ description: No Content/v1/users/refresh:get:security:diff --git a/backend/app/api/static/docs/swagger.json b/backend/app/api/static/docs/swagger.jsonindex d14e5ec3..432335d2 100644--- a/backend/app/api/static/docs/swagger.json+++ b/backend/app/api/static/docs/swagger.json@@ -2801,6 +2801,25 @@}}},+ "/v1/users/logout/all": {+ "post": {+ "security": [+ {+ "Bearer": []+ }+ ],+ "description": "Revokes every session token for the authenticated user across all\ndevices, including the current one. Use this to invalidate a session\ntoken that may have been leaked or stolen. API keys are stored\nseparately and are not affected; revoke them from the API keys page.",+ "tags": [+ "Authentication"+ ],+ "summary": "Log Out Of All Sessions",+ "responses": {+ "204": {+ "description": "No Content"+ }+ }+ }+ },"/v1/users/refresh": {"get": {"security": [diff --git a/backend/app/api/static/docs/swagger.yaml b/backend/app/api/static/docs/swagger.yamlindex 883fd83a..c162c752 100644--- a/backend/app/api/static/docs/swagger.yaml+++ b/backend/app/api/static/docs/swagger.yaml@@ -4087,6 +4087,21 @@ paths:summary: User Logouttags:- Authentication+ /v1/users/logout/all:+ post:+ description: |-+ Revokes every session token for the authenticated user across all+ devices, including the current one. Use this to invalidate a session+ token that may have been leaked or stolen. API keys are stored+ separately and are not affected; revoke them from the API keys page.+ responses:+ "204":+ description: No Content+ security:+ - Bearer: []+ summary: Log Out Of All Sessions+ tags:+ - Authentication/v1/users/refresh:get:description: |-diff --git a/backend/internal/core/services/service_user.go b/backend/internal/core/services/service_user.goindex 4b64b5e1..5aa4310d 100644--- a/backend/internal/core/services/service_user.go+++ b/backend/internal/core/services/service_user.go@@ -373,9 +373,9 @@ func (svc *UserService) Login(ctx context.Context, username, password string, exattribute.Bool("user.found", false),attribute.String("login.outcome", "user_not_found"),)- // SECURITY: Perform a real argon2id comparison against a valid dummy hash so- // response timing matches the "user found" path and accounts cannot be- // enumerated by measuring how long login takes.+ // Run a real argon2id comparison against a valid dummy hash so response+ // timing matches the "user found" path. Without this the absence of hashing+ // work would reveal that the account does not exist._, dummySpan := entityServiceTracer().Start(ctx, "service.UserService.Login.timingDummy",trace.WithAttributes(attribute.String("reason", "user_not_found")))hasher.CheckDummyPasswordHashCtx(ctx)@@ -618,6 +618,28 @@ func (svc *UserService) Logout(ctx context.Context, token string) error {return err}+// LogoutAll revokes every session token for the user, signing them out on all+// devices including the one making the request. It gives a user a way to+// unilaterally invalidate sessions they no longer trust — e.g. after a token is+// leaked or a device is lost — without waiting for the token TTL to elapse.+//+// API keys are deliberate long-lived credentials stored in a separate table and+// are intentionally left untouched; they are managed from the API keys page.+// Returns the number of session tokens revoked.+func (svc *UserService) LogoutAll(ctx context.Context, userID uuid.UUID) (int, error) {+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.LogoutAll",+ trace.WithAttributes(attribute.String("user.id", userID.String())))+ defer span.End()++ revoked, err := svc.repos.AuthTokens.DeleteAllByUser(ctx, userID)+ if err != nil {+ recordServiceSpanError(span, err)+ return 0, err+ }+ span.SetAttributes(attribute.Int("logout_all.sessions_revoked", revoked))+ return revoked, nil+}+func (svc *UserService) RenewToken(ctx context.Context, token string) (UserAuthTokenDetail, error) {ctx, span := entityServiceTracer().Start(ctx, "service.UserService.RenewToken",trace.WithAttributes(attribute.Int("token.length", len(token))))diff --git a/backend/internal/core/services/service_user_logout_all_test.go b/backend/internal/core/services/service_user_logout_all_test.gonew file mode 100644index 00000000..a46365bd--- /dev/null+++ b/backend/internal/core/services/service_user_logout_all_test.go@@ -0,0 +1,61 @@+package services++import (+ "context"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "github.com/sysadminsmedia/homebox/backend/pkgs/hasher"+)++// TestSessionPersistenceGap documents the reported behavior: authenticating again+// does not invalidate prior tokens, and logging out only revokes the single token+// used for the logout request. A token the user no longer trusts therefore survives+// both re-login and logout. (Concurrent sessions are intentional; this asserts the+// pre-existing behavior that motivates a revoke-all control.)+func TestSessionPersistenceGap(t *testing.T) {+ ctx := context.Background()+ usr := newTestUserWithPassword(t, "persist-pw-1")++ tok1, err := tSvc.User.createSessionToken(ctx, usr.ID, false)+ require.NoError(t, err)+ tok2, err := tSvc.User.createSessionToken(ctx, usr.ID, false)+ require.NoError(t, err)++ // Logging out with token 2 leaves token 1 fully valid.+ require.NoError(t, tSvc.User.Logout(ctx, tok2.Raw))++ _, err = tRepos.AuthTokens.GetUserFromToken(ctx, hasher.HashToken(tok1.Raw))+ require.NoError(t, err, "prior token survives logout of another session")+}++// TestLogoutAll_RevokesEverySession verifies the new revoke-all control: it+// invalidates every session token for the user (all devices), so a leaked/stolen+// token can be unilaterally revoked. API keys live in a separate table and are+// intentionally unaffected.+func TestLogoutAll_RevokesEverySession(t *testing.T) {+ ctx := context.Background()+ usr := newTestUserWithPassword(t, "logout-all-pw")++ tok1, err := tSvc.User.createSessionToken(ctx, usr.ID, false)+ require.NoError(t, err)+ tok2, err := tSvc.User.createSessionToken(ctx, usr.ID, false)+ require.NoError(t, err)+ _, err = tSvc.User.createSessionToken(ctx, usr.ID, false)+ require.NoError(t, err)+ require.Equal(t, 3, countUserSessions(t, ctx, usr.ID))++ revoked, err := tSvc.User.LogoutAll(ctx, usr.ID)+ require.NoError(t, err)+ assert.Positive(t, revoked, "should report revoked token count")++ // No session tokens remain.+ assert.Equal(t, 0, countUserSessions(t, ctx, usr.ID))++ // None of the previously issued tokens authenticate any longer.+ _, err = tRepos.AuthTokens.GetUserFromToken(ctx, hasher.HashToken(tok1.Raw))+ require.Error(t, err, "token 1 must be revoked")+ _, err = tRepos.AuthTokens.GetUserFromToken(ctx, hasher.HashToken(tok2.Raw))+ require.Error(t, err, "token 2 must be revoked")+}diff --git a/backend/internal/data/repo/repo_entities.go b/backend/internal/data/repo/repo_entities.goindex 2429c5bb..3bbe452d 100644--- a/backend/internal/data/repo/repo_entities.go+++ b/backend/internal/data/repo/repo_entities.go@@ -1713,7 +1713,11 @@ func (r *EntityRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, datfieldsSpan.End()r.publishMutationEvent(gid)- out, err := r.GetOne(ctx, data.ID)+ // Fetch the returned record scoped to the caller's group. The update above is+ // group-scoped and a no-op across tenants, so an unscoped GetOne would return+ // another group's entity in the response body. GetOneByGroup returns not-found+ // for a foreign entity, matching the 404 behavior of GET/DELETE.+ out, err := r.GetOneByGroup(ctx, gid, data.ID)recordSpanError(span, err)return out, err}@@ -2598,7 +2602,10 @@ func (r *EntityRepository) UpdateContainer(ctx context.Context, gid, id uuid.UUI}r.publishMutationEvent(gid)- out, err := r.GetOne(ctx, id)+ // Scope the returned record to the caller's group (see UpdateByGroup). The update+ // is group-scoped, so an unscoped GetOne would return a foreign group's entity+ // when id belongs to another tenant.+ out, err := r.GetOneByGroup(ctx, gid, id)recordSpanError(span, err)return out, err}diff --git a/backend/internal/data/repo/repo_entities_crosstenant_test.go b/backend/internal/data/repo/repo_entities_crosstenant_test.gonew file mode 100644index 00000000..7339122b--- /dev/null+++ b/backend/internal/data/repo/repo_entities_crosstenant_test.go@@ -0,0 +1,52 @@+package repo++import (+ "context"+ "testing"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// TestEntityRepository_UpdateByGroup_CrossTenantLeak guards against a cross-tenant+// IDOR in the entity update path. PUT /entities/{id} calls UpdateByGroup; the update+// itself is group-scoped (a no-op across tenants), but the record returned in the+// response must also be group-scoped. Returning the entity via an unscoped lookup+// leaks another tenant's full inventory record (name, notes, purchase/sale details)+// even though nothing is written.+func TestEntityRepository_UpdateByGroup_CrossTenantLeak(t *testing.T) {+ ctx := context.Background()++ // Victim tenant: a separate group with an entity holding sensitive data.+ victimGroup, err := tRepos.Groups.GroupCreate(ctx, "victim-group", uuid.Nil)+ require.NoError(t, err)++ victimET, err := tRepos.EntityTypes.GetDefault(ctx, victimGroup.ID, false)+ require.NoError(t, err)++ const secretName = "victim-secret-serial-and-notes"+ victim, err := tRepos.Entities.Create(ctx, victimGroup.ID, EntityCreate{+ Name: secretName,+ Description: "confidential cross-tenant data",+ EntityTypeID: victimET.ID,+ })+ require.NoError(t, err)++ // Attacker (tGroup) attempts a PUT against the victim's entity UUID with a+ // minimal body. gid is the attacker's group, ID is the victim's entity.+ out, err := tRepos.Entities.UpdateByGroup(ctx, tGroup.ID, EntityUpdate{+ ID: victim.ID,+ Name: "poc-test",+ })++ // The attacker must NOT receive the victim's record back.+ require.Error(t, err, "cross-tenant update must be rejected, not leak the entity")+ assert.NotEqual(t, secretName, out.Name, "victim's data must not leak through the response")+ assert.Equal(t, uuid.Nil, out.ID, "no entity should be returned to the attacker")++ // And the victim's entity must be untouched.+ stillThere, err := tRepos.Entities.GetOneByGroup(ctx, victimGroup.ID, victim.ID)+ require.NoError(t, err)+ assert.Equal(t, secretName, stillThere.Name, "victim entity must be unmodified")+}diff --git a/docs/public/api/openapi-3.0.json b/docs/public/api/openapi-3.0.jsonindex c541111a..72148253 100644--- a/docs/public/api/openapi-3.0.json+++ b/docs/public/api/openapi-3.0.json@@ -3017,6 +3017,25 @@}}},+ "/v1/users/logout/all": {+ "post": {+ "security": [+ {+ "Bearer": []+ }+ ],+ "description": "Revokes every session token for the authenticated user across all\ndevices, including the current one. Use this to invalidate a session\ntoken that may have been leaked or stolen. API keys are stored\nseparately and are not affected; revoke them from the API keys page.",+ "tags": [+ "Authentication"+ ],+ "summary": "Log Out Of All Sessions",+ "responses": {+ "204": {+ "description": "No Content"+ }+ }+ }+ },"/v1/users/refresh": {"get": {"security": [diff --git a/docs/public/api/openapi-3.0.yaml b/docs/public/api/openapi-3.0.yamlindex 9b0ce92c..79246bbd 100644--- a/docs/public/api/openapi-3.0.yaml+++ b/docs/public/api/openapi-3.0.yaml@@ -1797,6 +1797,21 @@ paths:responses:"204":description: No Content+ /v1/users/logout/all:+ post:+ security:+ - Bearer: []+ description: |-+ Revokes every session token for the authenticated user across all+ devices, including the current one. Use this to invalidate a session+ token that may have been leaked or stolen. API keys are stored+ separately and are not affected; revoke them from the API keys page.+ tags:+ - Authentication+ summary: Log Out Of All Sessions+ responses:+ "204":+ description: No Content/v1/users/refresh:get:security:diff --git a/docs/public/api/swagger-2.0.json b/docs/public/api/swagger-2.0.jsonindex d14e5ec3..432335d2 100644--- a/docs/public/api/swagger-2.0.json+++ b/docs/public/api/swagger-2.0.json@@ -2801,6 +2801,25 @@}}},+ "/v1/users/logout/all": {+ "post": {+ "security": [+ {+ "Bearer": []+ }+ ],+ "description": "Revokes every session token for the authenticated user across all\ndevices, including the current one. Use this to invalidate a session\ntoken that may have been leaked or stolen. API keys are stored\nseparately and are not affected; revoke them from the API keys page.",+ "tags": [+ "Authentication"+ ],+ "summary": "Log Out Of All Sessions",+ "responses": {+ "204": {+ "description": "No Content"+ }+ }+ }+ },"/v1/users/refresh": {"get": {"security": [diff --git a/docs/public/api/swagger-2.0.yaml b/docs/public/api/swagger-2.0.yamlindex 883fd83a..c162c752 100644--- a/docs/public/api/swagger-2.0.yaml+++ b/docs/public/api/swagger-2.0.yaml@@ -4087,6 +4087,21 @@ paths:summary: User Logouttags:- Authentication+ /v1/users/logout/all:+ post:+ description: |-+ Revokes every session token for the authenticated user across all+ devices, including the current one. Use this to invalidate a session+ token that may have been leaked or stolen. API keys are stored+ separately and are not affected; revoke them from the API keys page.+ responses:+ "204":+ description: No Content+ security:+ - Bearer: []+ summary: Log Out Of All Sessions+ tags:+ - Authentication/v1/users/refresh:get:description: |-diff --git a/frontend/lib/api/classes/users.ts b/frontend/lib/api/classes/users.tsindex 83216fd7..e0c32f58 100644--- a/frontend/lib/api/classes/users.ts+++ b/frontend/lib/api/classes/users.ts@@ -11,6 +11,12 @@ export class UserApi extends BaseAPI {return this.http.post<object, void>({ url: route("/users/logout") });}+ /** Revokes every session token for the current user across all devices,+ * including this one. Use to invalidate a session that may have been leaked. */+ public logoutAll() {+ return this.http.post<object, void>({ url: route("/users/logout/all") });+ }+public delete() {return this.http.delete<void>({ url: route("/users/self") });}diff --git a/frontend/locales/en.json b/frontend/locales/en.jsonindex 81d9e2f0..40232f16 100644--- a/frontend/locales/en.json+++ b/frontend/locales/en.json@@ -818,6 +818,8 @@"inactive": "Inactive","language": "Language","legacy_image_fit": "{ currentValue, select, true {Disable Legacy Fit: Fit Image with Bars} false {Enable Legacy Fit: Fill Image with Crop} other {Not Hit}}",+ "logout_all_confirm": "This signs you out on every device, including this one. You will need to log in again. Continue?",+ "logout_all_devices": "Log Out of All Devices","moved_notice_body": "Notifiers, invites, and currency settings have been moved to the collection pages.","moved_notice_description": "These settings are now managed per collection.","moved_notice_link_invites": "Collection invites",@@ -849,7 +851,9 @@"failed_test_notifier": "Failed to test notifier.","failed_update_group": "Failed to update group","failed_update_notifier": "Failed to update notifier.",+ "failed_logout_all": "Failed to sign out of all devices.","group_updated": "Group updated",+ "logout_all_success": "Signed out of all devices.","notifier_test_success": "Notifier test successful.","password_changed": "Password changed successfully."},diff --git a/frontend/pages/profile.vue b/frontend/pages/profile.vueindex b0c3e31f..0af80bb1 100644--- a/frontend/pages/profile.vue+++ b/frontend/pages/profile.vue@@ -111,6 +111,25 @@passwordChange.loading = false;}+ async function logoutAllDevices() {+ const result = await confirm.open(t("profile.logout_all_confirm"));+ if (result.isCanceled) {+ return;+ }++ const { error } = await api.user.logoutAll();+ if (error) {+ toast.error(t("profile.toast.failed_logout_all"));+ return;+ }++ // Every session token was revoked server-side, including this one, so clear+ // the local session and send the user back to the login flow.+ toast.success(t("profile.toast.logout_all_success"));+ auth.invalidateSession();+ navigateTo("/");+ }+// ---------------------------------------------------------------------------// API keys@@ -343,6 +362,9 @@<Button variant="secondary" size="sm" @click="openDialog(DialogID.ChangePassword)">{{ $t("profile.change_password") }}</Button>+ <Button variant="secondary" size="sm" @click="logoutAllDevices">+ {{ $t("profile.logout_all_devices") }}+ </Button><Button variant="secondary" size="sm" @click="openDialog(DialogID.DuplicateSettings)">{{ $t("items.duplicate.title") }}</Button>