Created
October 1, 2021 21:24
-
-
Save RutledgePaulV/c9eb8a5b8c1ef32cec59137d3efe6328 to your computer and use it in GitHub Desktop.
hikari rotating iam auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns auth | |
(:import (com.zaxxer.hikari HikariDataSource HikariConfig) | |
(com.amazonaws.services.rds.auth RdsIamAuthTokenGenerator GetIamAuthTokenRequest) | |
(com.amazonaws.auth DefaultAWSCredentialsProviderChain) | |
(com.amazonaws.regions DefaultAwsRegionProviderChain) | |
(java.util Properties) | |
(java.time Duration))) | |
(defn parse-jdbc-url [jdbc-url] | |
(let [matcher (re-matcher #"//(?<host>[^:]+):(?<port>\d+)/(?<database>[^\\?]+)" jdbc-url)] | |
(when (.find matcher) | |
{:host (.group matcher "host") | |
:port (some-> (.group matcher "port") (Integer/parseInt)) | |
:database (.group matcher "database")}))) | |
(defn ->properties ^Properties [m] | |
(let [props (Properties.)] | |
(doseq [[k v] m] | |
(.setProperty props (name k) (if (keyword? v) (name v) (str v)))) | |
props)) | |
(defn ->hikari-config ^HikariConfig [m] | |
(if (instance? HikariConfig m) m (HikariConfig. (->properties m)))) | |
(defn create-data-source [hikari-config] | |
(HikariDataSource. (->hikari-config hikari-config))) | |
(defn create-iam-data-source [hikari-config] | |
(let [region-provider (DefaultAwsRegionProviderChain.) | |
credential-provider (DefaultAWSCredentialsProviderChain.) | |
generator (.build | |
(doto (RdsIamAuthTokenGenerator/builder) | |
(.region (.getRegion region-provider)) | |
(.credentials credential-provider))) | |
hikari-config (doto (->hikari-config hikari-config) | |
(.setMaxLifetime (.toMillis (Duration/ofMinutes 14)))) | |
{:keys [host port]} (parse-jdbc-url (.getJdbcUrl hikari-config)) | |
username (.getUsername hikari-config) | |
request (.build | |
(doto (GetIamAuthTokenRequest/builder) | |
(.hostname host) | |
(.port port) | |
(.userName username)))] | |
(proxy [HikariDataSource] [hikari-config] | |
(getPassword [] (.getAuthToken generator request))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment