diff --git a/content/compatibility.yaml b/content/compatibility.yaml index 6f76dca..f43033a 100644 --- a/content/compatibility.yaml +++ b/content/compatibility.yaml @@ -40,6 +40,12 @@ plugins: - key: awsSecretsManager codes: { ruby: secrets_manager } page: using-plugins/aws-secrets-manager + - key: federatedAuth + codes: { ruby: federated_auth } + page: using-plugins/federated-auth + - key: oktaAuth + codes: { ruby: okta } + page: using-plugins/okta-auth - key: initialConnection codes: { ruby: initial_connection } page: using-plugins/initial-connection-strategy @@ -51,7 +57,7 @@ universal: - key: kmsEncryption codes: { ruby: kms_encryption } page: using-plugins/kms-encryption - description: "Transparent column-level encryption using AWS KMS." + description: "Transparent column-level encryption using AWS KMS. Not supported with the `trilogy` driver (it has no prepared statements); use `mysql2` or `pg`." # Reason text for the incompatible cells in the database-type and endpoint # matrices. Cells tag a `reason:` key; the generator emits one footnote per @@ -65,7 +71,7 @@ notes: gdbUseFailoverInstead: "The global database failover plugin can function here, but the failover plugin is recommended instead — it provides the same failover coverage for a single-region cluster while consuming fewer resources." failoverUseGdbInstead: "On an Aurora global database, use the global database failover plugin ({plugin:gdbFailover}) instead — it is region-aware and reconnects across the global cluster's regions, which the standard failover plugin does not do." initialConnNeedsClusterTopology: "The initial connection plugin resolves a cluster endpoint to an instance; this deployment has no cluster topology to resolve." - awsAuthNotCommunity: "IAM and Secrets Manager authentication are Amazon RDS/Aurora features; a community database you run yourself does not support them." + awsAuthNotCommunity: "IAM and Secrets Manager authentication are Amazon RDS/Aurora features; a community database you run yourself does not support them. The Federated Authentication (AD FS) and Okta Authentication plugins obtain their database credential through IAM as well, so the same limitation applies to them." bgNotGlobal: "AWS does not support Blue/Green deployments on Aurora global databases." bgNotMultiAzCluster: "AWS Blue/Green deployments are not available for RDS Multi-AZ DB clusters (only for Multi-AZ DB instance deployments)." bgNotCommunity: "Blue/Green deployments are an Amazon RDS/Aurora feature; a community database you run yourself cannot use one." @@ -198,6 +204,20 @@ databaseTypes: RDS Multi-AZ DB Instance deployment (2 instances) (MySQL and PG): { value: yes } RDS Single-AZ Instance deployment (1 instance) (MySQL and PG): { value: yes } Community Database (MySQL and PG): { value: no, reason: awsAuthNotCommunity } + federatedAuth: + Aurora Global Database (MySQL and PG): { value: yes } + Aurora Cluster (MySQL and PG): { value: yes } + RDS Multi-AZ DB Cluster deployment (3 instances) (MySQL and PG): { value: yes } + RDS Multi-AZ DB Instance deployment (2 instances) (MySQL and PG): { value: yes } + RDS Single-AZ Instance deployment (1 instance) (MySQL and PG): { value: yes } + Community Database (MySQL and PG): { value: no, reason: awsAuthNotCommunity } + oktaAuth: + Aurora Global Database (MySQL and PG): { value: yes } + Aurora Cluster (MySQL and PG): { value: yes } + RDS Multi-AZ DB Cluster deployment (3 instances) (MySQL and PG): { value: yes } + RDS Multi-AZ DB Instance deployment (2 instances) (MySQL and PG): { value: yes } + RDS Single-AZ Instance deployment (1 instance) (MySQL and PG): { value: yes } + Community Database (MySQL and PG): { value: no, reason: awsAuthNotCommunity } initialConnection: Aurora Global Database (MySQL and PG): { value: yes } Aurora Cluster (MySQL and PG): { value: yes } @@ -274,6 +294,30 @@ endpoints: DB Shard Group Endpoint (Aurora Limitless): { value: yes } IP address: { value: yes, noteRef: secretsNeedsRegion } User custom domain (CNAME alias): { value: yes, noteRef: secretsNeedsRegion } + federatedAuth: + Aurora Global Database Endpoint: { value: yes, noteRef: iamNeedsInitialConn } + Aurora Cluster Writer Endpoint: { value: yes } + Aurora Cluster Reader Endpoint: { value: yes } + Aurora Cluster Custom Endpoint: { value: yes } + Aurora Instance Endpoint, RDS Instance Endpoint: { value: yes } + RDS Multi-AZ DB Cluster Writer Endpoint: { value: yes } + RDS Multi-AZ DB Cluster Reader Endpoint: { value: yes } + RDS Proxy Endpoint: { value: yes } + DB Shard Group Endpoint (Aurora Limitless): { value: yes } + IP address: { value: yes, noteRef: iamNeedsHostOverride } + User custom domain (CNAME alias): { value: yes, noteRef: iamNeedsHostOverride } + oktaAuth: + Aurora Global Database Endpoint: { value: yes, noteRef: iamNeedsInitialConn } + Aurora Cluster Writer Endpoint: { value: yes } + Aurora Cluster Reader Endpoint: { value: yes } + Aurora Cluster Custom Endpoint: { value: yes } + Aurora Instance Endpoint, RDS Instance Endpoint: { value: yes } + RDS Multi-AZ DB Cluster Writer Endpoint: { value: yes } + RDS Multi-AZ DB Cluster Reader Endpoint: { value: yes } + RDS Proxy Endpoint: { value: yes } + DB Shard Group Endpoint (Aurora Limitless): { value: yes } + IP address: { value: yes, noteRef: iamNeedsHostOverride } + User custom domain (CNAME alias): { value: yes, noteRef: iamNeedsHostOverride } initialConnection: Aurora Global Database Endpoint: { value: yes } Aurora Cluster Writer Endpoint: { value: yes } @@ -310,7 +354,24 @@ crossPlugins: awsSecretsManager: failover2: { value: yes } gdbFailover: { value: yes } - iam: { value: no, note: "Two authentication plugins both trying to set the connection credential; only one authentication plugin may be active at a time." } + iam: { value: no, noteRef: oneAuthPlugin } + federatedAuth: + failover2: { value: yes } + gdbFailover: { value: yes } + customEndpoint: { value: yes } + initialConnection: { value: yes } + bg: { value: yes } + iam: { value: no, noteRef: oneAuthPlugin } + awsSecretsManager: { value: no, noteRef: oneAuthPlugin } + oktaAuth: + failover2: { value: yes } + gdbFailover: { value: yes } + customEndpoint: { value: yes } + initialConnection: { value: yes } + bg: { value: yes } + iam: { value: no, noteRef: oneAuthPlugin } + awsSecretsManager: { value: no, noteRef: oneAuthPlugin } + federatedAuth: { value: no, noteRef: oneAuthPlugin } customEndpoint: failover2: { value: yes } gdbFailover: { value: no, note: "Meaningless: a custom endpoint is a single-region Aurora cluster construct, while {plugin:gdbFailover} operates across regions on a global database." } diff --git a/content/dev-guide.yaml b/content/dev-guide.yaml index cf44711..0496ee1 100644 --- a/content/dev-guide.yaml +++ b/content/dev-guide.yaml @@ -76,7 +76,7 @@ wrappers: # Ruby diagram labels come from the `diagram:` block below. architectureComponents: | - 1. The connection entry points (`WrapperPgConnection`, `WrapperMysql2Client`, and the `aws_postgresql` / `aws_mysql2` ActiveRecord adapters) + 1. The connection entry points (`WrapperPgConnection`, `WrapperMysql2Client`, `WrapperTrilogyClient`, and the `aws_postgresql` / `aws_mysql2` / `aws_trilogy` ActiveRecord adapters) 2. The [plugin manager](./service-container#plugin-manager) (one of the services in the container) 3. The [loadable and extensible plugins](./loadable-plugins) 4. The [service container](./service-container) of discrete services @@ -96,7 +96,7 @@ wrappers: executeKey: "the qualified driver method name (e.g. `connection.query`, `connection.exec`)" notifyConnChangedKey: "notify_connection_changed" - devPrereqs: "Make sure you have Ruby 3.3+ installed, along with your choice of underlying driver gem (`pg` or `mysql2`)." + devPrereqs: "Make sure you have Ruby 3.3+ installed, along with your choice of underlying driver gem (`pg`, `mysql2`, or `trilogy`)." buildTool: "Bundler + RSpec" sampleCode: | A minimal connection example using the wrapper: @@ -166,8 +166,8 @@ wrappers: diagram: entryPoints: - - "WrapperPgConnection / WrapperMysql2Client" - - "aws_postgresql / aws_mysql2 (ActiveRecord)" + - "WrapperPgConnection / WrapperMysql2Client / WrapperTrilogyClient" + - "aws_postgresql / aws_mysql2 / aws_trilogy (ActiveRecord)" wrapperNode: "Wrapper Connection" samplePlugins: - "Plugin A" @@ -256,7 +256,8 @@ wrappers: - `hosts` / `all_hosts` — allowed and full host lists. - `host_list_provider` — the active provider. - `select_host(hosts, role, strategy, props = nil)` — pick a host by role and host-selection strategy name. - - `HostService.register_host_selector(name, selector)` — a class method that registers a custom strategy for all connections. Register the name in lowercase: `select_host` lowercases the requested strategy before looking it up. + - `HostService.register_host_selector(name, selector)` — a class method that registers a custom strategy for all connections. Strategy names are case-insensitive. + - `HostService.validate_strategy!(name)` — a class method that raises `Unsupported host selection strategy` when no selector is registered under the name. Plugins that take a strategy name call it when they are constructed. whenToUse: | Use it to read topology, register a custom host-selection strategy, or pick a host by role (writer/reader) and strategy. @@ -296,14 +297,15 @@ wrappers: background cleanup thread. Shared across the wrapper. offers: | - `register(name, ttl:)` — create a named cache partition. - - `set(name, key, value)` / `get(name, key)` — store and read items. - - `get_if_registered(name, key)` — read a partition that may not exist (e.g. a cache owned by an optional plugin). + - `set(name, key, value)` / `get(name, key, register_access: false)` — store and read items. + - `get_if_registered(name, key, register_access: false)` — read a partition that may not exist (e.g. a cache owned by an optional plugin). - `exists?(name, key)` / `remove(name, key)` / `clear(name)` / `clear_all`. whenToUse: | Use it to cache data reused across the wrapper — for example the - `RdsHostListProvider` caches cluster topology here. Reads publish a - `DataAccessEvent` (unless `register_access: false`), which keeps related - monitors alive. + `RdsHostListProvider` caches cluster topology here. A read publishes a + `DataAccessEvent` only when called with `register_access: true`, which + extends the expiration of any monitor that produces that cache's data. Pass + it only when the read should keep that monitor alive. - name: "Monitor Service" short: "Monitor Service" global: true @@ -333,7 +335,7 @@ wrappers: - `release_resources` — stop the background publishing thread. whenToUse: | Use it to decouple event producers and consumers. For example the Storage - Service publishes a `DataAccessEvent` on cache reads, and the Monitor Service + Service publishes a `DataAccessEvent` on cache reads made with `register_access: true`, and the Monitor Service subscribes to it to extend the matching monitor's expiration. - name: "Plugin Manager" short: "Plugin Manager" @@ -351,7 +353,7 @@ wrappers: your plugin. See the dedicated [Plugin Manager](#plugin-manager) section below. perf: - driverNames: "`mysql2`/`pg`" + driverNames: "`mysql2`/`trilogy`/`pg`" # Rough magnitude of the fixed per-call cost, stated in the intro. fixedCostMagnitude: "a microsecond" # The end-to-end real-database benchmark: display name (inline code) and link. diff --git a/content/failover.yaml b/content/failover.yaml index b631e13..ab59dbc 100644 --- a/content/failover.yaml +++ b/content/failover.yaml @@ -53,7 +53,7 @@ wrappers: compatibilityGuide: "../compatibility" pluginGroups: failover: [failover, gdb_failover] - auth: [iam, secrets_manager] + auth: [iam, secrets_manager, federated_auth, okta] connectSnippet: | require 'aws_advanced_ruby_driver_wrapper/postgresql' @@ -85,7 +85,7 @@ wrappers: # way because it needs a Rails application around it, so the two paths are # ordered by who the reader is, not by what fits in one file. gettingStarted: - note: "Requires Ruby 3.3 or later. The gem is `aws_advanced_ruby_driver_wrapper` on RubyGems. Tested with Active Record 7.2, 8.0, and 8.1, `pg` 1.6.3 or later, and `mysql2` 0.5.7 or later." + note: "Requires Ruby 3.3 or later. The gem is `aws_advanced_ruby_driver_wrapper` on RubyGems. Tested with Active Record 7.2, 8.0, and 8.1, `pg` 1.6.3 or later, `mysql2` 0.5.7 or later, and `trilogy` 2.13.2 or later." steps: - title: "1. Add the gem" blocks: @@ -93,7 +93,7 @@ wrappers: code: | # Gemfile gem 'aws_advanced_ruby_driver_wrapper' - gem 'pg' # or: gem 'mysql2' + gem 'pg' # or: gem 'mysql2' / gem 'trilogy' for MySQL - lang: bash code: | bundle install @@ -102,39 +102,44 @@ wrappers: does the same thing. # The house pattern for "this needs another gem" is a warning with # its own snippet, as on the IAM and Secrets Manager pages, rather - # than commented lines inside the main Gemfile. + # than commented lines inside the main Gemfile. The wrapper itself + # declares every gem it requires, so this warning is only for a gem + # `mysql2` requires on Windows without declaring it. - text: | :::warning - Which extra gems your Gemfile needs depends on your Ruby version, your platform, and whether you are using Active Record: - - | Version | Using Active Record | Extra gems | Reason | - | --- | --- | --- | --- | - | Ruby 3.3 | Either | None | `base64`, `bigdecimal` and `logger` are all still default gems | - | Ruby 3.4 | No | `base64`, `bigdecimal` | Ruby 3.4 removed both from the default gems | - | Ruby 3.4 | Yes | None | Active Record declares both itself | - | Ruby 4.0 or later | No | `base64`, `bigdecimal`, `logger` | Ruby 4.0 removed `logger` as well | - | Ruby 4.0 or later | Yes | None | Active Record declares all three itself | - | Ruby 4.0 or later, on Windows with `mysql2` | Either | `fiddle` | `mysql2` loads `libmysql.dll` through `fiddle` without declaring it, and neither does Active Record | - - A bundle missing any of them raises `LoadError` on the first require. + If you are using `mysql2` on Windows with Ruby 4.0 or later, you may also need to add `fiddle` to your Gemfile: + + ```ruby + gem 'fiddle' + ``` + + On Windows, `mysql2` uses `fiddle` to load `libmysql.dll` when you set + `RUBY_MYSQL2_LIBMYSQL_DLL`, when the gem ships its own `libmysql.dll`, or + when Ruby was not installed with RubyInstaller, but it does not declare + `fiddle` as a dependency. Ruby 4.0 removed `fiddle` from the default gems, + so in those cases a bundle without it raises `LoadError` when `mysql2` is + required. ::: - title: "2. Point Active Record at your cluster" blocks: - text: >- - The wrapper registers two adapters, `aws_postgresql` and `aws_mysql2`, - which are drop-in replacements for `postgresql` and `mysql2`. + The wrapper registers three adapters, `aws_postgresql`, `aws_mysql2`, + and `aws_trilogy`, which are drop-in replacements for `postgresql`, + `mysql2`, and `trilogy`. # Without this, Active Record raises AdapterNotFound and names only # its own built-in adapters, which does not hint that a require is # missing. Bundler covers the Rails case; a plain script does not. - text: >- Bundler requires the gem for you. In a plain Ruby script, add `require 'aws_advanced_ruby_driver_wrapper'` first: that single require - is what registers both adapters, and without it Active Record reports + is what registers all three adapters, and without it Active Record reports `aws_postgresql` as a nonexistent adapter. - text: >- - If you are starting without a Rails application, this is a complete - program. Save it as `main.rb` and run it: + If you are starting without a Rails application, add + `gem 'activerecord'` to the Gemfile from step 1 (outside Rails, nothing + else installs it), run `bundle install`, and this is a complete program. + Save it as `main.rb` and run it: - lang: ruby code: | # main.rb @@ -191,10 +196,21 @@ wrappers: - text: | :::note Mixing wrapped and standard adapters in one application The wrapped adapters register their type information under the underlying - `postgresql` and `mysql2` adapter names. If one application uses both a - standard connection (`postgresql`/`mysql2`) and a wrapped one - (`aws_postgresql`/`aws_mysql2`), a custom type registered for one is shared - with the other, because both resolve under the same underlying adapter key. + `postgresql`, `mysql2`, and `trilogy` adapter names. If one application uses + both a standard connection (`postgresql`/`mysql2`/`trilogy`) and a wrapped one + (`aws_postgresql`/`aws_mysql2`/`aws_trilogy`), a custom type registered for + one is shared with the other, because both resolve under the same underlying + adapter key. + ::: + - text: | + :::note Keeping the password out of your source + Read it from the environment with `ENV.fetch('PGPASSWORD')` in Ruby, or + `<%= ENV.fetch('PGPASSWORD') %>` in `config/database.yml`, or have + AWS manage it: add `secrets_manager` to `wrapper_plugins` and drop the + `password:` key, as described on + [AWS Secrets Manager Plugin](using-plugins/aws-secrets-manager). For a + database user with no password at all, consider using `iam` instead; see + [IAM Authentication Plugin](using-plugins/iam-authentication). ::: - text: | :::note Keeping the password out of your source @@ -210,8 +226,8 @@ wrappers: blocks: - text: >- Without Active Record, the wrapper provides connection classes that - stand in for `PG::Connection` and `Mysql2::Client`. This is a complete - program; save it as `main.rb` and run it: + stand in for `PG::Connection`, `Mysql2::Client`, and `Trilogy`. This is a + complete program; save it as `main.rb` and run it: - lang: ruby code: | # main.rb @@ -241,7 +257,10 @@ wrappers: stands in for `PG::Connection` and takes `dbname:` and `user:`. For MySQL, `require 'aws_advanced_ruby_driver_wrapper/mysql'` and use `AwsAdvancedRubyDriverWrapper::WrapperMysql2Client`, which stands in - for `Mysql2::Client` and takes `database:` and `username:`. Either + for `Mysql2::Client` and takes `database:` and `username:`. To use the + Trilogy driver instead, `require 'aws_advanced_ruby_driver_wrapper/trilogy'` + and use `AwsAdvancedRubyDriverWrapper::WrapperTrilogyClient`, which stands + in for `Trilogy` and takes the same `database:` and `username:`. Either way the calls your code already makes keep working, and the plugins act on each one. - title: "Next" @@ -323,7 +342,7 @@ wrapperOnly: - | ### ActiveRecord integration - Through ActiveRecord (the `aws_postgresql` / `aws_mysql2` adapters), the adapter's + Through ActiveRecord (the `aws_postgresql` / `aws_mysql2` / `aws_trilogy` adapters), the adapter's `translate_exception` decides what your code rescues, and only one failover error is translated: @@ -466,7 +485,7 @@ enhanced: thirdPartyNote: ruby: | :::note Using the wrapper through ActiveRecord - When you use the wrapper through ActiveRecord (`aws_postgresql` or `aws_mysql2`), + When you use the wrapper through ActiveRecord (`aws_postgresql`, `aws_mysql2`, or `aws_trilogy`), reconnection is partially handled for you. On a successful failover the adapter re-runs `configure_connection` and reuses the pooled connection in place rather than discarding it, so you should not call `disconnect!` or discard the connection object @@ -475,10 +494,48 @@ enhanced: wrapperOnly: ruby: + - | + ## Timeouts and idle connections on MySQL + + On MySQL, the failover plugin treats a connection that timed out or was closed by + the server as lost, and fails over. This applies to `mysql2` (`WrapperMysql2Client` + and `aws_mysql2`) and to `trilogy` (`WrapperTrilogyClient` and `aws_trilogy`), and + includes: + + - A query that runs longer than the client's `read_timeout`. The driver closes the + socket before it raises the timeout, so the connection cannot be reused. + - A query on a connection that sat idle longer than the server's `wait_timeout`. + The server closes such a connection; MySQL 8.0.24 and later reports error 4031, + and earlier versions report a lost connection (2006 or 2013). + - A connection lost during a query, or a server that has gone away (with `mysql2`, + errors 2006, 2013, and 2055). + + Your code then sees `FailoverSuccessError` (or `TransactionStateUnknownError` inside a + transaction) instead of the driver's timeout or connection error. Through ActiveRecord + these errors are re-raised unchanged (see [ActiveRecord integration](#activerecord-integration)), + and ActiveRecord does not retry them for you. To avoid a failover that is caused by a + slow query or an idle connection rather than by the database: + + - Set `read_timeout` higher than your slowest expected query. + - Keep pooled connections from outliving `wait_timeout`: raise `wait_timeout` on the + server, or have the pool close idle connections sooner, for example with + ActiveRecord's `idle_timeout`. + + A lock wait timeout (error 1205) does not trigger failover. The connection is still + healthy, and the driver's error is raised as usual. + + :::note Changed in 1.1.0 + Before 1.1.0, `mysql2` did not fail over on a `read_timeout` or on errors 4031 and + 2055. A `read_timeout` raised `Mysql2::Error::TimeoutError` (`ActiveRecord::AdapterTimeout` + under `aws_mysql2`), and errors 4031 and 2055 were raised as is. Under `aws_mysql2`, + error 4031 became `ActiveRecord::ConnectionFailed`, which ActiveRecord answered by + reconnecting to the original endpoint and retrying the queries it considers + retryable, and error 2055 became `ActiveRecord::StatementInvalid`. + ::: - | ## ActiveRecord integration - When using the wrapper through ActiveRecord (`aws_postgresql` or `aws_mysql2`), the + When using the wrapper through ActiveRecord (`aws_postgresql`, `aws_mysql2`, or `aws_trilogy`), the adapter's `translate_exception` decides what your code actually rescues, and the outcome differs by error: diff --git a/content/pages.yaml b/content/pages.yaml index 8e1b834..9670c6a 100644 --- a/content/pages.yaml +++ b/content/pages.yaml @@ -144,6 +144,24 @@ pages: template: plugin-aws-secrets-manager contextProfile: plugins + - id: using-plugins-federated-auth + path: using-plugins/federated-auth + title: Federated Authentication Plugin + category: Using Plugins + wrappers: [ruby] + parent: overview + template: plugin-saml-auth + contextProfile: plugins + + - id: using-plugins-okta-auth + path: using-plugins/okta-auth + title: Okta Authentication Plugin + category: Using Plugins + wrappers: [ruby] + parent: overview + template: plugin-saml-auth + contextProfile: plugins + - id: using-plugins-initial-connection-strategy path: using-plugins/initial-connection-strategy title: Initial Connection Strategy Plugin @@ -201,6 +219,15 @@ pages: template: cluster-id contextProfile: cluster-id + - id: telemetry + path: telemetry + title: Telemetry + category: Shared Configuration + wrappers: [ruby] + parent: overview + template: telemetry + contextProfile: telemetry + # --------------------------------------------------------------------------- # Compatibility guide. Each wrapper renders only its own plugins. # --------------------------------------------------------------------------- diff --git a/content/partials/plugin-exclusivity-banner.md.j2 b/content/partials/plugin-exclusivity-banner.md.j2 new file mode 100644 index 0000000..8510ecf --- /dev/null +++ b/content/partials/plugin-exclusivity-banner.md.j2 @@ -0,0 +1,27 @@ +{# + The "only one plugin from this group" warning admonition, emitted once per + plugin page. + + The import + group/`others` computation + warning block used to be copy-pasted + into every plugin template (iam, secrets-manager, saml, gdb-failover) and the + enhanced-failover page; a change to how `others` is derived or to the admonition + meant editing each one. Now each template does a single + `{% include "partials/plugin-exclusivity-banner.md.j2" %}`. + + Resolves the current plugin's group and code two ways, so it serves both page + shapes without duplication: + - plugin pages (the `plugins` profile exposes `plugin`): uses + `plugin.pluginGroup` and `plugin.code`. + - the enhanced-failover page (no `plugin` in context): the template sets + `banner_group` and `banner_code` before the include. + Also relies on `wrapper.pluginGroups`, `plugin_group_labels`, and `wrapper_id` + from the parent context. The exact sentence comes from the shared `exclusivity` + macro, so the wording still has a single source (see plugin-exclusivity.md.j2). +#} +{% import "partials/plugin-exclusivity.md.j2" as ex %} +{% set group = plugin.pluginGroup if plugin is defined else banner_group %} +{% set this_code = plugin.code if plugin is defined else banner_code %} +{% set others = (wrapper.pluginGroups[group] or []) | reject('equalto', this_code) | list %} +:::warning Only one {{ plugin_group_labels[group] }} plugin at a time +{{ ex.exclusivity(plugin_group_labels[group], this_code, others, 'PluginConflictError' if wrapper_id == 'ruby' else none) }} +::: diff --git a/content/partials/plugin-exclusivity.md.j2 b/content/partials/plugin-exclusivity.md.j2 index c192ad0..a2a0763 100644 --- a/content/partials/plugin-exclusivity.md.j2 +++ b/content/partials/plugin-exclusivity.md.j2 @@ -17,12 +17,20 @@ `conflict_error`, when given, names the error the wrapper raises if the group's plugins are combined. + + `lead` is the one canonical statement of the rule. #} +{% macro lead(group_label) -%} +Only one {{ group_label }} plugin may be enabled per connection. +{%- endmacro %} {% macro exclusivity(group_label, this_code, others, conflict_error=none) -%} -Only one {{ group_label }} plugin may be enabled per connection. Do not use `{{ this_code }}` together with +{{ lead(group_label) }} Do not use `{{ this_code }}` together with {%- if others | length == 1 %} the other `{{ others[0] }}` plugin {%- elif others | length > 1 %} any of the other {{ group_label }} plugins ({% for c in others %}`{{ c }}`{% if not loop.last %}, {% endif %}{% endfor %}) {%- else %} any other {{ group_label }} plugin {%- endif %} at the same time for the same connection. {%- if conflict_error %} Configuring more than one raises a `{{ conflict_error }}` at connection initialization.{% endif %} {%- endmacro %} +{% macro exclusivity_footnote(group_label, codes) -%} +{{ lead(group_label) }} The {% for c in codes %}`{{ c }}`{% if not loop.last %}{% if loop.revindex0 == 1 %}{% if codes | length > 2 %},{% endif %} and {% else %}, {% endif %}{% endif %}{% endfor %} plugins each set the connection credential, so enabling more than one conflicts. +{%- endmacro %} diff --git a/content/plugins.yaml b/content/plugins.yaml index 49018ef..d14d1ab 100644 --- a/content/plugins.yaml +++ b/content/plugins.yaml @@ -131,7 +131,7 @@ plugins: ruby: { name: iam_region, required: "No", defaultNote: "parsed from host", example: "us-east-1" } - concept: iamExpiration type: integer - description: "Number of seconds a generated IAM token is kept in the cache before a new one is generated. The token itself is valid for 15 minutes, and a cached token is never used within 60 seconds of that expiry, so values of `840.0` and above will all have their tokens refetched at the `840` mark. The token cache is shared by every connection in the process, and its lifetime is set by the first connection that uses the IAM plugin; later connections that set a different value use the first connection's value. A value greater than `870.0` or less than or equal to `0` is rejected." + description: "Number of seconds a generated IAM token is kept in the cache before a new one is generated. The token itself is valid for 15 minutes, and a cached token is never used within 60 seconds of that expiry, so values of `840.0` and above will all have their tokens refetched at the `840` mark. The token cache is shared by every connection in the process that uses the `iam`, `federated_auth`, or `okta` plugin, and its lifetime is set by the first such connection; later connections that set a different value use the first connection's value. A value greater than `870.0` or less than or equal to `0` is rejected." spellings: ruby: { name: iam_expiration_sec, type: float, required: "No", default: "870.0", unit: s, example: "600.0 (maximum 870.0)" } - concept: iamTokenProperty @@ -142,7 +142,7 @@ plugins: - concept: awsCredentialsProvider type: object availability: { ruby: true } - description: "A custom AWS credentials provider instance. One property is read by the IAM authentication, Secrets Manager and KMS encryption plugins, so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain." + description: "A custom AWS credentials provider instance. One property is read by every plugin that calls AWS — IAM authentication, Secrets Manager, KMS encryption and custom endpoint — so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain." spellings: ruby: { name: aws_credentials_provider, required: "No", defaultNote: "SDK default chain", example: "Aws::AssumeRoleCredentials.new(...)" } globalDatabases: | @@ -226,6 +226,16 @@ plugins: ) ``` + With the Trilogy driver, swap in + `AwsAdvancedRubyDriverWrapper::WrapperTrilogyClient`. IAM authentication works + the same way — keep `enable_cleartext_plugin: true` — but two TLS keys differ + on Trilogy: the CA certificate is `ssl_ca` (Trilogy's name for it) rather than + `sslca`, and on the direct client `ssl_mode` must be an integer constant + (`ssl_mode: Trilogy::SSL_VERIFY_IDENTITY`) — a string or symbol raises + `TypeError`. (The `aws_trilogy` ActiveRecord adapter does accept the string + mode names such as `verify_identity`.) See + [Configuring TLS/SSL](../configuring-tls) for the full per-driver table. + **PostgreSQL (`pg`):** ```ruby @@ -261,6 +271,10 @@ plugins: using the plugin with MySQL. Because the token is sent in cleartext, you must also use a TLS/SSL connection so it is encrypted in transit. This does not apply to PostgreSQL (`pg`). + + This applies to both MySQL drivers (`mysql2` and `trilogy`). On `trilogy`, + omitting `enable_cleartext_plugin: true` makes the driver raise + `Trilogy::AuthPluginError` and the token is never sent. ::: - | ## Token caching @@ -277,10 +291,11 @@ plugins: fresh token and retries the connection once. :::note - The token cache is shared by every connection in the process, and the first - connection that uses the IAM plugin sets its `iam_expiration_sec`. Connections - opened later with a different value still use the first connection's value, so - set `iam_expiration_sec` to the same value on every connection. + The token cache is shared by every connection in the process that uses the + `iam`, `federated_auth`, or `okta` plugin, and the first such connection sets + its `iam_expiration_sec`. Connections opened later with a different value still + use the first connection's value, so set `iam_expiration_sec` to the same value + on every connection. ::: ## Related @@ -290,6 +305,400 @@ plugins: - [Configuring TLS/SSL](../configuring-tls) — the token is sent as the password, and on MySQL it is sent in cleartext. + # ========================================================================= + # Federated Authentication Plugin (AD FS) + # ========================================================================= + federated-auth: + availableWrappers: [ruby] + intro: | + The Federated Authentication Plugin adds support for authenticating through a + federated identity provider — [Microsoft Active Directory Federation Services + (AD FS)](https://learn.microsoft.com/en-us/windows-server/identity/active-directory-federation-services) — + and then connecting to the database with AWS IAM. The plugin signs in to AD FS, + obtains a SAML assertion, exchanges it for temporary AWS credentials, and uses + those credentials to generate an IAM authentication token for the connection. + code: + ruby: federated_auth + pluginGroup: auth + availableSince: + ruby: "1.1.0" + enableSnippet: + ruby: | + require 'aws_advanced_ruby_driver_wrapper/postgresql' + + conn = AwsAdvancedRubyDriverWrapper::WrapperPgConnection.new( + host: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com", + wrapper_plugins: "federated_auth", + db_user: "iam_user", + idp_endpoint: "adfs.example.com", + idp_username: "someFederatedUsername@example.com", + idp_password: "someFederatedPassword", + iam_role_arn: "arn:aws:iam::123456789012:role/adfs_example_iam_role", + iam_idp_arn: "arn:aws:iam::123456789012:saml-provider/adfs_example", + iam_region: "us-east-1", + sslmode: "verify-full", + sslrootcert: "/path/to/global-bundle.pem" + ) + parameters: + - concept: dbUser + type: string + description: "The database username the generated IAM authentication token is minted for — the IAM-mapped database account the connection is made as." + spellings: + ruby: { name: db_user, required: "Yes", defaultNote: "—", example: "iam_user" } + - concept: idpEndpoint + type: string + description: "The host name of the AD FS identity provider used to authenticate." + spellings: + ruby: { name: idp_endpoint, required: "Yes", defaultNote: "—", example: "adfs.example.com" } + - concept: idpUsername + type: string + description: "The username used to sign in to the identity provider. If not set, the plugin falls back to the connection `user`/`username`." + spellings: + ruby: { name: idp_username, required: "No", defaultNote: "connection user", example: "someFederatedUsername@example.com" } + - concept: idpPassword + type: string + description: "The password used to sign in to the identity provider. If not set, the plugin falls back to the connection `password`." + spellings: + ruby: { name: idp_password, required: "No", defaultNote: "connection password", example: "someFederatedPassword" } + - concept: idpPort + type: integer + description: "The port the AD FS host listens on, used to build the sign-on URL." + spellings: + ruby: { name: idp_port, required: "No", default: "443", example: "443" } + - concept: rpIdentifier + type: string + description: "The relying-party identifier sent to AD FS when requesting the SAML assertion." + spellings: + ruby: { name: rp_identifier, required: "No", default: "urn:amazon:webservices", example: "urn:amazon:webservices" } + - concept: iamRoleArn + type: string + description: "The ARN of the IAM role assumed through the SAML assertion to obtain temporary AWS credentials." + spellings: + ruby: { name: iam_role_arn, required: "Yes", defaultNote: "—", example: "arn:aws:iam::123456789012:role/adfs_example_iam_role" } + - concept: iamIdpArn + type: string + description: "The ARN of the SAML identity provider registered in AWS IAM." + spellings: + ruby: { name: iam_idp_arn, required: "Yes", defaultNote: "—", example: "arn:aws:iam::123456789012:saml-provider/adfs_example" } + - concept: iamRegion + type: string + description: "Overrides the AWS region used to generate the IAM token. By default it is parsed from the connection host." + spellings: + ruby: { name: iam_region, required: "No", defaultNote: "parsed from host", example: "us-east-1" } + - concept: iamHost + type: string + description: "Overrides the host used to generate the IAM token. By default it is derived from the connection host." + spellings: + ruby: { name: iam_host, required: "No", defaultNote: "derived from host", example: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com" } + - concept: iamPort + type: integer + description: "Overrides the port used to generate the IAM token. By default it is taken from the connection, or the dialect's default port." + spellings: + ruby: { name: iam_port, required: "No", defaultNote: "dialect default", example: "5432" } + - concept: iamExpiration + type: float + description: "Number of seconds a generated IAM token is kept in the cache before a new one is generated. The token itself is valid for 15 minutes, and a cached token is never used within 60 seconds of that expiry, so values of `840.0` and above will all have their tokens refetched at the `840` mark. The token cache is shared by every connection in the process that uses the `iam`, `federated_auth`, or `okta` plugin, and its lifetime is set by the first such connection; later connections that set a different value use the first connection's value. A value greater than `870.0` or less than or equal to `0` is rejected." + spellings: + ruby: { name: iam_expiration_sec, required: "No", default: "870.0", unit: s, example: "600.0 (maximum 870.0)" } + - concept: sslInsecure + type: boolean + description: "When `true`, disables TLS certificate verification on the HTTPS requests the plugin makes to the identity provider. Intended for development only." + spellings: + ruby: { name: ssl_insecure, required: "No", default: "false", example: "true" } + - concept: httpClientSocketTimeout + type: float + description: "Read (socket) timeout for the HTTPS requests the plugin makes to the identity provider." + spellings: + ruby: { name: http_client_socket_timeout_sec, required: "No", default: "60.0", unit: s, example: "60.0" } + - concept: httpClientConnectTimeout + type: float + description: "Connect timeout for the HTTPS requests the plugin makes to the identity provider." + spellings: + ruby: { name: http_client_connect_timeout_sec, required: "No", default: "60.0", unit: s, example: "60.0" } + prereqCount: + ruby: 1 + wrapperOnly: + ruby: + - | + ## Prerequisites + + :::warning + This plugin requires the AWS SDK for RDS. Add it to your Gemfile: + + ```ruby + gem 'aws-sdk-rds' + ``` + ::: + + The plugin signs in to your identity provider over HTTPS using Ruby's standard + library HTTP client, so no additional SAML or XML parsing gem is required. It + obtains AWS credentials from the SAML assertion through AWS STS + `AssumeRoleWithSAML`; it does not read `aws_credentials_provider` or the AWS SDK + default credential provider chain. + + Before using the plugin, enable IAM database authentication on your database, + create an [IAM SAML identity provider](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html) + and an IAM role granting `rds-db:connect`, and create a database account mapped + to IAM: + + - MySQL: `CREATE USER iam_user IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS';` + - PostgreSQL: `CREATE USER iam_user; GRANT rds_iam TO iam_user;` + - | + ## Use TLS/SSL with federated authentication + + :::warning + Use a **TLS/SSL 1.2+ connection**. The plugin injects the generated IAM token as + the connection password, and TLS ensures it is encrypted in transit. + ::: + + **PostgreSQL (`pg`):** set `sslmode: "verify-full"` and point `sslrootcert` at the + [AWS global certificate bundle](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html). + + ```ruby + AwsAdvancedRubyDriverWrapper::WrapperPgConnection.new( + host: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com", + wrapper_plugins: "federated_auth", + db_user: "iam_user", + idp_endpoint: "adfs.example.com", + idp_username: "someFederatedUsername@example.com", + idp_password: "someFederatedPassword", + iam_role_arn: "arn:aws:iam::123456789012:role/adfs_example_iam_role", + iam_idp_arn: "arn:aws:iam::123456789012:saml-provider/adfs_example", + iam_region: "us-east-1", + sslmode: "verify-full", + sslrootcert: "/path/to/global-bundle.pem" + ) + ``` + + **MySQL (`mysql2`):** set `ssl_mode: "verify_identity"`, point `sslca` at the + global certificate bundle, and set `enable_cleartext_plugin: true`. RDS/Aurora + MySQL IAM authentication relies on the MySQL `mysql_clear_password` client plugin + because the token must be sent to the server in cleartext; the wrapper does + **not** set this for you. + + ```ruby + AwsAdvancedRubyDriverWrapper::WrapperMysql2Client.new( + host: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com", + wrapper_plugins: "federated_auth", + db_user: "iam_user", + idp_endpoint: "adfs.example.com", + idp_username: "someFederatedUsername@example.com", + idp_password: "someFederatedPassword", + iam_role_arn: "arn:aws:iam::123456789012:role/adfs_example_iam_role", + iam_idp_arn: "arn:aws:iam::123456789012:saml-provider/adfs_example", + iam_region: "us-east-1", + enable_cleartext_plugin: true, + sslca: "/path/to/global-bundle.pem", + ssl_mode: "verify_identity" + ) + ``` + + With the Trilogy driver, use + `AwsAdvancedRubyDriverWrapper::WrapperTrilogyClient`. `enable_cleartext_plugin: + true` is still required — without it Trilogy raises `Trilogy::AuthPluginError` + — but two TLS keys differ: the CA certificate is `ssl_ca` rather than `sslca`, + and on the direct client `ssl_mode` must be an integer constant + (`ssl_mode: Trilogy::SSL_VERIFY_IDENTITY`), not a string. See + [Configuring TLS/SSL](../configuring-tls). + + For the full picture, see [Configuring TLS/SSL](../configuring-tls). + + # ========================================================================= + # Okta Authentication Plugin + # ========================================================================= + okta-auth: + availableWrappers: [ruby] + intro: | + The Okta Authentication Plugin adds support for authenticating through + [Okta](https://www.okta.com/) as the federated identity provider and then + connecting to the database with AWS IAM. The plugin signs in to Okta, obtains a + SAML assertion for the configured AWS application, exchanges it for temporary AWS + credentials, and uses those credentials to generate an IAM authentication token + for the connection. + code: + ruby: okta + pluginGroup: auth + availableSince: + ruby: "1.1.0" + enableSnippet: + ruby: | + require 'aws_advanced_ruby_driver_wrapper/postgresql' + + conn = AwsAdvancedRubyDriverWrapper::WrapperPgConnection.new( + host: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com", + wrapper_plugins: "okta", + db_user: "iam_user", + idp_endpoint: "my-org.okta.com", + idp_username: "someFederatedUsername@example.com", + idp_password: "someFederatedPassword", + app_id: "0oa1b2c3d4EXAMPLE", + iam_role_arn: "arn:aws:iam::123456789012:role/okta_example_iam_role", + iam_idp_arn: "arn:aws:iam::123456789012:saml-provider/okta_example", + iam_region: "us-east-1", + sslmode: "verify-full", + sslrootcert: "/path/to/global-bundle.pem" + ) + parameters: + - concept: dbUser + type: string + description: "The database username the generated IAM authentication token is minted for — the IAM-mapped database account the connection is made as." + spellings: + ruby: { name: db_user, required: "Yes", defaultNote: "—", example: "iam_user" } + - concept: idpEndpoint + type: string + description: "The host name of your Okta organization used to authenticate." + spellings: + ruby: { name: idp_endpoint, required: "Yes", defaultNote: "—", example: "my-org.okta.com" } + - concept: idpUsername + type: string + description: "The username used to sign in to the identity provider. If not set, the plugin falls back to the connection `user`/`username`." + spellings: + ruby: { name: idp_username, required: "No", defaultNote: "connection user", example: "someFederatedUsername@example.com" } + - concept: idpPassword + type: string + description: "The password used to sign in to the identity provider. If not set, the plugin falls back to the connection `password`." + spellings: + ruby: { name: idp_password, required: "No", defaultNote: "connection password", example: "someFederatedPassword" } + - concept: appId + type: string + description: "The identifier of the AWS application configured in Okta." + spellings: + ruby: { name: app_id, required: "Yes", defaultNote: "—", example: "0oa1b2c3d4EXAMPLE" } + - concept: iamRoleArn + type: string + description: "The ARN of the IAM role assumed through the SAML assertion to obtain temporary AWS credentials." + spellings: + ruby: { name: iam_role_arn, required: "Yes", defaultNote: "—", example: "arn:aws:iam::123456789012:role/okta_example_iam_role" } + - concept: iamIdpArn + type: string + description: "The ARN of the SAML identity provider registered in AWS IAM." + spellings: + ruby: { name: iam_idp_arn, required: "Yes", defaultNote: "—", example: "arn:aws:iam::123456789012:saml-provider/okta_example" } + - concept: iamRegion + type: string + description: "Overrides the AWS region used to generate the IAM token. By default it is parsed from the connection host." + spellings: + ruby: { name: iam_region, required: "No", defaultNote: "parsed from host", example: "us-east-1" } + - concept: iamHost + type: string + description: "Overrides the host used to generate the IAM token. By default it is derived from the connection host." + spellings: + ruby: { name: iam_host, required: "No", defaultNote: "derived from host", example: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com" } + - concept: iamPort + type: integer + description: "Overrides the port used to generate the IAM token. By default it is taken from the connection, or the dialect's default port." + spellings: + ruby: { name: iam_port, required: "No", defaultNote: "dialect default", example: "5432" } + - concept: iamExpiration + type: float + description: "Number of seconds a generated IAM token is kept in the cache before a new one is generated. The token itself is valid for 15 minutes, and a cached token is never used within 60 seconds of that expiry, so values of `840.0` and above will all have their tokens refetched at the `840` mark. The token cache is shared by every connection in the process that uses the `iam`, `federated_auth`, or `okta` plugin, and its lifetime is set by the first such connection; later connections that set a different value use the first connection's value. A value greater than `870.0` or less than or equal to `0` is rejected." + spellings: + ruby: { name: iam_expiration_sec, required: "No", default: "870.0", unit: s, example: "600.0 (maximum 870.0)" } + - concept: sslInsecure + type: boolean + description: "When `true`, disables TLS certificate verification on the HTTPS requests the plugin makes to the identity provider. Intended for development only." + spellings: + ruby: { name: ssl_insecure, required: "No", default: "false", example: "true" } + - concept: httpClientSocketTimeout + type: float + description: "Read (socket) timeout for the HTTPS requests the plugin makes to the identity provider." + spellings: + ruby: { name: http_client_socket_timeout_sec, required: "No", default: "60.0", unit: s, example: "60.0" } + - concept: httpClientConnectTimeout + type: float + description: "Connect timeout for the HTTPS requests the plugin makes to the identity provider." + spellings: + ruby: { name: http_client_connect_timeout_sec, required: "No", default: "60.0", unit: s, example: "60.0" } + prereqCount: + ruby: 1 + wrapperOnly: + ruby: + - | + ## Prerequisites + + :::warning + This plugin requires the AWS SDK for RDS. Add it to your Gemfile: + + ```ruby + gem 'aws-sdk-rds' + ``` + ::: + + The plugin signs in to Okta over HTTPS using Ruby's standard library HTTP + client, so no additional SAML or XML parsing gem is required. It obtains AWS + credentials from the SAML assertion through AWS STS `AssumeRoleWithSAML`; it + does not read `aws_credentials_provider` or the AWS SDK default credential + provider chain. + + Before using the plugin, enable IAM database authentication on your database, + [configure Okta as an AWS identity provider](https://help.okta.com/en-us/content/topics/deploymentguides/aws/aws-deployment.htm), + create the matching IAM SAML identity provider and an IAM role granting + `rds-db:connect`, and create a database account mapped to IAM: + + - MySQL: `CREATE USER iam_user IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS';` + - PostgreSQL: `CREATE USER iam_user; GRANT rds_iam TO iam_user;` + - | + ## Use TLS/SSL with Okta authentication + + :::warning + Use a **TLS/SSL 1.2+ connection**. The plugin injects the generated IAM token as + the connection password, and TLS ensures it is encrypted in transit. + ::: + + **PostgreSQL (`pg`):** set `sslmode: "verify-full"` and point `sslrootcert` at the + [AWS global certificate bundle](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html). + + ```ruby + AwsAdvancedRubyDriverWrapper::WrapperPgConnection.new( + host: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com", + wrapper_plugins: "okta", + db_user: "iam_user", + idp_endpoint: "my-org.okta.com", + idp_username: "someFederatedUsername@example.com", + idp_password: "someFederatedPassword", + app_id: "0oa1b2c3d4EXAMPLE", + iam_role_arn: "arn:aws:iam::123456789012:role/okta_example_iam_role", + iam_idp_arn: "arn:aws:iam::123456789012:saml-provider/okta_example", + iam_region: "us-east-1", + sslmode: "verify-full", + sslrootcert: "/path/to/global-bundle.pem" + ) + ``` + + **MySQL (`mysql2`):** set `ssl_mode: "verify_identity"`, point `sslca` at the + global certificate bundle, and set `enable_cleartext_plugin: true`. RDS/Aurora + MySQL IAM authentication relies on the MySQL `mysql_clear_password` client plugin + because the token must be sent to the server in cleartext; the wrapper does + **not** set this for you. + + ```ruby + AwsAdvancedRubyDriverWrapper::WrapperMysql2Client.new( + host: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com", + wrapper_plugins: "okta", + db_user: "iam_user", + idp_endpoint: "my-org.okta.com", + idp_username: "someFederatedUsername@example.com", + idp_password: "someFederatedPassword", + app_id: "0oa1b2c3d4EXAMPLE", + iam_role_arn: "arn:aws:iam::123456789012:role/okta_example_iam_role", + iam_idp_arn: "arn:aws:iam::123456789012:saml-provider/okta_example", + iam_region: "us-east-1", + enable_cleartext_plugin: true, + sslca: "/path/to/global-bundle.pem", + ssl_mode: "verify_identity" + ) + ``` + + With the Trilogy driver, use + `AwsAdvancedRubyDriverWrapper::WrapperTrilogyClient`. `enable_cleartext_plugin: + true` is still required — without it Trilogy raises `Trilogy::AuthPluginError` + — but two TLS keys differ: the CA certificate is `ssl_ca` rather than `sslca`, + and on the direct client `ssl_mode` must be an integer constant + (`ssl_mode: Trilogy::SSL_VERIFY_IDENTITY`), not a string. See + [Configuring TLS/SSL](../configuring-tls). + + For the full picture, see [Configuring TLS/SSL](../configuring-tls). + # ========================================================================= # AWS Secrets Manager Plugin # ========================================================================= @@ -356,7 +765,7 @@ plugins: - concept: awsCredentialsProvider type: object availability: { ruby: true } - description: "A custom AWS credentials provider instance. One property is read by the IAM authentication, Secrets Manager and KMS encryption plugins, so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain." + description: "A custom AWS credentials provider instance. One property is read by every plugin that calls AWS — IAM authentication, Secrets Manager, KMS encryption and custom endpoint — so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain." spellings: ruby: { name: aws_credentials_provider, required: "No", defaultNote: "SDK default chain", example: "Aws::AssumeRoleCredentials.new(...)" } - concept: secretRetryTimeout @@ -463,6 +872,14 @@ plugins: column never holds plaintext. See [Server-side enforcement is required](#server-side-enforcement-is-required) and [Enforce encryption in the database](#enforce-encryption-in-the-database) below. ::: + + :::warning Not supported with the Trilogy driver + The plugin can encrypt a value only when it is sent as a bound parameter, which + requires prepared statements. The Trilogy driver does not support prepared + statements, so the plugin cannot be used with it: both the plugin and + `KeyManagementUtility` refuse a Trilogy connection with an explicit error. Use the + `mysql2` driver (or `pg` on PostgreSQL) for column encryption. + ::: code: ruby: kms_encryption availableSince: @@ -548,7 +965,7 @@ plugins: - concept: awsCredentialsProvider type: object availability: { ruby: true } - description: "A custom AWS credentials provider instance. One property is read by the IAM authentication, Secrets Manager and KMS encryption plugins, so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain." + description: "A custom AWS credentials provider instance. One property is read by every plugin that calls AWS — IAM authentication, Secrets Manager, KMS encryption and custom endpoint — so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain." spellings: ruby: { name: aws_credentials_provider, required: "No", defaultNote: "SDK default chain", example: "Aws::AssumeRoleCredentials.new(...)" } - concept: returnUnverified @@ -997,7 +1414,8 @@ plugins: ### Set up an encrypted column `KeyManagementUtility` runs on a plain `pg` or `mysql2` connection that you - open and close yourself. Build its configuration from the same `encryption_*` + open and close yourself. (It does not support `trilogy`, for the same + prepared-statement reason the plugin does not.) Build its configuration from the same `encryption_*` parameters the plugin uses, then create a master key and turn on encryption for an existing binary column: @@ -1401,6 +1819,12 @@ plugins: description: "Maximum time the plugin waits for custom endpoint info to be made available by the monitor." spellings: ruby: { name: wait_for_custom_endpoint_info_timeout_sec, type: float, required: "No", default: "5.0", unit: s, example: "7.0" } + - concept: awsCredentialsProvider + type: object + availability: { ruby: true } + description: "A custom AWS credentials provider instance. One property is read by every plugin that calls AWS — IAM authentication, Secrets Manager, KMS encryption and custom endpoint — so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain. The custom endpoint monitor is shared by every connection to the same custom endpoint, so it uses the provider of the first connection that starts it." + spellings: + ruby: { name: aws_credentials_provider, required: "No", defaultNote: "SDK default chain", example: "Aws::AssumeRoleCredentials.new(...)" } prereqCount: ruby: 1 wrapperOnly: @@ -1416,9 +1840,9 @@ plugins: gem 'aws-sdk-rds' ``` - The plugin uses the AWS SDK default credential provider chain, so the credentials - must be available through the chain (for example environment variables, an instance - profile, or an ECS task role). See [AWS Credentials](../aws-credentials). + The plugin signs these calls with the provider given in `aws_credentials_provider`, + or with the AWS SDK default credential provider chain when it is not set. See + [AWS Credentials](../aws-credentials). ::: # ========================================================================= @@ -1688,7 +2112,7 @@ plugins: - **Before the switchover**, it inventories the blue and green endpoints and their IP addresses. - **During the active switchover**, it temporarily suspends calls to blue nodes and substitutes hostnames with the corresponding IP addresses to avoid stale DNS. - - **After the switchover**, it monitors DNS until blue endpoints are reconfigured, then stops substituting. + - **After the switchover**, it monitors DNS until blue endpoints are reconfigured, then stops substituting. From this phase on, it also invalidates connections that were opened to the old blue environment before the switchover, so their next use raises an error instead of reading from retired blue nodes. See `bg_drop_blue_connections` below. - **Once switchover completes**, it rejects new connections to green nodes. - **If the switchover fails or rolls back**, it detects that and restores normal handling. code: @@ -1751,6 +2175,11 @@ plugins: description: "Maximum duration allowed for switchover completion. If the process stalls or exceeds this, the wrapper assumes completion and resumes normal operations." spellings: ruby: { name: bg_switchover_timeout_sec, type: float, required: "No", default: "180.0", unit: s, example: "180.0" } + - concept: dropBlueConnections + type: boolean + description: "Whether to invalidate connections that were opened to the old blue environment before a switchover. Once the switchover is confirmed (it reaches the Post or Completed phase), each such connection is closed the next time it is used. With the failover plugin enabled, that use triggers failover through Blue/Green routing and raises one of the [failover errors](../enhanced-failover#failover-errors): `FailoverSuccessError` or `TransactionStateUnknownError` (inside a transaction) when it reconnects, or `FailoverFailedError` when it cannot, for example during a network disconnect. Without it, the driver raises its closed-connection error; under ActiveRecord, a query it considers retryable may instead be reconnected and retried for you. In neither case is a stale read served from the old blue environment. Connections are invalidated only if the plugin saw the switchover while it was in progress, and none are invalidated if the switchover rolls back, or if `bg_switchover_timeout_sec` elapses before the switchover reaches the Post phase." + spellings: + ruby: { name: bg_drop_blue_connections, required: "No", default: "true", example: "false" } monitoringPrefix: ruby: "bg_monitoring_" monitoringSnippet: diff --git a/content/scenarios.yaml b/content/scenarios.yaml index 55e0b8f..1881e09 100644 --- a/content/scenarios.yaml +++ b/content/scenarios.yaml @@ -66,13 +66,13 @@ wrappers: ruby: - engineLabel: { pg: PostgreSQL, mysql: MySQL } - adapter: { pg: aws_postgresql, mysql: aws_mysql2 } - gem: { pg: pg, mysql: mysql2 } - requirePath: { pg: aws_advanced_ruby_driver_wrapper/postgresql, mysql: aws_advanced_ruby_driver_wrapper/mysql } - directClass: { pg: "AwsAdvancedRubyDriverWrapper::WrapperPgConnection", mysql: "AwsAdvancedRubyDriverWrapper::WrapperMysql2Client" } - standsIn: { pg: "PG::Connection", mysql: "Mysql2::Client" } - port: { pg: 5432, mysql: 3306 } + engineLabel: { pg: PostgreSQL, mysql: MySQL, trilogy: MySQL } + adapter: { pg: aws_postgresql, mysql: aws_mysql2, trilogy: aws_trilogy } + gem: { pg: pg, mysql: mysql2, trilogy: trilogy } + requirePath: { pg: aws_advanced_ruby_driver_wrapper/postgresql, mysql: aws_advanced_ruby_driver_wrapper/mysql, trilogy: aws_advanced_ruby_driver_wrapper/trilogy } + directClass: { pg: "AwsAdvancedRubyDriverWrapper::WrapperPgConnection", mysql: "AwsAdvancedRubyDriverWrapper::WrapperMysql2Client", trilogy: "AwsAdvancedRubyDriverWrapper::WrapperTrilogyClient" } + standsIn: { pg: "PG::Connection", mysql: "Mysql2::Client", trilogy: "Trilogy" } + port: { pg: 5432, mysql: 3306, trilogy: 3306 } # ----------------------------------------------------------------------------- # Links. Active Record concepts are linked, not explained. All Rails links point @@ -134,7 +134,8 @@ axes: default: pg options: - { id: pg, label: PostgreSQL } - - { id: mysql, label: MySQL } + - { id: mysql, label: MySQL (mysql2) } + - { id: trilogy, label: MySQL (Trilogy) } - id: arVersion label: Active Record @@ -175,7 +176,7 @@ questions: emit: links: [ar_multiple_databases] - id: direct - label: Through the pg or mysql2 gem directly + label: Through the pg, mysql2, or trilogy gem directly short: the gem directly hint: > The wrapper stands in for the gem's own connection class. There is no @@ -354,25 +355,44 @@ rules: # --- dialect: stating it explicitly removes a class of wrong-guess surprises - when: { deployment: [cluster, cluster_custom, cluster_readonly], engine: [pg] } emit: { params: { wrapper_dialect: aurora-pg } } - - when: { deployment: [cluster, cluster_custom, cluster_readonly], engine: [mysql] } + - when: { deployment: [cluster, cluster_custom, cluster_readonly], engine: [mysql, trilogy] } emit: { params: { wrapper_dialect: aurora-mysql } } - when: { deployment: [global], engine: [pg] } emit: { params: { wrapper_dialect: global-aurora-pg } } - - when: { deployment: [global], engine: [mysql] } + - when: { deployment: [global], engine: [mysql, trilogy] } emit: { params: { wrapper_dialect: global-aurora-mysql } } - when: { deployment: [multi_az_cluster], engine: [pg] } emit: { params: { wrapper_dialect: multi-az-pg-cluster } } - - when: { deployment: [multi_az_cluster], engine: [mysql] } + - when: { deployment: [multi_az_cluster], engine: [mysql, trilogy] } emit: { params: { wrapper_dialect: multi-az-mysql-cluster } } - when: { deployment: [multi_az_instance, instance, proxy], engine: [pg] } emit: { params: { wrapper_dialect: rds-pg } } - - when: { deployment: [multi_az_instance, instance, proxy], engine: [mysql] } + - when: { deployment: [multi_az_instance, instance, proxy], engine: [mysql, trilogy] } emit: { params: { wrapper_dialect: rds-mysql } } - when: { deployment: [community], engine: [pg] } emit: { params: { wrapper_dialect: pg } } - - when: { deployment: [community], engine: [mysql] } + - when: { deployment: [community], engine: [mysql, trilogy] } emit: { params: { wrapper_dialect: mysql } } + # --- IAM authentication: the token travels as the password, so a few more + # settings are needed. On MySQL the token is only sent with the cleartext + # client plugin, so `enable_cleartext_plugin` is required there (not on + # PostgreSQL). TLS is not strictly required but strongly recommended on every + # engine, because the token is sent as the password (in cleartext on MySQL); + # the verification mode and CA-certificate key names differ per driver. + - when: { credentials: [iam], engine: [mysql, trilogy] } + from: "required on MySQL: the IAM token is sent via mysql_clear_password" + emit: { params: { enable_cleartext_plugin: true } } + - when: { credentials: [iam], engine: [pg] } + from: "recommended: encrypts the IAM token (sent as the password) in transit" + emit: { params: { sslmode: verify-full, sslrootcert: "" } } + - when: { credentials: [iam], engine: [mysql] } + from: "recommended: encrypts the IAM token (sent in cleartext) in transit" + emit: { params: { ssl_mode: verify_identity, sslca: "" } } + - when: { credentials: [iam], engine: [trilogy] } + from: "recommended: encrypts the IAM token (sent in cleartext) in transit" + emit: { params: { ssl_mode: verify_identity, ssl_ca: "" } } + # --- resolving the cluster endpoint to a real instance at connect time - when: { continuity: [instance, region], deployment: [cluster, cluster_readonly, global, multi_az_cluster] } emit: @@ -492,7 +512,10 @@ addons: short: query retries requires: { integration: [active_record] } blocked: Active Record supplies this. Talking to the gem directly, retrying is your code's decision. - hint: Active Record retries safely retryable queries once by default. + hint: > + Active Record retries safely retryable queries once by default. It does not + retry `FailoverSuccessError` or `TransactionStateUnknownError`, which the + failover plugin raises after a successful failover. emit: pool: { connection_retries: 3, retry_deadline: 5 } links: [ar_retries] @@ -578,6 +601,7 @@ addons: - "A Blue/Green Deployment exists and the wrapper can read its status before the switchover starts." notes: - "The plugin holds traffic during the switchover instead of letting it fail, then resumes against the promoted deployment." + - "After the switchover, connections that were opened to the old blue environment are closed the next time they are used. If the failover plugin is enabled (list `failover` in `wrapper_plugins` alongside `bg`), that use triggers failover and raises one of the failover errors: `FailoverSuccessError` (or `TransactionStateUnknownError` inside a transaction) when the connection reconnects to the new environment, or `FailoverFailedError` when it cannot. Handle it as you would any other failover. Set `bg_drop_blue_connections: false` to keep using those connections instead, at the risk of reading from the retired blue environment." - "If you connect through an RDS Proxy, AWS requires the blue cluster to be registered with the proxy before the Blue/Green deployment is created — you cannot add the proxy afterward." links: [rds_bluegreen] @@ -596,6 +620,9 @@ addons: toggle: true label: Encrypt column values with AWS KMS short: column encryption + blockedIf: + - when: { engine: [trilogy] } + reason: kmsUnsupportedTrilogy emit: plugins: [kms_encryption] params: @@ -794,6 +821,7 @@ labels: bgUnsupportedGlobal: "AWS does not support Blue/Green deployments with RDS Proxy on Aurora global databases, and the wrapper's Blue/Green plugin does not support global databases. Use a global switchover or failover instead." bgUnsupportedMultiAzCluster: "AWS Blue/Green deployments are not available for RDS Multi-AZ DB clusters (they are supported for Multi-AZ DB instance deployments)." bgUnsupportedCommunity: "Blue/Green deployments are an Amazon RDS/Aurora feature. A community database you run yourself cannot be set up with one." + kmsUnsupportedTrilogy: "The KMS Encryption Plugin relies on prepared statements, which Trilogy does not support, so it cannot be used with the Trilogy driver. Use the mysql2 driver for column encryption." resultHeading: Your configuration assumesHeading: What this assumes pluginsHeading: Why each plugin is here diff --git a/content/telemetry.yaml b/content/telemetry.yaml new file mode 100644 index 0000000..6b5e07f --- /dev/null +++ b/content/telemetry.yaml @@ -0,0 +1,284 @@ +# ============================================================================= +# Telemetry (Monitoring) — shared-configuration page registry +# ============================================================================= +# +# Telemetry is not a plugin: it oversees every enabled plugin and the wrapper +# itself, and is turned on with a connection property rather than by being listed +# in the plugin parameter. It therefore lives under Shared Configuration. +# +# This registry is split the way the other shared pages are: +# +# shared: Wrapper-agnostic prose — what telemetry is, the difference +# between traces and metrics, the collector, and the +# top-level/nested trace idea. Reused verbatim by every +# wrapper, so it must not name a property, gem, or backend. +# wrappers.: Everything wrapper-specific — the exact property names and +# their types/defaults/units, the backends that wrapper +# supports, the gems and SDK setup code, and the metric names +# (which are spelled in that wrapper's own casing). +# +# The template reads the shared prose directly and the per-wrapper fields through +# `telemetry.wrappers[wrapper_id]`. Parameters follow the same shape as the other +# pages (a shared `concept`/`description` with per-wrapper `spellings`), so the +# page reuses `partials/plugin-parameters.md.j2`. +# ============================================================================= + +shared: + overview: | + Telemetry is the ability to gather data and insights on the execution of an + application, so you can inspect what happened and decide what to act on. When + telemetry is enabled, the wrapper records data about its own execution — both + at a global level and per plugin — so you can see how the wrapper as a whole, + and each plugin within it, is performing against your expectations. + + Telemetry oversees every plugin you have enabled and the wrapper itself; it is + **not a plugin**. You do not list it alongside the other plugins — you turn it + on with a connection property, described below. + + tracesIntro: | + A **trace** gives an overview of what happens in one section of an + application's execution. A trace is a hierarchical sequence of spans, each + carrying basic information about that section — how long it took, and whether + it succeeded or failed. + + The wrapper records a span for work it does and nests spans to show how that + work breaks down. Because spans are hierarchical, a span the wrapper records + can either nest inside a trace your application already has open or stand on + its own as a top-level trace — see + [top-level and nested traces](#top-level-and-nested-traces). + + metricsIntro: | + **Metrics** are numeric values measured over the execution of an application. + They show how many times something happened (for example, a failover, or a + token fetch) and, for things that happen repeatedly, how often each outcome + occurred. Metrics come in two kinds: a **counter**, which only ever increases, + and a **gauge**, which reports a current value each time metrics are collected. + + The metrics the wrapper records are listed in + [list of metrics](#list-of-metrics). Each one is submitted only while the + plugin that owns it is enabled. + + collectorIntro: | + The wrapper records telemetry through the [OpenTelemetry](https://opentelemetry.io/) + API only; it does not export anything on its own. Your application installs an + OpenTelemetry SDK — the tracer and meter providers plus the exporters — and the + wrapper's traces and metrics then go wherever that SDK sends them. Until the + SDK is installed, the API quietly discards what the wrapper records, so nothing + is exported and there is no error. + + A common target is the [AWS Distro for OpenTelemetry (ADOT) Collector](https://aws-otel.github.io/docs/getting-started/collector), + which receives telemetry over OTLP and forwards traces to + [AWS X-Ray](https://aws.amazon.com/xray/) and metrics to + [Amazon CloudWatch](https://aws.amazon.com/cloudwatch/). To view the data in + the AWS console you need an IAM principal with permissions for + [X-Ray](https://docs.aws.amazon.com/xray/latest/devguide/security-iam.html) and + [CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/auth-and-access-control-cw.html). + + :::warning + The collector is a separate application, not part of the wrapper. Without a + collector (or another OTLP backend) the wrapper still records telemetry, but + there is nowhere for it to be sent and visualized. + ::: + + topLevelIntro: | + Traces are hierarchical, so when the wrapper is called from code that already + has a trace open, there is a choice: should the wrapper's traces nest inside + that open trace, or stand on their own as top-level traces? + + A **top-level** trace has no parent and appears directly in the list of + submitted traces. A **nested** trace is linked under a parent — for example, + the individual plugin spans of one wrapper call are nested under that call's + span. By default the wrapper nests its traces under whatever trace is already + open, and records nothing when no trace is open. The properties below let you + change that. + + metricsTableIntro: | + The wrapper submits a set of metrics while it runs. They are predefined, and + each gives insight into what a plugin is doing while it is enabled. A metric is + either a **counter** or a **gauge**. Metrics are only submitted by the plugins + that are enabled, so a plugin you do not use contributes nothing. + +wrappers: + ruby: + availableSince: "1.1.0" + # Backends this wrapper can export to, for each signal. Ruby exports over OTLP + # only (plus `none`); it has no direct X-Ray trace backend — X-Ray is reached + # through the collector. + tracesBackends: "`otlp`, `none`" + metricsBackends: "`otlp`, `none`" + + # The scope name the wrapper registers its tracer and meter under, so you can + # find its telemetry among other instrumentation. + instrumentationScope: "aws-advanced-ruby-driver-wrapper" + + gemsBlock: | + The OpenTelemetry gems are optional dependencies of the wrapper, so add the + ones you need to your Gemfile. Traces and metrics are separate: add the + metrics gems only if you export metrics. + + ```ruby + # Gemfile + gem 'opentelemetry-sdk' # the SDK your application installs + gem 'opentelemetry-exporter-otlp' # exports traces over OTLP + gem 'opentelemetry-metrics-sdk' # metrics SDK (separate from the traces SDK) + gem 'opentelemetry-exporter-otlp-metrics' # exports metrics over OTLP + ``` + + The wrapper itself requires only the OpenTelemetry API (`opentelemetry-api` + for traces and `opentelemetry-metrics-api` for metrics); the SDK gems above + pull those in. If a selected backend's gem is missing when telemetry is + enabled, the wrapper raises on the first connection. + + sdkSetup: | + Install the SDK once, before opening connections. It owns the exporters and + their endpoints; the wrapper only feeds spans and metrics into the API. + + ```ruby + require 'opentelemetry/sdk' + require 'opentelemetry/exporter/otlp' # traces + require 'opentelemetry-metrics-sdk' # metrics + require 'opentelemetry/exporter/otlp_metrics' # metrics + + # Traces: an OTLP span exporter pointed at your collector. + OpenTelemetry::SDK.configure do |c| + c.service_name = 'my-app' + c.add_span_processor( + OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new( + OpenTelemetry::Exporter::OTLP::Exporter.new( + endpoint: ENV.fetch('OTEL_EXPORTER_OTLP_TRACES_ENDPOINT') # e.g. http://localhost:4318/v1/traces + ) + ) + ) + end + + # Metrics: register an OTLP metrics reader on the meter provider. + OpenTelemetry.meter_provider.add_metric_reader( + OpenTelemetry::SDK::Metrics::Export::PeriodicMetricReader.new( + exporter: OpenTelemetry::Exporter::OTLP::Metrics::MetricsExporter.new( + endpoint: ENV.fetch('OTEL_EXPORTER_OTLP_METRICS_ENDPOINT') # e.g. http://localhost:4318/v1/metrics + ) + ) + ) + ``` + + enableIntro: | + Telemetry is off until you enable it. Set `enable_telemetry` to `true` and + choose a backend for each signal you want exported; a backend left at `none` + records nothing for that signal. These are ordinary connection properties, so + they go wherever your other wrapper properties go. + enableBlock: | + ```yaml + # config/database.yml + production: + adapter: aws_postgresql + host: my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com + database: mydb + username: + password: + enable_telemetry: true + telemetry_traces_backend: otlp + telemetry_metrics_backend: otlp + ``` + + Using the driver directly, the same properties are keyword arguments: + + ```ruby + conn = AwsAdvancedRubyDriverWrapper::WrapperPgConnection.new( + host: 'my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com', + dbname: 'mydb', + user: '', + password: '', + enable_telemetry: true, + telemetry_traces_backend: 'otlp', + telemetry_metrics_backend: 'otlp' + ) + ``` + + # Top-level / nested behaviour, wrapper-specific wording for the two properties + # that control it. + topLevelDetail: | + Two properties control how the wrapper's traces relate to a trace your + application already has open: + + - **`telemetry_submit_top_level`** — by default (`false`) the wrapper nests + each wrapper-call trace under the trace already in progress, and records + nothing when no trace is open. Set it to `true` to submit every wrapper + call as a top-level trace of its own instead. + - **`telemetry_failover_additional_top_trace`** — a failover is normally + recorded as a span within the wrapper call that triggered it. Set this to + `true` to *also* submit each failover as a separate top-level trace, so it + can be found on its own. Only a failover that was already being traced is + submitted this way. + + # Parameters. Shared `concept`/`description`; per-wrapper `spellings`. Rendered + # by partials/plugin-parameters.md.j2, exactly like the plugin pages. + parameters: + - concept: enableTelemetry + type: boolean + description: "Enables telemetry and observability of the wrapper. While `false`, no telemetry is recorded, whatever the backend properties say." + spellings: + ruby: { name: enable_telemetry, required: "No", default: "false" } + - concept: telemetryTracesBackend + type: string + description: "Where recorded traces are exported. `otlp` exports to your OpenTelemetry SDK (and on to a collector); `none` records traces but exports them nowhere." + spellings: + ruby: { name: telemetry_traces_backend, required: "No", defaultNote: "none", example: "otlp" } + - concept: telemetryMetricsBackend + type: string + description: "Where recorded metrics are exported. `otlp` exports to your OpenTelemetry SDK (and on to a collector); `none` records metrics but exports them nowhere." + spellings: + ruby: { name: telemetry_metrics_backend, required: "No", defaultNote: "none", example: "otlp" } + - concept: telemetrySubmitTopLevel + type: boolean + description: "Submit each wrapper-call trace as a top-level trace rather than nesting it under a trace already in progress. See [top-level and nested traces](#top-level-and-nested-traces)." + spellings: + ruby: { name: telemetry_submit_top_level, required: "No", default: "false" } + - concept: telemetryFailoverAdditionalTopTrace + type: boolean + description: "Also submit the trace of each failover as a top-level trace of its own. Only a failover that was already being traced is submitted this way." + spellings: + ruby: { name: telemetry_failover_additional_top_trace, required: "No", default: "false" } + + # Metrics, grouped by the plugin that emits them. `[NODE]`-style per-node + # metrics do not exist in this wrapper, so none are listed. Names are in this + # wrapper's own casing (snake_case). + metricsNote: | + The `iam`, `federated_auth`, and `okta` plugins share one token cache, so + their three `*.token_cache.size` gauges all report the same value. + metricGroups: + - plugin: "Enhanced Failover — `failover`" + page: enhanced-failover + rows: + - { name: writer_failover.triggered.count, type: Counter, description: "Number of times writer failover was triggered." } + - { name: writer_failover.completed.success.count, type: Counter, description: "Number of times writer failover completed and succeeded." } + - { name: writer_failover.completed.failed.count, type: Counter, description: "Number of times writer failover completed and failed." } + - { name: reader_failover.triggered.count, type: Counter, description: "Number of times reader failover was triggered." } + - { name: reader_failover.completed.success.count, type: Counter, description: "Number of times reader failover completed and succeeded." } + - { name: reader_failover.completed.failed.count, type: Counter, description: "Number of times reader failover completed and failed." } + - plugin: "Custom Endpoint — `custom_endpoint`" + page: using-plugins/custom-endpoint + rows: + - { name: custom_endpoint.info_changed.count, type: Counter, description: "Number of times a monitor detected changed custom endpoint information." } + - { name: custom_endpoint.wait_for_info.count, type: Counter, description: "Number of times a connection attempt waited for custom endpoint information to be fetched." } + # The auth plugins (secrets_manager / iam / federated_auth / okta) come last, + # with the three that share a token cache at the very end so the + # shared-token-cache note below (metricsNote) sits directly after them. + - plugin: "AWS Secrets Manager — `secrets_manager`" + page: using-plugins/aws-secrets-manager + rows: + - { name: secrets_manager.fetch_credentials.count, type: Counter, description: "Number of times credentials were fetched from AWS Secrets Manager." } + - plugin: "IAM Authentication — `iam`" + page: using-plugins/iam-authentication + rows: + - { name: iam.fetch_token.count, type: Counter, description: "Number of times a token was fetched from IAM." } + - { name: iam.token_cache.size, type: Gauge, description: "Number of tokens held in the shared token cache." } + - plugin: "Federated Authentication — `federated_auth`" + page: using-plugins/federated-auth + rows: + - { name: federated.fetch_token.count, type: Counter, description: "Number of tokens generated after a SAML assertion exchange." } + - { name: federated.token_cache.size, type: Gauge, description: "Number of tokens held in the shared token cache." } + - plugin: "Okta Authentication — `okta`" + page: using-plugins/okta-auth + rows: + - { name: okta.fetch_token.count, type: Counter, description: "Number of tokens generated after a SAML assertion exchange." } + - { name: okta.token_cache.size, type: Gauge, description: "Number of tokens held in the shared token cache." } diff --git a/content/templates/aws-credentials.md.j2 b/content/templates/aws-credentials.md.j2 index 6a43552..01a8c96 100644 --- a/content/templates/aws-credentials.md.j2 +++ b/content/templates/aws-credentials.md.j2 @@ -40,9 +40,9 @@ aws_credentials_provider: Aws::AssumeRoleCredentials.new( ) ``` -This is a single property shared by the IAM, Secrets Manager, and KMS plugins, not one -property each, so setting it once covers token generation, secret retrieval, and data-key -unwrapping alike. When it is not set, each plugin falls back to the default chain above. +This is a single property shared by all four plugins, not one property each, so setting it +once covers token generation, secret retrieval, data-key unwrapping, and custom endpoint +lookups alike. When it is not set, each plugin falls back to the default chain above. ## Long-term and temporary credentials diff --git a/content/templates/configuring-tls.md.j2 b/content/templates/configuring-tls.md.j2 index adcfe5e..377c9f1 100644 --- a/content/templates/configuring-tls.md.j2 +++ b/content/templates/configuring-tls.md.j2 @@ -20,6 +20,9 @@ We strongly recommend a TLS 1.2+ connection **with certificate verification**: |---|---|---| | PostgreSQL (`pg`) | `sslmode: verify-full` | `sslrootcert` | | MySQL (`mysql2`) | `ssl_mode: verify_identity` | `sslca` | +{% if wrapper_id == 'ruby' %} +| MySQL (`trilogy`) | `ssl_mode: verify_identity` | `ssl_ca` | +{% endif %} `verify-full` and `verify_identity` check both the certificate chain **and** that the hostname matches the certificate, which is what protects the connection against a @@ -75,6 +78,12 @@ production: sslca: /path/to/global-bundle.pem ``` +{% if wrapper_id == 'ruby' %} +With the Trilogy driver, use `adapter: aws_trilogy` and name the certificate authority +`ssl_ca` instead of `sslca`; the `ssl_mode` verification names (`verify_identity`, +`verify_ca`, …) are the same. + +{% endif %} Using the driver directly, they are keyword arguments: ```ruby @@ -101,6 +110,13 @@ AwsAdvancedRubyDriverWrapper::WrapperMysql2Client.new( ) ``` +{% if wrapper_id == 'ruby' %} +With Trilogy, use `WrapperTrilogyClient`, name the certificate authority `ssl_ca` +instead of `sslca`, and pass `ssl_mode` as an **integer** constant +(`ssl_mode: Trilogy::SSL_VERIFY_IDENTITY`) — the direct client rejects a string or +symbol with `TypeError`. Without `ssl_mode`, Trilogy makes no TLS connection at all. + +{% endif %} ## Certificate bundle When connecting to an RDS or Aurora endpoint, use the AWS global certificate bundle as the @@ -112,7 +128,7 @@ name — the certificate authority you supply must be the one appropriate for *t endpoint, not for the RDS endpoint behind it. For TLS options beyond those shown here, see the driver documentation: -[`pg`](https://github.com/ged/ruby-pg) and [`mysql2`](https://github.com/brianmario/mysql2). +[`pg`](https://github.com/ged/ruby-pg), [`mysql2`](https://github.com/brianmario/mysql2){% if wrapper_id == 'ruby' %}, and [`trilogy`](https://github.com/trilogy-libraries/trilogy){% endif %}. ## Why this matters for authentication plugins @@ -121,6 +137,10 @@ TLS is not optional in practice when a credential travels over the connection: - [IAM Authentication](using-plugins/iam-authentication) sends the generated token as the password. With MySQL it is sent in cleartext, because IAM authentication relies on the `mysql_clear_password` client plugin. +- [Federated Authentication](using-plugins/federated-auth) and + [Okta Authentication](using-plugins/okta-auth) authenticate through an external identity + provider and then connect with an IAM token, so they send that token as the password in + exactly the same way as IAM Authentication — including in cleartext on MySQL. - [AWS Secrets Manager](using-plugins/aws-secrets-manager) sends the retrieved password on the connection like any other password. diff --git a/content/templates/enhanced-failover.md.j2 b/content/templates/enhanced-failover.md.j2 index 26b24f5..8302737 100644 --- a/content/templates/enhanced-failover.md.j2 +++ b/content/templates/enhanced-failover.md.j2 @@ -1,4 +1,3 @@ -{% import "partials/plugin-exclusivity.md.j2" as ex %} --- title: {{ page_title }} --- @@ -134,11 +133,9 @@ When `wrapper_plugins` is not specified, the wrapper loads `failover,initial_con Verify plugin compatibility within your {{ wrapper.label }} configuration using the [compatibility guide]({{ enhanced.wrappers[wrapper_id].compatibilityGuide }}). -{% set this_code = enhanced.wrappers[wrapper_id].pluginCode %} -{% set others = (wrapper.pluginGroups.failover or []) | reject('equalto', this_code) | list %} -:::warning -{{ ex.exclusivity(plugin_group_labels['failover'], this_code, others, 'PluginConflictError' if wrapper_id == 'ruby' else none) }} -::: +{% set banner_group = 'failover' %} +{% set banner_code = enhanced.wrappers[wrapper_id].pluginCode %} +{% include "partials/plugin-exclusivity-banner.md.j2" %} ## Enhanced failover parameters diff --git a/content/templates/host-selection-strategies.md.j2 b/content/templates/host-selection-strategies.md.j2 index 6ecf9f3..cc7e788 100644 --- a/content/templates/host-selection-strategies.md.j2 +++ b/content/templates/host-selection-strategies.md.j2 @@ -18,8 +18,9 @@ at random from the hosts that match the requested role and are currently marked | `random` | Selects at random from the available hosts matching the requested role. | none | It is also the default, so leaving the strategy properties unset gives you random -selection. -::: +selection. Strategy names are case-insensitive. Naming a strategy that is not registered +raises `Unsupported host selection strategy: ''` when the connection is set up, so a +typo fails fast instead of silently changing how hosts are chosen. ## Where it applies @@ -61,10 +62,13 @@ production: ``` Three constraints are worth knowing. A selector is shared by every connection in the process, -so `select_host` must be safe to call from multiple threads. Register the name in lowercase: -the wrapper lowercases the configured strategy name before looking it up. And a built-in name -cannot be replaced — registering `random` raises `Cannot override default host selection -strategy: 'random'`. +so `select_host` must be safe to call from multiple threads. Register the selector before +opening any connection that names it, because the plugins check the strategy name when the +connection is set up. And a built-in name cannot be replaced, in any casing — registering +`random` raises `Cannot override default host selection strategy: 'random'`. + +If a selector raises an error while choosing a host, the wrapper logs a warning and treats it +as "no eligible host" for that attempt. :::note Filtering to available hosts is the selector's own responsibility. The built-in `random` diff --git a/content/templates/plugin-aws-secrets-manager.md.j2 b/content/templates/plugin-aws-secrets-manager.md.j2 index 43e7874..6689a5b 100644 --- a/content/templates/plugin-aws-secrets-manager.md.j2 +++ b/content/templates/plugin-aws-secrets-manager.md.j2 @@ -8,9 +8,7 @@ title: {{ page_title }} Version {{ plugin.availableSince }} ::: -:::warning Only one authentication plugin at a time -The `secrets_manager` and `iam` plugins are mutually exclusive — only one authentication plugin may be active at a time. Configuring both in `{{ wrapper.pluginListParam }}` raises a `PluginConflictError` at connection initialization. -::: +{% include "partials/plugin-exclusivity-banner.md.j2" %} {% for block in prerequisites %} {{ block }} diff --git a/content/templates/plugin-blue-green.md.j2 b/content/templates/plugin-blue-green.md.j2 index 757b1d6..16292c6 100644 --- a/content/templates/plugin-blue-green.md.j2 +++ b/content/templates/plugin-blue-green.md.j2 @@ -30,6 +30,7 @@ stateDiagram-v2 end note note right of Post Monitor DNS; stop substitution; + invalidate pre-switchover blue connections; reject new connections to green nodes end note ``` diff --git a/content/templates/plugin-gdb-failover.md.j2 b/content/templates/plugin-gdb-failover.md.j2 index 472aee9..5443cd9 100644 --- a/content/templates/plugin-gdb-failover.md.j2 +++ b/content/templates/plugin-gdb-failover.md.j2 @@ -1,4 +1,3 @@ -{% import "partials/plugin-exclusivity.md.j2" as ex %} --- title: {{ page_title }} --- @@ -68,11 +67,7 @@ The plugin is not enabled by default. Add the plugin code `{{ plugin.code }}` to {{ plugin.enableSnippet }} ``` -{% set group = plugin.pluginGroup or 'failover' %} -{% set others = (wrapper.pluginGroups[group] or []) | reject('equalto', plugin.code) | list %} -:::warning -{{ ex.exclusivity(plugin_group_labels[group], plugin.code, others, 'PluginConflictError' if wrapper_id == 'ruby' else none) }} -::: +{% include "partials/plugin-exclusivity-banner.md.j2" %} Verify plugin compatibility within your {{ wrapper.label }} configuration using the [compatibility guide]({{ wrapper.compatibilityGuide }}). diff --git a/content/templates/plugin-iam-authentication.md.j2 b/content/templates/plugin-iam-authentication.md.j2 index af5ae3b..d010c6b 100644 --- a/content/templates/plugin-iam-authentication.md.j2 +++ b/content/templates/plugin-iam-authentication.md.j2 @@ -8,9 +8,7 @@ title: {{ page_title }} Version {{ plugin.availableSince }} ::: -:::warning Only one authentication plugin at a time -The `iam` and `secrets_manager` plugins are mutually exclusive — only one authentication plugin may be active at a time. Configuring both in `{{ wrapper.pluginListParam }}` raises a `PluginConflictError` at connection initialization. -::: +{% include "partials/plugin-exclusivity-banner.md.j2" %} {% for block in prerequisites %} {{ block }} diff --git a/content/templates/plugin-saml-auth.md.j2 b/content/templates/plugin-saml-auth.md.j2 new file mode 100644 index 0000000..11fc85c --- /dev/null +++ b/content/templates/plugin-saml-auth.md.j2 @@ -0,0 +1,78 @@ +--- +title: {{ page_title }} +--- + +{{ plugin.intro }} + +:::info Available since +Version {{ plugin.availableSince }} +::: + +{% include "partials/plugin-exclusivity-banner.md.j2" %} + +## What is federated identity + +Federated identity lets users authenticate once with an external identity provider (IdP) and use that single identity to reach services across organizations. The IdP authenticates the user and issues a signed security token — a SAML assertion — and any service provider that trusts the IdP accepts that assertion instead of managing its own credentials. + +This plugin applies that flow to database access. It signs in to your IdP with the configured credentials, receives a SAML assertion, exchanges the assertion for temporary AWS credentials through AWS STS `AssumeRoleWithSAML`, and uses those credentials to generate an AWS IAM authentication token. That IAM token is what the plugin uses to connect, so **AWS IAM database authentication must be enabled** on the target database. +{% for block in prerequisites %} + +{{ block }} +{% endfor %} + +## How to enable + +The plugin depends on AWS IAM database authentication: after it obtains a SAML assertion from your IdP, the assertion is exchanged for an AWS IAM authentication token, which is then used to connect to the database. Before enabling the plugin: + +1. [Enable IAM database authentication](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html) on your RDS or Aurora database. +2. Set up an [IAM SAML identity provider](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html) and an IAM role whose policy grants `rds-db:connect`, then federate your IdP into that AWS account. + +Then add the plugin code `{{ plugin.code }}` to the `{{ wrapper.pluginListParam }}` parameter and set the parameters required for your environment. + +```{{ wrapper.codeLang }} +{{ plugin.enableSnippet }} +``` + +Verify plugin compatibility within your {{ wrapper.label }} configuration using the [compatibility guide]({{ wrapper.compatibilityGuide }}). + +## Configuration parameters + +{% include "partials/plugin-parameters.md.j2" %} + +## Using this plugin with Global Databases + +When connecting to an +[Amazon Aurora Global Database](https://aws.amazon.com/rds/aurora/global-database/), +the IAM role assumed through the SAML assertion requires the additional +`rds:DescribeGlobalClusters` permission so the plugin can resolve the writer +region before generating the IAM token. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "rds-db:connect", + "rds:DescribeGlobalClusters" + ], + "Resource": "*" + } + ] +} +``` + +When you connect through an **Aurora Global Database endpoint**, also enable the +[Initial Connection Strategy plugin](./initial-connection-strategy) +(`initial_connection`). A global endpoint carries no region and points at +whichever regional cluster is currently the primary, so it must be resolved to the +writer instance before the IAM token is generated. + +For a global **writer** cluster, set `iam_region` explicitly when you can. Without +it, the plugin must perform one extra sign-in to your identity provider up front to +obtain the credentials needed to look up the writer region. +{% for block in wrapper_only %} + +{{ block }} +{% endfor %} diff --git a/content/templates/telemetry.md.j2 b/content/templates/telemetry.md.j2 new file mode 100644 index 0000000..f78d0e7 --- /dev/null +++ b/content/templates/telemetry.md.j2 @@ -0,0 +1,76 @@ +--- +title: {{ page_title }} +--- +{% set tw = telemetry.wrappers[wrapper_id] %} +{{ telemetry.shared.overview }} + +:::info Available since +Version {{ tw.availableSince }} +::: + +## Traces and metrics + +The {{ wrapper.wrapperName }} provides telemetry in two forms: **traces** and **metrics**. + +### Traces + +{{ telemetry.shared.tracesIntro }} + +### Metrics + +{{ telemetry.shared.metricsIntro }} + +## Where the data goes + +{{ telemetry.shared.collectorIntro }} + +## Enabling telemetry + +{{ tw.enableIntro }} + +{{ tw.enableBlock }} + +### Install the OpenTelemetry gems + +{{ tw.gemsBlock }} + +### Set up the OpenTelemetry SDK + +The {{ wrapper.wrapperName }} records telemetry through the OpenTelemetry API; your +application owns the SDK that exports it. Both traces and metrics are exported over +OTLP (the supported backends are {{ tw.tracesBackends }} for traces and +{{ tw.metricsBackends }} for metrics). The wrapper registers its tracer and meter +under the instrumentation scope `{{ tw.instrumentationScope }}`. + +{{ tw.sdkSetup }} + +## Configuration parameters + +{% set params = tw.parameters %} +{% include "partials/plugin-parameters.md.j2" %} + +## Top-level and nested traces + +{{ telemetry.shared.topLevelIntro }} + +{{ tw.topLevelDetail }} + +## List of metrics + +{{ telemetry.shared.metricsTableIntro }} + +{% for group in tw.metricGroups %} +### {{ group.plugin }} + +{% if group.page %} +See [{{ group.plugin.split('—')[0] | trim }}](./{{ group.page }}). + +{% endif %} +| Metric name | Type | Description | +|-------------|------|-------------| +{% for row in group.rows -%} +| `{{ row.name }}` | {{ row.type }} | {{ row.description }} | +{% endfor %} + +{% endfor %} +{{ tw.metricsNote }} diff --git a/generate.py b/generate.py index 350d632..e73dbbf 100644 --- a/generate.py +++ b/generate.py @@ -57,6 +57,7 @@ SITE = os.path.join(ROOT, "site") GENERATED = os.path.join(SITE, "src", "generated") +ENV = None def load(name): path = os.path.join(CONTENT, name) @@ -202,11 +203,20 @@ def catalog(entries): # Named note library (see `notes:` in compatibility.yaml). A note value is a # shared string, or a per-wrapper map; {plugin:} placeholders in the text # are substituted with this wrapper's plugin code. - note_library = reg.get("notes", {}) or {} + note_library = dict(reg.get("notes", {}) or {}) # Map every plugin the wrapper has (incl. universal) from abstract key -> code, # for {plugin:} placeholder substitution in note text. key_to_code = {p["key"]: p["code"] for p in all_plugins} + failover_reg = regs["failover"] + auth_label = (failover_reg.get("pluginGroupLabels", {}) or {}).get("auth", "authentication") + auth_group = ((failover_reg.get("wrappers", {}) or {}).get(wid, {}) or {}).get("pluginGroups", {}).get("auth", []) + present_codes = {p["code"] for p in all_plugins} + auth_codes = [c for c in auth_group if c in present_codes] + if ENV is not None and auth_codes: + excl = ENV.get_template("partials/plugin-exclusivity.md.j2").module + note_library["oneAuthPlugin"] = excl.exclusivity_footnote(auth_label, auth_codes).strip() + def note_text_for(*, reason="", note_ref="", literal=""): """Resolve final note text for one cell. Precedence: a library reference (reason key on a ❌ cell, or noteRef on any cell) wins over a literal @@ -308,6 +318,10 @@ def matrix(section, columns): order = list(all_plugins) pos = {p["code"]: i for i, p in enumerate(order)} notes = [] + # Cells that resolve to the same note text share one footnote number, reused + # across every table on the page (the auth-exclusivity note, for example, + # applies to many pairs). Numbers are assigned in reading order. + cross_marker_by_text = {} def build_table(columns, rows): out_rows = [] @@ -330,13 +344,17 @@ def build_table(columns, rows): cell = None marker = None if state == "no": - marker = len(notes) + 1 text = note_text_for( reason=cell.get("reason") or "", note_ref=cell.get("note_ref") or "", literal=cell.get("note") or "", ) - notes.append({"n": marker, "text": text}) + if text in cross_marker_by_text: + marker = cross_marker_by_text[text] + else: + marker = len(notes) + 1 + cross_marker_by_text[text] = marker + notes.append({"n": marker, "text": text}) cells.append({"state": state, "marker": marker}) out_rows.append({"plugin": row, "cells": cells}) return {"columns": columns, "rows": out_rows} @@ -499,13 +517,13 @@ def by_wrapper(field, default=None): "code": (entry.get("code") or {}).get(wid), "availableSince": (entry.get("availableSince") or {}).get(wid), "pluginGroup": entry.get("pluginGroup"), - "intro": entry.get("intro"), - "note": entry.get("note"), - "hostRequirement": entry.get("hostRequirement"), - "secretData": entry.get("secretData"), - "globalDatabases": entry.get("globalDatabases"), - "serverSideEnforcement": entry.get("serverSideEnforcement"), - "hardening": entry.get("hardening"), + "intro": by_wrapper("intro"), + "note": by_wrapper("note"), + "hostRequirement": by_wrapper("hostRequirement"), + "secretData": by_wrapper("secretData"), + "globalDatabases": by_wrapper("globalDatabases"), + "serverSideEnforcement": by_wrapper("serverSideEnforcement"), + "hardening": by_wrapper("hardening"), "adminUtility": (entry.get("adminUtility") or {}).get(wid), "supported": entry.get("supported"), "enableSnippet": (entry.get("enableSnippet") or {}).get(wid), @@ -534,6 +552,15 @@ def _profile_cluster_id(page, wid, regs): return {"cluster_id": reg} +def _profile_telemetry(page, wid, regs): + """Context for the Telemetry shared configuration page. + + Exposes shared (wrapper-agnostic) prose plus wrapper-specific property + spellings, backends, setup code, and metric names. + """ + return {"telemetry": regs["telemetry"]} + + CONTEXT_PROFILES = { "base": _profile_base, "failover": _profile_failover, @@ -543,6 +570,7 @@ def _profile_cluster_id(page, wid, regs): "plugins": _profile_plugins, "scenarios": _profile_scenarios, "cluster-id": _profile_cluster_id, + "telemetry": _profile_telemetry, } # Templates that imply a profile when a page omits `contextProfile`. Kept only @@ -660,6 +688,7 @@ def main(): plugins_reg = load("plugins.yaml") scenarios_reg = load("scenarios.yaml") cluster_id_reg = load("cluster-id.yaml") + telemetry_reg = load("telemetry.yaml") regs = { "failover": failover_reg, "devguide": devguide_reg, @@ -667,6 +696,7 @@ def main(): "plugins": plugins_reg, "scenarios": scenarios_reg, "cluster_id": cluster_id_reg, + "telemetry": telemetry_reg, } # Fail fast with friendly messages before rendering anything. @@ -682,6 +712,8 @@ def main(): lstrip_blocks=True, ) env.filters["wrapcode"] = lambda v: f"`{v}`" + global ENV + ENV = env # Clean previous generated output. for wid in wrappers: diff --git a/site/docs-ruby/aws-credentials.md b/site/docs-ruby/aws-credentials.md index b02e678..30cd6e7 100644 --- a/site/docs-ruby/aws-credentials.md +++ b/site/docs-ruby/aws-credentials.md @@ -40,9 +40,9 @@ aws_credentials_provider: Aws::AssumeRoleCredentials.new( ) ``` -This is a single property shared by the IAM, Secrets Manager, and KMS plugins, not one -property each, so setting it once covers token generation, secret retrieval, and data-key -unwrapping alike. When it is not set, each plugin falls back to the default chain above. +This is a single property shared by all four plugins, not one property each, so setting it +once covers token generation, secret retrieval, data-key unwrapping, and custom endpoint +lookups alike. When it is not set, each plugin falls back to the default chain above. ## Long-term and temporary credentials diff --git a/site/docs-ruby/compatibility.md b/site/docs-ruby/compatibility.md index 3211861..418557e 100644 --- a/site/docs-ruby/compatibility.md +++ b/site/docs-ruby/compatibility.md @@ -20,4 +20,4 @@ Legend: ✅ compatible · ❌ not compatible · blank = no constraint recorded. These plugins record no database-type, endpoint, or cross-plugin constraints: -- [`kms_encryption`](./using-plugins/kms-encryption) — Transparent column-level encryption using AWS KMS. \ No newline at end of file +- [`kms_encryption`](./using-plugins/kms-encryption) — Transparent column-level encryption using AWS KMS. Not supported with the `trilogy` driver (it has no prepared statements); use `mysql2` or `pg`. \ No newline at end of file diff --git a/site/docs-ruby/compatibility/cross-plugins.md b/site/docs-ruby/compatibility/cross-plugins.md index 44ea6d3..8953a3f 100644 --- a/site/docs-ruby/compatibility/cross-plugins.md +++ b/site/docs-ruby/compatibility/cross-plugins.md @@ -18,18 +18,29 @@ This is a lower-triangular matrix: **each plugin pair is shown only once.** To k | [`gdb_failover`](../using-plugins/gdb-failover) | ❌ [^1] | ❌ [^2] | — | | | [`iam`](../using-plugins/iam-authentication) | ✅ | ✅ | ✅ | — | | [`secrets_manager`](../using-plugins/aws-secrets-manager) | ✅ | ✅ | ✅ | ❌ [^3] | +| [`federated_auth`](../using-plugins/federated-auth) | ✅ | ✅ | ✅ | ❌ [^3] | +| [`okta`](../using-plugins/okta-auth) | ✅ | ✅ | ✅ | ❌ [^3] | | [`initial_connection`](../using-plugins/initial-connection-strategy) | ✅ | ✅ | ✅ | ✅ | | [`bg`](../using-plugins/blue-green) | ❌ [^4] | ✅ | ❌ [^5] | ✅ | | [`kms_encryption`](../using-plugins/kms-encryption) | ✅ | ✅ | ✅ | ✅ | -**Columns: `secrets_manager`, `initial_connection`, `bg`, `kms_encryption`** +**Columns: `secrets_manager`, `federated_auth`, `okta`, `initial_connection`** -| Plugin | `secrets_manager` | `initial_connection` | `bg` | `kms_encryption` | +| Plugin | `secrets_manager` | `federated_auth` | `okta` | `initial_connection` | | --- | --- | --- | --- | --- | | [`secrets_manager`](../using-plugins/aws-secrets-manager) | — | | | | -| [`initial_connection`](../using-plugins/initial-connection-strategy) | ✅ | — | | | -| [`bg`](../using-plugins/blue-green) | ✅ | ✅ | — | | -| [`kms_encryption`](../using-plugins/kms-encryption) | ✅ | ✅ | ✅ | — | +| [`federated_auth`](../using-plugins/federated-auth) | ❌ [^3] | — | | | +| [`okta`](../using-plugins/okta-auth) | ❌ [^3] | ❌ [^3] | — | | +| [`initial_connection`](../using-plugins/initial-connection-strategy) | ✅ | ✅ | ✅ | — | +| [`bg`](../using-plugins/blue-green) | ✅ | ✅ | ✅ | ✅ | +| [`kms_encryption`](../using-plugins/kms-encryption) | ✅ | ✅ | ✅ | ✅ | + +**Columns: `bg`, `kms_encryption`** + +| Plugin | `bg` | `kms_encryption` | +| --- | --- | --- | +| [`bg`](../using-plugins/blue-green) | — | | +| [`kms_encryption`](../using-plugins/kms-encryption) | ✅ | — | ## Notes @@ -37,7 +48,7 @@ This is a lower-triangular matrix: **each plugin pair is shown only once.** To k [^2]: Both drive cluster failover; `gdb_failover` is the region-aware superset, so running both means two components contend over reconnection and topology. -[^3]: Two authentication plugins both trying to set the connection credential; only one authentication plugin may be active at a time. +[^3]: Only one authentication plugin may be enabled per connection. The `iam`, `secrets_manager`, `federated_auth`, and `okta` plugins each set the connection credential, so enabling more than one conflicts. [^4]: Meaningless: a Blue/Green switchover replaces the whole deployment, so a custom endpoint's hand-picked instance subset does not carry over. diff --git a/site/docs-ruby/compatibility/database-types.md b/site/docs-ruby/compatibility/database-types.md index 277f012..1680eed 100644 --- a/site/docs-ruby/compatibility/database-types.md +++ b/site/docs-ruby/compatibility/database-types.md @@ -15,6 +15,8 @@ Legend: ✅ compatible · ❌ not compatible · a numbered footnote `[^n]` links | [`gdb_failover`](../using-plugins/gdb-failover) | ✅ | ❌ [^4] | ❌ [^4] | ❌ [^5] | ❌ [^5] | ❌ [^5] | | [`iam`](../using-plugins/iam-authentication) | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ [^6] | | [`secrets_manager`](../using-plugins/aws-secrets-manager) | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ [^6] | +| [`federated_auth`](../using-plugins/federated-auth) | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ [^6] | +| [`okta`](../using-plugins/okta-auth) | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ [^6] | | [`initial_connection`](../using-plugins/initial-connection-strategy) | ✅ | ✅ | ✅ | ❌ [^7] | ❌ [^7] | ❌ [^7] | | [`bg`](../using-plugins/blue-green) | ❌ [^8] | ✅ | ❌ [^9] | ✅ | ✅ | ❌ [^10] | @@ -30,7 +32,7 @@ Legend: ✅ compatible · ❌ not compatible · a numbered footnote `[^n]` links [^5]: The global database failover plugin needs an Aurora global database spanning regions; this deployment is not one. -[^6]: IAM and Secrets Manager authentication are Amazon RDS/Aurora features; a community database you run yourself does not support them. +[^6]: IAM and Secrets Manager authentication are Amazon RDS/Aurora features; a community database you run yourself does not support them. The Federated Authentication (AD FS) and Okta Authentication plugins obtain their database credential through IAM as well, so the same limitation applies to them. [^7]: The initial connection plugin resolves a cluster endpoint to an instance; this deployment has no cluster topology to resolve. diff --git a/site/docs-ruby/compatibility/endpoints.md b/site/docs-ruby/compatibility/endpoints.md index 684b2bf..b66bf52 100644 --- a/site/docs-ruby/compatibility/endpoints.md +++ b/site/docs-ruby/compatibility/endpoints.md @@ -29,6 +29,8 @@ Legend: ✅ compatible · ❌ not compatible · a numbered footnote `[^n]` links | [`gdb_failover`](../using-plugins/gdb-failover) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ [^2] | ❌ [^5] | ✅ [^6] | ✅ [^6] | | [`iam`](../using-plugins/iam-authentication) | ✅ [^7] | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [^8] | ✅ [^8] | | [`secrets_manager`](../using-plugins/aws-secrets-manager) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [^9] | ✅ [^9] | +| [`federated_auth`](../using-plugins/federated-auth) | ✅ [^7] | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [^8] | ✅ [^8] | +| [`okta`](../using-plugins/okta-auth) | ✅ [^7] | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [^8] | ✅ [^8] | | [`initial_connection`](../using-plugins/initial-connection-strategy) | ✅ | ✅ | ✅ | ✅ [^10] | ❌ [^11] | ✅ | ✅ | ❌ [^11] | ❌ [^11] | ❌ [^11] | ❌ [^11] | | [`bg`](../using-plugins/blue-green) | ❌ [^12] | ✅ | ✅ | ✅ | ✅ | ❌ [^13] | ❌ [^13] | ✅ | ❌ [^14] | ✅ [^15] | ❌ [^16] | diff --git a/site/docs-ruby/configuring-tls.md b/site/docs-ruby/configuring-tls.md index 7a80d53..abd8d98 100644 --- a/site/docs-ruby/configuring-tls.md +++ b/site/docs-ruby/configuring-tls.md @@ -20,6 +20,7 @@ We strongly recommend a TLS 1.2+ connection **with certificate verification**: |---|---|---| | PostgreSQL (`pg`) | `sslmode: verify-full` | `sslrootcert` | | MySQL (`mysql2`) | `ssl_mode: verify_identity` | `sslca` | +| MySQL (`trilogy`) | `ssl_mode: verify_identity` | `ssl_ca` | `verify-full` and `verify_identity` check both the certificate chain **and** that the hostname matches the certificate, which is what protects the connection against a @@ -75,6 +76,10 @@ production: sslca: /path/to/global-bundle.pem ``` +With the Trilogy driver, use `adapter: aws_trilogy` and name the certificate authority +`ssl_ca` instead of `sslca`; the `ssl_mode` verification names (`verify_identity`, +`verify_ca`, …) are the same. + Using the driver directly, they are keyword arguments: ```ruby @@ -101,6 +106,11 @@ AwsAdvancedRubyDriverWrapper::WrapperMysql2Client.new( ) ``` +With Trilogy, use `WrapperTrilogyClient`, name the certificate authority `ssl_ca` +instead of `sslca`, and pass `ssl_mode` as an **integer** constant +(`ssl_mode: Trilogy::SSL_VERIFY_IDENTITY`) — the direct client rejects a string or +symbol with `TypeError`. Without `ssl_mode`, Trilogy makes no TLS connection at all. + ## Certificate bundle When connecting to an RDS or Aurora endpoint, use the AWS global certificate bundle as the @@ -112,7 +122,7 @@ name — the certificate authority you supply must be the one appropriate for *t endpoint, not for the RDS endpoint behind it. For TLS options beyond those shown here, see the driver documentation: -[`pg`](https://github.com/ged/ruby-pg) and [`mysql2`](https://github.com/brianmario/mysql2). +[`pg`](https://github.com/ged/ruby-pg), [`mysql2`](https://github.com/brianmario/mysql2), and [`trilogy`](https://github.com/trilogy-libraries/trilogy). ## Why this matters for authentication plugins @@ -121,6 +131,10 @@ TLS is not optional in practice when a credential travels over the connection: - [IAM Authentication](using-plugins/iam-authentication) sends the generated token as the password. With MySQL it is sent in cleartext, because IAM authentication relies on the `mysql_clear_password` client plugin. +- [Federated Authentication](using-plugins/federated-auth) and + [Okta Authentication](using-plugins/okta-auth) authenticate through an external identity + provider and then connect with an IAM token, so they send that token as the password in + exactly the same way as IAM Authentication — including in cleartext on MySQL. - [AWS Secrets Manager](using-plugins/aws-secrets-manager) sends the retrieved password on the connection like any other password. diff --git a/site/docs-ruby/development-guide/architecture.md b/site/docs-ruby/development-guide/architecture.md index 9793b95..7a7f4dc 100644 --- a/site/docs-ruby/development-guide/architecture.md +++ b/site/docs-ruby/development-guide/architecture.md @@ -12,8 +12,8 @@ flowchart TB subgraph entry["Entry points"] direction LR - ep1["WrapperPgConnection / WrapperMysql2Client"] - ep2["aws_postgresql / aws_mysql2 (ActiveRecord)"] + ep1["WrapperPgConnection / WrapperMysql2Client / WrapperTrilogyClient"] + ep2["aws_postgresql / aws_mysql2 / aws_trilogy (ActiveRecord)"] end subgraph conn["Wrapper Connection — one per connection"] @@ -59,7 +59,7 @@ flowchart TB The AWS Advanced Ruby Driver Wrapper contains 5 main components: -1. The connection entry points (`WrapperPgConnection`, `WrapperMysql2Client`, and the `aws_postgresql` / `aws_mysql2` ActiveRecord adapters) +1. The connection entry points (`WrapperPgConnection`, `WrapperMysql2Client`, `WrapperTrilogyClient`, and the `aws_postgresql` / `aws_mysql2` / `aws_trilogy` ActiveRecord adapters) 2. The [plugin manager](./service-container#plugin-manager) (one of the services in the container) 3. The [loadable and extensible plugins](./loadable-plugins) 4. The [service container](./service-container) of discrete services diff --git a/site/docs-ruby/development-guide/development-guide.md b/site/docs-ruby/development-guide/development-guide.md index 3446a39..b901d5d 100644 --- a/site/docs-ruby/development-guide/development-guide.md +++ b/site/docs-ruby/development-guide/development-guide.md @@ -8,7 +8,7 @@ This guide is for **open-source contributors to the AWS Advanced Ruby Driver Wra ## Setup -Make sure you have Ruby 3.3+ installed, along with your choice of underlying driver gem (`pg` or `mysql2`). +Make sure you have Ruby 3.3+ installed, along with your choice of underlying driver gem (`pg`, `mysql2`, or `trilogy`). Clone the AWS Advanced Ruby Driver Wrapper repository, then you can make changes in the repository. This project is built using Bundler + RSpec. diff --git a/site/docs-ruby/development-guide/performance.md b/site/docs-ruby/development-guide/performance.md index 0a4c4af..b6ebca2 100644 --- a/site/docs-ruby/development-guide/performance.md +++ b/site/docs-ruby/development-guide/performance.md @@ -5,7 +5,7 @@ title: Performance and Overhead # Performance and Overhead Every database operation goes through the wrapper's plugin pipeline before reaching the underlying -`mysql2`/`pg` driver, which adds some cost. The short version: the wrapper adds a **small, fixed +`mysql2`/`trilogy`/`pg` driver, which adds some cost. The short version: the wrapper adds a **small, fixed amount of work per call** - on the order of a microsecond - and against a real query that cost is too small to measure, dwarfed by the network round trip to the database. diff --git a/site/docs-ruby/development-guide/service-container.md b/site/docs-ruby/development-guide/service-container.md index b692e40..4ca99ff 100644 --- a/site/docs-ruby/development-guide/service-container.md +++ b/site/docs-ruby/development-guide/service-container.md @@ -95,7 +95,8 @@ strategies. See [Host List Providers](#host-list-providers). - `hosts` / `all_hosts` — allowed and full host lists. - `host_list_provider` — the active provider. - `select_host(hosts, role, strategy, props = nil)` — pick a host by role and host-selection strategy name. -- `HostService.register_host_selector(name, selector)` — a class method that registers a custom strategy for all connections. Register the name in lowercase: `select_host` lowercases the requested strategy before looking it up. +- `HostService.register_host_selector(name, selector)` — a class method that registers a custom strategy for all connections. Strategy names are case-insensitive. +- `HostService.validate_strategy!(name)` — a class method that raises `Unsupported host selection strategy` when no selector is registered under the name. Plugins that take a strategy name call it when they are constructed. **When to use it** @@ -147,16 +148,17 @@ background cleanup thread. Shared across the wrapper. **What it offers** - `register(name, ttl:)` — create a named cache partition. -- `set(name, key, value)` / `get(name, key)` — store and read items. -- `get_if_registered(name, key)` — read a partition that may not exist (e.g. a cache owned by an optional plugin). +- `set(name, key, value)` / `get(name, key, register_access: false)` — store and read items. +- `get_if_registered(name, key, register_access: false)` — read a partition that may not exist (e.g. a cache owned by an optional plugin). - `exists?(name, key)` / `remove(name, key)` / `clear(name)` / `clear_all`. **When to use it** Use it to cache data reused across the wrapper — for example the -`RdsHostListProvider` caches cluster topology here. Reads publish a -`DataAccessEvent` (unless `register_access: false`), which keeps related -monitors alive. +`RdsHostListProvider` caches cluster topology here. A read publishes a +`DataAccessEvent` only when called with `register_access: true`, which +extends the expiration of any monitor that produces that cache's data. Pass +it only when the read should keep that monitor alive. ### Monitor Service @@ -194,7 +196,7 @@ events synchronously and batches the rest, deduplicating via `Set` semantics. **When to use it** Use it to decouple event producers and consumers. For example the Storage -Service publishes a `DataAccessEvent` on cache reads, and the Monitor Service +Service publishes a `DataAccessEvent` on cache reads made with `register_access: true`, and the Monitor Service subscribes to it to extend the matching monitor's expiration. ### Plugin Manager diff --git a/site/docs-ruby/enhanced-failover.md b/site/docs-ruby/enhanced-failover.md index 3201fbc..d52c778 100644 --- a/site/docs-ruby/enhanced-failover.md +++ b/site/docs-ruby/enhanced-failover.md @@ -143,7 +143,7 @@ conn = AwsAdvancedRubyDriverWrapper::WrapperPgConnection.new( Verify plugin compatibility within your Ruby configuration using the [compatibility guide](./compatibility). -:::warning +:::warning Only one failover plugin at a time Only one failover plugin may be enabled per connection. Do not use `failover` together with the other `gdb_failover` plugin at the same time for the same connection. Configuring more than one raises a `PluginConflictError` at connection initialization. ::: @@ -224,16 +224,54 @@ first and reuse the connection when failover succeeded. ::: :::note Using the wrapper through ActiveRecord -When you use the wrapper through ActiveRecord (`aws_postgresql` or `aws_mysql2`), +When you use the wrapper through ActiveRecord (`aws_postgresql`, `aws_mysql2`, or `aws_trilogy`), reconnection is partially handled for you. On a successful failover the adapter re-runs `configure_connection` and reuses the pooled connection in place rather than discarding it, so you should not call `disconnect!` or discard the connection object yourself — the pool already holds the live, reconnected connection. ::: +## Timeouts and idle connections on MySQL + +On MySQL, the failover plugin treats a connection that timed out or was closed by +the server as lost, and fails over. This applies to `mysql2` (`WrapperMysql2Client` +and `aws_mysql2`) and to `trilogy` (`WrapperTrilogyClient` and `aws_trilogy`), and +includes: + +- A query that runs longer than the client's `read_timeout`. The driver closes the + socket before it raises the timeout, so the connection cannot be reused. +- A query on a connection that sat idle longer than the server's `wait_timeout`. + The server closes such a connection; MySQL 8.0.24 and later reports error 4031, + and earlier versions report a lost connection (2006 or 2013). +- A connection lost during a query, or a server that has gone away (with `mysql2`, + errors 2006, 2013, and 2055). + +Your code then sees `FailoverSuccessError` (or `TransactionStateUnknownError` inside a +transaction) instead of the driver's timeout or connection error. Through ActiveRecord +these errors are re-raised unchanged (see [ActiveRecord integration](#activerecord-integration)), +and ActiveRecord does not retry them for you. To avoid a failover that is caused by a +slow query or an idle connection rather than by the database: + +- Set `read_timeout` higher than your slowest expected query. +- Keep pooled connections from outliving `wait_timeout`: raise `wait_timeout` on the + server, or have the pool close idle connections sooner, for example with + ActiveRecord's `idle_timeout`. + +A lock wait timeout (error 1205) does not trigger failover. The connection is still +healthy, and the driver's error is raised as usual. + +:::note Changed in 1.1.0 +Before 1.1.0, `mysql2` did not fail over on a `read_timeout` or on errors 4031 and +2055. A `read_timeout` raised `Mysql2::Error::TimeoutError` (`ActiveRecord::AdapterTimeout` +under `aws_mysql2`), and errors 4031 and 2055 were raised as is. Under `aws_mysql2`, +error 4031 became `ActiveRecord::ConnectionFailed`, which ActiveRecord answered by +reconnecting to the original endpoint and retrying the queries it considers +retryable, and error 2055 became `ActiveRecord::StatementInvalid`. +::: + ## ActiveRecord integration -When using the wrapper through ActiveRecord (`aws_postgresql` or `aws_mysql2`), the +When using the wrapper through ActiveRecord (`aws_postgresql`, `aws_mysql2`, or `aws_trilogy`), the adapter's `translate_exception` decides what your code actually rescues, and the outcome differs by error: diff --git a/site/docs-ruby/host-selection-strategies.md b/site/docs-ruby/host-selection-strategies.md index f8a210b..1387909 100644 --- a/site/docs-ruby/host-selection-strategies.md +++ b/site/docs-ruby/host-selection-strategies.md @@ -17,8 +17,9 @@ at random from the hosts that match the requested role and are currently marked | `random` | Selects at random from the available hosts matching the requested role. | none | It is also the default, so leaving the strategy properties unset gives you random -selection. -::: +selection. Strategy names are case-insensitive. Naming a strategy that is not registered +raises `Unsupported host selection strategy: ''` when the connection is set up, so a +typo fails fast instead of silently changing how hosts are chosen. ## Where it applies @@ -60,10 +61,13 @@ production: ``` Three constraints are worth knowing. A selector is shared by every connection in the process, -so `select_host` must be safe to call from multiple threads. Register the name in lowercase: -the wrapper lowercases the configured strategy name before looking it up. And a built-in name -cannot be replaced — registering `random` raises `Cannot override default host selection -strategy: 'random'`. +so `select_host` must be safe to call from multiple threads. Register the selector before +opening any connection that names it, because the plugins check the strategy name when the +connection is set up. And a built-in name cannot be replaced, in any casing — registering +`random` raises `Cannot override default host selection strategy: 'random'`. + +If a selector raises an error while choosing a host, the wrapper logs a warning and treats it +as "no eligible host" for that attempt. :::note Filtering to available hosts is the selector's own responsibility. The built-in `random` diff --git a/site/docs-ruby/overview.md b/site/docs-ruby/overview.md index 537786c..6c0284d 100644 --- a/site/docs-ruby/overview.md +++ b/site/docs-ruby/overview.md @@ -21,14 +21,14 @@ will follow your choice where an equivalent page exists. ## Getting started -Requires Ruby 3.3 or later. The gem is `aws_advanced_ruby_driver_wrapper` on RubyGems. Tested with Active Record 7.2, 8.0, and 8.1, `pg` 1.6.3 or later, and `mysql2` 0.5.7 or later. +Requires Ruby 3.3 or later. The gem is `aws_advanced_ruby_driver_wrapper` on RubyGems. Tested with Active Record 7.2, 8.0, and 8.1, `pg` 1.6.3 or later, `mysql2` 0.5.7 or later, and `trilogy` 2.13.2 or later. ### 1. Add the gem ```ruby # Gemfile gem 'aws_advanced_ruby_driver_wrapper' -gem 'pg' # or: gem 'mysql2' +gem 'pg' # or: gem 'mysql2' / gem 'trilogy' for MySQL ``` ```bash @@ -38,28 +38,28 @@ bundle install Without Bundler, `gem install aws_advanced_ruby_driver_wrapper pg` does the same thing. :::warning -Which extra gems your Gemfile needs depends on your Ruby version, your platform, and whether you are using Active Record: - -| Version | Using Active Record | Extra gems | Reason | -| --- | --- | --- | --- | -| Ruby 3.3 | Either | None | `base64`, `bigdecimal` and `logger` are all still default gems | -| Ruby 3.4 | No | `base64`, `bigdecimal` | Ruby 3.4 removed both from the default gems | -| Ruby 3.4 | Yes | None | Active Record declares both itself | -| Ruby 4.0 or later | No | `base64`, `bigdecimal`, `logger` | Ruby 4.0 removed `logger` as well | -| Ruby 4.0 or later | Yes | None | Active Record declares all three itself | -| Ruby 4.0 or later, on Windows with `mysql2` | Either | `fiddle` | `mysql2` loads `libmysql.dll` through `fiddle` without declaring it, and neither does Active Record | - -A bundle missing any of them raises `LoadError` on the first require. +If you are using `mysql2` on Windows with Ruby 4.0 or later, you may also need to add `fiddle` to your Gemfile: + +```ruby +gem 'fiddle' +``` + +On Windows, `mysql2` uses `fiddle` to load `libmysql.dll` when you set +`RUBY_MYSQL2_LIBMYSQL_DLL`, when the gem ships its own `libmysql.dll`, or +when Ruby was not installed with RubyInstaller, but it does not declare +`fiddle` as a dependency. Ruby 4.0 removed `fiddle` from the default gems, +so in those cases a bundle without it raises `LoadError` when `mysql2` is +required. ::: ### 2. Point Active Record at your cluster -The wrapper registers two adapters, `aws_postgresql` and `aws_mysql2`, which are drop-in replacements for `postgresql` and `mysql2`. +The wrapper registers three adapters, `aws_postgresql`, `aws_mysql2`, and `aws_trilogy`, which are drop-in replacements for `postgresql`, `mysql2`, and `trilogy`. -Bundler requires the gem for you. In a plain Ruby script, add `require 'aws_advanced_ruby_driver_wrapper'` first: that single require is what registers both adapters, and without it Active Record reports `aws_postgresql` as a nonexistent adapter. +Bundler requires the gem for you. In a plain Ruby script, add `require 'aws_advanced_ruby_driver_wrapper'` first: that single require is what registers all three adapters, and without it Active Record reports `aws_postgresql` as a nonexistent adapter. -If you are starting without a Rails application, this is a complete program. Save it as `main.rb` and run it: +If you are starting without a Rails application, add `gem 'activerecord'` to the Gemfile from step 1 (outside Rails, nothing else installs it), run `bundle install`, and this is a complete program. Save it as `main.rb` and run it: ```ruby # main.rb @@ -111,10 +111,22 @@ Active Record keeps its own connection pool and its reading and writing roles; t :::note Mixing wrapped and standard adapters in one application The wrapped adapters register their type information under the underlying -`postgresql` and `mysql2` adapter names. If one application uses both a -standard connection (`postgresql`/`mysql2`) and a wrapped one -(`aws_postgresql`/`aws_mysql2`), a custom type registered for one is shared -with the other, because both resolve under the same underlying adapter key. +`postgresql`, `mysql2`, and `trilogy` adapter names. If one application uses +both a standard connection (`postgresql`/`mysql2`/`trilogy`) and a wrapped one +(`aws_postgresql`/`aws_mysql2`/`aws_trilogy`), a custom type registered for +one is shared with the other, because both resolve under the same underlying +adapter key. +::: + + +:::note Keeping the password out of your source +Read it from the environment with `ENV.fetch('PGPASSWORD')` in Ruby, or +`<%= ENV.fetch('PGPASSWORD') %>` in `config/database.yml`, or have +AWS manage it: add `secrets_manager` to `wrapper_plugins` and drop the +`password:` key, as described on +[AWS Secrets Manager Plugin](using-plugins/aws-secrets-manager). For a +database user with no password at all, consider using `iam` instead; see +[IAM Authentication Plugin](using-plugins/iam-authentication). ::: @@ -130,7 +142,7 @@ database user with no password at all, consider using `iam` instead; see ### Or connect with the driver directly -Without Active Record, the wrapper provides connection classes that stand in for `PG::Connection` and `Mysql2::Client`. This is a complete program; save it as `main.rb` and run it: +Without Active Record, the wrapper provides connection classes that stand in for `PG::Connection`, `Mysql2::Client`, and `Trilogy`. This is a complete program; save it as `main.rb` and run it: ```ruby # main.rb @@ -157,7 +169,7 @@ end bundle exec ruby main.rb ``` -For PostgreSQL, `require 'aws_advanced_ruby_driver_wrapper/postgresql'` and use `AwsAdvancedRubyDriverWrapper::WrapperPgConnection`, which stands in for `PG::Connection` and takes `dbname:` and `user:`. For MySQL, `require 'aws_advanced_ruby_driver_wrapper/mysql'` and use `AwsAdvancedRubyDriverWrapper::WrapperMysql2Client`, which stands in for `Mysql2::Client` and takes `database:` and `username:`. Either way the calls your code already makes keep working, and the plugins act on each one. +For PostgreSQL, `require 'aws_advanced_ruby_driver_wrapper/postgresql'` and use `AwsAdvancedRubyDriverWrapper::WrapperPgConnection`, which stands in for `PG::Connection` and takes `dbname:` and `user:`. For MySQL, `require 'aws_advanced_ruby_driver_wrapper/mysql'` and use `AwsAdvancedRubyDriverWrapper::WrapperMysql2Client`, which stands in for `Mysql2::Client` and takes `database:` and `username:`. To use the Trilogy driver instead, `require 'aws_advanced_ruby_driver_wrapper/trilogy'` and use `AwsAdvancedRubyDriverWrapper::WrapperTrilogyClient`, which stands in for `Trilogy` and takes the same `database:` and `username:`. Either way the calls your code already makes keep working, and the plugins act on each one. ### Next diff --git a/site/docs-ruby/telemetry.md b/site/docs-ruby/telemetry.md new file mode 100644 index 0000000..8ea9c2c --- /dev/null +++ b/site/docs-ruby/telemetry.md @@ -0,0 +1,275 @@ +--- +title: Telemetry +--- +Telemetry is the ability to gather data and insights on the execution of an +application, so you can inspect what happened and decide what to act on. When +telemetry is enabled, the wrapper records data about its own execution — both +at a global level and per plugin — so you can see how the wrapper as a whole, +and each plugin within it, is performing against your expectations. + +Telemetry oversees every plugin you have enabled and the wrapper itself; it is +**not a plugin**. You do not list it alongside the other plugins — you turn it +on with a connection property, described below. + + +:::info Available since +Version 1.1.0 +::: + +## Traces and metrics + +The AWS Advanced Ruby Driver Wrapper provides telemetry in two forms: **traces** and **metrics**. + +### Traces + +A **trace** gives an overview of what happens in one section of an +application's execution. A trace is a hierarchical sequence of spans, each +carrying basic information about that section — how long it took, and whether +it succeeded or failed. + +The wrapper records a span for work it does and nests spans to show how that +work breaks down. Because spans are hierarchical, a span the wrapper records +can either nest inside a trace your application already has open or stand on +its own as a top-level trace — see +[top-level and nested traces](#top-level-and-nested-traces). + + +### Metrics + +**Metrics** are numeric values measured over the execution of an application. +They show how many times something happened (for example, a failover, or a +token fetch) and, for things that happen repeatedly, how often each outcome +occurred. Metrics come in two kinds: a **counter**, which only ever increases, +and a **gauge**, which reports a current value each time metrics are collected. + +The metrics the wrapper records are listed in +[list of metrics](#list-of-metrics). Each one is submitted only while the +plugin that owns it is enabled. + + +## Where the data goes + +The wrapper records telemetry through the [OpenTelemetry](https://opentelemetry.io/) +API only; it does not export anything on its own. Your application installs an +OpenTelemetry SDK — the tracer and meter providers plus the exporters — and the +wrapper's traces and metrics then go wherever that SDK sends them. Until the +SDK is installed, the API quietly discards what the wrapper records, so nothing +is exported and there is no error. + +A common target is the [AWS Distro for OpenTelemetry (ADOT) Collector](https://aws-otel.github.io/docs/getting-started/collector), +which receives telemetry over OTLP and forwards traces to +[AWS X-Ray](https://aws.amazon.com/xray/) and metrics to +[Amazon CloudWatch](https://aws.amazon.com/cloudwatch/). To view the data in +the AWS console you need an IAM principal with permissions for +[X-Ray](https://docs.aws.amazon.com/xray/latest/devguide/security-iam.html) and +[CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/auth-and-access-control-cw.html). + +:::warning +The collector is a separate application, not part of the wrapper. Without a +collector (or another OTLP backend) the wrapper still records telemetry, but +there is nowhere for it to be sent and visualized. +::: + + +## Enabling telemetry + +Telemetry is off until you enable it. Set `enable_telemetry` to `true` and +choose a backend for each signal you want exported; a backend left at `none` +records nothing for that signal. These are ordinary connection properties, so +they go wherever your other wrapper properties go. + + +```yaml +# config/database.yml +production: + adapter: aws_postgresql + host: my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com + database: mydb + username: + password: + enable_telemetry: true + telemetry_traces_backend: otlp + telemetry_metrics_backend: otlp +``` + +Using the driver directly, the same properties are keyword arguments: + +```ruby +conn = AwsAdvancedRubyDriverWrapper::WrapperPgConnection.new( + host: 'my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com', + dbname: 'mydb', + user: '', + password: '', + enable_telemetry: true, + telemetry_traces_backend: 'otlp', + telemetry_metrics_backend: 'otlp' +) +``` + + +### Install the OpenTelemetry gems + +The OpenTelemetry gems are optional dependencies of the wrapper, so add the +ones you need to your Gemfile. Traces and metrics are separate: add the +metrics gems only if you export metrics. + +```ruby +# Gemfile +gem 'opentelemetry-sdk' # the SDK your application installs +gem 'opentelemetry-exporter-otlp' # exports traces over OTLP +gem 'opentelemetry-metrics-sdk' # metrics SDK (separate from the traces SDK) +gem 'opentelemetry-exporter-otlp-metrics' # exports metrics over OTLP +``` + +The wrapper itself requires only the OpenTelemetry API (`opentelemetry-api` +for traces and `opentelemetry-metrics-api` for metrics); the SDK gems above +pull those in. If a selected backend's gem is missing when telemetry is +enabled, the wrapper raises on the first connection. + + +### Set up the OpenTelemetry SDK + +The AWS Advanced Ruby Driver Wrapper records telemetry through the OpenTelemetry API; your +application owns the SDK that exports it. Both traces and metrics are exported over +OTLP (the supported backends are `otlp`, `none` for traces and +`otlp`, `none` for metrics). The wrapper registers its tracer and meter +under the instrumentation scope `aws-advanced-ruby-driver-wrapper`. + +Install the SDK once, before opening connections. It owns the exporters and +their endpoints; the wrapper only feeds spans and metrics into the API. + +```ruby +require 'opentelemetry/sdk' +require 'opentelemetry/exporter/otlp' # traces +require 'opentelemetry-metrics-sdk' # metrics +require 'opentelemetry/exporter/otlp_metrics' # metrics + +# Traces: an OTLP span exporter pointed at your collector. +OpenTelemetry::SDK.configure do |c| + c.service_name = 'my-app' + c.add_span_processor( + OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new( + OpenTelemetry::Exporter::OTLP::Exporter.new( + endpoint: ENV.fetch('OTEL_EXPORTER_OTLP_TRACES_ENDPOINT') # e.g. http://localhost:4318/v1/traces + ) + ) + ) +end + +# Metrics: register an OTLP metrics reader on the meter provider. +OpenTelemetry.meter_provider.add_metric_reader( + OpenTelemetry::SDK::Metrics::Export::PeriodicMetricReader.new( + exporter: OpenTelemetry::Exporter::OTLP::Metrics::MetricsExporter.new( + endpoint: ENV.fetch('OTEL_EXPORTER_OTLP_METRICS_ENDPOINT') # e.g. http://localhost:4318/v1/metrics + ) + ) +) +``` + + +## Configuration parameters + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `enable_telemetry` | Boolean | No | `false` | Enables telemetry and observability of the wrapper. While `false`, no telemetry is recorded, whatever the backend properties say. | +| `telemetry_traces_backend` | String | No | none | Where recorded traces are exported. `otlp` exports to your OpenTelemetry SDK (and on to a collector); `none` records traces but exports them nowhere.

