diff --git a/.gitleaks.toml b/.gitleaks.toml index 26dd20b3..c5f5cee6 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -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$''', ] diff --git a/api/delegated_plugin_admin_test.go b/api/delegated_plugin_admin_test.go index 8ad412d9..ae76a48c 100644 --- a/api/delegated_plugin_admin_test.go +++ b/api/delegated_plugin_admin_test.go @@ -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()) diff --git a/go.mod b/go.mod index 12d0e2d9..e928e023 100644 --- a/go.mod +++ b/go.mod @@ -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 diff --git a/go.sum b/go.sum index 44fed64d..6664f7a3 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/middleware/captcha.go b/middleware/captcha.go index 1c00e3fa..f913d83f 100644 --- a/middleware/captcha.go +++ b/middleware/captcha.go @@ -1,10 +1,13 @@ package middleware import ( + "bytes" "context" "encoding/json" "errors" + "io" "net/http" + "strings" "sync" log "github.com/xraph/go-utils/log" @@ -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. diff --git a/middleware/captcha_test.go b/middleware/captcha_test.go index b917e65e..de0e93e7 100644 --- a/middleware/captcha_test.go +++ b/middleware/captcha_test.go @@ -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) { diff --git a/plugins/mfa/plugin.go b/plugins/mfa/plugin.go index a95d74aa..87268619 100644 --- a/plugins/mfa/plugin.go +++ b/plugins/mfa/plugin.go @@ -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 } diff --git a/plugins/mfa/plugin_test.go b/plugins/mfa/plugin_test.go index 2e2a0636..c1e108a3 100644 --- a/plugins/mfa/plugin_test.go +++ b/plugins/mfa/plugin_test.go @@ -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" diff --git a/plugins/mfa/ratelimit_test.go b/plugins/mfa/ratelimit_test.go index 6815e0f6..b6d6c50c 100644 --- a/plugins/mfa/ratelimit_test.go +++ b/plugins/mfa/ratelimit_test.go @@ -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())) @@ -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() @@ -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() @@ -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() @@ -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() diff --git a/plugins/mfa/verify_session_test.go b/plugins/mfa/verify_session_test.go index 41a2f913..ffa0a3e9 100644 --- a/plugins/mfa/verify_session_test.go +++ b/plugins/mfa/verify_session_test.go @@ -10,15 +10,14 @@ import ( "time" "github.com/pquerna/otp/totp" - "github.com/xraph/authsome/session" - "github.com/xraph/forge" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/xraph/forge" "github.com/xraph/authsome/bridge" "github.com/xraph/authsome/id" "github.com/xraph/authsome/middleware" + "github.com/xraph/authsome/session" ) type recordingStamper struct { @@ -98,11 +97,11 @@ func TestRecoveryVerify_StampsTheSession(t *testing.T) { require.NoError(t, err) require.NoError(t, s.CreateRecoveryCodes(context.Background(), codes)) - rec, sid := postAs(t, h, "/v1/mfa/recovery/verify", map[string]string{"code": "wrong"}, uid) + rec, _ := postAs(t, h, "/v1/mfa/recovery/verify", map[string]string{"code": "wrong"}, uid) assert.Equal(t, http.StatusUnauthorized, rec.Code) assert.Zero(t, r.calls, "a wrong code stamps nothing") - rec, sid = postAs(t, h, "/v1/mfa/recovery/verify", map[string]string{"code": plain[0]}, uid) + rec, sid := postAs(t, h, "/v1/mfa/recovery/verify", map[string]string{"code": plain[0]}, uid) require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) assert.Equal(t, 1, r.calls) assert.Equal(t, sid, r.sid) @@ -111,7 +110,7 @@ func TestRecoveryVerify_StampsTheSession(t *testing.T) { func TestSMSVerify_StampsTheSession(t *testing.T) { p, s, r, h := stampingPlugin(t) uid := id.NewUserID() - smsEnrollment(t, s, uid, "+15550001", true) + smsEnrollment(t, s, uid, true) raw, err := json.Marshal(SMSChallenge{Code: "123456", ExpiresAt: time.Now().Add(time.Minute)}) require.NoError(t, err) require.NoError(t, p.ceremonies.Set(context.Background(), "mfa:sms:"+uid.String(), raw, time.Minute)) @@ -149,10 +148,13 @@ func (r *recordingSMS) SendSMS(_ context.Context, msg *bridge.SMSMessage) error return nil } -func smsEnrollment(t *testing.T, s *MemoryStore, uid id.UserID, phone string, verified bool) { +// smsPhone is the number every SMS enrollment in these tests is made with. +const smsPhone = "+15550001" + +func smsEnrollment(t *testing.T, s *MemoryStore, uid id.UserID, verified bool) { t.Helper() require.NoError(t, s.CreateEnrollment(context.Background(), &Enrollment{ - ID: id.NewMFAID(), UserID: uid, Method: "sms", Secret: phone, Verified: verified, + ID: id.NewMFAID(), UserID: uid, Method: "sms", Secret: smsPhone, Verified: verified, CreatedAt: time.Now(), UpdatedAt: time.Now(), })) } @@ -174,7 +176,7 @@ func TestSMSSend_VerifiedEnrollmentIgnoresThePhoneOverride(t *testing.T) { sms := &recordingSMS{} p.SetSMSSender(sms) uid := id.NewUserID() - smsEnrollment(t, s, uid, "+15550001", true) + smsEnrollment(t, s, uid, true) rec, _ := postAs(t, h, "/v1/mfa/sms/send", map[string]string{"phone": "+15559999"}, uid) require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) @@ -196,7 +198,7 @@ func TestSMSSend_UnverifiedEnrollmentOverrideConfirmsWithoutStamping(t *testing. sms := &recordingSMS{} p.SetSMSSender(sms) uid := id.NewUserID() - smsEnrollment(t, s, uid, "+15550001", false) + smsEnrollment(t, s, uid, false) rec, _ := postAs(t, h, "/v1/mfa/sms/send", map[string]string{"phone": "+15550002"}, uid) require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) @@ -222,7 +224,7 @@ func TestSMSSend_UnverifiedOverrideNeedsTheExistingFactor(t *testing.T) { ID: id.NewMFAID(), UserID: uid, Method: "totp", Secret: "JBSWY3DPEHPK3PXP", Verified: true, CreatedAt: time.Now(), UpdatedAt: time.Now(), })) - smsEnrollment(t, s, uid, "+15550001", false) + smsEnrollment(t, s, uid, false) rec, _ := postAs(t, h, "/v1/mfa/sms/send", map[string]string{"phone": "+15559999"}, uid) assert.Equal(t, http.StatusUnauthorized, rec.Code, rec.Body.String()) diff --git a/plugins/organization/handlers.go b/plugins/organization/handlers.go index 80c446ee..b2866121 100644 --- a/plugins/organization/handlers.go +++ b/plugins/organization/handlers.go @@ -639,12 +639,12 @@ func (p *Plugin) handleListInvitations(ctx forge.Context, req *ListInvitationsRe // an invitation: the caller is an admin of the org, and may grant the role the // invitation carries (an admin cannot touch an owner's invitation). It returns // the invitation's org and ID. -func (p *Plugin) authorizeInvitationChange(ctx forge.Context) (id.OrgID, id.InvitationID, error) { - orgID, err := id.ParseOrgID(ctx.Param("orgId")) +func (p *Plugin) authorizeInvitationChange(ctx forge.Context) (orgID id.OrgID, invID id.InvitationID, err error) { + orgID, err = id.ParseOrgID(ctx.Param("orgId")) if err != nil { return id.OrgID{}, id.InvitationID{}, forge.BadRequest(fmt.Sprintf("invalid org id: %v", err)) } - invID, err := id.ParseInvitationID(ctx.Param("invitationId")) + invID, err = id.ParseInvitationID(ctx.Param("invitationId")) if err != nil { return id.OrgID{}, id.InvitationID{}, forge.BadRequest(fmt.Sprintf("invalid invitation id: %v", err)) } diff --git a/plugins/organization/invitation_accept_test.go b/plugins/organization/invitation_accept_test.go index 36434d46..c1da15d9 100644 --- a/plugins/organization/invitation_accept_test.go +++ b/plugins/organization/invitation_accept_test.go @@ -230,13 +230,12 @@ func TestInvitationTokens_onlyAVerifiedAddressCounts(t *testing.T) { appID, err := id.ParseAppID(orgTestAppID) require.NoError(t, err) - invite := func(email, token string) *organization.Invitation { + invite := func(email, token string) { inv := &organization.Invitation{ ID: id.NewInvitationID(), OrgID: f.org.ID, Email: email, Role: organization.RoleMember, Status: organization.InvitationPending, Token: token, } require.NoError(t, f.plugin.CreateInvitation(ctx, inv)) - return inv } signUp := func(email string) id.UserID { u, _, err := f.eng.SignUp(ctx, &account.SignUpRequest{AppID: appID, Email: email, Password: "SecureP@ss123", FirstName: "T"}) diff --git a/plugins/organization/service.go b/plugins/organization/service.go index c4a24321..42560918 100644 --- a/plugins/organization/service.go +++ b/plugins/organization/service.go @@ -455,7 +455,9 @@ func (p *Plugin) sendInvitationEmail(ctx context.Context, inv *organization.Invi var sender invitationSender if p.plugins != nil { if np := p.plugins.Plugin("notification"); np != nil { - sender, _ = np.(invitationSender) + if s, ok := np.(invitationSender); ok { + sender = s + } } } if sender == nil { diff --git a/plugins/waitlist/plugin.go b/plugins/waitlist/plugin.go index 1ed9257c..3a0aeb86 100644 --- a/plugins/waitlist/plugin.go +++ b/plugins/waitlist/plugin.go @@ -103,16 +103,18 @@ func (p *Plugin) OnInit(_ context.Context, engine plugin.Engine) error { p.logger = engine.Logger() p.settingsMgr = engine.Settings() p.defaultAppID = engine.DefaultAppID() - p.basePath = engine.BasePath() + // The router plugins register on is already grouped at the app's base + // path (extension/extension.go groups it before handing it over), so + // the routes carry only the version segment. engine.BasePath() here put + // them at /authsome/authsome/waitlist/join, while the UI client posts to + // {baseURL}/v1/waitlist/join. agentauth and consent use "/v1" for the + // same reason. + p.basePath = "/v1" if pc, ok := engine.(plugin.PermissionChecker); ok { p.permChecker = pc } - if p.basePath == "" { - p.basePath = "/v1" - } - return nil } @@ -632,6 +634,14 @@ func (p *Plugin) resolveAppID(ctx forge.Context, reqAppID string) (id.AppID, err if reqAppID != "" { return id.ParseAppID(reqAppID) } + // The publishable key (or an authenticated caller's tenant) puts the + // app on authsome's own context key, not forge's scope. The UI client's + // join sends nothing but the key, so without this every join from the + // sign-up form failed with "unable to determine app_id" on a host that + // has no single default app. + if keyApp, ok := middleware.AppIDFrom(ctx.Context()); ok && !keyApp.IsNil() { + return keyApp, nil + } if scopeAppID := forge.AppIDFrom(ctx.Context()); scopeAppID != "" { return id.ParseAppID(scopeAppID) } diff --git a/plugins/waitlist/routes_test.go b/plugins/waitlist/routes_test.go new file mode 100644 index 00000000..50fb0397 --- /dev/null +++ b/plugins/waitlist/routes_test.go @@ -0,0 +1,83 @@ +package waitlist + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/xraph/forge" + + authsome "github.com/xraph/authsome" + "github.com/xraph/authsome/id" + "github.com/xraph/authsome/internal/secutil" + "github.com/xraph/authsome/middleware" +) + +// The extension groups the router at the app's base path before plugins +// see it, and the UI client posts to {baseURL}/v1/waitlist/join. The +// plugin must therefore register under /v1 only. Prefixing the base path +// again put the routes at /authsome/authsome/waitlist/join, where nothing +// calls them. +func TestWaitlist_RoutesSitUnderV1NotTheBasePathAgain(t *testing.T) { + cfg := authsome.DefaultConfig() + cfg.AppID = "aapp_01jf0000000000000000000000" + cfg.BasePath = "/authsome" + p := New() + _ = secutil.NewTestEngine(t, authsome.WithConfig(cfg), authsome.WithPlugin(p)) + + root := forge.NewRouter() + require.NoError(t, p.RegisterRoutes(root.Group(cfg.BasePath))) + h := root.Handler() + + post := func(path string) int { + req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, path, strings.NewReader(`{"email":"joiner@example.com"}`)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec.Code + } + assert.NotEqual(t, http.StatusNotFound, post("/authsome/v1/waitlist/join"), "join must be where the UI client posts") + assert.Equal(t, http.StatusNotFound, post("/authsome/authsome/waitlist/join"), "the base path must not appear twice") +} + +// The UI client joins with only a publishable key, which the publishable-key +// middleware turns into an app on authsome's own context key. Reading only +// forge's scope missed it, so every join from the sign-up form failed with +// "unable to determine app_id" on a host with more than one app. +func TestWaitlist_JoinTakesTheAppFromThePublishableKey(t *testing.T) { + cfg := authsome.DefaultConfig() + cfg.AppID = "aapp_01jf0000000000000000000000" + p := New() + _ = secutil.NewTestEngine(t, authsome.WithConfig(cfg), authsome.WithPlugin(p)) + p.defaultAppID = "" // a multi-app host has no single default to fall back on + + keyApp := id.NewAppID() + root := forge.NewRouter() + // What PublishableKeyMiddleware does with a valid key. + root.Use(func(next forge.Handler) forge.Handler { + return func(ctx forge.Context) error { + ctx.WithContext(middleware.WithAppID(ctx.Context(), keyApp)) + return next(ctx) + } + }) + require.NoError(t, p.RegisterRoutes(root)) + h := root.Handler() + + join := func(body string) *httptest.ResponseRecorder { + req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/v1/waitlist/join", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec + } + + rec := join(`{"email":"joiner@example.com"}`) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + entry, err := p.store.GetEntryByEmail(context.Background(), keyApp, "joiner@example.com") + require.NoError(t, err) + assert.Equal(t, keyApp, entry.AppID, "the entry belongs to the key's app") +} diff --git a/store/postgres/machine_api_key_test.go b/store/postgres/machine_api_key_test.go index e0f737aa..130a2e80 100644 --- a/store/postgres/machine_api_key_test.go +++ b/store/postgres/machine_api_key_test.go @@ -360,6 +360,7 @@ func TestMigration_MachineAPIKeyOwners(t *testing.T) { }) t.Run("non destructive downgrade", func(t *testing.T) { orchestrator := migrate.NewOrchestrator(pgmigrate.New(db), pgstore.Migrations) + rollbackToMachineKeyOwners(t, db, orchestrator) _, rollbackErr := orchestrator.Rollback(ctx) require.ErrorContains(t, rollbackErr, "while machine keys exist") checkMachineKey(t, s, &machine, sa) @@ -419,11 +420,37 @@ func assertKeyPreserved(t *testing.T, want, got *apikey.APIKey) { require.Equal(t, want, &normalized) } +// machineKeyOwnersVersion is the api_key_machine_owners migration, the one +// whose Down the downgrade tests exercise. +const machineKeyOwnersVersion = "20261009000001" + +// rollbackToMachineKeyOwners undoes every migration applied after +// api_key_machine_owners. Rollback only ever reverses the newest migration, +// so without this the downgrade tests would stop exercising its Down as soon +// as a later migration lands. +func rollbackToMachineKeyOwners(t *testing.T, db *pgdriver.PgDB, orchestrator *migrate.Orchestrator) { + t.Helper() + ctx := context.Background() + exec := pgmigrate.New(db) + for { + applied, err := exec.ListApplied(ctx) + require.NoError(t, err) + require.NotEmpty(t, applied, "api_key_machine_owners is not applied") + if applied[len(applied)-1].Version == machineKeyOwnersVersion { + return + } + _, err = orchestrator.Rollback(ctx) + require.NoError(t, err) + } +} + func TestMigration_MachineAPIKeyDowngradeWaitsForIssuer(t *testing.T) { s, db := setupTestDatabase(t, true) ctx := context.Background() a := createTestApp(t, s, "rollback-race") sa := machineAccount(t, s, a.ID, "concurrent-issuer") + orchestrator := migrate.NewOrchestrator(pgmigrate.New(db), pgstore.Migrations) + rollbackToMachineKeyOwners(t, db, orchestrator) tx, err := db.BeginTx(ctx, nil) require.NoError(t, err) defer func() { _ = tx.Rollback() }() // Cleanup after commit or test failure. @@ -432,7 +459,7 @@ func TestMigration_MachineAPIKeyDowngradeWaitsForIssuer(t *testing.T) { require.NoError(t, err) finished := make(chan error, 1) go func() { - _, rollbackErr := migrate.NewOrchestrator(pgmigrate.New(db), pgstore.Migrations).Rollback(ctx) + _, rollbackErr := orchestrator.Rollback(ctx) finished <- rollbackErr }() require.Eventually(t, func() bool { diff --git a/ui/packages/components/src/components/auto-config-flow.test.tsx b/ui/packages/components/src/components/auto-config-flow.test.tsx index a7b24ebf..9e1e06d4 100644 --- a/ui/packages/components/src/components/auto-config-flow.test.tsx +++ b/ui/packages/components/src/components/auto-config-flow.test.tsx @@ -14,8 +14,18 @@ import { } from "../test-support"; vi.mock("./turnstile-widget", () => ({ - TurnstileWidget: ({ onToken }: { onToken: (token: string) => void }) => ( - ), @@ -212,6 +222,41 @@ describe("AutoConfig Continue", () => { }); describe("captcha retries and verification", () => { + // The server's captcha middleware binds each route to an action + // ("signup", "signin") and refuses a token whose action doesn't match. + // A widget rendered without one issues tokens with an empty action, so + // every real submission came back captcha_invalid. + it("binds the widget to the action the server checks", async () => { + const captcha = { + captcha: { required: true, provider: "turnstile", site_key: "site" }, + }; + const signIn = render( + withProvider(, { + fetch: routedFetch({}).fetchFn, + session: null, + clientConfig: captcha, + }), + ); + email(); + await screen.findByLabelText("Password"); + expect( + screen.getByText("Complete captcha").getAttribute("data-action"), + ).toBe("signin"); + signIn.unmount(); + + render( + withProvider(, { + fetch: routedFetch({}).fetchFn, + session: null, + clientConfig: captcha, + }), + ); + email(); + await screen.findByLabelText("Password"); + expect( + screen.getByText("Complete captcha").getAttribute("data-action"), + ).toBe("signup"); + }); it("blocks a required captcha with missing configuration, including form submission", async () => { const { fetchFn, calls } = routedFetch({}); render( diff --git a/ui/packages/components/src/components/sign-in-form.tsx b/ui/packages/components/src/components/sign-in-form.tsx index e3a0a702..70b4ec81 100644 --- a/ui/packages/components/src/components/sign-in-form.tsx +++ b/ui/packages/components/src/components/sign-in-form.tsx @@ -805,6 +805,9 @@ export function SignInForm({ setCaptchaToken(null)} onError={() => setCaptchaToken(null)} diff --git a/ui/packages/components/src/components/sign-up-form.tsx b/ui/packages/components/src/components/sign-up-form.tsx index 8b397750..4699277f 100644 --- a/ui/packages/components/src/components/sign-up-form.tsx +++ b/ui/packages/components/src/components/sign-up-form.tsx @@ -703,6 +703,9 @@ export function SignUpForm({ setCaptchaToken(null)} onError={() => setCaptchaToken(null)}