Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions src/app/logout/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/**
* © Copyright Union Systems Inc 2026. All rights reserved.
*/

import { beforeEach, describe, expect, it, vi } from 'vitest'

import { safeRedirectPath } from '@/lib/urlUtils'

import { GET } from './route'

const cookieJar = vi.hoisted(() => ({ names: [] as string[] }))
vi.mock('next/headers', () => ({
cookies: async () => ({
getAll: () => cookieJar.names.map((name) => ({ name, value: 'x' })),
}),
}))

describe('safeRedirectPath', () => {
it('keeps same-origin absolute paths', () => {
expect(safeRedirectPath('/v2/projects/foo')).toBe('/v2/projects/foo')
})

it('rejects off-site redirects', () => {
for (const bad of ['//evil.com', 'https://evil.com', '/\\evil.com', null]) {
expect(safeRedirectPath(bad)).toBe('/v2/projects')
}
})
})

describe('GET /v2/logout', () => {
beforeEach(() => {
cookieJar.names = []
delete process.env.OIDC_LOGOUT_URL
})

it('expires every ALB session cookie shard and redirects', async () => {
cookieJar.names = [
'AWSELBAuthSessionCookie-0',
'AWSELBAuthSessionCookie-1',
'unrelated',
]
const res = await GET(new Request('https://flyte.example/v2/logout'))

expect(res.status).toBe(302)
expect(res.headers.get('location')).toBe('https://flyte.example/v2/projects')

const setCookie = res.headers.getSetCookie()
expect(setCookie.every((c) => c.includes('Max-Age=0'))).toBe(true)
expect(setCookie.some((c) => c.includes('unrelated'))).toBe(false)
for (const name of ['AWSELBAuthSessionCookie-0', 'AWSELBAuthSessionCookie-1']) {
expect(setCookie.filter((c) => c.startsWith(`${name}=`))).toHaveLength(1)
}
})

it('expires the shards even when the proxy forwards no cookies', async () => {
const res = await GET(new Request('https://flyte.example/v2/logout'))
const setCookie = res.headers.getSetCookie()
expect(setCookie).toHaveLength(4)
expect(setCookie[0]).toContain('AWSELBAuthSessionCookie-0=;')
})

it('clears only what LOGOUT_CLEAR_COOKIES names, and nothing when it is empty', async () => {
// The route reads the env at module load, so exercise both via a fresh import.
vi.resetModules()
process.env.LOGOUT_CLEAR_COOKIES = '_oauth2_proxy'
cookieJar.names = ['_oauth2_proxy_0', 'AWSELBAuthSessionCookie-0']
const proxied = await import('./route')
let res = await proxied.GET(new Request('https://flyte.example/v2/logout'))
let setCookie = res.headers.getSetCookie()
expect(setCookie.map((c) => c.split('=')[0]).sort()).toEqual([
'_oauth2_proxy',
'_oauth2_proxy_0',
])

vi.resetModules()
process.env.LOGOUT_CLEAR_COOKIES = ''
const redirectOnly = await import('./route')
res = await redirectOnly.GET(new Request('https://flyte.example/v2/logout'))
setCookie = res.headers.getSetCookie()
expect(setCookie).toHaveLength(0)
expect(res.status).toBe(302)

delete process.env.LOGOUT_CLEAR_COOKIES
vi.resetModules()
})

it('redirects to the IdP when OIDC_LOGOUT_URL is set', async () => {
process.env.OIDC_LOGOUT_URL = 'https://okta.example/oauth2/v1/logout'
const res = await GET(new Request('https://flyte.example/v2/logout'))
expect(res.headers.get('location')).toBe(
'https://okta.example/oauth2/v1/logout',
)
})

it('ignores an attacker-supplied redirect_url', async () => {
const res = await GET(
new Request('https://flyte.example/v2/logout?redirect_url=//evil.com'),
)
expect(res.headers.get('location')).toBe('https://flyte.example/v2/projects')
})
})
76 changes: 76 additions & 0 deletions src/app/logout/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* © Copyright Union Systems Inc 2026. All rights reserved.
*/

