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

+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)