Created
March 31, 2022 13:56
-
-
Save kennyjwilli/f7a9b86378b305e60e59120de6b2b356 to your computer and use it in GitHub Desktop.
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
(defn generate-auth-token | |
"Create an authorization token used to connect to a database that uses RDS IAM | |
authentication. Use this token as the DB password when connecting with `user`. | |
To use IAM authentication, the user must be granted the rds_iam role. e.g., | |
`GRANT rds_iam TO db_userx;` | |
See also: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html" | |
[db-spec] | |
(.getAuthToken (.build (doto (RdsIamAuthTokenGenerator/builder) | |
(.credentials (DefaultAWSCredentialsProviderChain.)) | |
(.region (.getRegion (DefaultAwsRegionProviderChain.))))) | |
(.build | |
(doto (GetIamAuthTokenRequest/builder) | |
(.hostname (:host db-spec)) | |
(.port 5432) | |
(.userName (:user db-spec)))))) | |
(defn new-data-source | |
"Returns an uninitialized Hikari DataSource. To initialize the pool, call | |
`getConnection` on the returned datasource." | |
[db-url db-spec] | |
(let [init-props (doto (java.util.Properties.) | |
;; Any regular JDBC connection parameters can be added here. | |
(.putAll (cond-> {} | |
(:user db-spec) (assoc "user" (:user db-spec))))) | |
get-conn (fn get-conn | |
([] | |
(get-conn {"password" (generate-auth-token db-spec)})) | |
([props] | |
(java.sql.DriverManager/getConnection db-url | |
(doto init-props | |
(.putAll props))))) | |
*login-timeout (atom nil) | |
base-datasource (reify DataSource | |
(getConnection [_] (get-conn)) | |
(getConnection [_ user password] | |
(get-conn {"user" user "password" password})) | |
(getLoginTimeout [_] (or @*login-timeout 0)) | |
(setLoginTimeout [_ seconds] (reset! *login-timeout seconds)) | |
(toString [_] db-url))] | |
(doto (HikariDataSource.) | |
(.setDataSource base-datasource) | |
;; Optionally set Hikari specific properties here | |
))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment