mirror of
https://github.com/go-gitea/gitea.git
synced 2026-08-04 09:37:33 +00:00
13d0f24423
* Closes #36942 * Fixes #19265 Replaces the SSE-based push channel (`/user/events`) with a WebSocket endpoint (`/-/ws`). ### What changes - **New `/-/ws` endpoint** (authenticated). One WebSocket per origin, shared across tabs via a single `SharedWorker`. - **Pubsub broker** (`services/pubsub`) for fan-out by topic, behind a `Broker` interface. `MemoryBroker` is the default (single process); a Redis backend is available for multi-process setups, configured via `[websocket].PUBSUB_TYPE` / `PUBSUB_CONN_STR`. The internal Gitea queue was not usable here because it has FIFO/single-consumer semantics. - **Push-only event production.** Events are emitted by write-triggered notifiers — `NotificationCountChange`, `PublishStopwatchesForUser`, and the logout publisher — wired into the existing `notify.Notifier` interface. No server-side pollers. - **Typed pub/sub on the client.** `web_src/js/modules/worker.ts` is a singleton transport; features subscribe per event type via `onUserEvent('notification-count', cb)` instead of branching on `event.data.type`. - **Wire contract** (`UserEventType` union) is shared between the worker and consumers via `web_src/js/types.ts`, kept in sync with `services/websocket/events.go`. - **Client-side periodic polling fallback** kicks in only when the WebSocket cannot be established (e.g. proxy blocks WS, browser lacks module-SharedWorker support). ### What's removed - `modules/eventsource` (SSE manager, run loop, messenger). - `/user/events` route and `tests/integration/eventsource_test.go`. - All server-side polling for stopwatches and notification counts. ### Stopwatch multi-tab fix The navbar stopwatch icon was previously rendered conditionally on `{{if $activeStopwatch}}`, so tabs loaded before the timer started had no DOM element to update. The icon and popup are now always rendered (toggled with `tw-hidden`), and the start/stop/cancel handlers POST silently so all open tabs reflect the change in real time. ### Deployment note WebSocket needs the upgrade headers to pass through a reverse proxy, e.g. for nginx: ```nginx proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; ``` Without them the WebSocket cannot be established, and after 3 consecutive failed opens the shared worker signals `push-unavailable`: the notification count and stopwatch fall back to periodic polling on the existing `[ui.notification]` timeouts. Real-time push is lost, the features keep working. The reverse-proxy docs need the same note (see the `docs-update-needed` label). --------- Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: wxiaoguang <wxiaoguang@gmail.com> Co-authored-by: Epid <rexmrj@gmail.com>
205 lines
7.2 KiB
Go
205 lines
7.2 KiB
Go
// Copyright 2017 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package integration
|
|
|
|
import (
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"testing"
|
|
|
|
auth_model "gitea.dev/models/auth"
|
|
"gitea.dev/models/db"
|
|
"gitea.dev/models/unittest"
|
|
user_model "gitea.dev/models/user"
|
|
"gitea.dev/modules/setting"
|
|
"gitea.dev/modules/test"
|
|
"gitea.dev/modules/translation"
|
|
"gitea.dev/modules/web"
|
|
"gitea.dev/routers"
|
|
"gitea.dev/routers/web/auth"
|
|
"gitea.dev/services/context"
|
|
"gitea.dev/tests"
|
|
|
|
"github.com/markbates/goth"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func testLoginFailed(t *testing.T, username, password, message string) {
|
|
session := emptyTestSession(t)
|
|
req := NewRequestWithValues(t, "POST", "/user/login", map[string]string{
|
|
"user_name": username,
|
|
"password": password,
|
|
})
|
|
resp := session.MakeRequest(t, req, http.StatusOK)
|
|
|
|
htmlDoc := NewHTMLParser(t, resp.Body)
|
|
resultMsg := strings.TrimSpace(htmlDoc.doc.Find(".ui.message.flash-message").Text())
|
|
assert.Equal(t, message, resultMsg)
|
|
}
|
|
|
|
func TestSignin(t *testing.T) {
|
|
defer tests.PrepareTestEnv(t)()
|
|
|
|
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
|
|
|
// add new user with user2's email
|
|
user.Name = "testuser"
|
|
user.LowerName = strings.ToLower(user.Name)
|
|
user.ID = 0
|
|
require.NoError(t, db.Insert(t.Context(), user))
|
|
|
|
samples := []struct {
|
|
username string
|
|
password string
|
|
message string
|
|
}{
|
|
{username: "wrongUsername", password: "wrongPassword", message: translation.NewLocale("en-US").TrString("form.username_password_incorrect")},
|
|
{username: "wrongUsername", password: "password", message: translation.NewLocale("en-US").TrString("form.username_password_incorrect")},
|
|
{username: "user15", password: "wrongPassword", message: translation.NewLocale("en-US").TrString("form.username_password_incorrect")},
|
|
{username: "user1@example.com", password: "wrongPassword", message: translation.NewLocale("en-US").TrString("form.username_password_incorrect")},
|
|
}
|
|
|
|
for _, s := range samples {
|
|
testLoginFailed(t, s.username, s.password, s.message)
|
|
}
|
|
}
|
|
|
|
func TestSigninWithRememberMe(t *testing.T) {
|
|
defer tests.PrepareTestEnv(t)()
|
|
|
|
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
|
baseURL, _ := url.Parse(setting.AppURL)
|
|
|
|
session := emptyTestSession(t)
|
|
req := NewRequestWithValues(t, "POST", "/user/login", map[string]string{
|
|
"user_name": user.Name,
|
|
"password": userPassword,
|
|
"remember": "on",
|
|
})
|
|
session.MakeRequest(t, req, http.StatusSeeOther)
|
|
|
|
c := session.GetRawCookie(setting.CookieRememberName)
|
|
assert.NotNil(t, c)
|
|
|
|
session = emptyTestSession(t)
|
|
|
|
// Without session the settings page should not be reachable
|
|
req = NewRequest(t, "GET", "/user/settings")
|
|
session.MakeRequest(t, req, http.StatusSeeOther)
|
|
|
|
req = NewRequest(t, "GET", "/user/login")
|
|
// Set the remember me cookie for the login GET request
|
|
session.jar.SetCookies(baseURL, []*http.Cookie{c})
|
|
session.MakeRequest(t, req, http.StatusSeeOther)
|
|
|
|
// With session the settings page should be reachable
|
|
req = NewRequest(t, "GET", "/user/settings")
|
|
session.MakeRequest(t, req, http.StatusOK)
|
|
}
|
|
|
|
func TestEnablePasswordSignInFormAndEnablePasskeyAuth(t *testing.T) {
|
|
defer tests.PrepareTestEnv(t)()
|
|
|
|
mockLinkAccount := func(ctx *context.Context) {
|
|
authSource := auth_model.Source{ID: 1}
|
|
gothUser := goth.User{Email: "invalid-email", Name: "."}
|
|
_ = auth.Oauth2SetLinkAccountData(ctx, auth.LinkAccountData{AuthSourceID: authSource.ID, GothUser: gothUser})
|
|
}
|
|
|
|
t.Run("EnablePasswordSignInForm=false", func(t *testing.T) {
|
|
defer tests.PrintCurrentTest(t)()
|
|
defer test.MockVariableValue(&setting.Service.EnablePasswordSignInForm, false)()
|
|
|
|
req := NewRequest(t, "GET", "/user/login")
|
|
resp := MakeRequest(t, req, http.StatusOK)
|
|
doc := NewHTMLParser(t, resp.Body)
|
|
AssertHTMLElement(t, doc, "form[action='/user/login']", false)
|
|
|
|
req = NewRequest(t, "POST", "/user/login")
|
|
MakeRequest(t, req, http.StatusForbidden)
|
|
|
|
req = NewRequest(t, "GET", "/user/link_account")
|
|
defer web.RouteMockReset()
|
|
web.RouteMock(web.MockAfterMiddlewares, mockLinkAccount)
|
|
resp = MakeRequest(t, req, http.StatusOK)
|
|
doc = NewHTMLParser(t, resp.Body)
|
|
AssertHTMLElement(t, doc, "form[action='/user/link_account_signin']", false)
|
|
})
|
|
|
|
t.Run("EnablePasswordSignInForm=true", func(t *testing.T) {
|
|
defer tests.PrintCurrentTest(t)()
|
|
defer test.MockVariableValue(&setting.Service.EnablePasswordSignInForm, true)()
|
|
|
|
req := NewRequest(t, "GET", "/user/login")
|
|
resp := MakeRequest(t, req, http.StatusOK)
|
|
doc := NewHTMLParser(t, resp.Body)
|
|
AssertHTMLElement(t, doc, "form[action='/user/login']", true)
|
|
|
|
req = NewRequest(t, "POST", "/user/login")
|
|
MakeRequest(t, req, http.StatusOK)
|
|
|
|
req = NewRequest(t, "GET", "/user/link_account")
|
|
defer web.RouteMockReset()
|
|
web.RouteMock(web.MockAfterMiddlewares, mockLinkAccount)
|
|
resp = MakeRequest(t, req, http.StatusOK)
|
|
doc = NewHTMLParser(t, resp.Body)
|
|
AssertHTMLElement(t, doc, "form[action='/user/link_account_signin']", true)
|
|
})
|
|
|
|
t.Run("EnablePasskeyAuth=false", func(t *testing.T) {
|
|
defer tests.PrintCurrentTest(t)()
|
|
defer test.MockVariableValue(&setting.Service.EnablePasskeyAuth, false)()
|
|
|
|
req := NewRequest(t, "GET", "/user/login")
|
|
resp := MakeRequest(t, req, http.StatusOK)
|
|
doc := NewHTMLParser(t, resp.Body)
|
|
AssertHTMLElement(t, doc, ".signin-passkey", false)
|
|
})
|
|
|
|
t.Run("EnablePasskeyAuth=true", func(t *testing.T) {
|
|
defer tests.PrintCurrentTest(t)()
|
|
defer test.MockVariableValue(&setting.Service.EnablePasskeyAuth, true)()
|
|
|
|
req := NewRequest(t, "GET", "/user/login")
|
|
resp := MakeRequest(t, req, http.StatusOK)
|
|
doc := NewHTMLParser(t, resp.Body)
|
|
AssertHTMLElement(t, doc, ".signin-passkey", true)
|
|
})
|
|
}
|
|
|
|
func TestRequireSignInView(t *testing.T) {
|
|
defer tests.PrepareTestEnv(t)()
|
|
t.Run("NoRequireSignInView", func(t *testing.T) {
|
|
require.False(t, setting.Service.RequireSignInViewStrict)
|
|
require.False(t, setting.Service.BlockAnonymousAccessExpensive)
|
|
req := NewRequest(t, "GET", "/user2/repo1/src/branch/master")
|
|
MakeRequest(t, req, http.StatusOK)
|
|
req = NewRequest(t, "GET", "/-/ws")
|
|
MakeRequest(t, req, http.StatusUpgradeRequired)
|
|
})
|
|
t.Run("RequireSignInView", func(t *testing.T) {
|
|
defer test.MockVariableValue(&setting.Service.RequireSignInViewStrict, true)()
|
|
defer test.MockVariableValue(&testWebRoutes, routers.NormalRoutes())()
|
|
req := NewRequest(t, "GET", "/user2/repo1/src/branch/master")
|
|
resp := MakeRequest(t, req, http.StatusSeeOther)
|
|
assert.Equal(t, "/user/login?redirect_to=%2Fuser2%2Frepo1%2Fsrc%2Fbranch%2Fmaster", resp.Header().Get("Location"))
|
|
})
|
|
t.Run("BlockAnonymousAccessExpensive", func(t *testing.T) {
|
|
defer test.MockVariableValue(&setting.Service.RequireSignInViewStrict, false)()
|
|
defer test.MockVariableValue(&setting.Service.BlockAnonymousAccessExpensive, true)()
|
|
defer test.MockVariableValue(&testWebRoutes, routers.NormalRoutes())()
|
|
|
|
req := NewRequest(t, "GET", "/user2/repo1")
|
|
MakeRequest(t, req, http.StatusOK)
|
|
req = NewRequest(t, "GET", "/-/ws")
|
|
MakeRequest(t, req, http.StatusSeeOther)
|
|
|
|
req = NewRequest(t, "GET", "/user2/repo1/src/branch/master")
|
|
resp := MakeRequest(t, req, http.StatusSeeOther)
|
|
assert.Equal(t, "/user/login?redirect_to=%2Fuser2%2Frepo1%2Fsrc%2Fbranch%2Fmaster", resp.Header().Get("Location"))
|
|
})
|
|
}
|