import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'

import { safeRedirectPath } from '@/lib/urlUtils'

export const dynamic = 'force-dynamic'

/**
* Session cookies expired on sign out, as `LOGOUT_CLEAR_COOKIES` (comma-separated).
*
* Defaults to AWS ALB's four shards — it splits the session at 4K and supports 16K
* total, so `-0`…`-3` is the documented maximum, not a guess. Override this if the
* listener rule sets a custom `SessionCookieName`.
*
* They are expired unconditionally because ALB does NOT forward its own session
* cookie to the target (verified: the request arrives with none), so "expire what
* the request carries" clears nothing and leaves the user signed in. Expiring a
* cookie that was never set is a no-op.
*
* Most other proxies — oauth2-proxy (`/oauth2/sign_out`), GCP IAP
* (`/_gcp_iap/clear_login_cookie`), Cloudflare Access (`/cdn-cgi/access/logout`) —
* expose a sign-out endpoint that clears their own cookie. Point `OIDC_LOGOUT_URL`
* at it and set `LOGOUT_CLEAR_COOKIES=` (empty) so this route only redirects.
*/
const CLEAR_COOKIES = (
process.env.LOGOUT_CLEAR_COOKIES ??
'AWSELBAuthSessionCookie-0,AWSELBAuthSessionCookie-1,AWSELBAuthSessionCookie-2,AWSELBAuthSessionCookie-3'
)
.split(',')
.map((name) => name.trim())
.filter(Boolean)

/** Proxy session cookies are host-only on `/`; deletion must match to overwrite. */
const EXPIRED = 'Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; Secure; SameSite=Lax'

/**
* Signs the user out by expiring the proxy's session cookies, then handing off to
* the identity provider.
*
* Note: clearing the cookie only ends the *proxy* session. If the IdP session is
* still live, the next request re-authenticates silently — set `OIDC_LOGOUT_URL`
* (e.g. the Okta `/v1/logout` endpoint) to end that one too.
*/
export async function GET(request: Request) {
const url = new URL(request.url)
const target =
process.env.OIDC_LOGOUT_URL ||
new URL(safeRedirectPath(url.searchParams.get('redirect_url')), url.origin)
.toString()

const response = NextResponse.redirect(target, 302)

// Shards past the configured names, for proxies that do forward their session
// cookie and split it further than the defaults cover.
const forwarded = (await cookies())
.getAll()
.map((c) => c.name)
.filter((name) =>
CLEAR_COOKIES.some((base) => {
if (!name.startsWith(base)) return false
// `-0` (ALB) and `_0` (oauth2-proxy) are the shard suffixes in the wild.
const shard = name.slice(base.length)
return shard === '' || /^[-_]\d+$/.test(shard)
}),
)

for (const name of new Set([...CLEAR_COOKIES, ...forwarded])) {
response.headers.append('set-cookie', `${name}=; ${EXPIRED}`)
}

return response
}
39 changes: 39 additions & 0 deletions src/components/Header/Header.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* © Copyright Union Systems Inc 2026. All rights reserved.
*/

import React from 'react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vitest'

import { Header } from './Header'

const identity = vi.hoisted(() => ({ data: undefined as unknown }))
vi.mock('@/hooks/useIdentity', () => ({ useIdentity: () => identity }))

describe('Header', () => {
it('renders no user menu when there is no identity', () => {
identity.data = undefined
render(<Header />)
expect(screen.queryByLabelText('User menu')).not.toBeInTheDocument()
})

it('shows the user name and confirms before signing out', async () => {
identity.data = {
givenName: 'Kevin',
familyName: 'Su',
email: '',
subject: 'k',
}
render(<Header />)
expect(screen.getByText('Kevin Su')).toBeInTheDocument()

// The menu item opens the confirmation rather than signing out directly.
await userEvent.click(screen.getByLabelText('User menu'))
expect(screen.queryByText('Sign out of Flyte?')).not.toBeInTheDocument()

await userEvent.click(screen.getByRole('button', { name: 'Sign out' }))
expect(screen.getByText('Sign out of Flyte?')).toBeInTheDocument()
})
})
68 changes: 67 additions & 1 deletion src/components/Header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,85 @@

