|
| 1 | +{-# LANGUAGE FlexibleContexts #-} |
| 2 | +{-# LANGUAGE OverloadedStrings #-} |
| 3 | +{-# LANGUAGE RecordWildCards #-} |
| 4 | +module Kubernetes.Client.Auth.OIDC |
| 5 | + (oidcAuth, OIDCCache, cachedOIDCAuth) |
| 6 | +where |
| 7 | + |
| 8 | +import Control.Applicative |
| 9 | +import Control.Concurrent.STM |
| 10 | +import Data.Either.Combinators |
| 11 | +import Data.Function ((&)) |
| 12 | +import Data.Map (Map) |
| 13 | +import Data.Maybe |
| 14 | +import Data.Text |
| 15 | +import Data.Time.Clock.POSIX (getPOSIXTime) |
| 16 | +import Kubernetes.Client.Auth.Internal.Types |
| 17 | +import Kubernetes.Client.Internal.TLSUtils |
| 18 | +import Kubernetes.Client.KubeConfig |
| 19 | +import Kubernetes.OpenAPI.Core |
| 20 | +import Network.HTTP.Client |
| 21 | +import Network.HTTP.Client.TLS |
| 22 | +import Network.OAuth.OAuth2 as OAuth hiding (error) |
| 23 | +import Network.TLS as TLS |
| 24 | +import URI.ByteString |
| 25 | +import Web.JWT as JWT |
| 26 | +import Web.OIDC.Client.Discovery as OIDC |
| 27 | + |
| 28 | +import qualified Data.ByteString as BS |
| 29 | +import qualified Data.ByteString.Base64 as B64 |
| 30 | +import qualified Data.Map as Map |
| 31 | +import qualified Data.Text as Text |
| 32 | +import qualified Data.Text.Encoding as Text |
| 33 | +import qualified Lens.Micro as L |
| 34 | + |
| 35 | +data OIDCAuth = OIDCAuth { issuerURL :: Text |
| 36 | + , clientID :: Text |
| 37 | + , clientSecret :: Text |
| 38 | + , tlsParams :: TLS.ClientParams |
| 39 | + , idTokenMVar :: TVar(Maybe Text) |
| 40 | + , refreshTokenMVar :: TVar(Maybe Text) |
| 41 | + } |
| 42 | + |
| 43 | +-- | Cache OIDCAuth based on issuerURL and clientID. |
| 44 | +type OIDCCache = TVar (Map (Text, Text) OIDCAuth) |
| 45 | + |
| 46 | +instance AuthMethod OIDCAuth where |
| 47 | + applyAuthMethod _ oidc req = do |
| 48 | + token <- getToken oidc |
| 49 | + pure |
| 50 | + $ setHeader req [("Authorization", "Bearer " <> (Text.encodeUtf8 token))] |
| 51 | + & L.set rAuthTypesL [] |
| 52 | + |
| 53 | +-- TODO: Consider a token expired few seconds before actual expiry to account for time skew |
| 54 | +getToken :: OIDCAuth -> IO Text |
| 55 | +getToken o@(OIDCAuth{..}) = do |
| 56 | + now <- getPOSIXTime |
| 57 | + mgr <- newManager tlsManagerSettings |
| 58 | + idToken <- atomically $ readTVar idTokenMVar |
| 59 | + let maybeExp = idToken |
| 60 | + & (>>= decode) |
| 61 | + & (fmap claims) |
| 62 | + & (>>= JWT.exp) |
| 63 | + & (fmap secondsSinceEpoch) |
| 64 | + isValidToken = fromMaybe False (fmap (now <) maybeExp) |
| 65 | + if not isValidToken |
| 66 | + then fetchToken mgr o |
| 67 | + else return $ fromMaybe (error "impossible") idToken |
| 68 | + |
| 69 | +fetchToken :: Manager -> OIDCAuth -> IO Text |
| 70 | +fetchToken mgr o@(OIDCAuth{..}) = do |
| 71 | + maybeToken <- atomically $ readTVar refreshTokenMVar |
| 72 | + case maybeToken of |
| 73 | + Nothing -> error "cannot refresh id-token without a refresh token" |
| 74 | + Just token -> do |
| 75 | + tokenEndpoint <- fetchTokenEndpoint mgr o |
| 76 | + tokenURI <- exceptEither $ parseURI strictURIParserOptions (Text.encodeUtf8 tokenEndpoint) |
| 77 | + let oauth = OAuth2{ oauthClientId = clientID |
| 78 | + , oauthClientSecret = clientSecret |
| 79 | + , oauthAccessTokenEndpoint = tokenURI |
| 80 | + , oauthOAuthorizeEndpoint = tokenURI |
| 81 | + , oauthCallback = Nothing |
| 82 | + } |
| 83 | + oauthToken <- refreshAccessToken mgr oauth (RefreshToken token) |
| 84 | + >>= exceptEither |
| 85 | + case OAuth.idToken oauthToken of |
| 86 | + Nothing -> error "token response did not contain an id_token, either the scope \"openid\" wasn't requested upon login, or the provider doesn't support id_tokens as part of the refresh response." |
| 87 | + Just (IdToken t) -> do |
| 88 | + _ <- atomically $ writeTVar idTokenMVar (Just t) |
| 89 | + return t |
| 90 | + |
| 91 | +fetchTokenEndpoint :: Manager -> OIDCAuth -> IO Text |
| 92 | +fetchTokenEndpoint mgr OIDCAuth{..} = do |
| 93 | + discover issuerURL mgr |
| 94 | + & (fmap configuration) |
| 95 | + & (fmap tokenEndpoint) |
| 96 | + |
| 97 | +exceptEither :: Show b => Either b a -> IO a |
| 98 | +exceptEither (Right a) = pure a |
| 99 | +exceptEither (Left t) = error (show t) |
| 100 | + |
| 101 | +{- |
| 102 | + Detects if auth-provier name is oidc, if it is configures the 'KubernetesClientConfig' with OIDCAuth 'AuthMethod'. |
| 103 | + Does not use cache, consider using 'cachedOIDCAuth'. |
| 104 | +-} |
| 105 | +oidcAuth :: DetectAuth |
| 106 | +oidcAuth AuthInfo{authProvider = Just(AuthProviderConfig "oidc" (Just cfg))} (tls, kubecfg) |
| 107 | + = Just |
| 108 | + $ parseOIDCAuthInfo cfg |
| 109 | + >>= either error (\oidc -> pure (tls, addAuthMethod kubecfg oidc)) |
| 110 | +oidcAuth _ _ = Nothing |
| 111 | + |
| 112 | +-- TODO: Consider doing this whole function atomically, as two threads may miss the cache simultaneously |
| 113 | +{- |
| 114 | + Detects if auth-provier name is oidc, if it is configures the 'KubernetesClientConfig' with OIDCAuth 'AuthMethod'. |
| 115 | + First looks for Auth information to be present in 'OIDCCache'. If found returns that, otherwise creates new Auth information and persists it in cache. |
| 116 | +-} |
| 117 | +cachedOIDCAuth :: OIDCCache -> DetectAuth |
| 118 | +cachedOIDCAuth cache AuthInfo{authProvider = Just(AuthProviderConfig "oidc" (Just cfg))} (tls, kubecfg) = Just $ do |
| 119 | + m <- atomically $ readTVar cache |
| 120 | + o <- case findInCache m cfg of |
| 121 | + Left e -> error e |
| 122 | + Right (Just o) -> return o |
| 123 | + Right Nothing -> do |
| 124 | + o@(OIDCAuth{..}) <- either error pure =<< parseOIDCAuthInfo cfg |
| 125 | + let newCache = Map.insert (issuerURL, clientID) o m |
| 126 | + _ <- atomically $ swapTVar cache newCache |
| 127 | + return o |
| 128 | + pure (tls, addAuthMethod kubecfg o) |
| 129 | +cachedOIDCAuth _ _ _ = Nothing |
| 130 | + |
| 131 | +findInCache :: Map (Text, Text) a -> Map Text Text -> Either String (Maybe a) |
| 132 | +findInCache cache cfg = do |
| 133 | + issuerURL <- lookupEither cfg "idp-issuer-url" |
| 134 | + clientID <- lookupEither cfg "client-id" |
| 135 | + return $ Map.lookup (issuerURL, clientID) cache |
| 136 | + |
| 137 | +parseOIDCAuthInfo :: Map Text Text -> IO (Either String OIDCAuth) |
| 138 | +parseOIDCAuthInfo m = do |
| 139 | + eitherTLSParams <- parseCA m |
| 140 | + idTokenMVar <- atomically $ newTVar $ Map.lookup "id-token" m |
| 141 | + refreshTokenMVar <- atomically $ newTVar $ Map.lookup "refresh-token" m |
| 142 | + return $ do |
| 143 | + tlsParams <- eitherTLSParams |
| 144 | + issuerURL <- lookupEither m "idp-issuer-url" |
| 145 | + clientID <- lookupEither m "client-id" |
| 146 | + clientSecret <- lookupEither m "client-secret" |
| 147 | + return OIDCAuth{..} |
| 148 | + |
| 149 | +parseCA :: Map Text Text -> IO (Either String TLS.ClientParams) |
| 150 | +parseCA m = do |
| 151 | + t <- defaultTLSClientParams |
| 152 | + fromMaybe (pure $ pure t) (parseCAFile t m <|> parseCAData t m) |
| 153 | + |
| 154 | +parseCAFile :: TLS.ClientParams -> Map Text Text -> Maybe (IO (Either String TLS.ClientParams)) |
| 155 | +parseCAFile t m = do |
| 156 | + caFile <- Text.unpack <$> Map.lookup "idp-certificate-authority" m |
| 157 | + return $ updateClientParams t <$> BS.readFile caFile |
| 158 | + |
| 159 | +parseCAData :: TLS.ClientParams -> Map Text Text -> Maybe (IO (Either String TLS.ClientParams)) |
| 160 | +parseCAData t m = do |
| 161 | + caText <- Map.lookup "idp-certificate-authority-data" m |
| 162 | + pure . pure |
| 163 | + $ (B64.decode $ Text.encodeUtf8 caText) |
| 164 | + >>= updateClientParams t |
| 165 | + |
| 166 | +lookupEither :: (Show key, Ord key) => Map key val -> key -> Either String val |
| 167 | +lookupEither m k = maybeToRight e $ Map.lookup k m |
| 168 | + where e = "Couldn't find key: " <> show k <> " in OIDC auth info" |
0 commit comments