Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitleaks.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,7 @@ regexes = [
# docs/content/docs/plugins/oauth2provider.mdx: the id_token in the sample
# token response, cut off after the start of an RS256 header.
'''^eyJhbGciOiJSUzI1NiIs\.\.\.$''',
# middleware/captcha_test.go: the password in a sign-up body the captcha
# middleware must pass through to the handler unchanged.
'''^Abcdefgh-1234$''',
]
2 changes: 1 addition & 1 deletion api/delegated_plugin_admin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func TestPluginAdminGroups_RefuseAgentToken(t *testing.T) {
CreatedAt: time.Now(), UpdatedAt: time.Now(),
}
require.NoError(t, wlStore.CreateEntry(ctx, entry))
path := eng.BasePath() + "/admin/waitlist/" + entry.ID.String() + "/approve"
path := "/v1/admin/waitlist/" + entry.ID.String() + "/approve"

rec := call(agentSess.Token, http.MethodPost, path, `{}`)
assert.Equal(t, http.StatusForbidden, rec.Code, "body=%s", rec.Body.String())
Expand Down
8 changes: 4 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ require (
github.com/xraph/forge v1.13.6
github.com/xraph/forge/extensions/auth v1.13.6
github.com/xraph/go-utils v1.5.0
github.com/xraph/grove v1.10.2
github.com/xraph/grove/drivers/mongodriver v1.10.2
github.com/xraph/grove/drivers/pgdriver v1.10.2
github.com/xraph/grove/drivers/sqlitedriver v1.10.2
github.com/xraph/grove v1.10.3
github.com/xraph/grove/drivers/mongodriver v1.10.3
github.com/xraph/grove/drivers/pgdriver v1.10.3
github.com/xraph/grove/drivers/sqlitedriver v1.10.3
github.com/xraph/herald v1.10.3
github.com/xraph/keysmith v1.9.1
github.com/xraph/ledger v1.9.2
Expand Down
16 changes: 8 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -437,14 +437,14 @@ github.com/xraph/forge/extensions/auth v1.13.6 h1:3OIiG/fkn0i3FmO7NGO9S9RoK1l5kW
github.com/xraph/forge/extensions/auth v1.13.6/go.mod h1:TXaOpGXHhjtZfFSzhjDu23uEM16wfjbJscou0Yfy8uk=
github.com/xraph/go-utils v1.5.0 h1:44pIJooK565ds/Ica0yyPoRNbr0qUTgj1aay8ewad1w=
github.com/xraph/go-utils v1.5.0/go.mod h1:fMahP6kPUjJP5UmzVje2GSL7OGT9+xpYkukK2dLjSMM=
github.com/xraph/grove v1.10.2 h1:3ZoKJpU21gIv8p98RjQE4wFcAhesXvTqSSqrroNOXaI=
github.com/xraph/grove v1.10.2/go.mod h1:oQ5d+MiSDkDxiRCKBOlmieJmzFXvanY/kk9VfvQO40w=
github.com/xraph/grove/drivers/mongodriver v1.10.2 h1:IrIqWzg72iL6qroh/llft+CH0FygMS2wyBwYkVeNQ2s=
github.com/xraph/grove/drivers/mongodriver v1.10.2/go.mod h1:x/t82VUmjCAuUluOHHfDrJCHdGKtd3M2pnKvBnUxvwU=
github.com/xraph/grove/drivers/pgdriver v1.10.2 h1:LMMqPMPtj1OgA1npfqOWsknMQZbJ7kFwMrdrj32Mp3I=
github.com/xraph/grove/drivers/pgdriver v1.10.2/go.mod h1:aV31nDRM4Igx4vqwjM9u8v0A1URL8YyDyXCuABLOuPA=
github.com/xraph/grove/drivers/sqlitedriver v1.10.2 h1:YLB9bGSxJnIquPN31etQGtrCWQfuuqfbcjk4eCkPT9Y=
github.com/xraph/grove/drivers/sqlitedriver v1.10.2/go.mod h1:UlTGQQRp7VD4Rjj8HN6XjW1TMZl0iSNI4LApoQnChYQ=
github.com/xraph/grove v1.10.3 h1:bTVuW6le1hIBLYzpmPBgcVO826FcncYYFFDJntZT7DY=
github.com/xraph/grove v1.10.3/go.mod h1:oQ5d+MiSDkDxiRCKBOlmieJmzFXvanY/kk9VfvQO40w=
github.com/xraph/grove/drivers/mongodriver v1.10.3 h1:hk6xPlpDKeBFfp9MfFVdzValnITY5lG1ypseBwzIaJo=
github.com/xraph/grove/drivers/mongodriver v1.10.3/go.mod h1:x/t82VUmjCAuUluOHHfDrJCHdGKtd3M2pnKvBnUxvwU=
github.com/xraph/grove/drivers/pgdriver v1.10.3 h1:firu2F10BdN2ciaYmFw1MrQ4z0DKnNQz4ifg0gLzxes=
github.com/xraph/grove/drivers/pgdriver v1.10.3/go.mod h1:aV31nDRM4Igx4vqwjM9u8v0A1URL8YyDyXCuABLOuPA=
github.com/xraph/grove/drivers/sqlitedriver v1.10.3 h1:a7f/Ir/4iMQsE+EDshgOtUf+Vpu2EIhOMsVDlONveeI=
github.com/xraph/grove/drivers/sqlitedriver v1.10.3/go.mod h1:UlTGQQRp7VD4Rjj8HN6XjW1TMZl0iSNI4LApoQnChYQ=
github.com/xraph/grove/kv v1.10.2 h1:3ic9NWFSGLmcxmy+eHw9t0HrU4WCGnTsSdn56rabS1U=
github.com/xraph/grove/kv v1.10.2/go.mod h1:qW3j9k8OV14itMSQTLpC/INh35HL5ppWRknzUNas2/o=
github.com/xraph/herald v1.10.3 h1:eLPh3/RnVzoTriD5VuRg8cZmJMzG2Fj7HXFMJLG3+Us=
Expand Down
46 changes: 46 additions & 0 deletions middleware/captcha.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package middleware

import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"sync"

log "github.com/xraph/go-utils/log"
Expand Down Expand Up @@ -285,13 +288,56 @@ func captchaResolveString(ctx context.Context, mgr *settings.Manager, key string
return val, nil
}

// captchaJSONPeekLimit bounds how much of a JSON body the middleware reads
// to find the token. Sign-up and sign-in bodies are a few hundred bytes; a
// larger body is passed through untouched and has to use the header.
const captchaJSONPeekLimit = 64 << 10

func captchaExtractToken(r *http.Request) string {
if v := r.Header.Get(captchaTokenHeader); v != "" {
return v
}
if isJSONRequest(r) {
return captchaTokenFromJSON(r)
}
return r.FormValue(captchaTokenFormField)
}

func isJSONRequest(r *http.Request) bool {
ct := r.Header.Get("Content-Type")
if i := strings.IndexByte(ct, ';'); i >= 0 {
ct = ct[:i]
}
ct = strings.TrimSpace(strings.ToLower(ct))
return ct == "application/json" || strings.HasSuffix(ct, "+json")
}

// captchaTokenFromJSON reads captcha_token from a JSON body, which is how
// the UI SDK sends it and what the sign-up and sign-in request schemas
// document. The middleware runs before the handler binds the body, so the
// bytes it reads are put back in front of whatever is left: the handler
// sees the body exactly as it arrived.
func captchaTokenFromJSON(r *http.Request) string {
if r.Body == nil || r.Body == http.NoBody {
return ""
}
peeked, err := io.ReadAll(io.LimitReader(r.Body, captchaJSONPeekLimit+1))
r.Body = struct {
io.Reader
io.Closer
}{io.MultiReader(bytes.NewReader(peeked), r.Body), r.Body}
if err != nil || len(peeked) > captchaJSONPeekLimit {
return ""
}
var body struct {
CaptchaToken string `json:"captcha_token"`
}
if json.Unmarshal(peeked, &body) != nil {
return ""
}
return body.CaptchaToken
}

func captchaClientIP(r *http.Request) string {
// Trusted-proxy-aware resolution so the CAPTCHA's remote-IP binding can't be
// forged by a direct client spoofing X-Forwarded-For.
Expand Down
82 changes: 82 additions & 0 deletions middleware/captcha_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,88 @@ func TestCaptchaMiddleware_TokenFromHeaderOrForm(t *testing.T) {
assert.Equal(t, "header-tok", sawToken, "header should take precedence over form field")
}

// The UI SDK posts sign-up and sign-in as JSON with captcha_token in the
// body, which is also what the request schema documents. The token has to
// be found there, and the handler behind the middleware must still read the
// whole body.
func TestCaptchaMiddleware_TokenFromJSONBody(t *testing.T) {
env := newCaptchaTestEnv(t, true)
var sawToken string
stub := &stubVerifier{fn: func(_ context.Context, token, _, _ string) (*captcha.Result, error) {
sawToken = token
return &captcha.Result{Success: true}, nil
}}
var handlerSaw map[string]any
router := forge.NewRouter()
router.Use(middleware.CaptchaMiddleware(middleware.CaptchaOptions{
Settings: env.manager,
VerifierFor: func(string, string) (captcha.Verifier, error) { return stub, nil },
}))
router.POST("/test", func(ctx forge.Context) error {
handlerSaw = decodeJSON(t, ctx.Request().Body)
return ctx.NoContent(http.StatusOK)
})
handler := router.Handler()

post := func(contentType, body string) *httptest.ResponseRecorder {
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/test", strings.NewReader(body))
req.Header.Set("Content-Type", contentType)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return rec
}

rec := post("application/json; charset=utf-8", `{"email":"a@b.io","password":"pw","captcha_token":"json-tok"}`)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "json-tok", sawToken, "captcha_token in a JSON body should populate the token")
assert.Equal(t, "a@b.io", handlerSaw["email"], "the handler must still read the full body")

// No token in the body: still refused.
sawToken = ""
rec = post("application/json", `{"email":"a@b.io"}`)
assert.Equal(t, http.StatusForbidden, rec.Code)
assert.Empty(t, sawToken)

// A body that isn't JSON at all is refused, not a crash.
rec = post("application/json", `not json`)
assert.Equal(t, http.StatusForbidden, rec.Code)
}

// The real sign-up and sign-in routes bind into a typed request, the way
// every authsome handler does. The body the middleware read must reach that
// binding whole, or a passed captcha would hand the handler an empty
// request.
func TestCaptchaMiddleware_JSONBodyStillBindsTypedRequest(t *testing.T) {
env := newCaptchaTestEnv(t, true)
stub := &stubVerifier{fn: func(context.Context, string, string, string) (*captcha.Result, error) {
return &captcha.Result{Success: true}, nil
}}
type signUp struct {
Email string `json:"email"`
Password string `json:"password"`
CaptchaToken string `json:"captcha_token,omitempty"`
}
var bound signUp
router := forge.NewRouter()
router.Use(middleware.CaptchaMiddleware(middleware.CaptchaOptions{
Settings: env.manager,
VerifierFor: func(string, string) (captcha.Verifier, error) { return stub, nil },
}))
require.NoError(t, router.POST("/signup", func(_ forge.Context, req *signUp) (*signUp, error) {
bound = *req
return req, nil
}))

req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/signup",
strings.NewReader(`{"email":"a@b.io","password":"Abcdefgh-1234","captcha_token":"json-tok"}`))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)

