* feat(rds): add StartExportTask, DescribeExportTasks and CancelExportTask with the export task lifecycle
* docs(rds): document the snapshot export task API
* fix(rds): route the export task actions to RDS when a request has no signing scope
* fix(rds): refuse an export to a bucket outside the snapshot's region
* fix(rds): answer export task calls with a copy of the task taken under the lock
* fix(rds): refuse an unknown DescribeExportTasks filter name before matching any task
* fix(rds): fail an export to a bucket in another region as a task, as RDS does, rather than refuse it
* docs(rds): say that a bucket in another region fails an export in mock mode too
* fix(rds): serve a CA-signed proxy TLS leaf certificate
* fix(rds): renew proxy TLS leaves before expiry
* fix(rds): sign proxy leaves with the shared Floci CA
Reuse the canonical CA and preserve legacy SAN metadata without loading or modifying the old RDS-only certificate and key. Keep leaf renewal and expiry rejection unchanged.
* fix(rds): preserve legacy CA certificate paths
Refresh rds-ca.crt from the shared Floci root and remove the unused RDS-only key. Replace the certificate path atomically so legacy links cannot overwrite shared key material, and leave failed initialization retryable.
* feat(rds): DescribeDBLogFiles and DownloadDBLogFilePortion
Both answered UnsupportedOperation, so an instance's log could only be
read with docker logs, outside the AWS API.
An instance's log is now read from its database container and cut into
files the way RDS names them: hourly error/postgresql.log.* files for
PostgreSQL, error/mysql-error.log for MySQL and MariaDB, and log/ERROR
for SQL Server. DescribeDBLogFiles filters and pages them, and
DownloadDBLogFilePortion follows the API reference's marker rules with
a 1 MB block cap. Control characters XML cannot carry come back as
U+FFFD. In mock RDS mode an instance has no log files.
Closes#5733
* fix(rds): bound and validate log file reads
A log read now takes the most recent 100,000 lines instead of the whole
history, fails when Docker does not finish in time instead of returning
part of the log, and, when Docker no longer knows the container, finds
or starts the backend once before answering DBInstanceNotReady rather
than an empty log. A single line over 1 MB is cut at 1 MB like the rest
of the block. Negative FileSize, FileLastWritten and Marker values are
InvalidParameterValue; the shared offset paging refuses a negative
marker instead of starting over.
* fix(rds): close the Docker log stream when a log read times out
A timed-out read now closes its callback before failing, so the stream
stops and nothing writes into the buffer after the read gives up; the
buffer is also written and read under one lock.
* refactor(rds): keep portion's Javadoc on portion
truncateUtf8 had landed between portion's comment and portion itself. It now follows portion.
* test(rds): read log files on the first call, and import class names
CreateDBInstance returns once the database accepts connections, so the startup log is already in the container's output. The Docker and SDK log tests now assert on the first DescribeDBLogFiles and DownloadDBLogFilePortion call instead of polling. The timeout test and RdsLogFilesTest import the classes they had written out in full.
* feat(rds): EnableHttpEndpoint, DisableHttpEndpoint and HttpEndpointEnabled
EnableHttpEndpoint and DisableHttpEndpoint answered UnsupportedOperation
and DBCluster carried no HttpEndpointEnabled, so Terraform's
enable_http_endpoint and CDK's enableDataApi never read back what they
set.
Clusters now record the flag and report it. The two actions take the
cluster's ARN and raise ResourceNotFoundFault and
InvalidResourceStateFault as the model lists them; CreateDBCluster,
ModifyDBCluster and the AWS::RDS::DBCluster EnableHttpEndpoint property
set it too. Turning it on is refused for engines other than Aurora
PostgreSQL and Aurora MySQL. The Data API itself does not check the
flag, so existing callers keep working.
Closes#5732
* refactor(rds): one cluster ARN parser, and stricter Data API inputs
clusterForResourceArn repeated the ARN parsing, cluster: prefix and
account and Region check of clusterIdentifierFromArnOrName; both now
call clusterIdFromArn, each raising the error its API documents.
The Data API engine check takes aurora-postgresql, aurora-mysql and the
older aurora name exactly instead of any name starting with aurora, and
the AWS::RDS::DBCluster EnableHttpEndpoint property accepts true or
false only, so a malformed value fails instead of turning the endpoint
off.
* fix(rds): take only aurora-mysql and aurora-postgresql for the Data API
The API reference lists those two engines, and new clusters cannot carry
the bare aurora name, so the check no longer accepts it.
* feat(rds): refuse role feature names the engine does not support
AddRoleToDBInstance, AddRoleToDBCluster and CreateDBCluster
AssociatedRoles stored any FeatureName, so Lambda on a MySQL instance
was accepted although MySQL supports no role features.
A FeatureName now has to be one the engine lists in
SupportedFeatureNames, matched without regard to case, or the call is
InvalidParameterValue; CreateDBCluster refuses before any cluster
exists. A cluster role with no feature, and an engine the catalogue
does not list, are left alone. Aurora PostgreSQL also lists Bedrock,
which the Aurora user guide offers next to Comprehend and SageMaker.
Closes#5631
* refactor(rds): keep the two-argument cluster role check
Callers that check an AssociatedRoles list without knowing the engine,
such as the CloudFormation provisioner in #5656, keep the signature they
compile against; it runs the same checks without the feature check.
* fix(rds): match feature names without regard to case in every role check
The supported-feature check matched without regard to case, but the
instance duplicate check and both removal lookups compared exactly, so
an instance could take s3Import and then s3import as two roles. All of
them now match the same way. The two-argument cluster role check, which
nothing here calls, is removed.
* fix(rds): inherit cluster IAM settings for new members
* fix(rds): keep new member authentication in step with cluster changes
* fix(rds): allow metadata reads during member creation
* fix(rds): keep member creation consistent with lifecycle changes
* fix(rds): preserve metadata access during instance reboot
* fix(rds): use one cluster state for member creation
* test(rds): check IAM authentication consistently
* feat(rds): IAM role associations for DB clusters and instances
AddRoleToDBCluster, RemoveRoleFromDBCluster, AddRoleToDBInstance and
RemoveRoleFromDBInstance answered UnsupportedOperation, and DBCluster
and DBInstance carried no AssociatedRoles, so Terraform's
aws_rds_cluster_role_association and aws_db_instance_role_association
could not apply.
Clusters and instances now keep their associated roles and report them
as AssociatedRoles, ACTIVE as soon as they are added. The four actions
raise the faults the API model lists, and CreateDBCluster accepts
AssociatedRoles, checked before the cluster is created. Feature names
are not yet validated against the engine.
Closes#5343
* fix(rds): route the instance role actions, and refuse only a repeated cluster role
AddRoleToDBInstance and RemoveRoleFromDBInstance were missing from
RDS_ACTIONS, so a request with no credential scope reached SQS.
DBClusterRoleAlreadyExists covers the role ARN only, so a cluster now
takes a second role for a feature that already has one. Instances keep
refusing a repeated role or feature, as their fault documents.
CreateDBCluster reads every AssociatedRoles index, gaps included, and
refuses an entry without a RoleArn. It associates the roles in one step
and deletes the new cluster if that is refused.
* refactor(rds): import the types parseAssociatedRoles uses
The regex and sorted-set types were written with their packages inline;
AGENTS.md asks for imports. The role association compat test gains a
DisplayName like the others in its class.
* docs(rds): count the role association actions alongside the catalogue reads
#5196 and this branch each added four RDS actions, so the service matrix
count is 98.
* feat(rds): engine versions, engine defaults and valid modifications
Serve DescribeDBEngineVersions, DescribeEngineDefaultParameters,
DescribeEngineDefaultClusterParameters and
DescribeValidDBInstanceModifications.
A curated engine catalogue lists one representative version per major
version Floci knows through its managed parameter and option groups.
Each version carries the parameter group family the create path computes
for it, its major version and its upgrade targets; each engine's default
is the version Floci creates when a request names none.
DescribeDBEngineVersions serves it with Engine, EngineVersion (exact or
major), DBParameterGroupFamily, DefaultOnly, the documented filters and
paging, and DescribeOrderableDBInstanceOptions now reads the same
catalogue.
The engine default calls check the family against the catalogue and
return an empty list, as Floci's default parameter groups hold no
parameters. DescribeValidDBInstanceModifications reports the instance's
storage type with a range from its current allocation to the engine's
maximum, and nothing for an Aurora instance.
Closes#5186
* feat(rds): one source for engine defaults, and engine version capabilities
Create paths, the cluster parameter group family check and global
clusters each kept their own default engine version, and Aurora MySQL's
disagreed with the catalogue: 8.0.36 against 8.0.mysql_aurora.3.05.2.
All four now read the catalogue's default, so a create that names no
version gets what DescribeDBEngineVersions reports with DefaultOnly.
DescribeDBEngineVersions and DescribeDBClusterEndpoints share one
offset paging helper and one MaxRecords check, which
DescribeEventSubscriptions also uses.
Each engine version now reports ExportableLogTypes,
SupportsLogExportsToCloudwatchLogs, SupportsReadReplica,
SupportedFeatureNames, SupportsParallelQuery, SupportsGlobalDatabases
and SupportsBabelfish, following what Floci supports.
* fix(rds): route the catalogue reads to RDS without a credential scope
DescribeDBEngineVersions, DescribeEngineDefaultParameters,
DescribeEngineDefaultClusterParameters and
DescribeValidDBInstanceModifications were missing from RDS_ACTIONS, so a
request with no credential scope reached SQS.
* fix(rds): load the token role's ALTER ROLE defaults into IAM sessions
* fix(rds): open IAM sessions with the role's defaults as startup options so RESET keeps them
* fix(rds): reject malformed restore flags
* fix(rds): disable IAM authentication by default on restore
* fix(rds): honor IAM settings on instance snapshot restore
* fix(rds): apply PostgreSQL startup parameters to IAM sessions as the token's role
* fix(rds): refuse a session_authorization change and match PostgreSQL's parsing for IAM startup parameters
* test(rds): share the IAM integration tests' setup and document RESET for IAM startup parameters
* fix(rds,elasticache): decode IAM auth token parameters once
SigV4RequestValidator, which verifies the IAM auth tokens the RDS, Redshift,
ElastiCache and MemoryDB proxies receive, URL-decoded every query parameter
as it looked it up, then decoded X-Amz-Credential and X-Amz-Security-Token a
second time. Session tokens are drawn from an alphabet that includes '+',
'/' and '='. A presigner writes '+' as %2B; the first decode restored it and
the second turned it into a space, so the session no longer matched and the
token was refused with "password authentication failed". Every token signed
with a Lambda function's execution-role credentials failed this way, from
the AWS CLI, botocore and the Go SDK's feature/rds/auth alike, while
AssumeRole credentials passed only because their tokens are alphanumeric.
The second decode also let a token carrying %252B stand in for a session
whose token holds a literal '+'.
SigV4 defines the canonical query string as each parameter name and value
URI-encoded (only A-Z a-z 0-9 - . _ ~ left as they are, uppercase hex, a
space as %20, '/' encoded), sorted by encoded name and then by value. The
validator now decodes each parameter exactly once, keeping a literal '+' as
a plus as the API Gateway and EKS verifiers already do, looks the session
up with that value, and rebuilds the canonical query string from the
decoded parameters rather than hashing the bytes on the wire, so the token
is checked against the string its signer hashed whichever valid
percent-encoding it travelled in. Using the raw pairs as before would have
fixed the session lookup alone, but would still reject a token whose
credential travels with literal slashes or lowercase hex.
The test token helper encoded values with URLEncoder, whose form encoding
writes a space as '+' and leaves '*' unescaped, which no SDK presigner does;
it now applies SigV4's UriEncode. S3 presigned URLs do not go through this
validator and read X-Amz-Security-Token once already: a URL presigned with
a Lambda session's credentials is served, and one whose token reads a space
for the '+' is refused.
* fix(rds): authorize the key the token's signature was verified with
The signature check reads a token's parameters with their names
percent-decoded, and takes the first X-Amz-Credential it finds. The
rds-db:connect check read the credential again from the raw query, matching
the name byte for byte. A token that spelled its signer's credential as
X-Amz%2DCredential and added a plain X-Amz-Credential of a key IAM does not
know was verified with the signer's key and authorized on the unknown one,
which IAM enforcement waves through: the connection was allowed whatever
the signer's policy said.
SigV4RequestValidator.queryParameter reads a parameter exactly as the
signature check does, and RdsSigV4Validator takes the credential scope from
there, so the key authorized is the key that signed.
validateAuthorizesTheKeyTheSignatureWasVerifiedWith signs such a token as
SigV4 signs a query and expects it refused; it was accepted before.
RdsIamAuthLambdaSessionIntegrationTest now creates its database inside the
try whose finally deletes it, so a create that fails an assertion leaves no
container behind.
* fix(rds): forward PostgreSQL startup parameters through the proxy
The RDS proxy parsed the client's StartupMessage but opened the backend
session with only user and database, so options, application_name and
every other run-time parameter were silently dropped.
Forward them in the order the client sent them. The proxy keeps setting
user and database itself, and drops _pq_. protocol extension requests,
which it does not negotiate with the backend.
An IAM login for a role other than the master still sends only user and
database: its backend session is the master's until the handover, and a
startup "-c role=<master>" would outlive SET SESSION AUTHORIZATION, so
RESET ROLE would regain the master. Redshift keeps today's behaviour, as
its drivers send parameters PostgreSQL rejects.
* fix(rds): relay PostgreSQL's refusal of the backend login to the client
Forwarding startup parameters makes new backend refusals possible, such as
replication=true with no pg_hba.conf entry allowing it. PostgreSQL answers
those with an ErrorResponse where the proxy expected an Authentication
message, and the proxy reported only "Backend database authentication
failed". Every read that expects an Authentication message now reads a
refusal whole and the proxy sends it to the client unchanged, so the client
sees PostgreSQL's SQLSTATE and reason. This covers a refusal before the
password exchange and one after it. Other unexpected replies keep the
generic error.
* test(rds): reuse the IAM auth harness and the handler's startup parser
Fold the IAM startup-parameter check into iamSessionRunsAsTheRoleNamedInTheToken, let backendStartupFor start its auth thread through startIamAuth, and make PostgresProtocolHandler.parseStartupParams package-private so the test no longer keeps its own copy.
Serve CreateDBClusterEndpoint, DescribeDBClusterEndpoints,
ModifyDBClusterEndpoint and DeleteDBClusterEndpoint.
A custom endpoint is stored per Region with the rules from the API
reference and the Aurora user guide: type READER or ANY, a static or an
exclusion member list but not both, members that are instances of the
cluster, no writer in a READER endpoint, an RDS identifier stored lower
case and unique in the Region, and at most five per cluster. Its ARN
(cluster-endpoint:<id>) works with the tagging actions.
DescribeDBClusterEndpoints lists each cluster's built-in WRITER and
READER endpoints with its custom ones, and supports the cluster and
endpoint identifiers, the four documented filters and paging. Deleting a
cluster deletes its custom endpoints, and a deleted instance drops out of
the member lists.
Custom endpoints are modelled, not routed: one reports the cluster's own
endpoint host, so connections through it go where the cluster endpoint
sends them.
Closes#5072
Serve RestoreDBInstanceToPointInTime and RestoreDBClusterToPointInTime,
and report the restorable window: LatestRestorableTime on
DescribeDBInstances, EarliestRestorableTime and LatestRestorableTime on
DescribeDBClusters.
Requests are checked as the API reference describes: exactly one of
RestoreTime (RestoreToTime) and UseLatestRestorableTime, a time inside
the window or InvalidRestoreFault, PointInTimeRestoreNotEnabled for an
instance with backups off, and exactly one source. An instance source is
named by identifier or DbiResourceId, a cluster source by identifier, ARN
or DbClusterResourceId; automated backups ARNs answer
DBInstanceAutomatedBackupNotFound since no automated backups are kept.
Floci keeps no transaction log, so the target is seeded from a
pg_dumpall of the source taken when the request arrives, as read
replicas are. The restored data is the source's latest state for any
time in the window, and LatestRestorableTime is the current time. Only
PostgreSQL sources are accepted, as for CreateDBSnapshot.
Closes#4952
* fix(rds): honor requested port when restoring a cluster snapshot
Reserve an explicit RestoreDBClusterFromSnapshot port for the cluster endpoint and proxy, validate its AWS range, and reject local port collisions. Keep automatic allocation when Port is omitted.
* fix(rds): keep requested ports within published proxy range
* fix(rds): reject occupied requested ports and preserve handler calls
* feat(rds): add and remove a subscription's source identifiers
SourceIds was write-once. CreateEventSubscription accepts the list and
ModifyEventSubscription has no SourceIds member, so
AddSourceIdentifierToSubscription and RemoveSourceIdentifierFromSubscription
are the only way to change it and neither existed.
Adding an id the subscription already carries is a no-op. The model declares
only SourceNotFoundFault and SubscriptionNotFoundFault for these operations,
so no fault fits a duplicate. Removing an id the subscription does not carry is
SourceNotFound, which is the fault that does fit.
* fix(rds): refuse a missing SubscriptionName as a parameter error
SubscriptionName and SourceIdentifier are both required by the model, and only
the identifier was checked. A missing name fell through to the subscription
lookup and came back as SubscriptionNotFound, telling the caller the
subscription does not exist when the request simply did not name one. The two
required members now fail the same way on both operations.
Also imports assertEquals in the new test rather than qualifying it inline.
* feat(rds): manage event notification subscriptions
CreateEventSubscription, DescribeEventSubscriptions, ModifyEventSubscription
and DeleteEventSubscription were all missing, so the subscription resource
could not be created.
Constraints come from the model. A SubscriptionName under 255 characters, a
required SnsTopicArn, SourceType limited to the documented valid values, and a
SourceIds list that may only be supplied alongside the SourceType its ids
belong to. An omitted Enabled activates the subscription, which the model
describes only in the negative: a subscription that is not activated is
created but not active. Modify applies only the members the request names.
Nothing is published to the topic. A subscription is stored and reported back
and no RDS event reaches SNS through it. The docs say so.
* fix(rds): synchronize the event subscription methods and cite the SourceIds constraint
createEventSubscription checked for a duplicate name and then stored, so two
concurrent creates of the same name both passed the check and the second
overwrote the first with neither caller seeing SubscriptionAlreadyExist. The
four methods are synchronized now, matching the 48 other public synchronized
methods in this file and the find-then-throw-then-store shape of
createDbSnapshot.
The comment on the SourceIds coupling said only that the model states it,
which sent a reviewer to the operation documentation where it is absent. It
now quotes the constraint and says it lives on
CreateEventSubscriptionMessage.SourceIds rather than on the operation.
* fix(rds): keep a rejected modify inert, carry subscription tags, and page the describe
Four findings from the automated review, all confirmed against the model.
ModifyEventSubscription wrote SnsTopicArn before validating SourceType, so a
request carrying a new topic and an unmodelled source type answered 400 with
the topic already changed. The store returns the live instance, so a later
describe reported it. This is the same shape as the Lambda code signing bug in
#4286 and I did not carry the lesson across.
CreateEventSubscriptionMessage has a Tags member that was dropped on the
floor, and resolveTagHandle had no arm for an es: ARN, so a subscription could
neither be created with tags nor tagged afterwards.
DescribeEventSubscriptionsMessage has MaxRecords and Marker, and its output
shape has Marker. None were read or emitted, so a bounded page returned
everything with no way to continue.
The new test used var, which AGENTS.md prohibits, the same thing flagged on
#4286.
* fix(rds): bound MaxRecords and resume paging past a deleted marker
Two defects I introduced in the pagination added last round.
MaxRecords was unbounded. Zero built an empty page and then read its last
element, throwing IndexOutOfBoundsException, and a negative value produced
invalid bounds. The model documents minimum 20, maximum 100, default 100, and
handleDescribeEvents a few hundred lines up already enforces that range. An
omitted value now defaults to 100 rather than returning everything.
The marker resumed by looking for its own name, so a subscription deleted
between calls left the offset at zero and handed back the first page again.
Resuming at the first name strictly greater than the marker is stable under
deletion.
The test used MaxRecords 1, a value the model rejects, so it exercised a page
size real RDS never serves. It now creates 21 subscriptions and pages with 20.
* fix(rds): validate MaxRecords before the named-subscription shortcut
The range check sat after the early return for a named subscription, so a
request naming one alongside an out-of-range MaxRecords succeeded. Request
validation should not depend on which branch serves the read.
An Aurora cluster whose ServerlessV2ScalingConfiguration has MinCapacity 0
now freezes its database container with docker pause once nothing has used
it for SecondsUntilAutoPause, and resumes it for the next client, as Aurora
Serverless v2 does.
Every client of a backend container holds a lease while it uses it: each
connection through the auth proxy (cluster, reader, instance and RDS Proxy
endpoints), each RDS Data API call and open transaction, and each command
Floci runs inside the container. A client that reaches a paused cluster is
held, not refused, until the container runs again, after
FLOCI_SERVICES_RDS_AURORA_RESUME_DELAY_MILLIS (default 0; Aurora takes
about 15000). A connection that arrives while the pause is under way
cancels it.
While paused, the cluster and its instances stay available,
DescribeEvents reports RDS-EVENT-0370 to 0374 for each instance, and
ServerlessDatabaseCapacity, ACUUtilization and CPUUtilization report 0
once a minute. A cluster with a provisioned instance, in a global database
or behind an RDS Proxy never pauses. A ModifyDBCluster that changes
MinCapacity or SecondsUntilAutoPause resumes a paused cluster. Stopping,
deleting or rebooting a cluster, shutting Floci down and resetting its
state thaw a paused container first.
FLOCI_SERVICES_RDS_AURORA_AUTO_PAUSE_ENABLED=false keeps every cluster
running.
Closes#4219
* fix(rds): apply DBInstanceClass, AllocatedStorage and EngineVersion on ModifyDBInstance
ModifyDBInstance parsed the password, IAM auth, subnet group, option group,
security groups and the backup and monitoring settings, but never read
DBInstanceClass, AllocatedStorage or EngineVersion. A resize or an engine
upgrade returned 200 while DescribeDBInstances kept reporting the values the
instance was created with, so a caller that diffs its configuration against a
read-back saw the same pending change on every run.
The three members move into a DbInstanceScalingChanges record that the handler
fills from the request and the service applies, with the rules the AWS API
reference states for them:
- AllocatedStorage below the current size fails with InvalidParameterCombination
- an increase under 10% is rounded up to 10% greater on PostgreSQL, MySQL and
MariaDB, and taken as given on SQL Server
- the same size is not a change and is left alone
- a different major EngineVersion needs AllowMajorVersionUpgrade
Floci applies the change immediately rather than deferring it to the preferred
maintenance window: it runs no maintenance window and models no
PendingModifiedValues, so a deferred change would never be applied at all.
* fix(rds): reject a ModifyDBInstance scaling change before applying any member
The scaling members were validated as they were assigned: the class was set,
then the storage was resolved, which can refuse a shrink, then the engine
version was checked, which can refuse a major upgrade. The instance a modify
works on is the stored object rather than a copy, so a request refused at the
second or third step had already written the earlier ones, and a read-back
reported a class the 400 said it never got.
The checks now run in resolveFor, ahead of every setter in modifyDbInstance,
including the password rotation that reaches the running container. applyTo is
left as pure assignment of an already-resolved record.
* fix(rds): bind PostgreSQL IAM tokens to the published endpoint
The PostgreSQL proxy validated IAM auth tokens with the two-argument
validator, so a token generated for any host, port or region was
accepted as long as the signature and DBUser matched. The MySQL proxy
already checked the token against the endpoint it publishes. Thread the
same binding into the PostgreSQL handler and validate against it.
* fix(rds): carry account and resource ids in the proxy binding
RdsService now builds the proxy binding itself at every relay start
(instances, clusters, RDS Proxy relays and restart restores) from the
published endpoint, port, region, account and DbiResourceId or
DbClusterResourceId, so the auth proxy has everything rds-db:connect
is scoped to. The convenience startProxy overload that re-derived the
region from the relay key is gone along with it.
* feat(rds): authorize rds-db:connect when IAM enforcement is on
After the token signature checks out, the auth proxy now asks IAM whether
the token's principal may perform rds-db:connect on
arn:aws:rds-db:<region>:<account>:dbuser:<resource-id>/<db-user>, the
same check AWS runs. It only applies when services.iam.enforcement-enabled
is on; a caller IAM does not know keeps the filter's bypass. The client
still sees the engine's generic authentication failure, and the denial is
logged in AWS's wording so the cause is visible server-side.
* refactor(rds): rename RdsMysqlBinding to RdsProxyBinding
Both engines, Aurora clusters and RDS Proxy relays now validate IAM
tokens against it, so the MySQL-specific name was misleading.
* docs(rds): describe IAM token endpoint binding and rds-db:connect
* test(rds): cover a replayed IAM token in the JDBC compat suite
* fix(rds): accept IAM tokens generated for the loopback name of the endpoint
Floci advertises the name containers reach it by (host.docker.internal
natively, its own address in Docker), while a client on the host connects
to the same proxy over the loopback interface and generates its token for
localhost or 127.0.0.1. Binding tokens strictly to the advertised host
therefore refused every native client; the published port still has to
match, so a token for another instance on the same host is still refused.
The compatibility workflow sets FLOCI_SERVICES_RDS_ENDPOINT_HOST=floci as
it already does for Redshift, so the tests' tokens name what the
containerised Floci publishes.
* feat(rds): make the PostgreSQL IAM token endpoint binding opt-in
Refusing a PostgreSQL token generated for another hostname, port or
region matches RDS but breaks clients whose tokens name a different
host than the endpoint publishes, so the check now sits behind
services.rds.iam-token-endpoint-binding
(FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING), off by default.
MySQL and MariaDB keep requiring the endpoint as before, and the
rds-db:connect check still runs whenever IAM enforcement is on.
The compatibility workflow turns the flag on so the replayed-token
case stays covered.
* fix(rds): refuse an IAM token that reaches the validator without a binding
Every proxy publishes a binding, so a token without one has nothing to
be checked against; validating its signature alone was a fail-open
path. The signature-only validate(token, user) overload and the MySQL
handleAuth overloads that passed no binding are removed; production
only ever used the ones that pass it.
* fix(rds): sanitize the rds-db resource named in the refused connection warning
The database user is part of that resource and comes straight from the
client's startup message, so it is stripped of control characters like
the other client-controlled values in the warning.
* docs(rds): call a refused IAM token the engine's ordinary authentication failure
The exact message differs per engine, and RDS PostgreSQL words it
differently from Floci's handler today, so the docs no longer promise
one wording.
* docs(rds): move the IAM token binding row into the RDS variables table
The row had landed above the page heading, where it rendered as a
stray one-row table; it now follows FLOCI_SERVICES_RDS_ENDPOINT_HOST
as it does on the RDS page.
* fix(rds): bind PostgreSQL IAM tokens to the endpoint by default
A stock Floci still accepted a PostgreSQL token generated for another
endpoint, the replay this change set out to close, and PostgreSQL and
MySQL disagreed about it in a way RDS never has. The endpoint check is
now on for every engine. services.rds.iam-token-endpoint-binding
(FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING=false) stays as the
escape hatch for clients that generate tokens for a container name or
DNS alias the endpoint does not publish. The compatibility workflow no
longer needs to turn the check on.
* chore(ci): rerun after a Docker Hub rate limit failed shard 1
* feat(rds): DB cluster snapshots
Add CreateDBClusterSnapshot, DeleteDBClusterSnapshot, CopyDBClusterSnapshot,
RestoreDBClusterFromSnapshot, DescribeDBClusterSnapshotAttributes and
ModifyDBClusterSnapshotAttribute, and make DescribeDBClusterSnapshots list
real snapshots with its three filters instead of an empty list.
A cluster snapshot records the cluster's description and a dump of its
database; a restore creates a new cluster from the snapshot's settings
and loads the dump into it. Copies carry the data, CopyTags and Tags and
record SourceDBClusterSnapshotArn; the restore attribute is shared the way
instance snapshots share it.
Closes#4042
* feat(rds): restore a cluster from a snapshot named by ARN, simplify the cluster snapshot handlers
RestoreDBClusterFromSnapshot resolves SnapshotIdentifier by name or ARN
through the helper CopyDBClusterSnapshot already uses, as the API
reference allows and aws_rds_cluster commonly sends. The six handlers
use the shared firstMissingParam helper and the central AwsException
handling; the new service lines import InMemoryStorage and Predicate
instead of qualifying them inline, and the tests import
DbClusterSnapshot.
* feat(rds): stop, start and reboot DB instances and clusters
Add StopDBInstance, StartDBInstance, StopDBCluster, StartDBCluster and
RebootDBCluster. A stop reports "stopping", takes the optional snapshot,
removes the container and proxy and settles the record to "stopped"
while its identifier, endpoint, groups and Docker volume stay; a start
reports "starting" and brings the container back on the kept volume and
port. Cluster stop, start and reboot carry the member instances along.
StopDBInstance refuses cluster members, read replicas and their sources,
and anything not available; ModifyDBInstance refuses a stopped instance;
a stopped resource stays stopped across an emulator restart.
Closes#4043
* feat(rds): refuse starting a stopped cluster's member alone, serialize cluster lifecycle calls
StartDBInstance now refuses a cluster member as StopDBInstance does, and
both answer InvalidDBClusterStateFault, the fault the model lists for a
member on either call; a member started alone would have got a
standalone container on its own volume while the cluster stayed stopped.
stopDbCluster, startDbCluster and rebootDbCluster are synchronized like
the instance calls, so two concurrent starts cannot both see STOPPED.
The five handler arms use the shared required-parameter helper and the
central AwsException handling.
* test(rds): import DbInstanceStatus instead of qualifying it inline
AGENTS.md asks for imports over inline fully-qualified names; the file
already imports DbInstanceStatus.
CreateGlobalCluster creates an Aurora global database, empty or with an
existing Aurora cluster as its primary, in which case engine, version,
database name and encryption come from that cluster and may not be
given. CreateDBCluster with GlobalClusterIdentifier joins a cluster: the
first becomes the primary, every later one a secondary in a region that
holds no member yet, with the primary's credentials and database name and
a point-in-time copy of its data through the pg_dumpall mechanism that
snapshots and read replicas use. DescribeGlobalClusters answers the real
records for RDS, with IsWriter and Readers per member; DocumentDB and
Neptune keep the shared empty answer.
SwitchoverGlobalCluster and FailoverGlobalCluster promote the named
secondary and demote the current primary to a secondary, the topology
AWS keeps on switchover and restores after a managed failover.
RemoveFromGlobalCluster detaches a member into a standalone cluster and
the primary goes last; DeleteGlobalCluster needs an empty, unprotected
global cluster; ModifyGlobalCluster renames, protects or upgrades, with
members following.
DBCluster now carries the writer role: the first instance is the writer,
IsClusterWriter reports it instead of true for every member, deleting the
writer promotes a remaining member, and FailoverDBCluster moves the role
to the named reader or the first one; a cluster without a reader is
refused with InvalidDBClusterStateFault.
Closes#3778
CreateDBInstanceReadReplica creates a standalone instance with its own
container and endpoint that inherits the source's engine, version,
credentials, database name and, unless overridden, class, storage and
minor version upgrades; a same-region replica also inherits the parameter,
option, subnet and security groups, a cross-region one (source named by
ARN) gets the region's defaults, as the API reference states. The replica
starts with automated backups off, and both ends report the link the way
DescribeDBInstances does: ReadReplicaSourceDBInstanceIdentifier plus a
"read replication" StatusInfos entry on the replica,
ReadReplicaDBInstanceIdentifiers on the source, identifier within a region
and ARN across regions. A subnet group with a plain identifier source is
refused with DBSubnetGroupNotAllowedFault.
The replica's database is initialised from a pg_dumpall of the source taken
at creation, the mechanism RestoreDBInstanceFromDBSnapshot already uses, so
only PostgreSQL sources are accepted (CreateDBSnapshot draws the same
line). Writes after creation are not streamed; the docs say so.
PromoteReadReplica clears the link on both ends, turns backups on with the
requested retention (one day when omitted) and window, and reboots the
instance as RDS does. Deleting a source promotes its same-region replicas
and leaves a cross-region replica with replication terminated, as the user
guide documents for PostgreSQL; deleting a replica drops it from the
source.
SwitchoverReadReplica is refused with InvalidDBInstanceState, the only
state error the API reference lists, since AWS supports it for Oracle and
SQL Server only. PromoteReadReplicaDBCluster answers
InvalidDBClusterStateFault because no cluster here is created as a replica.
Refs #3778
Add CopyDBParameterGroup, CopyDBClusterParameterGroup, CopyOptionGroup,
ResetDBParameterGroup and ResetDBClusterParameterGroup. The groups, their
overrides and options were already modelled and served by the create,
modify, describe and delete actions; these five answered
UnsupportedOperation.
A copy resolves its source by name or ARN, creates the target through the
existing create path so the already-exists check and the ARN come from one
place, and copies the family and overrides, or the engine, major version
and options for an option group, with any Tags applied. Source and target
names must pass AWS's identifier rule, which is how AWS refuses to copy a
managed default group: its name carries periods, and the answer is
InvalidParameterValue with the identifier message. A reset drops the named overrides or all of
them; ResetAllParameters together with a Parameters list is
InvalidParameterCombination, and a managed default cluster group answers
InvalidDBParameterGroupState as Modify does. Responses use the model's
result wrappers and shapes. The action table in docs/services/rds.md is
regenerated and its note that CopyOptionGroup is unimplemented removed.
Closes#3777
CreateDBProxy/AWS::RDS::DBProxy rejected EndpointNetworkType/TargetConnectionNetworkType
outright for anything other than IPV4 ("Floci currently exposes IPv4 proxy networking only").
Both fields are now accepted and stored on the DbProxy record:
- EndpointNetworkType: IPV4, IPV6, or DUAL
- TargetConnectionNetworkType: IPV4 or IPV6 (no DUAL, matching AWS's own constraint)
They round-trip through DescribeDBProxies and CloudFormation the same way the proxy's other
control-plane settings (pool sizing, TLS, idle timeout) already did.
AWS's RDS Proxy network prerequisites require both the VPC and every selected subnet to carry
an associated IPv6 CIDR block for IPV6/DUAL. floci already modeled VPC-level IPv6 CIDR
associations; subnet-level association is now modeled too (Subnet.ipv6CidrBlockAssociationSet,
CreateSubnet's Ipv6CidrBlock parameter, and the DescribeSubnets/CreateSubnet response), and
createDbProxy validates both the VPC and every VpcSubnetIds entry before accepting a non-IPV4
network type, rejecting with InvalidParameterValue otherwise. Genuinely invalid enum values are
still rejected at both the RDS Query API and CloudFormation provisioner layers.
The CloudFormation update path now also refuses a changed EndpointNetworkType or
TargetConnectionNetworkType the same way it already refused a changed DBProxyName, EngineFamily,
or VpcSubnetIds: both are createOnlyProperties in the AWS::RDS::DBProxy registry schema, and
ModifyDBProxy has no such parameters, so silently accepting a changed value on UpdateStack would
report UPDATE_COMPLETE while the proxy's actual network type stayed put.
Added a Terraform compatibility scenario (rds-proxy-network-type-tf) with a genuinely
dual-stack VPC and subnets, plus negative cases for an IPv4-only VPC and for a dual-stack VPC
whose subnets lack an IPv6 CIDR block.
TagResource/UntagResource/ListTagsForResource rejected a snapshot ARN
outright ("not yet implemented by Floci"), and CreateDBSnapshot
silently dropped its Tags parameter even though DbSnapshot already had
a tags field. Both are now wired up: CreateDBSnapshot stores Tags, the
generic tag-resource dispatch resolves a "snapshot" ARN type against
the snapshot store, and DescribeDBSnapshots echoes DBSnapshotArn and
TagList like the other tagged resource types already do.
Snapshots are now region-scoped the same way DB instances and clusters
already are: CreateDBSnapshot/DescribeDBSnapshots/DescribeDBSnapshot-
Attributes/ModifyDBSnapshotAttribute/RestoreDBInstanceFromDBSnapshot
all thread the request's signed region through to snapshot storage and
lookup (via the same dbResourceKey/hasRdsResourceIdentity scoping the
instance/cluster stores use), so DBSnapshotArn reflects the request's
actual region and a snapshot created in one region is not visible to
Describe/Tag calls signed for another.
Verifying this live against a real floci instance via Terraform
surfaced two more gaps blocking any use of aws_db_snapshot at all,
regardless of tagging: DescribeDBSnapshotAttributes (called on every
read of the resource) and ModifyDBSnapshotAttribute were both
completely unimplemented. Added minimal support for both (the
"restore" attribute, i.e. cross-account copy/restore authorization,
modeled as plain in-memory state, no real cross-account sharing).
DeleteDBSnapshot is also unimplemented and was not added here — a
snapshot can be created and tagged but not destroyed via Terraform.
Noted in docs/services/rds.md as a follow-up, along with the other
resource types the original gap report mentioned (Aurora cluster
snapshots, reserved instances) that aren't modeled in Floci at all, so
tagging doesn't apply to them either.
Added a Terraform compatibility scenario (aws_db_snapshot with tags,
verifying create, tag read-back, a clean second plan, and an in-place
tag update) and ran it against a live floci instance before
committing, including a re-run after the region-scoping fix.
Cap concurrent proxy connections with a per-proxy semaphore, apply
configurable handshake and backend-connect timeouts to both the
client and backend sockets, and defer backend PostgreSQL connects
until after client auth completes. Close leaked backend sockets
defensively on every exit path, including a RuntimeException thrown
between authenticate() returning a session and the bridge finishing
its own cleanup, and bound backend-side reads during the handshake
so a silent backend that accepts TCP but never answers cannot pin a
handler thread and its connection permit forever.
New EmulatorConfig keys under services.rds and services.redshift:
proxy-handshake-timeout-millis (default 10000),
proxy-backend-connect-timeout-millis (default 5000),
proxy-max-connections (default 100).
CreateDBCluster with Engine aurora-mysql and an Aurora version such as
8.0.mysql_aurora.3.08.0 used the version literally as the container
image tag. Docker has no such tag, leading the pull to 404.
Take the MySQL version in front of the Aurora suffix, so that example
runs mysql:8.0. Plain mysql versions still map to their own tag.
The Go compatibility tests for the RDS Data API on aurora-mysql skip
when the cluster cannot be created, so this failure never showed in
CI. They now run with the mapping fixed.
* feat(rds): implement CreateDBSnapshot and RestoreDBInstanceFromDBSnapshot for postgres (#1817)
* feat(rds): implement CreateDBSnapshot and RestoreDBInstanceFromDBSnapshot for postgres (#1817)
* feat(rds): generated docs
* fix(rds): preserve master password across DbSnapshot restore
* fix(rds): preserve thread interrupt flag in restorePostgresSnapshot
* fix(rds): handle duplicate RDS snapshots and mock mode operations
* fix(rds): separate stdout and stderr in container exec to prevent snapshot corruption
* fix(rds): add missing stderr argument to ContainerExecResult on timeout
* fix(rds): cleanup RDS instance on snapshot restore failure
* fix(rds): return structured AWS error when RDS snapshot restore fails
* fix(rds): address PR #1894 snapshot and restore review comments
- Wire handleDescribeDbSnapshots to use the new snapshots storage backend
- Change engine validation error from UnsupportedOperation to InvalidDBInstanceState
- Change restore failure error from InvalidDBSnapshotStateFault to InvalidDBSnapshotState
- Add corresponding unit and query handler tests
* fix(rds): address PR #1894 review feedback and restore process issues
- Wire DescribeDBSnapshots to the snapshots storage backend with filtering support
- Align CreateDBSnapshot engine error code to InvalidDBInstanceState
- Align restore snapshot failure error code to InvalidDBSnapshotState
- Carry over dbName from DbSnapshot to the restored DBInstance
- Connect to template1 during psql restore to prevent active postgres connection drop failures
- Remove unused AwsNamespaces import in RdsService
- Add corresponding unit and query handler tests
* fix(rds): address PR #1894 review feedback and snapshot error handling
* fix(rds): add --if-exists to pg_dumpall snapshot command
- Appends the --if-exists flag to pg_dumpall commands during database snapshot creation. This ensures DROP DATABASE statements are emitted conditionally, preventing restore failures on fresh container instances where user databases do not yet exist.
* fix(rds): added real docker test
* docs(rds): add descriptions for snapshot actions
Added concise, handwritten descriptions for the `CreateDBSnapshot` and
`RestoreDBInstanceFromDBSnapshot` actions in the RDS documentation
action table to comply with the contributing guidelines.
* feat(rds): improve RDS snapshot restore reliability and API coverage
- Update `postgresRestoreScript` to explicitly filter out the master user `CREATE ROLE` statement, preventing restore failures when `ON_ERROR_STOP=1` is enabled.
- Add strict validation for `masterUsername` in `CreateDBInstance` to adhere to AWS requirements (only alphanumeric chars starting with a letter, max 16 chars).
- Ensure `dbInstanceClass` is accurately preserved in the `DbSnapshot` model so it can be restored to the same hardware class automatically.
- Fix missing Windows absolute path detection in `ContainerStorageHelper`, resolving test-environment `NoSuchElement` errors on Windows.
- Make `RdsAwsIntegrationTest` gracefully skip on agents without a Docker daemon, matching test suite expectations.
- Update `rds.md` to include concise handwritten descriptions for all remaining placeholder actions.
- Improve exception logging inside container execution wrappers.
* fix(rds): keep the control plane working with no Docker daemon
CreateDBInstance and CreateDBCluster write the record and reach
available when no Docker daemon is reachable, instead of failing with
a raw socket error. The backing container is retried by reboot and the
RDS Data API, so it starts once a daemon appears. Delete no longer
touches Docker for a record that never had a container, and restore
keeps such records available on their recorded proxy ports.
Ported from lex00/floci#38, the RDS half left out of #2975.
* fix(rds): keep created-container identities and roll back a failed proxy start on retry
The retry updated the record before the auth proxy was up, so a proxy
failure left it pointing at a container nothing listened on and later
retries returned early. The proxy now starts from the handle first and
the record is written only after both halves are up. A proxy failure
stops the container.
tryStart no longer drops a retained cleanup identity that names a
created container. The next retry cleans it up before starting once the
daemon is back. Only an identity carrying the fixed container name,
from a start that failed before Docker created anything, is dropped
while the daemon is unreachable.
* fix(rds): retry a container cleanup that failed before the runtime starts again
A stop that failed after the auth proxy did not start left the live
handle and the runtime claim retained, and nothing retried that
cleanup, so the next start for the runtime failed on the claim. The
container manager now remembers a runtime whose cleanup failed, from a
failed start or a failed stop alike, and cleans it up before that
runtime starts again. A live handle with no pending cleanup is left
alone, so a concurrent duplicate start is still rejected.
* fix(rds): run IAM PostgreSQL sessions as the role named in the token
The proxy validated the token and then connected as master. It now hands
the session over with SET SESSION AUTHORIZATION, so the role's own
privileges apply and an unknown role is refused.
Closes#3087
Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
* fix(rds): keep IAM PostgreSQL sessions from switching back to master
The backend connection is master underneath, so RESET SESSION AUTHORIZATION
regained superuser. The proxy now watches PostgreSQL's own
session_authorization report and terminates the session when it changes.
Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
---------
Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
* fix(rds): store and return the encryption and backup settings given on create
DescribeDBInstances never returned StorageEncrypted, KmsKeyId,
BackupRetentionPeriod or CopyTagsToSnapshot, and wrote both windows as
constants. Store the six values from CreateDBInstance, apply the backup
settings and windows from ModifyDBInstance, and emit them from the
instance XML. A record persisted without them reads as AWS defaults.
KmsKeyId is resolved against the KMS store in the request's region — a
key ARN, key id, alias ARN or alias name — and stored as the key ARN, as
a live account reports it; a key that does not exist or is not enabled
is KMSKeyNotAccessibleFault.
Validation follows a live account: KmsKeyId needs StorageEncrypted,
window times are checked with AWS's wording, windows are at least 30
minutes and may not overlap; the retention period is not range-checked
since AWS accepted 40 days.
Closes#2611
* fix(rds): check window overlap against the windows that will be in effect
A window given alone was not checked at all: the request's other window
was null, so validate() skipped the overlap check although the instance
kept its stored counterpart on modify and got a default on create. Check
the pair that results from the request — on modify the stored other
window, on create the default, swapped for an alternate default when the
given window overlaps it, since AWS picks a random window clear of the
given one. Verified on a live account: a modify overlapping the stored
window is refused either way, replacing both at once checks only the new
pair.
* fix(rds): detect window overlap across the week boundary in both directions
A Sunday backup window running past midnight lies beyond the end of the
week, so comparing it with a Monday maintenance window needs the
maintenance interval shifted forward as well as back.
* fix(rds): derive the default counterpart window from the given one's end
A fixed alternate default cannot be clear of every window a request can
give — a 00:00-07:00 backup window covers it. When the window given on
create overlaps the usual default, pair it with a 30-minute window that
starts the minute the given one ends, which is clear of a daily window by
construction; the overlap check stays as the backstop.
* fix(rds): refuse a window given alone that leaves no room for the other, in AWS's words
The derived counterpart is clear of any window that leaves a 30-minute
gap (swept over every start and length in DbInstanceSettingsTest); a
window longer than that has no clear counterpart, and a live account
refuses it: "The specified backup window overlaps all available default
maintenance windows. Shrink the backup window or specify a non-overlapping
maintenance window." (mirrored for maintenance), and a maintenance
window of 24 hours or more is "Maintenance window must be less than 24
hours."
* refactor(rds): share the window checks with BackupWindows
* fix(rds,docdb): list DocumentDB clusters and instances in the RDS-family list form
The list form of DescribeDBClusters and DescribeDBInstances answered from
one store: on the rds scope from RDS, on the docdb scope from DocumentDB,
so a DocumentDB cluster was invisible to every list while its identifier
form worked. A live account lists the whole family from either endpoint.
RdsQueryHandler now assembles the list from both stores, honouring the
db-cluster-id / db-instance-id filters in each and an engine filter across
them (case-insensitive, OR over values, refused for a name outside the
family's engine list as on AWS), and the controller sends the docdb-scope
list form there too. The identifier form keeps routing to the store that
owns the identifier. Both halves list the region the request is signed
for.
Closes#2613
* fix(rds): report and filter an Aurora member instance by its Aurora engine name
DbInstance collapsed aurora-postgresql and aurora-mysql onto the community
engine enum, so a cluster member reported Engine postgres and the engine
filter matched it as postgres, where a live account says and matches
aurora-postgresql. Keep the engine name the request gave (or the
cluster's, for a member created without one) on the instance, and read it
for both the Engine element and the filter; a record persisted before the
field existed falls back to the enum.
* fix(rds): give a persisted instance its engine name on restore
An instance written before engineIdentifier existed deserializes with it
null, and a runtime fallback to the enum would keep reporting an Aurora
member as postgres. Backfill it in restorePersistedRuntime from the state
that knows: the member's cluster for a member, the enum for a standalone
instance.
* fix(rds): never persist a guessed engine name for a member of a nameless cluster
A cluster persisted before its own engineIdentifier existed (#1829) has
none to hand down, and writing the member's enum in that case would store
postgres for what may be an Aurora member — a guess that outlives the
code able to tell. The backfill writes only what is certain: the
cluster's stored name for a member, the enum for a standalone instance;
a member of a nameless cluster is left unset.
* fix(rds,neptune): list Neptune clusters and instances in the RDS-family list form too
A live account lists a Neptune cluster from the rds, docdb and neptune
endpoints alike and selects it with engine=neptune. The list form now
merges Neptune rows the way it merges DocumentDB ones, and the neptune
scope's list form goes to the same assembly. The Neptune store is not
keyed by region, so its rows are scoped to the request's region by ARN.
* fix(rds): close the subnet-group tags test in rds.bats
---------
Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>