feat(identity): enforce shared session and browser request security

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 11:33:40 +03:00
1 parent 7df521bd89
commit 86f562f5b6
23 files changed
+430 -121

No files matched your search

@@ -493,6 +493,9 @@ func (harness *registrationHarness) confirm(t *testing.T, token, password string
if err != nil {
t.Fatalf("encode confirmation request: %v", err)
}
if origin == nil {
return harness.postWithoutDefaultOrigin(t, emailVerificationPath, string(body), headers)
}
return harness.post(t, emailVerificationPath, string(body), headers)
}
+82 -1
View File
@@ -73,6 +73,7 @@ type registrationHarness struct {
clock *testClock
logs *syncBuffer
identity *postgresadapter.IdentityStore
origin string
// registration is the usecase behind the router.
registration *identity.Registration
// nextKey makes every request carry a new Idempotency-Key.
@@ -170,7 +171,9 @@ func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironm
responder := problem.NewResponder(logger)
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(v1.NewIdentityHandler(
registration, v1.WithEmailConfirmation(confirmation, env.Config.AppPublicURL),
registration,
v1.WithEmailConfirmation(confirmation),
v1.WithPublicOrigin(env.Config.AppPublicURL),
)))
router, err := httpadapter.NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), responder, metrics, logger, nil)
if err != nil {
@@ -196,6 +199,7 @@ func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironm
}
return &registrationHarness{
start: start, pool: pool, router: router, sender: sender, fixture: fixture, clock: clock, logs: logs, identity: identityStore,
origin: env.Config.AppPublicURL,
registration: registration,
}
}
@@ -210,9 +214,20 @@ type registrationResponse struct {
}
func (harness *registrationHarness) post(t *testing.T, path, body string, headers map[string]string) registrationResponse {
return harness.postWithOriginDefault(t, path, body, headers, true)
}
func (harness *registrationHarness) postWithoutDefaultOrigin(t *testing.T, path, body string, headers map[string]string) registrationResponse {
return harness.postWithOriginDefault(t, path, body, headers, false)
}
func (harness *registrationHarness) postWithOriginDefault(t *testing.T, path, body string, headers map[string]string, setDefaultOrigin bool) registrationResponse {
t.Helper()
request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
request.Header.Set("Content-Type", "application/json")
if setDefaultOrigin {
request.Header.Set("Origin", harness.origin)
}
for name, value := range headers {
request.Header.Set(name, value)
}
@@ -678,6 +693,72 @@ func TestRegistrationOverHTTP(t *testing.T) {
})
}
func TestPublicIdentityOriginRefusalDoesNotMutateAccountsOrMailState(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout)
defer cancel()
harness := newRegistrationHarness(ctx, t, env, 1000)
harness.truncate(ctx, t)
harness.clock.Set(harness.start)
const verifiedFlowEmail = "origin-check@example.test"
token := harness.registerAndSendVerification(ctx, t, verifiedFlowEmail, "candidate", registrationPassword)
stateCounts := func() map[string]int {
t.Helper()
counts := make(map[string]int)
for _, table := range []string{"users", "consent_records", "email_tokens", "idempotency_records", "outbox_events", "deliveries"} {
counts[table] = harness.count(ctx, t, "SELECT count(*) FROM "+table)
}
return counts
}
assertCountsUnchanged := func(want map[string]int) {
t.Helper()
for table, expected := range want {
if got := harness.count(ctx, t, "SELECT count(*) FROM "+table); got != expected {
t.Errorf("%s count = %d after Origin refusal, want unchanged at %d", table, got, expected)
}
}
}
before := stateCounts()
register := harness.post(t, registrationPath,
registrationBody("rejected@example.test", "candidate", registrationPassword, registrationC1),
map[string]string{"Idempotency-Key": "origin-refused-registration", "Origin": "https://attacker.example"},
)
requireProblemStatus(t, register, http.StatusForbidden, "csrf_check_failed")
assertCountsUnchanged(before)
resend := harness.post(t, resendPath, `{"email":"`+verifiedFlowEmail+`"}`, map[string]string{"Origin": "https://attacker.example"})
requireProblemStatus(t, resend, http.StatusForbidden, "csrf_check_failed")
assertCountsUnchanged(before)
confirmation := harness.post(t, emailVerificationPath,
`{"token":"`+token+`","password":"`+registrationPassword+`"}`,
map[string]string{"Origin": "https://attacker.example"},
)
requireProblemStatus(t, confirmation, http.StatusForbidden, "csrf_check_failed")
assertCountsUnchanged(before)
var verifiedAt *time.Time
var registrationVersion int64
if err := harness.pool.QueryRow(ctx,
`SELECT email_verified_at, registration_version FROM users WHERE email_normalized = $1`, verifiedFlowEmail,
).Scan(&verifiedAt, &registrationVersion); err != nil {
t.Fatalf("read account after Origin refusals: %v", err)
}
if verifiedAt != nil || registrationVersion != 1 {
t.Fatalf("account state after refused operations: verified=%v registration version=%d", verifiedAt, registrationVersion)
}
var consumedAt, invalidatedAt *time.Time
if err := harness.pool.QueryRow(ctx,
`SELECT consumed_at, invalidated_at FROM email_tokens WHERE user_id = (SELECT id FROM users WHERE email_normalized = $1)`, verifiedFlowEmail,
).Scan(&consumedAt, &invalidatedAt); err != nil {
t.Fatalf("read verification token state after Origin refusals: %v", err)
}
if consumedAt != nil || invalidatedAt != nil {
t.Fatalf("verification token changed after Origin refusals: consumed=%v invalidated=%v", consumedAt, invalidatedAt)
}
}
func TestRegistrationClientLimit(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout)
+50 -4
View File
@@ -86,12 +86,15 @@ func newSessionHTTPHarnessWithSettings(
logger := slog.New(slog.NewJSONHandler(logs, nil))
responder := problem.NewResponder(logger)
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(service, env.Config.AppPublicURL))
identityHandler := v1.NewIdentityHandler(nil,
v1.WithSessionService(service),
v1.WithPublicOrigin(env.Config.AppPublicURL),
)
handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler))
router, err := httpadapter.NewRouter(
healthHandler,
handler,
v1.NewSessionSecurity(service, env.Config.AppPublicURL),
identityHandler.SessionSecurity(),
responder,
prometheus.New(),
logger,
@@ -323,12 +326,55 @@ func TestIdentitySessionsOverHTTP(t *testing.T) {
if sessionBody.Account.Email != verifiedEmail || !sessionBody.Account.EmailVerified || sessionBody.CSRFToken != firstBody.CSRFToken {
t.Fatalf("current session response = %+v, want the authenticated account and CSRF token", sessionBody)
}
var userVersionBefore int64
if err := harness.pool.QueryRow(ctx, `SELECT version FROM users WHERE id = $1`, verifiedUser.ID).Scan(&userVersionBefore); err != nil {
t.Fatalf("read current account version before protected reads: %v", err)
}
var outboxBefore, idempotencyBefore int64
if err := harness.pool.QueryRow(ctx,
`SELECT (SELECT count(*) FROM outbox_events), (SELECT count(*) FROM idempotency_records)`,
).Scan(&outboxBefore, &idempotencyBefore); err != nil {
t.Fatalf("read business side-effect counts before protected reads: %v", err)
}
currentAccount := harness.request(t, http.MethodGet, "/api/v1/identity/me", "", "", firstCookie.Value, "", "192.0.2.7:1234")
if currentAccount.Code != http.StatusOK || currentAccount.Header().Get("Cache-Control") != "no-store" || !strings.Contains(currentAccount.Body.String(), verifiedEmail) {
t.Fatalf("current account response = %d %s, Cache-Control=%q", currentAccount.Code, currentAccount.Body.String(), currentAccount.Header().Get("Cache-Control"))
}
unsupported := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", "", firstCookie.Value, "", "192.0.2.8:1234")
requireSessionProblem(t, unsupported, http.StatusUnauthorized, "unauthenticated")
var accountBody struct {
ID string `json:"id"`
EmailVerified bool `json:"email_verified"`
}
if err := json.Unmarshal(currentAccount.Body.Bytes(), &accountBody); err != nil {
t.Fatalf("decode current account response: %v", err)
}
if accountBody.ID != verifiedUser.ID.String() || !accountBody.EmailVerified {
t.Fatalf("current account = %+v, want verified account resolved from PostgreSQL session", accountBody)
}
guestProfile := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", "", "", "", "192.0.2.8:1234")
requireSessionProblem(t, guestProfile, http.StatusUnauthorized, "unauthenticated")
guestWrite := harness.request(t, http.MethodPut, "/api/v1/me/privacy/search-status", `{"expected_version":0,"value":"looking"}`, "", "", "", "192.0.2.9:1234")
requireSessionProblem(t, guestWrite, http.StatusUnauthorized, "unauthenticated")
unsupported := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", "", firstCookie.Value, "", "192.0.2.18:1234")
requireSessionProblem(t, unsupported, http.StatusNotImplemented, "not_implemented")
unsupportedWrite := harness.request(
t, http.MethodPut, "/api/v1/me/privacy/search-status", `{"expected_version":0,"value":"looking"}`,
sessionHTTPTestOrigin, firstCookie.Value, firstBody.CSRFToken, "192.0.2.19:1234",
)
requireSessionProblem(t, unsupportedWrite, http.StatusNotImplemented, "not_implemented")
var userVersionAfter int64
if err := harness.pool.QueryRow(ctx, `SELECT version FROM users WHERE id = $1`, verifiedUser.ID).Scan(&userVersionAfter); err != nil {
t.Fatalf("read current account version after protected reads: %v", err)
}
var outboxAfter, idempotencyAfter int64
if err := harness.pool.QueryRow(ctx,
`SELECT (SELECT count(*) FROM outbox_events), (SELECT count(*) FROM idempotency_records)`,
).Scan(&outboxAfter, &idempotencyAfter); err != nil {
t.Fatalf("read business side-effect counts after protected reads: %v", err)
}
if userVersionAfter != userVersionBefore || outboxAfter != outboxBefore || idempotencyAfter != idempotencyBefore {
t.Fatalf("protected reads changed account or business side effects: user version %d -> %d, outbox %d -> %d, idempotency %d -> %d",
userVersionBefore, userVersionAfter, outboxBefore, outboxAfter, idempotencyBefore, idempotencyAfter)
}
wrongPasswordWithSession := loginSessionHTTP(t, harness, verifiedEmail, "incorrect horse battery staple", sessionHTTPTestOrigin, firstCookie.Value, "192.0.2.9:1234")
requireSessionProblem(t, wrongPasswordWithSession, http.StatusUnauthorized, "invalid_credentials")