require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
assert.Equal(t, signUp{Email: "a@b.io", Password: "Abcdefgh-1234", CaptchaToken: "json-tok"}, bound)
}

func TestCaptchaMiddleware_VerifierCachedAcrossRequests(t *testing.T) {
env := newCaptchaTestEnv(t, true)
stub := &stubVerifier{fn: func(_ context.Context, _, _, _ string) (*captcha.Result, error) {
Expand Down
8 changes: 4 additions & 4 deletions plugins/mfa/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -1294,13 +1294,13 @@ func (p *Plugin) handleSMSSend(ctx forge.Context, req *SMSSendRequest) (*SMSSend
// got the code.
phone := enrollment.Secret // Phone stored as the enrollment secret
if req.Phone != "" && req.Phone != phone && !enrollment.Verified {
if err := p.requireStepUp(ctx, userID, ""); err != nil {
return nil, err
if stepErr := p.requireStepUp(ctx, userID, ""); stepErr != nil {
return nil, stepErr
}
enrollment.Secret = req.Phone
enrollment.UpdatedAt = time.Now()
if err := p.store.UpdateEnrollment(ctx.Context(), enrollment); err != nil {
return nil, middleware.InternalError(ctx, fmt.Errorf("failed to update SMS enrollment: %w", err))
if updErr := p.store.UpdateEnrollment(ctx.Context(), enrollment); updErr != nil {
return nil, middleware.InternalError(ctx, fmt.Errorf("failed to update SMS enrollment: %w", updErr))
}
phone = req.Phone
}
Expand Down
2 changes: 1 addition & 1 deletion plugins/mfa/plugin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import (
"bytes"
"context"
"encoding/json"
"github.com/pquerna/otp/totp"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/pquerna/otp/totp"
log "github.com/xraph/go-utils/log"

"github.com/stretchr/testify/assert"
Expand Down
31 changes: 15 additions & 16 deletions plugins/mfa/ratelimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,17 @@ import (
wardenmem "github.com/xraph/warden/store/memory"
)

// newMFARateLimited builds an engine with rate limiting enabled at the given
// MFA-challenge limit, mounts the MFA plugin routes, and returns the handler.
func newMFARateLimited(t *testing.T, limit int) http.Handler {
// mfaChallengeLimit is the MFA-challenge limit newMFARateLimited configures.
const mfaChallengeLimit = 3

// newMFARateLimited builds an engine with rate limiting enabled at
// mfaChallengeLimit, mounts the MFA plugin routes, and returns the handler.
func newMFARateLimited(t *testing.T) http.Handler {
t.Helper()
cfg := authsome.DefaultConfig()
cfg.AppID = "aapp_01jf0000000000000000000000"
cfg.RateLimit.Enabled = true
cfg.RateLimit.MFAChallengeLimit = limit
cfg.RateLimit.MFAChallengeLimit = mfaChallengeLimit
cfg.RateLimit.WindowSeconds = 60

w, err := warden.NewEngine(warden.WithStore(wardenmem.New()))
Expand Down Expand Up @@ -55,11 +58,10 @@ func newMFARateLimited(t *testing.T, limit int) http.Handler {
// throttled: past the MFAChallengeLimit, further attempts return 429. Without
// this an attacker can brute-force the 6-digit code space unthrottled.
func TestMFAVerify_RateLimited(t *testing.T) {
const limit = 3
h := newMFARateLimited(t, limit)
h := newMFARateLimited(t)

var lastCode int
for i := 0; i < limit+1; i++ {
for i := 0; i < mfaChallengeLimit+1; i++ {
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/mfa/verify", nil)
req.RemoteAddr = "203.0.113.7:5555"
rec := httptest.NewRecorder()
Expand All @@ -73,11 +75,10 @@ func TestMFAVerify_RateLimited(t *testing.T) {

// TestMFASMSVerify_RateLimited pins the same protection on the SMS verify route.
func TestMFASMSVerify_RateLimited(t *testing.T) {
const limit = 3
h := newMFARateLimited(t, limit)
h := newMFARateLimited(t)

var lastCode int
for i := 0; i < limit+1; i++ {
for i := 0; i < mfaChallengeLimit+1; i++ {
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/mfa/sms/verify", nil)
req.RemoteAddr = "203.0.113.8:5555"
rec := httptest.NewRecorder()
Expand All @@ -92,11 +93,10 @@ func TestMFASMSVerify_RateLimited(t *testing.T) {
// TestMFARecoveryRegenerate_RateLimited pins that regenerate, which accepts a
// TOTP code, is throttled like the other code-submission routes.
func TestMFARecoveryRegenerate_RateLimited(t *testing.T) {
const limit = 3
h := newMFARateLimited(t, limit)
h := newMFARateLimited(t)

var lastCode int
for i := 0; i < limit+1; i++ {
for i := 0; i < mfaChallengeLimit+1; i++ {
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/mfa/recovery/regenerate", nil)
req.RemoteAddr = "203.0.113.9:5555"
rec := httptest.NewRecorder()
Expand All @@ -113,14 +113,13 @@ func TestMFARecoveryRegenerate_RateLimited(t *testing.T) {
// factor) and DELETE /enrollment (turning MFA off). Without it a stolen
// session can guess the code that removes the second factor.
func TestMFAEnrollAndDisable_RateLimited(t *testing.T) {
const limit = 3
for _, c := range []struct{ method, path, addr string }{
{"POST", "/v1/mfa/enroll", "203.0.113.10:5555"},
{"DELETE", "/v1/mfa/enrollment", "203.0.113.11:5555"},
} {
h := newMFARateLimited(t, limit)
h := newMFARateLimited(t)
var lastCode int
for i := 0; i < limit+1; i++ {
for i := 0; i < mfaChallengeLimit+1; i++ {
req := httptest.NewRequestWithContext(context.Background(), c.method, c.path, nil)
req.RemoteAddr = c.addr
rec := httptest.NewRecorder()
Expand Down
Loading
Loading