'use client'

import React from 'react'
import React, { useMemo, useState } from 'react'

import { type MenuItem, PopoverMenu } from '@/components/Popovers'
import { SignOutPanel } from '@/components/SignOutPanel'
import { UserIcon } from '@/components/UserIdentityInfo'
import { useIdentity } from '@/hooks/useIdentity'
import { resolveUserNameFields } from '@/lib/userIdentityUtils'

interface HeaderProps {
logoComponent?: React.ReactNode
showSearch?: boolean
}

export function Header({ logoComponent }: HeaderProps) {
const { data: identity } = useIdentity()
const [menuOpen, setMenuOpen] = useState(false)
const [signOutOpen, setSignOutOpen] = useState(false)

const menuItems: MenuItem[] = useMemo(
() => [
{
id: 'logout',
type: 'custom',
component: (
<button
type="button"
className="flex w-full cursor-pointer items-center px-4.5 py-2 text-left text-[13px] text-(--system-gray-6)"
onClick={() => {
setMenuOpen(false)
setSignOutOpen(true)
}}
>
Sign out
</button>
),
},
],
[],
)

const { firstName, lastName, userIdentityString } = resolveUserNameFields(
identity?.givenName,
identity?.familyName,
identity?.email,
identity?.subject,
)

return (
<div
className={`flex h-[56px] w-full items-center justify-between bg-(--system-gray-1) px-5 py-3`}
>
{logoComponent ? logoComponent : <div />}
{/* No identity — nothing is authenticating this deployment, so no menu. */}
{identity && (
<PopoverMenu
items={menuItems}
showChevron={false}
showCheckboxes={false}
noSelectedBackground={true}
open={menuOpen}
onOpenChange={setMenuOpen}
placement="bottom-end"
>
<button
type="button"
className="cursor-pointer rounded-full !p-0 focus:ring-2 focus:ring-(--union) focus:ring-offset-2 focus:ring-offset-(--system-gray-1) focus:outline-none"
aria-label="User menu"
>
<UserIcon
firstName={firstName}
lastName={lastName}
userIdentityString={userIdentityString}
showUserName
/>
</button>
</PopoverMenu>
)}
{/* Outside the menu so closing the popover doesn't unmount the dialog. */}
<SignOutPanel open={signOutOpen} onCancel={() => setSignOutOpen(false)} />
</div>
)
}
33 changes: 33 additions & 0 deletions src/components/SignOutPanel.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* © Copyright Union Systems Inc 2026. All rights reserved.
*/

import React from 'react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vitest'

import { SignOutPanel } from './SignOutPanel'

const location = vi.hoisted(() => ({ href: '' }))
vi.mock('@/lib/windowUtils', () => ({ getWindow: () => ({ location }) }))

describe('SignOutPanel', () => {
it('renders nothing while closed', () => {
render(<SignOutPanel open={false} onCancel={vi.fn()} />)
expect(screen.queryByText('Sign out of Flyte?')).not.toBeInTheDocument()
})

it('confirms to the logout url and cancels without leaving', async () => {
const onCancel = vi.fn()
render(<SignOutPanel open onCancel={onCancel} />)
expect(screen.getByText('Sign out of Flyte?')).toBeInTheDocument()

await userEvent.click(screen.getByTestId('signout-cancel'))
expect(onCancel).toHaveBeenCalled()
expect(location.href).toBe('')

await userEvent.click(screen.getByTestId('signout-confirm'))
expect(location.href).toBe('/v2/logout?redirect_url=%2Fv2%2Fprojects')
})
})
Loading
Loading