0e4f0fc611
## Summary Manual smoke after PR #113 surfaced a dev-only bug: after `/auth/callback` the BFF correctly sets the `portal_session` cookie and redirects to the SPA, but the SPA's next call to `/api/auth/me` comes back **401 with no `cookie:` header at all**. The user lands "back at the portal" but the header still shows "Sign in". **Root cause.** Angular's `HttpClient` via `withFetch()` inherits `fetch`'s default `credentials: 'same-origin'`. In dev, `localhost:4200` (SPA) → `localhost:3000` (BFF) is cross-origin (different ports), so the browser drops the session cookie on the way out. SameSite=Lax is a red herring: both URLs share the registrable domain, so the cookie is still same-site — what was missing was opting the fetch into credentials. **Fix.** Per-call `withCredentials: true` on the /me request. Only /me needs cookies today; login/logout are full-page navigations through `window.location`, which the browser hydrates with cookies regardless. A global `HttpInterceptor` will be the right abstraction once other authenticated BFF endpoints exist — premature for one consumer. **BFF side was already correct.** `enableCors({ credentials: true })` in `main.ts`. Nothing to change. A new spec pins `withCredentials === true` on the /me request so a future refactor can't silently drop the flag and reintroduce the bug. ## Test plan - [x] `pnpm nx test feature-auth` → **9/9 pass** (was 8 before; +1 spec pinning the credentials flag). - [x] `pnpm nx test portal-shell` → **32/32 pass**. - [x] `pnpm nx lint feature-auth portal-shell` → clean. - [x] `pnpm nx build portal-shell` → clean. - [ ] Manual smoke against the running BFF: anonymous landing → click "Sign in" → Entra → callback → SPA lands with avatar + display name in the header (the very last step that failed before this fix). --------- Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr> Reviewed-on: #114
138 lines
5.0 KiB
TypeScript
138 lines
5.0 KiB
TypeScript
import { provideHttpClient } from '@angular/common/http';
|
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
|
import { TestBed } from '@angular/core/testing';
|
|
import { AUTH_BFF_BASE_URL, AUTH_NAVIGATOR } from './auth.config';
|
|
import { AuthService } from './auth.service';
|
|
import type { CurrentUser } from './auth.types';
|
|
|
|
const BFF_BASE = 'http://bff.test/api';
|
|
const ME_URL = `${BFF_BASE}/auth/me`;
|
|
|
|
const USER: CurrentUser = {
|
|
oid: 'user-oid',
|
|
tid: 'tenant-id',
|
|
username: 'jane.doe@apf.example',
|
|
displayName: 'Jane Doe',
|
|
};
|
|
|
|
interface Fixture {
|
|
service: AuthService;
|
|
http: HttpTestingController;
|
|
navigate: ReturnType<typeof vi.fn>;
|
|
}
|
|
|
|
function setup(): Fixture {
|
|
const navigate = vi.fn();
|
|
TestBed.configureTestingModule({
|
|
providers: [
|
|
provideHttpClient(),
|
|
provideHttpClientTesting(),
|
|
{ provide: AUTH_BFF_BASE_URL, useValue: BFF_BASE },
|
|
{ provide: AUTH_NAVIGATOR, useValue: navigate },
|
|
AuthService,
|
|
],
|
|
});
|
|
const service = TestBed.inject(AuthService);
|
|
const http = TestBed.inject(HttpTestingController);
|
|
return { service, http, navigate };
|
|
}
|
|
|
|
describe('AuthService', () => {
|
|
afterEach(() => {
|
|
TestBed.resetTestingModule();
|
|
});
|
|
|
|
describe('bootstrap fetch', () => {
|
|
it('starts in the loading state before /me resolves', () => {
|
|
const { service, http } = setup();
|
|
expect(service.state().kind).toBe('loading');
|
|
expect(service.isLoading()).toBe(true);
|
|
expect(service.currentUser()).toBeNull();
|
|
// Drain the in-flight bootstrap request to keep the controller clean.
|
|
http.expectOne(ME_URL).flush({}, { status: 401, statusText: 'Unauthorized' });
|
|
});
|
|
|
|
it('transitions to authenticated when /me returns the user', async () => {
|
|
const { service, http } = setup();
|
|
http.expectOne(ME_URL).flush(USER);
|
|
// Let the awaited firstValueFrom commit the state.
|
|
await Promise.resolve();
|
|
expect(service.state()).toEqual({ kind: 'authenticated', user: USER });
|
|
expect(service.currentUser()).toEqual(USER);
|
|
expect(service.isLoading()).toBe(false);
|
|
});
|
|
|
|
it('issues /me with withCredentials so the session cookie crosses the SPA→BFF origin gap', () => {
|
|
const { http } = setup();
|
|
const req = http.expectOne(ME_URL);
|
|
// Without this, `fetch`'s default `credentials: 'same-origin'`
|
|
// would suppress the session cookie on the cross-origin
|
|
// (localhost:4200 → localhost:3000) request and /me would
|
|
// always answer 401 in dev. Verified manually against the BFF
|
|
// log on 2026-05-12.
|
|
expect(req.request.withCredentials).toBe(true);
|
|
req.flush({ error: 'unauthenticated' }, { status: 401, statusText: 'Unauthorized' });
|
|
});
|
|
|
|
it('transitions to anonymous on 401', async () => {
|
|
const { service, http } = setup();
|
|
http
|
|
.expectOne(ME_URL)
|
|
.flush({ error: 'unauthenticated' }, { status: 401, statusText: 'Unauthorized' });
|
|
await Promise.resolve();
|
|
expect(service.state().kind).toBe('anonymous');
|
|
expect(service.currentUser()).toBeNull();
|
|
});
|
|
|
|
it('transitions to error on a non-401 failure (network / 5xx / malformed)', async () => {
|
|
const { service, http } = setup();
|
|
http.expectOne(ME_URL).flush('boom', { status: 500, statusText: 'Internal Server Error' });
|
|
await Promise.resolve();
|
|
expect(service.state().kind).toBe('error');
|
|
expect(service.currentUser()).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe('refresh()', () => {
|
|
it('can be called again after the bootstrap fetch and re-fetches /me', async () => {
|
|
const { service, http } = setup();
|
|
http.expectOne(ME_URL).flush(USER);
|
|
await Promise.resolve();
|
|
expect(service.state().kind).toBe('authenticated');
|
|
|
|
const promise = service.refresh();
|
|
http
|
|
.expectOne(ME_URL)
|
|
.flush({ error: 'unauthenticated' }, { status: 401, statusText: 'Unauthorized' });
|
|
await promise;
|
|
expect(service.state().kind).toBe('anonymous');
|
|
});
|
|
});
|
|
|
|
describe('URL accessors', () => {
|
|
it('derives me / login / logout URLs from the injected base', () => {
|
|
const { service, http } = setup();
|
|
expect(service.meUrl).toBe(`${BFF_BASE}/auth/me`);
|
|
expect(service.loginUrl).toBe(`${BFF_BASE}/auth/login`);
|
|
expect(service.logoutUrl).toBe(`${BFF_BASE}/auth/logout`);
|
|
http.expectOne(ME_URL).flush({}, { status: 401, statusText: 'Unauthorized' });
|
|
});
|
|
});
|
|
|
|
describe('login() / logout()', () => {
|
|
it('navigates to /auth/login via AUTH_NAVIGATOR', () => {
|
|
const { service, http, navigate } = setup();
|
|
service.login();
|
|
expect(navigate).toHaveBeenCalledWith(`${BFF_BASE}/auth/login`);
|
|
http.expectOne(ME_URL).flush({}, { status: 401, statusText: 'Unauthorized' });
|
|
});
|
|
|
|
it('navigates to /auth/logout via AUTH_NAVIGATOR', () => {
|
|
const { service, http, navigate } = setup();
|
|
service.logout();
|
|
expect(navigate).toHaveBeenCalledWith(`${BFF_BASE}/auth/logout`);
|
|
http.expectOne(ME_URL).flush({}, { status: 401, statusText: 'Unauthorized' });
|
|
});
|
|
});
|
|
});
|