|
| 1 | +/* |
| 2 | + * Copyright 2025 The Kubernetes Authors |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import Alert from '@mui/material/Alert'; |
| 18 | +import Button from '@mui/material/Button'; |
| 19 | +import Typography from '@mui/material/Typography'; |
| 20 | +import React from 'react'; |
| 21 | +import { useTranslation } from 'react-i18next'; |
| 22 | +import { matchPath, useLocation } from 'react-router-dom'; |
| 23 | +import { fetchClusterMe, logout } from '../../lib/auth'; |
| 24 | +import type { ClusterMeResult } from '../../lib/auth'; |
| 25 | +import { getCluster } from '../../lib/cluster'; |
| 26 | +import { getRoute } from '../../lib/router/getRoute'; |
| 27 | +import { getRoutePath } from '../../lib/router/getRoutePath'; |
| 28 | + |
| 29 | +/** How often to poll the /clusters/:cluster/me endpoint (ms). */ |
| 30 | +const POLL_INTERVAL_MS = 60 * 1000; |
| 31 | + |
| 32 | +/** Show a warning banner when fewer than this many seconds remain before expiry. */ |
| 33 | +const WARNING_BEFORE_EXPIRY_SECONDS = 2 * 60; |
| 34 | + |
| 35 | +/** Routes where the banner is suppressed — these pages handle auth state themselves. */ |
| 36 | +const ROUTES_WITHOUT_EXPIRY_CHECK = ['login', 'token', 'settingsCluster']; |
| 37 | + |
| 38 | +export interface PureTokenExpiryNotificationProps { |
| 39 | + /** Injected fetch function so tests can control responses without hitting the network. */ |
| 40 | + fetchClusterMeFn: (cluster: string) => Promise<ClusterMeResult>; |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * Polls the Headlamp /clusters/:cluster/me endpoint and shows a banner when the |
| 45 | + * session token is about to expire or has already expired. |
| 46 | + * |
| 47 | + * Exported as `PureTokenExpiryNotification` so it can be unit-tested with a |
| 48 | + * mocked fetch function. |
| 49 | + */ |
| 50 | +export function PureTokenExpiryNotification({ |
| 51 | + fetchClusterMeFn, |
| 52 | +}: PureTokenExpiryNotificationProps) { |
| 53 | + const { t } = useTranslation(); |
| 54 | + const { pathname } = useLocation(); |
| 55 | + |
| 56 | + const [tokenExpiry, setTokenExpiry] = React.useState<number | null>(null); |
| 57 | + const [tokenExpired, setTokenExpired] = React.useState(false); |
| 58 | + |
| 59 | + // Restart the poller whenever the route changes (covers cluster switches too). |
| 60 | + React.useEffect(() => { |
| 61 | + setTokenExpiry(null); |
| 62 | + setTokenExpired(false); |
| 63 | + |
| 64 | + const cluster = getCluster(); |
| 65 | + if (!cluster) { |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + let mounted = true; |
| 70 | + |
| 71 | + const check = async () => { |
| 72 | + if (!mounted) return; |
| 73 | + const result = await fetchClusterMeFn(cluster); |
| 74 | + if (!mounted) return; |
| 75 | + |
| 76 | + if (result.tokenExpired) { |
| 77 | + setTokenExpired(true); |
| 78 | + } else if (result.data?.tokenExpiry != null) { |
| 79 | + setTokenExpiry(result.data.tokenExpiry); |
| 80 | + } |
| 81 | + }; |
| 82 | + |
| 83 | + // Run once immediately, then on the regular interval. |
| 84 | + check(); |
| 85 | + const id = setInterval(check, POLL_INTERVAL_MS); |
| 86 | + |
| 87 | + return () => { |
| 88 | + mounted = false; |
| 89 | + clearInterval(id); |
| 90 | + }; |
| 91 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 92 | + }, [pathname]); |
| 93 | + |
| 94 | + // Auto-logout as soon as the backend confirms the token is expired. |
| 95 | + React.useEffect(() => { |
| 96 | + if (!tokenExpired) return; |
| 97 | + const cluster = getCluster(); |
| 98 | + if (cluster) { |
| 99 | + logout(cluster); |
| 100 | + } |
| 101 | + }, [tokenExpired]); |
| 102 | + |
| 103 | + const showOnRoute = React.useMemo(() => { |
| 104 | + for (const routeName of ROUTES_WITHOUT_EXPIRY_CHECK) { |
| 105 | + const maybeRoute = getRoute(routeName); |
| 106 | + if (!maybeRoute) continue; |
| 107 | + if (matchPath(pathname, getRoutePath(maybeRoute))?.isExact) return false; |
| 108 | + } |
| 109 | + return true; |
| 110 | + }, [pathname]); |
| 111 | + |
| 112 | + if (!showOnRoute || !getCluster()) { |
| 113 | + return null; |
| 114 | + } |
| 115 | + |
| 116 | + if (tokenExpired) { |
| 117 | + return ( |
| 118 | + <Alert |
| 119 | + variant="filled" |
| 120 | + severity="error" |
| 121 | + sx={theme => ({ |
| 122 | + color: theme.palette.common.white, |
| 123 | + background: theme.palette.error.main, |
| 124 | + textAlign: 'center', |
| 125 | + display: 'flex', |
| 126 | + paddingTop: theme.spacing(0.5), |
| 127 | + paddingBottom: theme.spacing(1), |
| 128 | + paddingRight: theme.spacing(3), |
| 129 | + justifyContent: 'center', |
| 130 | + position: 'fixed', |
| 131 | + zIndex: theme.zIndex.snackbar + 1, |
| 132 | + top: '0', |
| 133 | + alignItems: 'center', |
| 134 | + left: '50%', |
| 135 | + width: 'auto', |
| 136 | + transform: 'translateX(-50%)', |
| 137 | + })} |
| 138 | + > |
| 139 | + <Typography |
| 140 | + variant="body2" |
| 141 | + sx={theme => ({ |
| 142 | + paddingTop: theme.spacing(0.5), |
| 143 | + fontWeight: 'bold', |
| 144 | + fontSize: '16px', |
| 145 | + })} |
| 146 | + > |
| 147 | + {t('translation|Session expired. Logging out…')} |
| 148 | + </Typography> |
| 149 | + </Alert> |
| 150 | + ); |
| 151 | + } |
| 152 | + |
| 153 | + const now = Math.floor(Date.now() / 1000); |
| 154 | + const secondsLeft = tokenExpiry !== null ? tokenExpiry - now : null; |
| 155 | + const isExpiring = |
| 156 | + secondsLeft !== null && secondsLeft > 0 && secondsLeft <= WARNING_BEFORE_EXPIRY_SECONDS; |
| 157 | + |
| 158 | + if (!isExpiring) { |
| 159 | + return null; |
| 160 | + } |
| 161 | + |
| 162 | + const minutes = Math.floor(secondsLeft! / 60); |
| 163 | + const seconds = secondsLeft! % 60; |
| 164 | + const timeStr = `${minutes}:${String(seconds).padStart(2, '0')}`; |
| 165 | + |
| 166 | + return ( |
| 167 | + <Alert |
| 168 | + variant="filled" |
| 169 | + severity="warning" |
| 170 | + sx={theme => ({ |
| 171 | + color: theme.palette.common.white, |
| 172 | + background: theme.palette.warning.main, |
| 173 | + textAlign: 'center', |
| 174 | + display: 'flex', |
| 175 | + paddingTop: theme.spacing(0.5), |
| 176 | + paddingBottom: theme.spacing(1), |
| 177 | + paddingRight: theme.spacing(3), |
| 178 | + justifyContent: 'center', |
| 179 | + position: 'fixed', |
| 180 | + zIndex: theme.zIndex.snackbar + 1, |
| 181 | + top: '0', |
| 182 | + alignItems: 'center', |
| 183 | + left: '50%', |
| 184 | + width: 'auto', |
| 185 | + transform: 'translateX(-50%)', |
| 186 | + })} |
| 187 | + action={ |
| 188 | + <Button |
| 189 | + size="small" |
| 190 | + sx={theme => ({ |
| 191 | + color: theme.palette.warning.main, |
| 192 | + borderColor: theme.palette.warning.main, |
| 193 | + background: theme.palette.common.white, |
| 194 | + lineHeight: theme.typography.body2.lineHeight, |
| 195 | + '&:hover': { |
| 196 | + color: theme.palette.common.white, |
| 197 | + borderColor: theme.palette.common.white, |
| 198 | + background: theme.palette.warning.dark, |
| 199 | + }, |
| 200 | + })} |
| 201 | + onClick={() => { |
| 202 | + const cluster = getCluster(); |
| 203 | + if (cluster) { |
| 204 | + logout(cluster); |
| 205 | + } |
| 206 | + }} |
| 207 | + > |
| 208 | + {t('translation|Log out')} |
| 209 | + </Button> |
| 210 | + } |
| 211 | + > |
| 212 | + <Typography |
| 213 | + variant="body2" |
| 214 | + sx={theme => ({ |
| 215 | + paddingTop: theme.spacing(0.5), |
| 216 | + fontWeight: 'bold', |
| 217 | + fontSize: '16px', |
| 218 | + })} |
| 219 | + > |
| 220 | + {t('translation|Session expires in {{time}}', { time: timeStr })} |
| 221 | + </Typography> |
| 222 | + </Alert> |
| 223 | + ); |
| 224 | +} |
| 225 | + |
| 226 | +export default function TokenExpiryNotification() { |
| 227 | + return <PureTokenExpiryNotification fetchClusterMeFn={fetchClusterMe} />; |
| 228 | +} |
0 commit comments