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
6 changes: 4 additions & 2 deletions app/(auth)/auth/login/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ function LoginPageContent() {
sessionToken: "",
})
const loginPendingRef = useRef(false)
const expirationWarningShownRef = useRef(false)
const [submitting, setSubmitting] = useState(false)
const [oidcProviders, setOidcProviders] = useState<OidcProvider[]>([])
// The pending second-factor exchange. The long-term credentials it needs stay
Expand All @@ -56,11 +57,12 @@ function LoginPageContent() {
}, [isAuthenticated, router])

useEffect(() => {
if (searchParams.get("unauthorized") === "true") {
if (!isAuthenticated && searchParams.get("unauthorized") === "true" && !expirationWarningShownRef.current) {
expirationWarningShownRef.current = true
message.warning(t("Your session has expired. Please log in again."))
router.replace("/auth/login")
}
}, [searchParams, message, t, router])
}, [isAuthenticated, searchParams, message, t, router])

// Fetch OIDC providers after the first paint path has had a chance to settle.
useEffect(() => {
Expand Down
42 changes: 16 additions & 26 deletions contexts/api-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { ApiErrorHandler } from "@/lib/api-error-handler"
import { useAuth } from "@/contexts/auth-context"
import { configManager } from "@/lib/config"
import { scheduleMicrotask } from "@/lib/schedule-microtask"
import { isSameSession, type SessionCredentials } from "@/lib/auth-session"

interface ApiContextValue {
api: ApiClient | null
Expand All @@ -17,8 +18,8 @@ interface ApiContextValue {
const ApiContext = createContext<ApiContextValue>({ api: null, isReady: false })

export function ApiProvider({ children }: { children: React.ReactNode }) {
const { credentials, isAuthenticated, logout, getIsLoggingOut } = useAuth()
const [apiClient, setApiClient] = useState<ApiClient | null>(null)
const { credentials, isAuthenticated, expireSession, isCurrentSession, getIsLoggingOut } = useAuth()
const [apiClient, setApiClient] = useState<{ client: ApiClient; credentials: SessionCredentials } | null>(null)
const [isReady, setIsReady] = useState(false)
const router = useRouter()
const pathname = usePathname()
Expand Down Expand Up @@ -58,19 +59,10 @@ export function ApiProvider({ children }: { children: React.ReactNode }) {

const errorHandler = new ApiErrorHandler({
onUnauthorized: async () => {
if (getIsLoggingOut()) return
logout()
router.replace("/auth/login/")
if (expireSession(credentials)) router.replace("/auth/login/?unauthorized=true")
},
onForbidden: async (url) => {
if (getIsLoggingOut()) return
// If the forbidden error happens on the accountinfo endpoint, it means the session is invalid
// or the user has no permissions at all. In this case, we should log out.
if (url?.includes("/is-admin") || url?.includes("/accountinfo") || url?.includes("/version")) {
logout()
router.replace("/auth/login/")
return
}
onForbidden: async () => {
if (getIsLoggingOut() || !isCurrentSession(credentials)) return

if (pathnameRef.current === "/403/") return
router.replace("/403/")
Expand All @@ -83,24 +75,22 @@ export function ApiProvider({ children }: { children: React.ReactNode }) {
errorHandler,
})

setApiClient(client)
setApiClient({ client, credentials })
setIsReady(true)
})

return () => {
cancelled = true
}
}, [
isAuthenticated,
credentials?.AccessKeyId,
credentials?.SecretAccessKey,
credentials?.SessionToken,
logout,
getIsLoggingOut,
router,
])

return <ApiContext.Provider value={{ api: apiClient, isReady }}>{children}</ApiContext.Provider>
}, [isAuthenticated, credentials, expireSession, isCurrentSession, getIsLoggingOut, router])

const currentClient =
isAuthenticated && apiClient && isSameSession(credentials, apiClient.credentials) ? apiClient.client : null
return (
<ApiContext.Provider value={{ api: currentClient, isReady: isReady && (!isAuthenticated || !!currentClient) }}>
{children}
</ApiContext.Provider>
)
}

export function useApi() {
Expand Down
79 changes: 57 additions & 22 deletions contexts/auth-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,11 @@ import type { SiteConfig } from "@/types/config"
import { getLoginRoute } from "@/lib/routes"
import { configManager } from "@/lib/config"
import { useLocalStorage } from "@/hooks/use-local-storage"
import { isSameSession, isValidCredentials, type SessionCredentials as Credentials } from "@/lib/auth-session"
import { buildOidcLogoutUrl, type OidcLogoutSession } from "@/lib/oidc"
import { isMfaRequiredError } from "@/lib/mfa"
import { fetchMfaChallenge } from "@/lib/mfa-challenge"

interface Credentials {
AccessKeyId?: string
SecretAccessKey?: string
SessionToken?: string
Expiration?: string
}

/**
* Result of a first login attempt.
*
Expand All @@ -51,6 +45,8 @@ interface AuthContextValue {
logoutAndRedirect: () => void
logoutWithOidcRedirect: () => Promise<boolean>
getIsLoggingOut: () => boolean
isCurrentSession: (credentials: Credentials) => boolean
expireSession: (credentials: Credentials) => boolean
setIsAdmin: (value: boolean) => void
getIsAdmin: () => boolean
credentials: Credentials | undefined
Expand All @@ -60,19 +56,6 @@ interface AuthContextValue {

const AuthContext = createContext<AuthContextValue | null>(null)

function isValidCredentials(credentials: Credentials | undefined): boolean {
if (
!credentials?.AccessKeyId ||
!credentials?.SecretAccessKey ||
!credentials?.SessionToken ||
!credentials?.Expiration
) {
return false
}
const isExpired = (exp: string) => (exp ? new Date(exp) < new Date() : false)
return !isExpired(credentials.Expiration)
}

/**
* Whether these credentials are a static key pair we can sign a probe with.
*
Expand All @@ -94,7 +77,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// Old API/S3 callbacks must see this flag before React commits the cleared credentials.
const loggingOutRef = useRef(false)
const getIsLoggingOut = useCallback(() => loggingOutRef.current, [])
const [store, setStore] = useLocalStorage<Credentials | undefined>("auth.credentials", undefined)
const [store, setStore, getStoredCredentials] = useLocalStorage<Credentials | undefined>(
"auth.credentials",
undefined,
true,
)
const [isAdminStore, setIsAdminStore] = useLocalStorage<boolean | undefined>("auth.isAdmin", undefined)
const [oidcSessionStore, setOidcSessionStore] = useLocalStorage<OidcLogoutSession | undefined>(
"auth.oidcSession",
Expand All @@ -103,8 +90,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {

const setCredentials = useCallback(
(credentials: Credentials) => {
loggingOutRef.current = false
setStore(credentials)
loggingOutRef.current = false
},
[setStore],
)
Expand Down Expand Up @@ -235,6 +222,50 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setOidcSessionStore(undefined)
}, [setStore, setIsAdminStore, setOidcSessionStore])

const isCurrentSession = useCallback(
(expected: Credentials) => {
return isSameSession(getStoredCredentials(), expected)
},
[getStoredCredentials],
)

const expireSession = useCallback(
(expected: Credentials) => {
if (loggingOutRef.current || !isCurrentSession(expected)) return false
logout()
Comment on lines +234 to +235
return true
},
[isCurrentSession, logout],
)

useEffect(() => {
if (!store?.Expiration) return
const expiration = Date.parse(store.Expiration)
let timer: number | undefined
const checkExpiration = () => {
window.clearTimeout(timer)
if (!isCurrentSession(store) || loggingOutRef.current) return
const remaining = expiration - Date.now()
if (!Number.isFinite(remaining) || remaining <= 0) {
expireSession(store)
return
}
// Browsers clamp larger delays to 1 ms; recheck long-lived sessions in bounded steps.
timer = window.setTimeout(checkExpiration, Math.min(remaining, 2 ** 31 - 1))
}
const handleVisibility = () => {
if (document.visibilityState === "visible") checkExpiration()
}
checkExpiration()
document.addEventListener("visibilitychange", handleVisibility)
window.addEventListener("pageshow", checkExpiration)
return () => {
window.clearTimeout(timer)
document.removeEventListener("visibilitychange", handleVisibility)
window.removeEventListener("pageshow", checkExpiration)
}
}, [store, isCurrentSession, expireSession])

useEffect(() => {
const handlePageShow = (event: PageTransitionEvent) => {
if (!event.persisted || !loggingOutRef.current) return
Expand Down Expand Up @@ -293,6 +324,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
logoutAndRedirect,
logoutWithOidcRedirect,
getIsLoggingOut,
isCurrentSession,
expireSession,
setIsAdmin,
getIsAdmin,
credentials,
Expand All @@ -307,6 +340,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
logoutAndRedirect,
logoutWithOidcRedirect,
getIsLoggingOut,
isCurrentSession,
expireSession,
setIsAdmin,
getIsAdmin,
credentials,
Expand Down
Loading
Loading