-
Notifications
You must be signed in to change notification settings - Fork 104
Fix session cookie being recreated on every export #2471
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rfontanarosa
wants to merge
12
commits into
master
Choose a base branch
from
rfontanarosa/1160/only-generate-new-session-cookie-when-needed
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
5064b2e
Fix session cookie being recreated on every export
rfontanarosa e567618
fixed test
rfontanarosa b2782c5
some fixes
rfontanarosa 4b30bd9
2025 -> 2026
rfontanarosa a4c65b2
Merge branch 'master' into rfontanarosa/1160/only-generate-new-sessio…
rfontanarosa a89a180
Merge branch 'master' into rfontanarosa/1160/only-generate-new-sessio…
rfontanarosa 9725ea7
Merge branch 'master' into rfontanarosa/1160/only-generate-new-sessio…
rfontanarosa 2b689f1
Merge branch 'master' into rfontanarosa/1160/only-generate-new-sessio…
rfontanarosa 6680070
Merge branch 'master' into rfontanarosa/1160/only-generate-new-sessio…
rfontanarosa cd1253f
removed agenti comment
rfontanarosa 0d4bac2
added a time buffer to avoid cookie expiring during processes
rfontanarosa da62c24
test cookie expire buffer
rfontanarosa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| /** | ||
| * Copyright 2026 The Ground Authors. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| import * as adminAuth from 'firebase-admin/auth'; | ||
| import type { Auth } from 'firebase-admin/auth'; | ||
| import { Request } from 'firebase-functions/v2/https'; | ||
| import type { Response } from 'express'; | ||
| import { StatusCodes } from 'http-status-codes'; | ||
| import { sessionLoginHandler } from './session-login'; | ||
|
|
||
| const FIVE_DAYS_MS = 60 * 60 * 24 * 5 * 1000; | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please refactor into lib. |
||
|
|
||
| describe('sessionLoginHandler', () => { | ||
| let req: Request; | ||
| let res: jasmine.SpyObj<Response>; | ||
| let createSessionCookieSpy: jasmine.Spy; | ||
|
|
||
| beforeEach(() => { | ||
| req = { | ||
| headers: { authorization: 'Bearer fake-id-token' }, | ||
| cookies: {}, | ||
| } as unknown as Request; | ||
|
|
||
| res = jasmine.createSpyObj<Response>('response', [ | ||
| 'setHeader', | ||
| 'cookie', | ||
| 'json', | ||
| 'status', | ||
| 'send', | ||
| ]); | ||
| res.status.and.returnValue(res); | ||
|
|
||
| createSessionCookieSpy = jasmine | ||
| .createSpy('createSessionCookie') | ||
| .and.resolveTo('fake-session-cookie'); | ||
| spyOn(adminAuth, 'getAuth').and.returnValue({ | ||
| createSessionCookie: createSessionCookieSpy, | ||
| } as unknown as Auth); | ||
| }); | ||
|
|
||
| it('returns expiresAt approximately 5 days in the future', async () => { | ||
| const before = Date.now(); | ||
| await sessionLoginHandler(req, res); | ||
| const after = Date.now(); | ||
|
|
||
| expect(res.json).toHaveBeenCalledOnceWith( | ||
| jasmine.objectContaining({ expiresAt: jasmine.any(Number) }) | ||
| ); | ||
| const { expiresAt } = (res.json as jasmine.Spy).calls.mostRecent().args[0]; | ||
| expect(expiresAt).toBeGreaterThanOrEqual(before + FIVE_DAYS_MS); | ||
| expect(expiresAt).toBeLessThanOrEqual(after + FIVE_DAYS_MS); | ||
| }); | ||
|
|
||
| it('sets httpOnly secure session cookie', async () => { | ||
| await sessionLoginHandler(req, res); | ||
|
|
||
| // Cast needed: Express's `cookie` overloads cause TS to resolve it as a | ||
| // 2-param function, but `setSessionCookie` calls the 3-param overload. | ||
| expect(res.cookie as jasmine.Spy).toHaveBeenCalledOnceWith( | ||
| '__session', | ||
| 'fake-session-cookie', | ||
| jasmine.objectContaining({ httpOnly: true, secure: true }) | ||
| ); | ||
| }); | ||
|
|
||
| it('returns 401 on auth error', async () => { | ||
| createSessionCookieSpy.and.rejectWith(new Error('invalid token')); | ||
|
|
||
| await sessionLoginHandler(req, res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(StatusCodes.UNAUTHORIZED); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -16,17 +16,60 @@ | |
|
|
||
| import { TestBed } from '@angular/core/testing'; | ||
| import { initializeApp, provideFirebaseApp } from '@angular/fire/app'; | ||
| import { getAuth, provideAuth } from '@angular/fire/auth'; | ||
| import { | ||
| Auth, | ||
| User as FirebaseUser, | ||
| getAuth, | ||
| provideAuth, | ||
| } from '@angular/fire/auth'; | ||
| import { Firestore } from '@angular/fire/firestore'; | ||
| import { Functions } from '@angular/fire/functions'; | ||
| import { Router } from '@angular/router'; | ||
| import { of } from 'rxjs'; | ||
|
|
||
| import { AuthService } from 'app/services/auth/auth.service'; | ||
| import { DataStoreService } from 'app/services/data-store/data-store.service'; | ||
| import { User } from 'app/models/user.model'; | ||
| import { environment } from 'environments/environment'; | ||
|
|
||
| import { HttpClientService } from '../http-client/http-client.service'; | ||
|
|
||
| const SESSION_COOKIE_EXPIRES_AT_KEY = 'sessionCookieExpiresAt'; | ||
| const FIVE_DAYS_MS = 60 * 60 * 24 * 5 * 1000; | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please use lib. |
||
|
|
||
| /** Providers shared by all describe blocks that use a mock Auth. */ | ||
| function mockAuthProviders(mockAuth: Partial<Auth>, postWithAuth: jasmine.Spy) { | ||
| return [ | ||
| { provide: Auth, useValue: mockAuth }, | ||
| { provide: Firestore, useValue: {} }, | ||
| { provide: Functions, useValue: {} }, | ||
| { | ||
| provide: DataStoreService, | ||
| useValue: { | ||
| user$: () => | ||
| of({ | ||
| id: 'user-1', | ||
| email: 'test@test.com', | ||
| displayName: 'Test User', | ||
| isAuthenticated: true, | ||
| } as User), | ||
| }, | ||
| }, | ||
| { provide: Router, useValue: { events: of() } }, | ||
| { provide: HttpClientService, useValue: { postWithAuth } }, | ||
| ]; | ||
| } | ||
|
|
||
| /** Returns a minimal Auth mock where onAuthStateChanged is a no-op. */ | ||
| function createMockAuth(onIdTokenChanged: jasmine.Spy): Partial<Auth> { | ||
| return { | ||
| onIdTokenChanged, | ||
| onAuthStateChanged: jasmine | ||
| .createSpy('onAuthStateChanged') | ||
| .and.returnValue(() => {}), | ||
| }; | ||
| } | ||
|
|
||
| describe('AuthService', () => { | ||
| beforeEach(() => { | ||
| TestBed.configureTestingModule({ | ||
|
|
@@ -50,3 +93,116 @@ describe('AuthService', () => { | |
| expect(service).toBeTruthy(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('AuthService createSessionCookie()', () => { | ||
| let service: AuthService; | ||
| let postWithAuthSpy: jasmine.Spy; | ||
| const futureExpiry = Date.now() + FIVE_DAYS_MS; | ||
|
|
||
| beforeEach(() => { | ||
| localStorage.clear(); | ||
|
|
||
| postWithAuthSpy = jasmine | ||
| .createSpy('postWithAuth') | ||
| .and.resolveTo({ expiresAt: futureExpiry }); | ||
|
|
||
| const mockAuth = createMockAuth( | ||
| jasmine.createSpy('onIdTokenChanged').and.returnValue(() => {}) | ||
| ); | ||
|
|
||
| TestBed.configureTestingModule({ | ||
| providers: mockAuthProviders(mockAuth, postWithAuthSpy), | ||
| }); | ||
|
|
||
| service = TestBed.inject(AuthService); | ||
| }); | ||
|
|
||
| afterEach(() => localStorage.clear()); | ||
|
|
||
| it('calls sessionLogin and persists expiresAt in localStorage on first call', async () => { | ||
| await service.createSessionCookie(); | ||
|
|
||
| expect(postWithAuthSpy).toHaveBeenCalledOnceWith( | ||
| `${environment.cloudFunctionsUrl}/sessionLogin`, | ||
| {} | ||
| ); | ||
| expect(localStorage.getItem(SESSION_COOKIE_EXPIRES_AT_KEY)).toBe( | ||
| String(futureExpiry) | ||
| ); | ||
| }); | ||
|
|
||
| it('skips sessionLogin when a valid cookie already exists in localStorage', async () => { | ||
| localStorage.setItem(SESSION_COOKIE_EXPIRES_AT_KEY, String(futureExpiry)); | ||
|
|
||
| await service.createSessionCookie(); | ||
|
|
||
| expect(postWithAuthSpy).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('calls sessionLogin again when the stored cookie has expired', async () => { | ||
| localStorage.setItem(SESSION_COOKIE_EXPIRES_AT_KEY, String(Date.now() - 1)); | ||
|
|
||
| await service.createSessionCookie(); | ||
|
|
||
| expect(postWithAuthSpy).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it('calls sessionLogin when the stored cookie expires within the refresh buffer', async () => { | ||
| const expiresWithinBuffer = Date.now() + 60 * 1000; // 1 minute from now, within the 5-minute buffer | ||
| localStorage.setItem( | ||
| SESSION_COOKIE_EXPIRES_AT_KEY, | ||
| String(expiresWithinBuffer) | ||
| ); | ||
|
|
||
| await service.createSessionCookie(); | ||
|
|
||
| expect(postWithAuthSpy).toHaveBeenCalledTimes(1); | ||
| }); | ||
| }); | ||
|
|
||
| describe('AuthService session cookie invalidation', () => { | ||
| let service: AuthService; | ||
| let capturedIdTokenCallback: (user: FirebaseUser | null) => void; | ||
|
|
||
| beforeEach(() => { | ||
| localStorage.setItem( | ||
| SESSION_COOKIE_EXPIRES_AT_KEY, | ||
| String(Date.now() + FIVE_DAYS_MS) | ||
| ); | ||
|
|
||
| const onIdTokenChangedSpy = jasmine | ||
| .createSpy('onIdTokenChanged') | ||
| .and.callFake((cb: (user: FirebaseUser | null) => void) => { | ||
| capturedIdTokenCallback = cb; | ||
| return () => {}; | ||
| }); | ||
|
|
||
| const mockAuth = createMockAuth(onIdTokenChangedSpy); | ||
|
|
||
| TestBed.configureTestingModule({ | ||
| providers: mockAuthProviders(mockAuth, jasmine.createSpy('postWithAuth')), | ||
| }); | ||
|
|
||
| service = TestBed.inject(AuthService); | ||
| }); | ||
|
|
||
| afterEach(() => localStorage.clear()); | ||
|
|
||
| it('clears localStorage entry when user signs out', () => { | ||
| expect(localStorage.getItem(SESSION_COOKIE_EXPIRES_AT_KEY)).not.toBeNull(); | ||
|
|
||
| capturedIdTokenCallback!(null); | ||
|
|
||
| expect(localStorage.getItem(SESSION_COOKIE_EXPIRES_AT_KEY)).toBeNull(); | ||
| }); | ||
|
|
||
| it('preserves localStorage entry on token refresh for the same user', () => { | ||
| // Spy on callProfileRefresh to prevent it from calling httpsCallable with | ||
| // the mock Functions instance, which would fail with a missing _url error. | ||
| spyOn(service, 'callProfileRefresh').and.resolveTo(); | ||
|
|
||
| capturedIdTokenCallback!({ uid: 'user-1' } as FirebaseUser); | ||
|
|
||
| expect(localStorage.getItem(SESSION_COOKIE_EXPIRES_AT_KEY)).not.toBeNull(); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please move into a constant in common lib.