Example: `otlp` | +| `telemetry_metrics_backend` | String | No | none | Where recorded metrics are exported. `otlp` exports to your OpenTelemetry SDK (and on to a collector); `none` records metrics but exports them nowhere.

Example: `otlp` | +| `telemetry_submit_top_level` | Boolean | No | `false` | Submit each wrapper-call trace as a top-level trace rather than nesting it under a trace already in progress. See [top-level and nested traces](#top-level-and-nested-traces). | +| `telemetry_failover_additional_top_trace` | Boolean | No | `false` | Also submit the trace of each failover as a top-level trace of its own. Only a failover that was already being traced is submitted this way. | + +## Top-level and nested traces + +Traces are hierarchical, so when the wrapper is called from code that already +has a trace open, there is a choice: should the wrapper's traces nest inside +that open trace, or stand on their own as top-level traces? + +A **top-level** trace has no parent and appears directly in the list of +submitted traces. A **nested** trace is linked under a parent — for example, +the individual plugin spans of one wrapper call are nested under that call's +span. By default the wrapper nests its traces under whatever trace is already +open, and records nothing when no trace is open. The properties below let you +change that. + + +Two properties control how the wrapper's traces relate to a trace your +application already has open: + +- **`telemetry_submit_top_level`** — by default (`false`) the wrapper nests + each wrapper-call trace under the trace already in progress, and records + nothing when no trace is open. Set it to `true` to submit every wrapper + call as a top-level trace of its own instead. +- **`telemetry_failover_additional_top_trace`** — a failover is normally + recorded as a span within the wrapper call that triggered it. Set this to + `true` to *also* submit each failover as a separate top-level trace, so it + can be found on its own. Only a failover that was already being traced is + submitted this way. + + +## List of metrics + +The wrapper submits a set of metrics while it runs. They are predefined, and +each gives insight into what a plugin is doing while it is enabled. A metric is +either a **counter** or a **gauge**. Metrics are only submitted by the plugins +that are enabled, so a plugin you do not use contributes nothing. + + +### Enhanced Failover — `failover` + +See [Enhanced Failover](./enhanced-failover). + +| Metric name | Type | Description | +|-------------|------|-------------| +| `writer_failover.triggered.count` | Counter | Number of times writer failover was triggered. | +| `writer_failover.completed.success.count` | Counter | Number of times writer failover completed and succeeded. | +| `writer_failover.completed.failed.count` | Counter | Number of times writer failover completed and failed. | +| `reader_failover.triggered.count` | Counter | Number of times reader failover was triggered. | +| `reader_failover.completed.success.count` | Counter | Number of times reader failover completed and succeeded. | +| `reader_failover.completed.failed.count` | Counter | Number of times reader failover completed and failed. | + +### Custom Endpoint — `custom_endpoint` + +See [Custom Endpoint](./using-plugins/custom-endpoint). + +| Metric name | Type | Description | +|-------------|------|-------------| +| `custom_endpoint.info_changed.count` | Counter | Number of times a monitor detected changed custom endpoint information. | +| `custom_endpoint.wait_for_info.count` | Counter | Number of times a connection attempt waited for custom endpoint information to be fetched. | + +### AWS Secrets Manager — `secrets_manager` + +See [AWS Secrets Manager](./using-plugins/aws-secrets-manager). + +| Metric name | Type | Description | +|-------------|------|-------------| +| `secrets_manager.fetch_credentials.count` | Counter | Number of times credentials were fetched from AWS Secrets Manager. | + +### IAM Authentication — `iam` + +See [IAM Authentication](./using-plugins/iam-authentication). + +| Metric name | Type | Description | +|-------------|------|-------------| +| `iam.fetch_token.count` | Counter | Number of times a token was fetched from IAM. | +| `iam.token_cache.size` | Gauge | Number of tokens held in the shared token cache. | + +### Federated Authentication — `federated_auth` + +See [Federated Authentication](./using-plugins/federated-auth). + +| Metric name | Type | Description | +|-------------|------|-------------| +| `federated.fetch_token.count` | Counter | Number of tokens generated after a SAML assertion exchange. | +| `federated.token_cache.size` | Gauge | Number of tokens held in the shared token cache. | + +### Okta Authentication — `okta` + +See [Okta Authentication](./using-plugins/okta-auth). + +| Metric name | Type | Description | +|-------------|------|-------------| +| `okta.fetch_token.count` | Counter | Number of tokens generated after a SAML assertion exchange. | +| `okta.token_cache.size` | Gauge | Number of tokens held in the shared token cache. | + +The `iam`, `federated_auth`, and `okta` plugins share one token cache, so +their three `*.token_cache.size` gauges all report the same value. + diff --git a/site/docs-ruby/using-plugins/aws-secrets-manager.md b/site/docs-ruby/using-plugins/aws-secrets-manager.md index e5db259..805bcd5 100644 --- a/site/docs-ruby/using-plugins/aws-secrets-manager.md +++ b/site/docs-ruby/using-plugins/aws-secrets-manager.md @@ -14,7 +14,7 @@ Version 1.0.0 ::: :::warning Only one authentication plugin at a time -The `secrets_manager` and `iam` plugins are mutually exclusive — only one authentication plugin may be active at a time. Configuring both in `wrapper_plugins` raises a `PluginConflictError` at connection initialization. +Only one authentication plugin may be enabled per connection. Do not use `secrets_manager` together with any of the other authentication plugins (`iam`, `federated_auth`, `okta`) at the same time for the same connection. Configuring more than one raises a `PluginConflictError` at connection initialization. ::: ## Prerequisites @@ -65,7 +65,7 @@ Verify plugin compatibility within your Ruby configuration using the [compatibil | `secret_expiration_sec` | Float | No | `870.0` | Time in seconds that secrets are cached before being re-fetched. When the credentials have a bounded lifetime (for example a rotation schedule), keep this comfortably below that lifetime — roughly 30 seconds less — so a rotated secret is picked up before the cached copy goes stale. Values outside `300.0`–`1140.0` are clamped into that range, with a warning logged. *(sec)*

Example: `600.0 (300.0 to 1140.0)` | | `secret_username_key` | String | No | `username` | The key in the JSON secret that contains the username for the database connection.

Example: `writerUsername` | | `secret_password_key` | String | No | `password` | The key in the JSON secret that contains the password for the database connection.

Example: `readerPassword` | -| `aws_credentials_provider` | Object | No | SDK default chain | A custom AWS credentials provider instance. One property is read by the IAM authentication, Secrets Manager and KMS encryption plugins, so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain.

Example: `Aws::AssumeRoleCredentials.new(...)` | +| `aws_credentials_provider` | Object | No | SDK default chain | A custom AWS credentials provider instance. One property is read by every plugin that calls AWS — IAM authentication, Secrets Manager, KMS encryption and custom endpoint — so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain.

Example: `Aws::AssumeRoleCredentials.new(...)` | | `secret_rotation_retry_timeout_sec` | Float | No | `0.0` | Time budget for the exponential-backoff retry loop used to bridge an in-progress secret rotation, re-fetching the credentials before each retry. `0` (the default) disables this timed retry loop; the plugin still performs a single forced re-fetch and one retry when a connection fails to authenticate with the cached secret. *(sec)*

Example: `30.0` | | `secret_rotation_retry_base_delay_sec` | Float | No | `0.5` | Initial delay before a failed connection is retried. The delay grows exponentially between attempts. Only used when the retry timeout is greater than `0`. *(sec)*

Example: `1.0` | diff --git a/site/docs-ruby/using-plugins/blue-green.md b/site/docs-ruby/using-plugins/blue-green.md index 9c3b027..36e82ef 100644 --- a/site/docs-ruby/using-plugins/blue-green.md +++ b/site/docs-ruby/using-plugins/blue-green.md @@ -16,7 +16,7 @@ switchover status and adjusting connection handling at each phase: - **Before the switchover**, it inventories the blue and green endpoints and their IP addresses. - **During the active switchover**, it temporarily suspends calls to blue nodes and substitutes hostnames with the corresponding IP addresses to avoid stale DNS. -- **After the switchover**, it monitors DNS until blue endpoints are reconfigured, then stops substituting. +- **After the switchover**, it monitors DNS until blue endpoints are reconfigured, then stops substituting. From this phase on, it also invalidates connections that were opened to the old blue environment before the switchover, so their next use raises an error instead of reading from retired blue nodes. See `bg_drop_blue_connections` below. - **Once switchover completes**, it rejects new connections to green nodes. - **If the switchover fails or rolls back**, it detects that and restores normal handling. @@ -61,6 +61,7 @@ stateDiagram-v2 end note note right of Post Monitor DNS; stop substitution; + invalidate pre-switchover blue connections; reject new connections to green nodes end note ``` @@ -92,6 +93,7 @@ Verify plugin compatibility within your Ruby configuration using the [compatibil | `bg_increased_sec` | Float | No | `1.0` | Increased interval for checking Blue/Green Deployment status. Configure within 0.5–2 sec. *(sec)*

Example: `1.0` | | `bg_high_sec` | Float | No | `0.1` | High-frequency interval for checking Blue/Green Deployment status. Configure within 0.05–0.5 sec. *(sec)*

Example: `0.1` | | `bg_switchover_timeout_sec` | Float | No | `180.0` | Maximum duration allowed for switchover completion. If the process stalls or exceeds this, the wrapper assumes completion and resumes normal operations. *(sec)*

Example: `180.0` | +| `bg_drop_blue_connections` | Boolean | No | `true` | Whether to invalidate connections that were opened to the old blue environment before a switchover. Once the switchover is confirmed (it reaches the Post or Completed phase), each such connection is closed the next time it is used. With the failover plugin enabled, that use triggers failover through Blue/Green routing and raises one of the [failover errors](../enhanced-failover#failover-errors): `FailoverSuccessError` or `TransactionStateUnknownError` (inside a transaction) when it reconnects, or `FailoverFailedError` when it cannot, for example during a network disconnect. Without it, the driver raises its closed-connection error; under ActiveRecord, a query it considers retryable may instead be reconnected and retried for you. In neither case is a stale read served from the old blue environment. Connections are invalidated only if the plugin saw the switchover while it was in progress, and none are invalidated if the switchover rolls back, or if `bg_switchover_timeout_sec` elapses before the switchover reaches the Post phase.

Example: `false` | ## Configuring monitoring connections diff --git a/site/docs-ruby/using-plugins/custom-endpoint.md b/site/docs-ruby/using-plugins/custom-endpoint.md index 68d804d..9d29abc 100644 --- a/site/docs-ruby/using-plugins/custom-endpoint.md +++ b/site/docs-ruby/using-plugins/custom-endpoint.md @@ -77,9 +77,9 @@ endpoint's members, so add `aws-sdk-rds` to your Gemfile: gem 'aws-sdk-rds' ``` -The plugin uses the AWS SDK default credential provider chain, so the credentials -must be available through the chain (for example environment variables, an instance -profile, or an ECS task role). See [AWS Credentials](../aws-credentials). +The plugin signs these calls with the provider given in `aws_credentials_provider`, +or with the AWS SDK default credential provider chain when it is not set. See +[AWS Credentials](../aws-credentials). ::: @@ -94,3 +94,4 @@ profile, or an ECS task role). See [AWS Credentials](../aws-credentials). | `custom_endpoint_monitor_expiration_sec` | Float | No | `900.0` | How long a monitor runs without use before expiring and being removed. *(sec)*

