refactor: implement mcaptcha client and add comments/tests (#38561)

End users still need it, so it's better to make it maintainable with
tests and OOM-safe.

---------

Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
wxiaoguang
2026-07-21 13:41:54 +00:00
committed by GitHub
co-authored by silverwind
parent 91eb14c944
commit 4af9156c36
5 changed files with 109 additions and 19 deletions
-5
View File
File diff suppressed because one or more lines are too long
-1
View File
@@ -3,7 +3,6 @@ module gitea.dev
go 1.26.5
require (
codeberg.org/gusted/mcaptcha v0.0.0-20220723083913-4f3072e1d570
connectrpc.com/connect v1.20.0
gitea.com/gitea/runner v1.0.8
gitea.com/go-chi/binding v0.0.0-20260414111559-654cea7ac60a
-2
View File
@@ -2,8 +2,6 @@ cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdB
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
code.pfad.fr/check v1.1.0 h1:GWvjdzhSEgHvEHe2uJujDcpmZoySKuHQNrZMfzfO0bE=
code.pfad.fr/check v1.1.0/go.mod h1:NiUH13DtYsb7xp5wll0U4SXx7KhXQVCtRgdC96IPfoM=
codeberg.org/gusted/mcaptcha v0.0.0-20220723083913-4f3072e1d570 h1:TXbikPqa7YRtfU9vS6QJBg77pUvbEb6StRdZO8t1bEY=
codeberg.org/gusted/mcaptcha v0.0.0-20220723083913-4f3072e1d570/go.mod h1:IIAjsijsd8q1isWX8MACefDEgTQslQ4stk2AeeTt3kM=
connectrpc.com/connect v1.20.0 h1:6TNDAB+WeNd2uolWNlYczB5E0KNNaVMNUEx8JEUsPmQ=
connectrpc.com/connect v1.20.0/go.mod h1:A2ygJrukXwWy32vkCAAHNVguZrqZ+jeZ9rGRnGR4dN4=
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
+56 -11
View File
@@ -1,26 +1,71 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
// https://github.com/go-gitea/gitea/pull/37492#issuecomment-4355482585
// End users need it "since it is the only one open-source option in Gitea besides the image captcha"
package mcaptcha
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"strings"
"gitea.dev/modules/json"
"gitea.dev/modules/setting"
"codeberg.org/gusted/mcaptcha"
"gitea.dev/modules/util"
)
func Verify(ctx context.Context, token string) (bool, error) {
valid, err := mcaptcha.Verify(ctx, &mcaptcha.VerifyOpts{
InstanceURL: setting.Service.McaptchaURL,
Sitekey: setting.Service.McaptchaSitekey,
Secret: setting.Service.McaptchaSecret,
Token: token,
})
if err != nil {
return false, fmt.Errorf("wasn't able to verify mCaptcha: %w", err)
c := &client{
ServerURL: setting.Service.McaptchaURL,
SiteKey: setting.Service.McaptchaSitekey,
Secret: setting.Service.McaptchaSecret,
Token: token,
}
return valid, nil
return c.Verify(ctx)
}
type client struct {
ServerURL string
Secret string
SiteKey string
Token string
}
func (c *client) Verify(ctx context.Context) (bool, error) {
verifyURL := strings.TrimSuffix(c.ServerURL, "/") + "/api/v1/pow/siteverify"
reqParams := map[string]string{"secret": c.Secret, "key": c.SiteKey, "token": c.Token}
reqBody, _ := json.Marshal(reqParams)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, verifyURL, bytes.NewReader(reqBody))
if err != nil {
return false, fmt.Errorf("unable to create verify request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return false, fmt.Errorf("unable to complete verify request: %w", err)
}
defer res.Body.Close()
respContent, err := io.ReadAll(io.LimitReader(res.Body, 16*1024))
if err != nil {
return false, fmt.Errorf("unable to read response body: %w", err)
}
if res.StatusCode != http.StatusOK {
return false, fmt.Errorf("unexpected response status %d: %q", res.StatusCode, util.TruncateRunes(util.UnsafeBytesToString(respContent), 100))
}
var resp struct {
Valid bool `json:"valid"`
}
err = json.Unmarshal(respContent, &resp)
if err != nil {
return false, fmt.Errorf("unable to decode response: %w", err)
}
return resp.Valid, nil
}
+53
View File
@@ -0,0 +1,53 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package mcaptcha
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"gitea.dev/modules/json"
"gitea.dev/modules/setting"
"gitea.dev/modules/test"
"github.com/stretchr/testify/assert"
)
func TestMCaptchaVerify(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/api/v1/pow/siteverify":
var req map[string]string
_ = json.NewDecoder(r.Body).Decode(&req)
if req["key"] == "test-site-key" {
w.WriteHeader(http.StatusOK)
assert.Equal(t, "test-secret", req["secret"])
resp := map[string]bool{"valid": req["token"] == "token-valid"}
_ = json.NewEncoder(w).Encode(resp)
} else {
w.WriteHeader(http.StatusBadRequest)
}
}
}))
defer srv.Close()
defer test.MockVariableValue(&setting.Service)()
setting.Service.McaptchaURL = strings.TrimSuffix(srv.URL, "/") + "/"
setting.Service.McaptchaSitekey = "test-site-key"
setting.Service.McaptchaSecret = "test-secret"
valid, err := Verify(t.Context(), "token-valid")
assert.NoError(t, err)
assert.True(t, valid)
valid, err = Verify(t.Context(), "token-invalid")
assert.NoError(t, err)
assert.False(t, valid)
setting.Service.McaptchaSitekey = "test-site-key-invalid"
valid, err = Verify(t.Context(), "token-invalid")
assert.Error(t, err)
assert.False(t, valid)
}