Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

fix(auth): follow webfinger redirects and allow fediverse auth retries

Gabe Kangas3c9af03795dd
diff --git a/auth/fediverse/fediverse.go b/auth/fediverse/fediverse.go
index 69b93e0e18..fe158568e2 100644
--- a/auth/fediverse/fediverse.go
+++ b/auth/fediverse/fediverse.go
@@ -69,19 +69,24 @@ func (s *Service) runExpiredRequestPruner() {
// RegisterFediverseOTP will start the OTP flow for a user, creating a new
// code and returning it to be sent to a destination.
func (s *Service) RegisterFediverseOTP(accessToken, userID, userDisplayName, account string) (OTPRegistration, bool, error) {
- request, requestExists := s.pendingAuthRequests[accessToken]
-
- // If a request is already registered and has not expired then return that
- // existing request.
- if requestExists && time.Since(request.Timestamp) < registrationTimeout {
- return request, false, nil
- }
+ account = strings.ToLower(account)
s.lock.Lock()
defer s.lock.Unlock()
- if len(s.pendingAuthRequests)+1 > maxPendingRequests {
- return request, false, errors.New("too many pending requests, please try again later")
+ existing, exists := s.pendingAuthRequests[accessToken]
+
+ // Block a duplicate request for the same account so we don't re-send a code,
+ // but allow a request for a different account to replace a pending one so a
+ // user who entered the wrong address can immediately retry.
+ if exists && time.Since(existing.Timestamp) < registrationTimeout && existing.Account == account {
+ return existing, false, nil
+ }
+
+ // Only the global cap applies when adding a new entry; replacing one does
+ // not grow the map.
+ if !exists && len(s.pendingAuthRequests)+1 > maxPendingRequests {
+ return OTPRegistration{}, false, errors.New("too many pending requests, please try again later")
}
code, _ := createCode()
@@ -89,7 +94,7 @@ func (s *Service) RegisterFediverseOTP(accessToken, userID, userDisplayName, acc
Code: code,
UserID: userID,
UserDisplayName: userDisplayName,
- Account: strings.ToLower(account),
+ Account: account,
Timestamp: time.Now(),
}
s.pendingAuthRequests[accessToken] = r
@@ -99,15 +104,14 @@ func (s *Service) RegisterFediverseOTP(accessToken, userID, userDisplayName, acc
// ValidateFediverseOTP will verify a OTP code for a auth request.
func (s *Service) ValidateFediverseOTP(accessToken, code string) (bool, *OTPRegistration) {
- request, ok := s.pendingAuthRequests[accessToken]
+ s.lock.Lock()
+ defer s.lock.Unlock()
+ request, ok := s.pendingAuthRequests[accessToken]
if !ok || request.Code != code || time.Since(request.Timestamp) > registrationTimeout {
return false, nil
}
- s.lock.Lock()
- defer s.lock.Unlock()
-
delete(s.pendingAuthRequests, accessToken)
return true, &request
}
diff --git a/auth/fediverse/fediverse_test.go b/auth/fediverse/fediverse_test.go
index eedb6b1fd2..215ea767d8 100644
--- a/auth/fediverse/fediverse_test.go
+++ b/auth/fediverse/fediverse_test.go
@@ -69,6 +69,35 @@ func TestSingleOTPFlowRequest(t *testing.T) {
}
}
+func TestReplacePendingWhenAccountDiffers(t *testing.T) {
+ svc := New()
+ token := "retry-token"
+
+ first, _, _ := svc.RegisterFediverseOTP(token, userID, userDisplayName, "[email protected]")
+
+ // A different account replaces the pending request with a fresh code.
+ second, ok, _ := svc.RegisterFediverseOTP(token, userID, userDisplayName, "[email protected]")
+ if !ok {
+ t.Fatal("a request for a different account should replace the pending one")
+ }
+ if second.Code == first.Code {
+ t.Error("replacement should issue a new code")
+ }
+
+ // The same account is still blocked from re-sending.
+ if _, ok, _ := svc.RegisterFediverseOTP(token, userID, userDisplayName, "[email protected]"); ok {
+ t.Error("a duplicate request for the same account should be blocked")
+ }
+
+ // Only the replacement code is valid now.
+ if valid, _ := svc.ValidateFediverseOTP(token, first.Code); valid {
+ t.Error("the replaced code should no longer validate")
+ }
+ if valid, _ := svc.ValidateFediverseOTP(token, second.Code); !valid {
+ t.Error("the replacement code should validate")
+ }
+}
+
func TestAccountCaseInsensitive(t *testing.T) {
svc := New()
account := "Account"
diff --git a/openapi.yaml b/openapi.yaml
index 2626e8f01b..c065c44928 100644
--- a/openapi.yaml
+++ b/openapi.yaml
@@ -3847,8 +3847,6 @@ paths:
$ref: '#/components/schemas/BaseAPIResponse'
'400':
$ref: '#/components/responses/400'
- '403':
- $ref: '#/components/responses/403'
components:
schemas:
diff --git a/services/activitypub/webfinger/webfinger.go b/services/activitypub/webfinger/webfinger.go
index c3a99678ab..9beb7640ad 100644
--- a/services/activitypub/webfinger/webfinger.go
+++ b/services/activitypub/webfinger/webfinger.go
@@ -46,12 +46,10 @@ func GetWebfingerLinks(account string) ([]map[string]interface{}, error) {
query.Add("resource", fmt.Sprintf("acct:%s", account))
requestURL.RawQuery = query.Encode()
- // Do not support redirects.
- client := &http.Client{
- CheckRedirect: func(req *http.Request, via []*http.Request) error {
- return http.ErrUseLastResponse
- },
- }
+ // Follow redirects (e.g. subdomain -> canonical domain, as Mastodon does).
+ // GetRetryableHTTPClient re-validates each hop against the internal-host
+ // check to prevent SSRF and caps the redirect count.
+ client := utils.GetRetryableHTTPClient()
req, err := http.NewRequest("GET", requestURL.String(), nil)
if err != nil {
diff --git a/services/activitypub/webfinger/webfinger_test.go b/services/activitypub/webfinger/webfinger_test.go
new file mode 100644
index 0000000000..6f9b606d1b
--- /dev/null
+++ b/services/activitypub/webfinger/webfinger_test.go
@@ -0,0 +1,76 @@
+package webfinger
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+)
+
+// TestMain sets the test escape hatches before any test runs: they are read
+// once via sync.Once, and httptest servers use loopback + self-signed certs
+// that the resolver would otherwise reject.
+func TestMain(m *testing.M) {
+ if err := os.Setenv("OWNCAST_ALLOW_INTERNAL_FEDERATION", "true"); err != nil {
+ panic(err)
+ }
+ if err := os.Setenv("OWNCAST_INSECURE_SKIP_VERIFY", "true"); err != nil {
+ panic(err)
+ }
+ os.Exit(m.Run())
+}
+
+// Regression test for #4696: a webfinger host that redirects the lookup must be
+// followed, and the acct resource query must survive the redirect.
+func TestGetWebfingerLinksFollowsRedirect(t *testing.T) {
+ var gotResource string
+ final := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotResource = r.URL.Query().Get("resource")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"links":[{"rel":"self","type":"application/activity+json","href":"https://example.com/actor"}]}`))
+ }))
+ defer final.Close()
+
+ entry := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, final.URL+r.URL.Path+"?"+r.URL.RawQuery, http.StatusFound)
+ }))
+ defer entry.Close()
+
+ account := "user@" + strings.TrimPrefix(entry.URL, "https://")
+
+ links, err := GetWebfingerLinks(account)
+ if err != nil {
+ t.Fatalf("expected redirect to be followed, got error: %v", err)
+ }
+ if len(links) != 1 {
+ t.Fatalf("expected 1 link, got %d", len(links))
+ }
+ if want := "acct:" + account; gotResource != want {
+ t.Errorf("resource query not preserved across redirect: got %q, want %q", gotResource, want)
+ }
+}
+
+func TestGetWebfingerLinksRedirectLoop(t *testing.T) {
+ loop := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, r.URL.String(), http.StatusFound)
+ }))
+ defer loop.Close()
+
+ account := "user@" + strings.TrimPrefix(loop.URL, "https://")
+ if _, err := GetWebfingerLinks(account); err == nil {
+ t.Error("expected an error from an endless redirect chain, got nil")
+ }
+}
+
+func TestGetWebfingerLinksTerminalError(t *testing.T) {
+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, "nope", http.StatusNotFound)
+ }))
+ defer server.Close()
+
+ account := "user@" + strings.TrimPrefix(server.URL, "https://")
+ if _, err := GetWebfingerLinks(account); err == nil {
+ t.Error("expected an error for a non-200 webfinger response, got nil")
+ }
+}
diff --git a/test/automated/api/010_auth.test.js b/test/automated/api/010_auth.test.js
index c240a29bc8..03c39f852d 100644
--- a/test/automated/api/010_auth.test.js
+++ b/test/automated/api/010_auth.test.js
@@ -51,3 +51,15 @@ paths.forEach((path) => {
expect([200, 301]).toContain(r.status);
});
});
+
+// A wrong or expired fediverse OTP code returns a JSON error rather than a
+// bodyless 403 the web client can't parse. Regression test for #4696.
+test('fediverse verify with a bad code returns a JSON error', async () => {
+ const r = await request
+ .post('/api/auth/fediverse/verify?accessToken=nonexistent-token')
+ .send({ code: '000000' })
+ .expect(400);
+ expect(r.body.success).toBe(false);
+ expect(typeof r.body.message).toBe('string');
+ expect(r.body.message.length).toBeGreaterThan(0);
+});
diff --git a/web/components/modals/FediAuthModal/FediAuthModal.tsx b/web/components/modals/FediAuthModal/FediAuthModal.tsx
index 49929ae7bd..df242917a1 100644
--- a/web/components/modals/FediAuthModal/FediAuthModal.tsx
+++ b/web/components/modals/FediAuthModal/FediAuthModal.tsx
@@ -68,10 +68,21 @@ export const FediAuthModal: FC<FediAuthModalProps> = ({
body: JSON.stringify(data),
});
- const content = await rawResponse.json();
+ let content: { message?: string } = {};
+ try {
+ content = await rawResponse.json();
+ } catch {
+ // Non-JSON response; the status check below handles it.
+ }
+
if (content.message) {
+ // Callers set the error message, so just surface it.
+ setLoading(false);
+ throw new Error(content.message);
+ }
+ if (!rawResponse.ok) {
setLoading(false);
- throw new Error(content.message); // let the callers handle setting error message since they already are
+ throw new Error('Something went wrong. Please try again.');
}
};
@@ -87,7 +98,7 @@ export const FediAuthModal: FC<FediAuthModalProps> = ({
window.location.href = '/';
} catch (e) {
console.error(e);
- setErrorMessage(e.toString());
+ setErrorMessage(e.message);
}
setLoading(false);
};
@@ -108,7 +119,7 @@ export const FediAuthModal: FC<FediAuthModalProps> = ({
setVerifyingCode(true);
} catch (e) {
console.error(e);
- setErrorMessage(e.toString());
+ setErrorMessage(e.message);
}
setLoading(false);
};
diff --git a/webserver/handlers/auth/fediverse/fediverse.go b/webserver/handlers/auth/fediverse/fediverse.go
index 0ddf1b3ec1..64f0d455dc 100644
--- a/webserver/handlers/auth/fediverse/fediverse.go
+++ b/webserver/handlers/auth/fediverse/fediverse.go
@@ -101,7 +101,7 @@ func (h *Handler) VerifyFediverseOTPRequest(w http.ResponseWriter, r *http.Reque
accessToken := r.URL.Query().Get("accessToken")
valid, authRegistration := h.fediverseAuth.ValidateFediverseOTP(accessToken, *req.Code)
if !valid {
- w.WriteHeader(http.StatusForbidden)
+ webutils.WriteSimpleResponse(w, false, "Incorrect or expired code. Please request a new one and try again.")
return
}