Example: `600.0` | | `wait_for_custom_endpoint_info` | Boolean | No | `true` | Whether to wait for custom endpoint info to become available before connecting or executing a method. Disabling this may result in occasional connections to instances outside of the custom endpoint.

Example: `true` | | `wait_for_custom_endpoint_info_timeout_sec` | Float | No | `5.0` | Maximum time the plugin waits for custom endpoint info to be made available by the monitor. *(sec)*

Example: `7.0` | +| `aws_credentials_provider` | Object | No | SDK default chain | A custom AWS credentials provider instance. One property is read by every plugin that calls AWS — IAM authentication, Secrets Manager, KMS encryption and custom endpoint — so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain. The custom endpoint monitor is shared by every connection to the same custom endpoint, so it uses the provider of the first connection that starts it.

Example: `Aws::AssumeRoleCredentials.new(...)` | diff --git a/site/docs-ruby/using-plugins/federated-auth.md b/site/docs-ruby/using-plugins/federated-auth.md new file mode 100644 index 0000000..d63dd87 --- /dev/null +++ b/site/docs-ruby/using-plugins/federated-auth.md @@ -0,0 +1,194 @@ +--- +title: Federated Authentication Plugin +--- + +The Federated Authentication Plugin adds support for authenticating through a +federated identity provider — [Microsoft Active Directory Federation Services +(AD FS)](https://learn.microsoft.com/en-us/windows-server/identity/active-directory-federation-services) — +and then connecting to the database with AWS IAM. The plugin signs in to AD FS, +obtains a SAML assertion, exchanges it for temporary AWS credentials, and uses +those credentials to generate an IAM authentication token for the connection. + + +:::info Available since +Version 1.1.0 +::: + +:::warning Only one authentication plugin at a time +Only one authentication plugin may be enabled per connection. Do not use `federated_auth` together with any of the other authentication plugins (`iam`, `secrets_manager`, `okta`) at the same time for the same connection. Configuring more than one raises a `PluginConflictError` at connection initialization. +::: + +## What is federated identity + +Federated identity lets users authenticate once with an external identity provider (IdP) and use that single identity to reach services across organizations. The IdP authenticates the user and issues a signed security token — a SAML assertion — and any service provider that trusts the IdP accepts that assertion instead of managing its own credentials. + +This plugin applies that flow to database access. It signs in to your IdP with the configured credentials, receives a SAML assertion, exchanges the assertion for temporary AWS credentials through AWS STS `AssumeRoleWithSAML`, and uses those credentials to generate an AWS IAM authentication token. That IAM token is what the plugin uses to connect, so **AWS IAM database authentication must be enabled** on the target database. + +## Prerequisites + +:::warning +This plugin requires the AWS SDK for RDS. Add it to your Gemfile: + +```ruby +gem 'aws-sdk-rds' +``` +::: + +The plugin signs in to your identity provider over HTTPS using Ruby's standard +library HTTP client, so no additional SAML or XML parsing gem is required. It +obtains AWS credentials from the SAML assertion through AWS STS +`AssumeRoleWithSAML`; it does not read `aws_credentials_provider` or the AWS SDK +default credential provider chain. + +Before using the plugin, enable IAM database authentication on your database, +create an [IAM SAML identity provider](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html) +and an IAM role granting `rds-db:connect`, and create a database account mapped +to IAM: + +- MySQL: `CREATE USER iam_user IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS';` +- PostgreSQL: `CREATE USER iam_user; GRANT rds_iam TO iam_user;` + + +## How to enable + +The plugin depends on AWS IAM database authentication: after it obtains a SAML assertion from your IdP, the assertion is exchanged for an AWS IAM authentication token, which is then used to connect to the database. Before enabling the plugin: + +1. [Enable IAM database authentication](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html) on your RDS or Aurora database. +2. Set up an [IAM SAML identity provider](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html) and an IAM role whose policy grants `rds-db:connect`, then federate your IdP into that AWS account. + +Then add the plugin code `federated_auth` to the `wrapper_plugins` parameter and set the parameters required for your environment. + +```ruby +require 'aws_advanced_ruby_driver_wrapper/postgresql' + +conn = AwsAdvancedRubyDriverWrapper::WrapperPgConnection.new( + host: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com", + wrapper_plugins: "federated_auth", + db_user: "iam_user", + idp_endpoint: "adfs.example.com", + idp_username: "someFederatedUsername@example.com", + idp_password: "someFederatedPassword", + iam_role_arn: "arn:aws:iam::123456789012:role/adfs_example_iam_role", + iam_idp_arn: "arn:aws:iam::123456789012:saml-provider/adfs_example", + iam_region: "us-east-1", + sslmode: "verify-full", + sslrootcert: "/path/to/global-bundle.pem" +) + +``` + +Verify plugin compatibility within your Ruby configuration using the [compatibility guide](../compatibility). + +## Configuration parameters + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `db_user` | String | Yes | — | The database username the generated IAM authentication token is minted for — the IAM-mapped database account the connection is made as.

Example: `iam_user` | +| `idp_endpoint` | String | Yes | — | The host name of the AD FS identity provider used to authenticate.

Example: `adfs.example.com` | +| `idp_username` | String | No | connection user | The username used to sign in to the identity provider. If not set, the plugin falls back to the connection `user`/`username`.

Example: `someFederatedUsername@example.com` | +| `idp_password` | String | No | connection password | The password used to sign in to the identity provider. If not set, the plugin falls back to the connection `password`.

Example: `someFederatedPassword` | +| `idp_port` | Integer | No | `443` | The port the AD FS host listens on, used to build the sign-on URL.

Example: `443` | +| `rp_identifier` | String | No | `urn:amazon:webservices` | The relying-party identifier sent to AD FS when requesting the SAML assertion.

Example: `urn:amazon:webservices` | +| `iam_role_arn` | String | Yes | — | The ARN of the IAM role assumed through the SAML assertion to obtain temporary AWS credentials.

Example: `arn:aws:iam::123456789012:role/adfs_example_iam_role` | +| `iam_idp_arn` | String | Yes | — | The ARN of the SAML identity provider registered in AWS IAM.

Example: `arn:aws:iam::123456789012:saml-provider/adfs_example` | +| `iam_region` | String | No | parsed from host | Overrides the AWS region used to generate the IAM token. By default it is parsed from the connection host.

Example: `us-east-1` | +| `iam_host` | String | No | derived from host | Overrides the host used to generate the IAM token. By default it is derived from the connection host.

Example: `my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com` | +| `iam_port` | Integer | No | dialect default | Overrides the port used to generate the IAM token. By default it is taken from the connection, or the dialect's default port.

Example: `5432` | +| `iam_expiration_sec` | Float | No | `870.0` | Number of seconds a generated IAM token is kept in the cache before a new one is generated. The token itself is valid for 15 minutes, and a cached token is never used within 60 seconds of that expiry, so values of `840.0` and above will all have their tokens refetched at the `840` mark. The token cache is shared by every connection in the process that uses the `iam`, `federated_auth`, or `okta` plugin, and its lifetime is set by the first such connection; later connections that set a different value use the first connection's value. A value greater than `870.0` or less than or equal to `0` is rejected. *(sec)*

Example: `600.0 (maximum 870.0)` | +| `ssl_insecure` | Boolean | No | `false` | When `true`, disables TLS certificate verification on the HTTPS requests the plugin makes to the identity provider. Intended for development only.

Example: `true` | +| `http_client_socket_timeout_sec` | Float | No | `60.0` | Read (socket) timeout for the HTTPS requests the plugin makes to the identity provider. *(sec)*

Example: `60.0` | +| `http_client_connect_timeout_sec` | Float | No | `60.0` | Connect timeout for the HTTPS requests the plugin makes to the identity provider. *(sec)*

Example: `60.0` | + +## Using this plugin with Global Databases + +When connecting to an +[Amazon Aurora Global Database](https://aws.amazon.com/rds/aurora/global-database/), +the IAM role assumed through the SAML assertion requires the additional +`rds:DescribeGlobalClusters` permission so the plugin can resolve the writer +region before generating the IAM token. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "rds-db:connect", + "rds:DescribeGlobalClusters" + ], + "Resource": "*" + } + ] +} +``` + +When you connect through an **Aurora Global Database endpoint**, also enable the +[Initial Connection Strategy plugin](./initial-connection-strategy) +(`initial_connection`). A global endpoint carries no region and points at +whichever regional cluster is currently the primary, so it must be resolved to the +writer instance before the IAM token is generated. + +For a global **writer** cluster, set `iam_region` explicitly when you can. Without +it, the plugin must perform one extra sign-in to your identity provider up front to +obtain the credentials needed to look up the writer region. + +## Use TLS/SSL with federated authentication + +:::warning +Use a **TLS/SSL 1.2+ connection**. The plugin injects the generated IAM token as +the connection password, and TLS ensures it is encrypted in transit. +::: + +**PostgreSQL (`pg`):** set `sslmode: "verify-full"` and point `sslrootcert` at the +[AWS global certificate bundle](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html). + +```ruby +AwsAdvancedRubyDriverWrapper::WrapperPgConnection.new( + host: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com", + wrapper_plugins: "federated_auth", + db_user: "iam_user", + idp_endpoint: "adfs.example.com", + idp_username: "someFederatedUsername@example.com", + idp_password: "someFederatedPassword", + iam_role_arn: "arn:aws:iam::123456789012:role/adfs_example_iam_role", + iam_idp_arn: "arn:aws:iam::123456789012:saml-provider/adfs_example", + iam_region: "us-east-1", + sslmode: "verify-full", + sslrootcert: "/path/to/global-bundle.pem" +) +``` + +**MySQL (`mysql2`):** set `ssl_mode: "verify_identity"`, point `sslca` at the +global certificate bundle, and set `enable_cleartext_plugin: true`. RDS/Aurora +MySQL IAM authentication relies on the MySQL `mysql_clear_password` client plugin +because the token must be sent to the server in cleartext; the wrapper does +**not** set this for you. + +```ruby +AwsAdvancedRubyDriverWrapper::WrapperMysql2Client.new( + host: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com", + wrapper_plugins: "federated_auth", + db_user: "iam_user", + idp_endpoint: "adfs.example.com", + idp_username: "someFederatedUsername@example.com", + idp_password: "someFederatedPassword", + iam_role_arn: "arn:aws:iam::123456789012:role/adfs_example_iam_role", + iam_idp_arn: "arn:aws:iam::123456789012:saml-provider/adfs_example", + iam_region: "us-east-1", + enable_cleartext_plugin: true, + sslca: "/path/to/global-bundle.pem", + ssl_mode: "verify_identity" +) +``` + +With the Trilogy driver, use +`AwsAdvancedRubyDriverWrapper::WrapperTrilogyClient`. `enable_cleartext_plugin: +true` is still required — without it Trilogy raises `Trilogy::AuthPluginError` +— but two TLS keys differ: the CA certificate is `ssl_ca` rather than `sslca`, +and on the direct client `ssl_mode` must be an integer constant +(`ssl_mode: Trilogy::SSL_VERIFY_IDENTITY`), not a string. See +[Configuring TLS/SSL](../configuring-tls). + +For the full picture, see [Configuring TLS/SSL](../configuring-tls). + diff --git a/site/docs-ruby/using-plugins/gdb-failover.md b/site/docs-ruby/using-plugins/gdb-failover.md index 8e12c07..c7d2277 100644 --- a/site/docs-ruby/using-plugins/gdb-failover.md +++ b/site/docs-ruby/using-plugins/gdb-failover.md @@ -87,7 +87,7 @@ conn = AwsAdvancedRubyDriverWrapper::WrapperPgConnection.new( ``` -:::warning +:::warning Only one failover plugin at a time Only one failover plugin may be enabled per connection. Do not use `gdb_failover` together with the other `failover` plugin at the same time for the same connection. Configuring more than one raises a `PluginConflictError` at connection initialization. ::: diff --git a/site/docs-ruby/using-plugins/iam-authentication.md b/site/docs-ruby/using-plugins/iam-authentication.md index 0caa1cb..3ee660a 100644 --- a/site/docs-ruby/using-plugins/iam-authentication.md +++ b/site/docs-ruby/using-plugins/iam-authentication.md @@ -16,7 +16,7 @@ Version 1.0.0 ::: :::warning Only one authentication plugin at a time -The `iam` and `secrets_manager` plugins are mutually exclusive — only one authentication plugin may be active at a time. Configuring both in `wrapper_plugins` raises a `PluginConflictError` at connection initialization. +Only one authentication plugin may be enabled per connection. Do not use `iam` together with any of the other authentication plugins (`secrets_manager`, `federated_auth`, `okta`) at the same time for the same connection. Configuring more than one raises a `PluginConflictError` at connection initialization. ::: ## Prerequisites @@ -66,6 +66,16 @@ AwsAdvancedRubyDriverWrapper::WrapperMysql2Client.new( ) ``` +With the Trilogy driver, swap in +`AwsAdvancedRubyDriverWrapper::WrapperTrilogyClient`. IAM authentication works +the same way — keep `enable_cleartext_plugin: true` — but two TLS keys differ +on Trilogy: the CA certificate is `ssl_ca` (Trilogy's name for it) rather than +`sslca`, and on the direct client `ssl_mode` must be an integer constant +(`ssl_mode: Trilogy::SSL_VERIFY_IDENTITY`) — a string or symbol raises +`TypeError`. (The `aws_trilogy` ActiveRecord adapter does accept the string +mode names such as `verify_identity`.) See +[Configuring TLS/SSL](../configuring-tls) for the full per-driver table. + **PostgreSQL (`pg`):** ```ruby @@ -102,6 +112,10 @@ does **not** set this for you, so pass `enable_cleartext_plugin: true` when using the plugin with MySQL. Because the token is sent in cleartext, you must also use a TLS/SSL connection so it is encrypted in transit. This does not apply to PostgreSQL (`pg`). + +This applies to both MySQL drivers (`mysql2` and `trilogy`). On `trilogy`, +omitting `enable_cleartext_plugin: true` makes the driver raise +`Trilogy::AuthPluginError` and the token is never sent. ::: @@ -140,9 +154,9 @@ Verify plugin compatibility within your Ruby configuration using the [compatibil | `iam_host` | String | No | derived from host | Overrides the hostname used to generate the IAM token. Required when connecting through a custom endpoint. The default is derived from the connection host.

Example: `my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com` | | `iam_port` | Integer | No | dialect default | Overrides the port used to generate the IAM token. The default is determined from the underlying driver protocol or the dialect default.

Example: `5432` | | `iam_region` | String | No | parsed from host | Overrides the AWS region used to generate the IAM token. The default is parsed from the connection string.

Example: `us-east-1` | -| `iam_expiration_sec` | Float | No | `870.0` | Number of seconds a generated IAM token is kept in the cache before a new one is generated. The token itself is valid for 15 minutes, and a cached token is never used within 60 seconds of that expiry, so values of `840.0` and above will all have their tokens refetched at the `840` mark. The token cache is shared by every connection in the process, and its lifetime is set by the first connection that uses the IAM plugin; later connections that set a different value use the first connection's value. A value greater than `870.0` or less than or equal to `0` is rejected. *(sec)*

Example: `600.0 (maximum 870.0)` | +| `iam_expiration_sec` | Float | No | `870.0` | Number of seconds a generated IAM token is kept in the cache before a new one is generated. The token itself is valid for 15 minutes, and a cached token is never used within 60 seconds of that expiry, so values of `840.0` and above will all have their tokens refetched at the `840` mark. The token cache is shared by every connection in the process that uses the `iam`, `federated_auth`, or `okta` plugin, and its lifetime is set by the first such connection; later connections that set a different value use the first connection's value. A value greater than `870.0` or less than or equal to `0` is rejected. *(sec)*

Example: `600.0 (maximum 870.0)` | | `iam_access_token_property_name` | Symbol | No | `:password` | The connection property name the generated token is injected into. Some underlying drivers require a specific property name for the token.

Example: `:password` | -| `aws_credentials_provider` | Object | No | SDK default chain | A custom AWS credentials provider instance. One property is read by the IAM authentication, Secrets Manager and KMS encryption plugins, so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain.

Example: `Aws::AssumeRoleCredentials.new(...)` | +| `aws_credentials_provider` | Object | No | SDK default chain | A custom AWS credentials provider instance. One property is read by every plugin that calls AWS — IAM authentication, Secrets Manager, KMS encryption and custom endpoint — so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain.

Example: `Aws::AssumeRoleCredentials.new(...)` | ## Using IAM authentication with Global Databases @@ -191,10 +205,11 @@ login error occurs with a cached token, the plugin automatically fetches a fresh token and retries the connection once. :::note -The token cache is shared by every connection in the process, and the first -connection that uses the IAM plugin sets its `iam_expiration_sec`. Connections -opened later with a different value still use the first connection's value, so -set `iam_expiration_sec` to the same value on every connection. +The token cache is shared by every connection in the process that uses the +`iam`, `federated_auth`, or `okta` plugin, and the first such connection sets +its `iam_expiration_sec`. Connections opened later with a different value still +use the first connection's value, so set `iam_expiration_sec` to the same value +on every connection. ::: ## Related diff --git a/site/docs-ruby/using-plugins/kms-encryption.md b/site/docs-ruby/using-plugins/kms-encryption.md index bfd83ad..02acc5d 100644 --- a/site/docs-ruby/using-plugins/kms-encryption.md +++ b/site/docs-ruby/using-plugins/kms-encryption.md @@ -20,6 +20,14 @@ column never holds plaintext. See [Server-side enforcement is required](#server- and [Enforce encryption in the database](#enforce-encryption-in-the-database) below. ::: +:::warning Not supported with the Trilogy driver +The plugin can encrypt a value only when it is sent as a bound parameter, which +requires prepared statements. The Trilogy driver does not support prepared +statements, so the plugin cannot be used with it: both the plugin and +`KeyManagementUtility` refuse a Trilogy connection with an explicit error. Use the +`mysql2` driver (or `pg` on PostgreSQL) for column encryption. +::: + :::info Available since Version 1.0.0 @@ -139,7 +147,8 @@ then use `Plugins::Encryption::KeyManagementUtility` to set up each column. ### Set up an encrypted column `KeyManagementUtility` runs on a plain `pg` or `mysql2` connection that you -open and close yourself. Build its configuration from the same `encryption_*` +open and close yourself. (It does not support `trilogy`, for the same +prepared-statement reason the plugin does not.) Build its configuration from the same `encryption_*` parameters the plugin uses, then create a master key and turn on encryption for an existing binary column: @@ -213,7 +222,7 @@ Verify plugin compatibility within your Ruby configuration using the [compatibil | `encryption_key_management_max_retries` | Integer | No | `3` | Maximum number of retries for throttled or failed key-management (KMS) operations.

Example: `5` | | `encryption_key_management_retry_backoff_base_sec` | Float | No | `0.1` | Base delay for the exponential backoff between key-management (KMS) retries. *(sec)*

Example: `0.25` | | `encryption_audit_logging_enabled` | Boolean | No | `false` | Log an audit record for every key-management, encryption, and decryption operation.

Example: `true` | -| `aws_credentials_provider` | Object | No | SDK default chain | A custom AWS credentials provider instance. One property is read by the IAM authentication, Secrets Manager and KMS encryption plugins, so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain.

Example: `Aws::AssumeRoleCredentials.new(...)` | +| `aws_credentials_provider` | Object | No | SDK default chain | A custom AWS credentials provider instance. One property is read by every plugin that calls AWS — IAM authentication, Secrets Manager, KMS encryption and custom endpoint — so setting it once covers all of them. When unset, each falls back to the AWS SDK default credential provider chain.

Example: `Aws::AssumeRoleCredentials.new(...)` | | `encryption_return_unverified_data` | Boolean | No | `false` | **Do not enable in production.** On read, return a value as stored when it cannot be confirmed to be this column's encrypted data instead of raising. Intended only for reading data written before the column was encrypted.

Example: `false` | ## Server-side enforcement is required diff --git a/site/docs-ruby/using-plugins/okta-auth.md b/site/docs-ruby/using-plugins/okta-auth.md new file mode 100644 index 0000000..5829e70 --- /dev/null +++ b/site/docs-ruby/using-plugins/okta-auth.md @@ -0,0 +1,196 @@ +--- +title: Okta Authentication Plugin +--- + +The Okta Authentication Plugin adds support for authenticating through +[Okta](https://www.okta.com/) as the federated identity provider and then +connecting to the database with AWS IAM. The plugin signs in to Okta, obtains a +SAML assertion for the configured AWS application, exchanges it for temporary AWS +credentials, and uses those credentials to generate an IAM authentication token +for the connection. + + +:::info Available since +Version 1.1.0 +::: + +:::warning Only one authentication plugin at a time +Only one authentication plugin may be enabled per connection. Do not use `okta` together with any of the other authentication plugins (`iam`, `secrets_manager`, `federated_auth`) at the same time for the same connection. Configuring more than one raises a `PluginConflictError` at connection initialization. +::: + +## What is federated identity + +Federated identity lets users authenticate once with an external identity provider (IdP) and use that single identity to reach services across organizations. The IdP authenticates the user and issues a signed security token — a SAML assertion — and any service provider that trusts the IdP accepts that assertion instead of managing its own credentials. + +This plugin applies that flow to database access. It signs in to your IdP with the configured credentials, receives a SAML assertion, exchanges the assertion for temporary AWS credentials through AWS STS `AssumeRoleWithSAML`, and uses those credentials to generate an AWS IAM authentication token. That IAM token is what the plugin uses to connect, so **AWS IAM database authentication must be enabled** on the target database. + +## Prerequisites + +:::warning +This plugin requires the AWS SDK for RDS. Add it to your Gemfile: + +```ruby +gem 'aws-sdk-rds' +``` +::: + +The plugin signs in to Okta over HTTPS using Ruby's standard library HTTP +client, so no additional SAML or XML parsing gem is required. It obtains AWS +credentials from the SAML assertion through AWS STS `AssumeRoleWithSAML`; it +does not read `aws_credentials_provider` or the AWS SDK default credential +provider chain. + +Before using the plugin, enable IAM database authentication on your database, +[configure Okta as an AWS identity provider](https://help.okta.com/en-us/content/topics/deploymentguides/aws/aws-deployment.htm), +create the matching IAM SAML identity provider and an IAM role granting +`rds-db:connect`, and create a database account mapped to IAM: + +- MySQL: `CREATE USER iam_user IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS';` +- PostgreSQL: `CREATE USER iam_user; GRANT rds_iam TO iam_user;` + + +## How to enable + +The plugin depends on AWS IAM database authentication: after it obtains a SAML assertion from your IdP, the assertion is exchanged for an AWS IAM authentication token, which is then used to connect to the database. Before enabling the plugin: + +1. [Enable IAM database authentication](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html) on your RDS or Aurora database. +2. Set up an [IAM SAML identity provider](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html) and an IAM role whose policy grants `rds-db:connect`, then federate your IdP into that AWS account. + +Then add the plugin code `okta` to the `wrapper_plugins` parameter and set the parameters required for your environment. + +```ruby +require 'aws_advanced_ruby_driver_wrapper/postgresql' + +conn = AwsAdvancedRubyDriverWrapper::WrapperPgConnection.new( + host: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com", + wrapper_plugins: "okta", + db_user: "iam_user", + idp_endpoint: "my-org.okta.com", + idp_username: "someFederatedUsername@example.com", + idp_password: "someFederatedPassword", + app_id: "0oa1b2c3d4EXAMPLE", + iam_role_arn: "arn:aws:iam::123456789012:role/okta_example_iam_role", + iam_idp_arn: "arn:aws:iam::123456789012:saml-provider/okta_example", + iam_region: "us-east-1", + sslmode: "verify-full", + sslrootcert: "/path/to/global-bundle.pem" +) + +``` + +Verify plugin compatibility within your Ruby configuration using the [compatibility guide](../compatibility). + +## Configuration parameters + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `db_user` | String | Yes | — | The database username the generated IAM authentication token is minted for — the IAM-mapped database account the connection is made as.

Example: `iam_user` | +| `idp_endpoint` | String | Yes | — | The host name of your Okta organization used to authenticate.

Example: `my-org.okta.com` | +| `idp_username` | String | No | connection user | The username used to sign in to the identity provider. If not set, the plugin falls back to the connection `user`/`username`.

Example: `someFederatedUsername@example.com` | +| `idp_password` | String | No | connection password | The password used to sign in to the identity provider. If not set, the plugin falls back to the connection `password`.

Example: `someFederatedPassword` | +| `app_id` | String | Yes | — | The identifier of the AWS application configured in Okta.

Example: `0oa1b2c3d4EXAMPLE` | +| `iam_role_arn` | String | Yes | — | The ARN of the IAM role assumed through the SAML assertion to obtain temporary AWS credentials.

Example: `arn:aws:iam::123456789012:role/okta_example_iam_role` | +| `iam_idp_arn` | String | Yes | — | The ARN of the SAML identity provider registered in AWS IAM.

Example: `arn:aws:iam::123456789012:saml-provider/okta_example` | +| `iam_region` | String | No | parsed from host | Overrides the AWS region used to generate the IAM token. By default it is parsed from the connection host.

Example: `us-east-1` | +| `iam_host` | String | No | derived from host | Overrides the host used to generate the IAM token. By default it is derived from the connection host.

Example: `my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com` | +| `iam_port` | Integer | No | dialect default | Overrides the port used to generate the IAM token. By default it is taken from the connection, or the dialect's default port.

Example: `5432` | +| `iam_expiration_sec` | Float | No | `870.0` | Number of seconds a generated IAM token is kept in the cache before a new one is generated. The token itself is valid for 15 minutes, and a cached token is never used within 60 seconds of that expiry, so values of `840.0` and above will all have their tokens refetched at the `840` mark. The token cache is shared by every connection in the process that uses the `iam`, `federated_auth`, or `okta` plugin, and its lifetime is set by the first such connection; later connections that set a different value use the first connection's value. A value greater than `870.0` or less than or equal to `0` is rejected. *(sec)*

Example: `600.0 (maximum 870.0)` | +| `ssl_insecure` | Boolean | No | `false` | When `true`, disables TLS certificate verification on the HTTPS requests the plugin makes to the identity provider. Intended for development only.

Example: `true` | +| `http_client_socket_timeout_sec` | Float | No | `60.0` | Read (socket) timeout for the HTTPS requests the plugin makes to the identity provider. *(sec)*

Example: `60.0` | +| `http_client_connect_timeout_sec` | Float | No | `60.0` | Connect timeout for the HTTPS requests the plugin makes to the identity provider. *(sec)*

Example: `60.0` | + +## Using this plugin with Global Databases + +When connecting to an +[Amazon Aurora Global Database](https://aws.amazon.com/rds/aurora/global-database/), +the IAM role assumed through the SAML assertion requires the additional +`rds:DescribeGlobalClusters` permission so the plugin can resolve the writer +region before generating the IAM token. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "rds-db:connect", + "rds:DescribeGlobalClusters" + ], + "Resource": "*" + } + ] +} +``` + +When you connect through an **Aurora Global Database endpoint**, also enable the +[Initial Connection Strategy plugin](./initial-connection-strategy) +(`initial_connection`). A global endpoint carries no region and points at +whichever regional cluster is currently the primary, so it must be resolved to the +writer instance before the IAM token is generated. + +For a global **writer** cluster, set `iam_region` explicitly when you can. Without +it, the plugin must perform one extra sign-in to your identity provider up front to +obtain the credentials needed to look up the writer region. + +## Use TLS/SSL with Okta authentication + +:::warning +Use a **TLS/SSL 1.2+ connection**. The plugin injects the generated IAM token as +the connection password, and TLS ensures it is encrypted in transit. +::: + +**PostgreSQL (`pg`):** set `sslmode: "verify-full"` and point `sslrootcert` at the +[AWS global certificate bundle](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html). + +```ruby +AwsAdvancedRubyDriverWrapper::WrapperPgConnection.new( + host: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com", + wrapper_plugins: "okta", + db_user: "iam_user", + idp_endpoint: "my-org.okta.com", + idp_username: "someFederatedUsername@example.com", + idp_password: "someFederatedPassword", + app_id: "0oa1b2c3d4EXAMPLE", + iam_role_arn: "arn:aws:iam::123456789012:role/okta_example_iam_role", + iam_idp_arn: "arn:aws:iam::123456789012:saml-provider/okta_example", + iam_region: "us-east-1", + sslmode: "verify-full", + sslrootcert: "/path/to/global-bundle.pem" +) +``` + +**MySQL (`mysql2`):** set `ssl_mode: "verify_identity"`, point `sslca` at the +global certificate bundle, and set `enable_cleartext_plugin: true`. RDS/Aurora +MySQL IAM authentication relies on the MySQL `mysql_clear_password` client plugin +because the token must be sent to the server in cleartext; the wrapper does +**not** set this for you. + +```ruby +AwsAdvancedRubyDriverWrapper::WrapperMysql2Client.new( + host: "my-cluster.cluster-xyz.us-east-1.rds.amazonaws.com", + wrapper_plugins: "okta", + db_user: "iam_user", + idp_endpoint: "my-org.okta.com", + idp_username: "someFederatedUsername@example.com", + idp_password: "someFederatedPassword", + app_id: "0oa1b2c3d4EXAMPLE", + iam_role_arn: "arn:aws:iam::123456789012:role/okta_example_iam_role", + iam_idp_arn: "arn:aws:iam::123456789012:saml-provider/okta_example", + iam_region: "us-east-1", + enable_cleartext_plugin: true, + sslca: "/path/to/global-bundle.pem", + ssl_mode: "verify_identity" +) +``` + +With the Trilogy driver, use +`AwsAdvancedRubyDriverWrapper::WrapperTrilogyClient`. `enable_cleartext_plugin: +true` is still required — without it Trilogy raises `Trilogy::AuthPluginError` +— but two TLS keys differ: the CA certificate is `ssl_ca` rather than `sslca`, +and on the direct client `ssl_mode` must be an integer constant +(`ssl_mode: Trilogy::SSL_VERIFY_IDENTITY`), not a string. See +[Configuring TLS/SSL](../configuring-tls). + +For the full picture, see [Configuring TLS/SSL](../configuring-tls). + diff --git a/site/sidebars-ruby.js b/site/sidebars-ruby.js index 78626ec..9876781 100644 --- a/site/sidebars-ruby.js +++ b/site/sidebars-ruby.js @@ -16,6 +16,8 @@ const sidebars = { "using-plugins/gdb-failover", "using-plugins/iam-authentication", "using-plugins/aws-secrets-manager", + "using-plugins/federated-auth", + "using-plugins/okta-auth", "using-plugins/initial-connection-strategy", "using-plugins/kms-encryption" ], @@ -28,7 +30,8 @@ const sidebars = { "configuring-tls", "aws-credentials", "host-selection-strategies", - "cluster-id" + "cluster-id", + "telemetry" ], }, { diff --git a/site/src/components/ConfigBuilder/emitters.js b/site/src/components/ConfigBuilder/emitters.js index ff666d1..d9aba69 100644 --- a/site/src/components/ConfigBuilder/emitters.js +++ b/site/src/components/ConfigBuilder/emitters.js @@ -242,6 +242,15 @@ function directArgs(config, ctx, { reader }) { lines.push({ text: " failover_mode: 'strict-reader'", why: 'readers only' }); return; } + // The Trilogy driver's direct client takes ssl_mode as an integer constant + // (Trilogy::SSL_VERIFY_IDENTITY), not a string — a string or symbol raises + // TypeError. The aws_trilogy ActiveRecord adapter accepts the string names, + // so this applies only to the direct client. + if (engine === 'trilogy' && key === 'ssl_mode') { + const constant = `Trilogy::SSL_${String(cfg.params[key].value).toUpperCase()}`; + lines.push({ text: ` ${key}: ${constant}`, why: cfg.params[key].from }); + return; + } lines.push({ text: ` ${key}: ${rubyValue(cfg.params[key].value)}`, why: cfg.params[key].from }); }); return lines; diff --git a/site/src/components/ConfigBuilder/model.js b/site/src/components/ConfigBuilder/model.js index d81bda4..23a1eeb 100644 --- a/site/src/components/ConfigBuilder/model.js +++ b/site/src/components/ConfigBuilder/model.js @@ -151,7 +151,24 @@ export function buildConfig(data, state, active) { // The rules key on `deployment`; it comes from the db_type add-on, but only // when that selection is still valid under the current answers. const deployment = effectiveDeployment(data, state, active); - const axisState = { ...state, ...active, deployment }; + // Expose each exclusive add-on's current selection under its add-on id (e.g. + // `credentials: iam`), so a rule can emit configuration that depends on both + // an add-on choice and an axis — for example the cleartext client plugin that + // IAM authentication needs on MySQL but not PostgreSQL. Only a selection that + // actually applies is exposed: if the add-on or its chosen option is blocked + // (e.g. IAM on a community database), it is left out so no rule fires for it. + const baseState = { ...state, ...active, deployment }; + const addonSelections = {}; + for (const addon of data.addons || []) { + if (!addon.exclusive) continue; + const selected = state.addons[addon.id]; + if (!selected) continue; + if (blockReason(addon, baseState, data)) continue; + const option = (addon.options || []).find((o) => o.id === selected); + if (option && blockReason(option, baseState, data)) continue; + addonSelections[addon.id] = selected; + } + const axisState = { ...baseState, ...addonSelections }; for (const question of data.questions) { const chosen = active[question.id]; @@ -161,7 +178,7 @@ export function buildConfig(data, state, active) { } for (const rule of data.rules) { - if (condMet(rule.when, axisState)) applyPatch(config, rule.emit, 'your deployment', data); + if (condMet(rule.when, axisState)) applyPatch(config, rule.emit, rule.from || 'your deployment', data); } for (const addon of data.addons) { diff --git a/site/src/generated/manifest.json b/site/src/generated/manifest.json index d31d580..095f106 100644 --- a/site/src/generated/manifest.json +++ b/site/src/generated/manifest.json @@ -79,6 +79,24 @@ "parentPath": "overview", "category": "Using Plugins" }, + "using-plugins/federated-auth": { + "path": "using-plugins/federated-auth", + "title": "Federated Authentication Plugin", + "wrappers": [ + "ruby" + ], + "parentPath": "overview", + "category": "Using Plugins" + }, + "using-plugins/okta-auth": { + "path": "using-plugins/okta-auth", + "title": "Okta Authentication Plugin", + "wrappers": [ + "ruby" + ], + "parentPath": "overview", + "category": "Using Plugins" + }, "using-plugins/initial-connection-strategy": { "path": "using-plugins/initial-connection-strategy", "title": "Initial Connection Strategy Plugin", @@ -133,6 +151,15 @@ "parentPath": "overview", "category": "Shared Configuration" }, + "telemetry": { + "path": "telemetry", + "title": "Telemetry", + "wrappers": [ + "ruby" + ], + "parentPath": "overview", + "category": "Shared Configuration" + }, "compatibility": { "path": "compatibility", "title": "Plugin Compatibility", diff --git a/site/src/generated/scenarios-ruby.json b/site/src/generated/scenarios-ruby.json index 461dd33..da6be9f 100644 --- a/site/src/generated/scenarios-ruby.json +++ b/site/src/generated/scenarios-ruby.json @@ -3,31 +3,38 @@ "meta": { "engineLabel": { "pg": "PostgreSQL", - "mysql": "MySQL" + "mysql": "MySQL", + "trilogy": "MySQL" }, "adapter": { "pg": "aws_postgresql", - "mysql": "aws_mysql2" + "mysql": "aws_mysql2", + "trilogy": "aws_trilogy" }, "gem": { "pg": "pg", - "mysql": "mysql2" + "mysql": "mysql2", + "trilogy": "trilogy" }, "requirePath": { "pg": "aws_advanced_ruby_driver_wrapper/postgresql", - "mysql": "aws_advanced_ruby_driver_wrapper/mysql" + "mysql": "aws_advanced_ruby_driver_wrapper/mysql", + "trilogy": "aws_advanced_ruby_driver_wrapper/trilogy" }, "directClass": { "pg": "AwsAdvancedRubyDriverWrapper::WrapperPgConnection", - "mysql": "AwsAdvancedRubyDriverWrapper::WrapperMysql2Client" + "mysql": "AwsAdvancedRubyDriverWrapper::WrapperMysql2Client", + "trilogy": "AwsAdvancedRubyDriverWrapper::WrapperTrilogyClient" }, "standsIn": { "pg": "PG::Connection", - "mysql": "Mysql2::Client" + "mysql": "Mysql2::Client", + "trilogy": "Trilogy" }, "port": { "pg": 5432, - "mysql": 3306 + "mysql": 3306, + "trilogy": 3306 } }, "links": { @@ -229,6 +236,7 @@ "bgUnsupportedGlobal": "AWS does not support Blue/Green deployments with RDS Proxy on Aurora global databases, and the wrapper's Blue/Green plugin does not support global databases. Use a global switchover or failover instead.", "bgUnsupportedMultiAzCluster": "AWS Blue/Green deployments are not available for RDS Multi-AZ DB clusters (they are supported for Multi-AZ DB instance deployments).", "bgUnsupportedCommunity": "Blue/Green deployments are an Amazon RDS/Aurora feature. A community database you run yourself cannot be set up with one.", + "kmsUnsupportedTrilogy": "The KMS Encryption Plugin relies on prepared statements, which Trilogy does not support, so it cannot be used with the Trilogy driver. Use the mysql2 driver for column encryption.", "resultHeading": "Your configuration", "assumesHeading": "What this assumes", "pluginsHeading": "Why each plugin is here", @@ -280,7 +288,8 @@ "cluster_readonly" ], "engine": [ - "mysql" + "mysql", + "trilogy" ] }, "emit": { @@ -310,7 +319,8 @@ "global" ], "engine": [ - "mysql" + "mysql", + "trilogy" ] }, "emit": { @@ -340,7 +350,8 @@ "multi_az_cluster" ], "engine": [ - "mysql" + "mysql", + "trilogy" ] }, "emit": { @@ -374,7 +385,8 @@ "proxy" ], "engine": [ - "mysql" + "mysql", + "trilogy" ] }, "emit": { @@ -404,7 +416,8 @@ "community" ], "engine": [ - "mysql" + "mysql", + "trilogy" ] }, "emit": { @@ -413,6 +426,74 @@ } } }, + { + "when": { + "credentials": [ + "iam" + ], + "engine": [ + "mysql", + "trilogy" + ] + }, + "from": "required on MySQL: the IAM token is sent via mysql_clear_password", + "emit": { + "params": { + "enable_cleartext_plugin": true + } + } + }, + { + "when": { + "credentials": [ + "iam" + ], + "engine": [ + "pg" + ] + }, + "from": "recommended: encrypts the IAM token (sent as the password) in transit", + "emit": { + "params": { + "sslmode": "verify-full", + "sslrootcert": "" + } + } + }, + { + "when": { + "credentials": [ + "iam" + ], + "engine": [ + "mysql" + ] + }, + "from": "recommended: encrypts the IAM token (sent in cleartext) in transit", + "emit": { + "params": { + "ssl_mode": "verify_identity", + "sslca": "" + } + } + }, + { + "when": { + "credentials": [ + "iam" + ], + "engine": [ + "trilogy" + ] + }, + "from": "recommended: encrypts the IAM token (sent in cleartext) in transit", + "emit": { + "params": { + "ssl_mode": "verify_identity", + "ssl_ca": "" + } + } + }, { "when": { "continuity": [ @@ -599,7 +680,11 @@ }, { "id": "mysql", - "label": "MySQL" + "label": "MySQL (mysql2)" + }, + { + "id": "trilogy", + "label": "MySQL (Trilogy)" } ] }, @@ -644,7 +729,7 @@ }, { "id": "direct", - "label": "Through the pg or mysql2 gem directly", + "label": "Through the pg, mysql2, or trilogy gem directly", "short": "the gem directly", "hint": "The wrapper stands in for the gem's own connection class. There is no pool and no role concept, so both are yours to build.\n", "emit": { @@ -1003,7 +1088,7 @@ ] }, "blocked": "Active Record supplies this. Talking to the gem directly, retrying is your code's decision.", - "hint": "Active Record retries safely retryable queries once by default.", + "hint": "Active Record retries safely retryable queries once by default. It does not retry `FailoverSuccessError` or `TransactionStateUnknownError`, which the failover plugin raises after a successful failover.\n", "emit": { "pool": { "connection_retries": 3, @@ -1165,6 +1250,7 @@ ], "notes": [ "The plugin holds traffic during the switchover instead of letting it fail, then resumes against the promoted deployment.", + "After the switchover, connections that were opened to the old blue environment are closed the next time they are used. If the failover plugin is enabled (list `failover` in `wrapper_plugins` alongside `bg`), that use triggers failover and raises one of the failover errors: `FailoverSuccessError` (or `TransactionStateUnknownError` inside a transaction) when the connection reconnects to the new environment, or `FailoverFailedError` when it cannot. Handle it as you would any other failover. Set `bg_drop_blue_connections: false` to keep using those connections instead, at the risk of reading from the retired blue environment.", "If you connect through an RDS Proxy, AWS requires the blue cluster to be registered with the proxy before the Blue/Green deployment is created \u2014 you cannot add the proxy afterward." ], "links": [ @@ -1193,6 +1279,16 @@ "toggle": true, "label": "Encrypt column values with AWS KMS", "short": "column encryption", + "blockedIf": [ + { + "when": { + "engine": [ + "trilogy" + ] + }, + "reason": "kmsUnsupportedTrilogy" + } + ], "emit": { "plugins": [ "kms_encryption"