|
| 1 | +package sessions_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "net/http" |
| 7 | + "net/http/httptest" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/alicebob/miniredis/v2" |
| 11 | + "github.com/redis/go-redis/v9" |
| 12 | + "github.com/stretchr/testify/assert" |
| 13 | + "github.com/stretchr/testify/require" |
| 14 | + |
| 15 | + "github.com/theopenlane/iam/sessions" |
| 16 | +) |
| 17 | + |
| 18 | +// errDeleteSession simulates a backing-store failure when deleting a persisted session |
| 19 | +var errDeleteSession = errors.New("delete failed") |
| 20 | + |
| 21 | +// failingDeleteStore wraps a PersistentStore but always fails DeleteSession, used to exercise the |
| 22 | +// error path of DestroySession |
| 23 | +type failingDeleteStore struct { |
| 24 | + sessions.PersistentStore |
| 25 | +} |
| 26 | + |
| 27 | +// DeleteSession always returns an error |
| 28 | +func (failingDeleteStore) DeleteSession(context.Context, string) error { |
| 29 | + return errDeleteSession |
| 30 | +} |
| 31 | + |
| 32 | +// newDestroyTestConfig builds a redis-backed session config sharing a single named cookie config |
| 33 | +// between the cookie store and the session config, mirroring how the server wires sessions |
| 34 | +func newDestroyTestConfig(t *testing.T) (sessions.SessionConfig, sessions.Store[map[string]any], *miniredis.Miniredis) { |
| 35 | + t.Helper() |
| 36 | + |
| 37 | + mr, err := miniredis.Run() |
| 38 | + require.NoError(t, err) |
| 39 | + |
| 40 | + rc := redis.NewClient(&redis.Options{Addr: mr.Addr()}) |
| 41 | + |
| 42 | + cc := sessions.DebugOnlyCookieConfig |
| 43 | + sm := sessions.NewCookieStore[map[string]any](cc, []byte("my-signing-secret"), []byte("encryptionsecret")) |
| 44 | + |
| 45 | + sc := sessions.NewSessionConfig(sm, sessions.WithPersistence(rc)) |
| 46 | + sc.CookieConfig = cc |
| 47 | + |
| 48 | + return sc, sm, mr |
| 49 | +} |
| 50 | + |
| 51 | +// requestWithSessionCookie creates a session in the store and returns a request carrying its cookie |
| 52 | +func requestWithSessionCookie(t *testing.T, sc sessions.SessionConfig, userID string) *http.Request { |
| 53 | + t.Helper() |
| 54 | + |
| 55 | + createRec := httptest.NewRecorder() |
| 56 | + _, err := sc.CreateAndStoreSession(context.Background(), createRec, userID) |
| 57 | + require.NoError(t, err) |
| 58 | + |
| 59 | + req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/logout", nil) |
| 60 | + for _, c := range createRec.Result().Cookies() { |
| 61 | + req.AddCookie(c) |
| 62 | + } |
| 63 | + |
| 64 | + return req |
| 65 | +} |
| 66 | + |
| 67 | +func TestDestroySession(t *testing.T) { |
| 68 | + ctx := context.Background() |
| 69 | + |
| 70 | + t.Run("removes the persisted session and expires the cookie", func(t *testing.T) { |
| 71 | + sc, _, mr := newDestroyTestConfig(t) |
| 72 | + defer mr.Close() |
| 73 | + |
| 74 | + req := requestWithSessionCookie(t, sc, "user-123") |
| 75 | + |
| 76 | + session, err := sc.SessionManager.Get(req, sc.CookieConfig.Name) |
| 77 | + require.NoError(t, err) |
| 78 | + |
| 79 | + sessionID := sc.SessionManager.GetSessionIDFromCookie(session) |
| 80 | + require.NotEmpty(t, sessionID) |
| 81 | + |
| 82 | + exists, err := sc.RedisStore.Exists(ctx, sessionID) |
| 83 | + require.NoError(t, err) |
| 84 | + require.Equal(t, int64(1), exists) |
| 85 | + |
| 86 | + destroyRec := httptest.NewRecorder() |
| 87 | + err = sc.DestroySession(ctx, destroyRec, req) |
| 88 | + require.NoError(t, err) |
| 89 | + |
| 90 | + // the persisted session is gone |
| 91 | + exists, err = sc.RedisStore.Exists(ctx, sessionID) |
| 92 | + require.NoError(t, err) |
| 93 | + assert.Equal(t, int64(0), exists) |
| 94 | + |
| 95 | + // the cookie is expired on the response |
| 96 | + cookies := destroyRec.Result().Cookies() |
| 97 | + require.Len(t, cookies, 1) |
| 98 | + assert.Equal(t, sc.CookieConfig.Name, cookies[0].Name) |
| 99 | + assert.Equal(t, -1, cookies[0].MaxAge) |
| 100 | + }) |
| 101 | + |
| 102 | + t.Run("no session cookie is a no-op that still returns nil", func(t *testing.T) { |
| 103 | + sc, _, mr := newDestroyTestConfig(t) |
| 104 | + defer mr.Close() |
| 105 | + |
| 106 | + req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/logout", nil) |
| 107 | + rec := httptest.NewRecorder() |
| 108 | + |
| 109 | + err := sc.DestroySession(ctx, rec, req) |
| 110 | + assert.NoError(t, err) |
| 111 | + }) |
| 112 | + |
| 113 | + t.Run("malformed session cookie is a no-op that still returns nil", func(t *testing.T) { |
| 114 | + sc, _, mr := newDestroyTestConfig(t) |
| 115 | + defer mr.Close() |
| 116 | + |
| 117 | + req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/logout", nil) |
| 118 | + req.AddCookie(&http.Cookie{ |
| 119 | + Name: sc.CookieConfig.Name, |
| 120 | + Value: "not-a-valid-encoded-cookie", |
| 121 | + Secure: true, |
| 122 | + HttpOnly: true, |
| 123 | + SameSite: http.SameSiteStrictMode, |
| 124 | + }) |
| 125 | + |
| 126 | + rec := httptest.NewRecorder() |
| 127 | + |
| 128 | + err := sc.DestroySession(ctx, rec, req) |
| 129 | + assert.NoError(t, err) |
| 130 | + }) |
| 131 | + |
| 132 | + t.Run("returns an error and keeps the cookie when the persisted session cannot be deleted", func(t *testing.T) { |
| 133 | + sc, _, mr := newDestroyTestConfig(t) |
| 134 | + defer mr.Close() |
| 135 | + |
| 136 | + req := requestWithSessionCookie(t, sc, "user-err") |
| 137 | + |
| 138 | + // swap in a store whose DeleteSession always fails |
| 139 | + failing := sc |
| 140 | + failing.RedisStore = failingDeleteStore{PersistentStore: sc.RedisStore} |
| 141 | + |
| 142 | + destroyRec := httptest.NewRecorder() |
| 143 | + err := failing.DestroySession(ctx, destroyRec, req) |
| 144 | + |
| 145 | + // the failure is surfaced, not swallowed |
| 146 | + assert.ErrorIs(t, err, errDeleteSession) |
| 147 | + |
| 148 | + // the cookie is NOT expired, so the client is forced to retry rather than believe it logged out |
| 149 | + assert.Empty(t, destroyRec.Result().Cookies()) |
| 150 | + }) |
| 151 | + |
| 152 | + t.Run("expires the cookie without a persistent store", func(t *testing.T) { |
| 153 | + cc := sessions.DebugOnlyCookieConfig |
| 154 | + sm := sessions.NewCookieStore[map[string]any](cc, []byte("my-signing-secret"), []byte("encryptionsecret")) |
| 155 | + |
| 156 | + // no WithPersistence, so RedisStore is nil |
| 157 | + sc := sessions.NewSessionConfig(sm) |
| 158 | + sc.CookieConfig = cc |
| 159 | + require.Nil(t, sc.RedisStore) |
| 160 | + |
| 161 | + // manually create a session cookie using the same store |
| 162 | + setRec := httptest.NewRecorder() |
| 163 | + session := sm.New(cc.Name) |
| 164 | + session.Set(sessions.GenerateSessionID(), map[string]any{sessions.UserIDKey: "user-x"}) |
| 165 | + require.NoError(t, session.Save(setRec)) |
| 166 | + |
| 167 | + req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/logout", nil) |
| 168 | + for _, c := range setRec.Result().Cookies() { |
| 169 | + req.AddCookie(c) |
| 170 | + } |
| 171 | + |
| 172 | + destroyRec := httptest.NewRecorder() |
| 173 | + err := sc.DestroySession(ctx, destroyRec, req) |
| 174 | + assert.NoError(t, err) |
| 175 | + |
| 176 | + cookies := destroyRec.Result().Cookies() |
| 177 | + require.Len(t, cookies, 1) |
| 178 | + assert.Equal(t, -1, cookies[0].MaxAge) |
| 179 | + }) |
| 180 | +} |
| 181 | + |
| 182 | +// TestCookieStoreDestroy covers the fix that makes Store.Destroy build the deletion cookie from the |
| 183 | +// full store config rather than only the path, so it reliably matches the original cookie |
| 184 | +func TestCookieStoreDestroy(t *testing.T) { |
| 185 | + t.Run("replaces the original cookie with an expired one matching its identity", func(t *testing.T) { |
| 186 | + cfg := &sessions.CookieConfig{ |
| 187 | + Name: "sess", |
| 188 | + Domain: "example.com", |
| 189 | + Path: "/app", |
| 190 | + Secure: true, |
| 191 | + HTTPOnly: true, |
| 192 | + SameSite: http.SameSiteStrictMode, |
| 193 | + } |
| 194 | + cs := sessions.NewCookieStore[map[string]any](cfg, []byte("my-signing-secret"), []byte("encryptionsecret")) |
| 195 | + |
| 196 | + // set a real session cookie and capture the original that we intend to remove |
| 197 | + setRec := httptest.NewRecorder() |
| 198 | + session := cs.New(cfg.Name) |
| 199 | + session.Set(sessions.GenerateSessionID(), map[string]any{sessions.UserIDKey: "user-x"}) |
| 200 | + require.NoError(t, session.Save(setRec)) |
| 201 | + |
| 202 | + setCookies := setRec.Result().Cookies() |
| 203 | + require.Len(t, setCookies, 1) |
| 204 | + |
| 205 | + original := setCookies[0] |
| 206 | + require.NotEmpty(t, original.Value) |
| 207 | + require.Equal(t, "example.com", original.Domain) // the attribute the buggy deletion dropped |
| 208 | + |
| 209 | + // destroy and capture the deletion cookie |
| 210 | + destroyRec := httptest.NewRecorder() |
| 211 | + cs.Destroy(destroyRec, cfg.Name) |
| 212 | + |
| 213 | + delCookies := destroyRec.Result().Cookies() |
| 214 | + require.Len(t, delCookies, 1) |
| 215 | + |
| 216 | + deletion := delCookies[0] |
| 217 | + |
| 218 | + // the deletion cookie must share the original's identity (name+domain+path) and security |
| 219 | + // attributes, otherwise the browser stores a second, non-matching cookie and keeps the original. |
| 220 | + // This is exactly what the old Destroy did by dropping Domain/Secure/SameSite |
| 221 | + assert.Equal(t, original.Name, deletion.Name) |
| 222 | + assert.Equal(t, original.Domain, deletion.Domain) |
| 223 | + assert.Equal(t, original.Path, deletion.Path) |
| 224 | + assert.Equal(t, original.Secure, deletion.Secure) |
| 225 | + assert.Equal(t, original.SameSite, deletion.SameSite) |
| 226 | + |
| 227 | + // and it must actually expire and empty the value so the original is replaced, not duplicated |
| 228 | + assert.Equal(t, -1, deletion.MaxAge) |
| 229 | + assert.Empty(t, deletion.Value) |
| 230 | + }) |
| 231 | + |
| 232 | + t.Run("sets no cookie when no name can be resolved", func(t *testing.T) { |
| 233 | + cfg := &sessions.CookieConfig{Path: "/"} // empty Name |
| 234 | + cs := sessions.NewCookieStore[map[string]any](cfg, []byte("my-signing-secret"), []byte("encryptionsecret")) |
| 235 | + |
| 236 | + rec := httptest.NewRecorder() |
| 237 | + cs.Destroy(rec, "") // empty name and empty config name resolves to no cookie |
| 238 | + |
| 239 | + assert.Empty(t, rec.Result().Cookies()) |
| 240 | + }) |
| 241 | +} |
0 commit comments