Files
floci/compatibility-tests/sdk-test-python/conftest.py
T
Priamo Germosen 233253334d fix(elbv2): reject a listener certificate the account does not have (#5474)
A listener stored whatever certificate ARN it was given. CreateListener,
ModifyListener and AddListenerCertificates each model CertificateNotFound,
and all three took an ARN naming nothing and answered 200, so a listener
could be left serving a certificate that was never uploaded. Only the other
direction worked: ELBv2 reports its references to IAM, so
DeleteServerCertificate already refused with DeleteConflict while a listener
held one.

The error is the one AWS publishes on those three operations and no others:
botocore gives CertificateNotFoundException the code CertificateNotFound,
400, senderFault, and the API reference lists it under
AddListenerCertificates, CreateListener and ModifyListener with one
sentence, "The specified certificate does not exist." That sentence is the
message rather than one naming the ARN, because it is the one the reference
publishes.

The check covers the listener types the member belongs to and no more. The
reference marks Certificates "[HTTPS and TLS listeners]" on CreateListener
and ModifyListener, and describes AddListenerCertificates as adding to the
list "for the specified HTTPS or TLS listener", so a certificate on a
listener of any other protocol is a configuration it does not describe. What
AWS answers there is not CertificateNotFound on any evidence to hand, so
such a request keeps the behaviour it had rather than being refused with a
code read off the wrong case. A test pins each side of that line. The line
follows the protocol the listener ends the call with, not the one it started
with: ModifyListener takes a protocol without taking certificates, so when
none arrive the certificates checked are the ones already on file. An HTTP
listener holding an ARN that resolves to nothing is left alone, and the
request that turns it into an HTTPS one, which is where those certificates
start being served, is refused.

A blank entry is refused the same way, rather than skipped. Certificates is
the list of certificates the listener serves, an empty value in it names one
no better than a value that is no ARN at all, and the Query parser turns an
empty CertificateArn parameter into exactly that entry, so skipping it
stored a certificate the listener cannot serve.

ELB Classic already answered this question in full, resolving an ARN to an
IAM server certificate or an ACM one and holding IAM's certificate lock
across the write. This is the second caller, so the three private methods it
kept, certificateExists, iamServerCertificate and acmCertificateExists, move
to CertificateReferenceResolver in core.common and Classic reads them from
there. Neither referrer owns the lookup: IAM holds server certificates, ACM
holds the rest, and a listener carries only the ARN. Classic's public
constructors are untouched, so its unit tests still build it the same way.

The check alone is not enough, which is why the lock moves with it. A
certificate can be deleted between the check and the write, and the delete
walks the reference providers under IAM's own lock, so every write that
records an IAM certificate runs inside that lock and re-checks there, while
the fail-fast check outside it keeps the error precedence. That covers
CreateListener as much as the two writes to a listener already published:
until the new listener is in the map, nothing the delete walks can see that
it holds the certificate. A race test drives each of them against
DeleteServerCertificate over the wire, and with the lock removed they leave
a listener holding a deleted certificate in 1 of 30 trials for
AddListenerCertificates and 4 of 30 for CreateListener, so the guarantee is
measured rather than asserted.

Where the check sits in ModifyListener is part of the fix. The listener it
modifies is the stored object, and the port, protocol and SSL policy were
set before anything could refuse the request, so a refusal answered 400 over
a listener already moved to the new port: no later read put it back, and the
data plane was never restarted to match. Every refusal now lands before the
first setter.

An absent resolver leaves the old behaviour in place. ElbV2Service is wired
by hand in its unit tests, with no IAM and no ACM, and a listener write
there is the write it was before any certificate existed to check. The
dependency is a field rather than a constructor parameter because that is
how this class takes all six of its others, and converting it would be a
refactor this change does not need.

docs/services/elb.md said listener certificate ARNs are not validated when
they are added, which was true and is the behaviour this removes, so it now
documents the three operations, the protocols they cover, the empty value,
the protocol change, the error and the lock, as the Classic page already
does.

Sixteen integration tests cover a missing IAM certificate, a missing ACM
one, a blank entry, a value that is no ARN at all and an ARN of a service
that serves no certificates, an uploaded certificate and an ACM certificate
being accepted, a listener carrying no certificate, a TLS listener held to
the same check as an HTTPS one and a listener of a protocol with no
certificates left alone, a protocol change refused over the certificate it
already held and allowed over one that exists, a second certificate being
added, a refused change leaving the port and protocol as they were, and the
two writes that must refuse without changing what the listener already
serves. Every certificate and load balancer they make is registered for
cleanup: the account's certificate quota is 20 and the Quarkus instance is
shared, so one left behind fails an unrelated class's upload instead of
anything here.

Three things the reference states about these operations stay open, each
wanting an error code no source here gives: CreateListener and
ModifyListener take "exactly one certificate" and AddListenerCertificates
"one certificate per call", where Floci accepts a list; TooManyCertificates
is modeled on all three and no quota is enforced; and
DescribeListenerCertificates is documented to report the default certificate
alongside the list, with IsDefault telling them apart, which Floci does not
model.

Driven through the standard hashicorp/aws provider against a local instance
as well, which is how the change was checked against a real client rather
than only against the suite: an aws_iam_server_certificate and an
aws_lb_listener serving it apply clean, and a listener naming a certificate
nobody uploaded fails with CertificateNotFound and the reference's sentence.
That failure arrives at the end of the provider's create timeout rather than
at once, because the provider retries this error on all three calls, the
AddListenerCertificates one against a constant named iamPropagationTimeout:
real AWS is eventually consistent about a certificate just imported, so a
client waits it out. Floci's storage is immediately consistent and nothing
here models a propagation delay, so the retry simply ends in the refusal.

The same contract is pinned at the SDK boundary too, as eight boto3 tests in
compatibility-tests: the refusal on each of the three operations, the
accepted cases, and both protocol edges. They run in under a second, where
driving the same thing through Terraform in CI costs about a minute for the
accepted case and nearly two for the refusal, almost all of it the
provider's waiter and the retry above rather than anything Floci does. The
suite had no ELB coverage at all before this. Each test takes its load
balancer back out before its certificates, which is the order that frees
them, and test_acm.py's private certificate builder moves to a conftest
fixture taking the common name rather than being copied, since the new file
needs the same pair.
2026-10-11 21:47:38 -05:00

373 lines
11 KiB
Python

"""Shared fixtures for AWS service integration tests."""
import datetime
import os
import uuid
import io
import zipfile
import logging
import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
logger = logging.getLogger(__name__)
@pytest.fixture(scope="session")
def endpoint_url():
"""Return the Floci endpoint URL."""
return os.environ.get("FLOCI_ENDPOINT", "http://localhost:4566")
@pytest.fixture(scope="session")
def aws_config(endpoint_url):
"""Common AWS configuration from environment variables."""
return {
"endpoint_url": endpoint_url,
"region_name": os.environ.get("AWS_DEFAULT_REGION", "us-east-1"),
"aws_access_key_id": os.environ.get("AWS_ACCESS_KEY_ID", "test"),
"aws_secret_access_key": os.environ.get("AWS_SECRET_ACCESS_KEY", "test"),
}
@pytest.fixture(scope="session")
def client_config():
"""Botocore client configuration with retry settings."""
return Config(retries={"max_attempts": 1})
# ============================================
# Service Client Fixtures
# ============================================
@pytest.fixture
def ssm_client(aws_config, client_config):
"""Create SSM client."""
return boto3.client("ssm", config=client_config, **aws_config)
@pytest.fixture
def sqs_client(aws_config, client_config):
"""Create SQS client."""
return boto3.client("sqs", config=client_config, **aws_config)
@pytest.fixture
def sns_client(aws_config, client_config):
"""Create SNS client."""
return boto3.client("sns", config=client_config, **aws_config)
@pytest.fixture
def s3_client(aws_config, client_config):
"""Create S3 client."""
return boto3.client("s3", config=client_config, **aws_config)
@pytest.fixture
def dynamodb_client(aws_config, client_config):
"""Create DynamoDB client."""
return boto3.client("dynamodb", config=client_config, **aws_config)
@pytest.fixture
def lambda_client(aws_config, client_config):
"""Create Lambda client."""
return boto3.client("lambda", config=client_config, **aws_config)
@pytest.fixture
def iam_client(aws_config, client_config):
"""Create IAM client."""
return boto3.client("iam", config=client_config, **aws_config)
@pytest.fixture
def sts_client(aws_config, client_config):
"""Create STS client."""
return boto3.client("sts", config=client_config, **aws_config)
@pytest.fixture
def secretsmanager_client(aws_config, client_config):
"""Create Secrets Manager client."""
return boto3.client("secretsmanager", config=client_config, **aws_config)
@pytest.fixture
def kms_client(aws_config, client_config):
"""Create KMS client."""
return boto3.client("kms", config=client_config, **aws_config)
@pytest.fixture
def kinesis_client(aws_config, client_config):
"""Create Kinesis client."""
return boto3.client("kinesis", config=client_config, **aws_config)
@pytest.fixture
def firehose_client(aws_config, client_config):
"""Create Firehose client."""
return boto3.client("firehose", config=client_config, **aws_config)
@pytest.fixture
def cloudwatch_client(aws_config, client_config):
"""Create CloudWatch client."""
return boto3.client("cloudwatch", config=client_config, **aws_config)
@pytest.fixture
def glue_client(aws_config, client_config):
"""Create Glue client."""
return boto3.client("glue", config=client_config, **aws_config)
@pytest.fixture
def resourcegroupstaggingapi_client(aws_config, client_config):
"""Create Resource Groups Tagging API client."""
return boto3.client("resourcegroupstaggingapi", config=client_config, **aws_config)
@pytest.fixture
def logs_client(aws_config, client_config):
"""Create CloudWatch Logs client."""
return boto3.client("logs", config=client_config, **aws_config)
@pytest.fixture
def cognito_client(aws_config, client_config):
"""Create Cognito Identity Provider client."""
return boto3.client("cognito-idp", config=client_config, **aws_config)
@pytest.fixture
def cloudformation_client(aws_config, client_config):
"""Create CloudFormation client."""
return boto3.client("cloudformation", config=client_config, **aws_config)
@pytest.fixture
def config_client(aws_config, client_config):
"""Create AWS Config client."""
return boto3.client("config", config=client_config, **aws_config)
@pytest.fixture
def acm_client(aws_config, client_config):
"""Create ACM client."""
return boto3.client("acm", config=client_config, **aws_config)
@pytest.fixture
def ecr_client(aws_config, client_config):
"""Create ECR client."""
return boto3.client("ecr", config=client_config, **aws_config)
@pytest.fixture
def neptune_client(aws_config, client_config):
"""Create Neptune client."""
return boto3.client("neptune", config=client_config, **aws_config)
@pytest.fixture
def pipes_client(aws_config, client_config):
"""Create EventBridge Pipes client."""
return boto3.client("pipes", config=client_config, **aws_config)
@pytest.fixture
def ses_client(aws_config, client_config):
"""Create SES (v1) client."""
return boto3.client("ses", config=client_config, **aws_config)
@pytest.fixture
def sesv2_client(aws_config, client_config):
"""Create SES v2 client."""
return boto3.client("sesv2", config=client_config, **aws_config)
@pytest.fixture
def iot_client(aws_config, client_config):
"""Create AWS IoT client."""
return boto3.client("iot", config=client_config, **aws_config)
@pytest.fixture
def iot_data_client(aws_config, client_config):
"""Create AWS IoT Data client."""
return boto3.client("iot-data", config=client_config, **aws_config)
@pytest.fixture
def iot_jobs_data_client(aws_config, client_config):
"""Create AWS IoT Jobs Data client."""
return boto3.client("iot-jobs-data", config=client_config, **aws_config)
@pytest.fixture
def ec2_client(aws_config, client_config):
"""Create EC2 client."""
return boto3.client("ec2", config=client_config, **aws_config)
@pytest.fixture
def elbv2_client(aws_config, client_config):
"""Create Elastic Load Balancing v2 client."""
return boto3.client("elbv2", config=client_config, **aws_config)
# ============================================
# Utility Fixtures
# ============================================
@pytest.fixture
def unique_name():
"""Generate a unique name for test resources."""
return f"pytest-{uuid.uuid4().hex[:8]}"
@pytest.fixture
def minimal_lambda_zip():
"""Create a minimal Node.js Lambda deployment package."""
code = (
"exports.handler = async (event) => {\n"
" console.log('[handler] event:', JSON.stringify(event));\n"
" const name = (event && event.name) ? event.name : 'World';\n"
" return { statusCode: 200, body: JSON.stringify({ message: `Hello, ${name}!`, input: event }) };\n"
"};\n"
)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("index.js", code)
return buf.getvalue()
@pytest.fixture
def make_self_signed_certificate():
"""Return a factory for a self-signed certificate and its private key.
The factory takes the common name and returns a tuple of (cert_pem, key_pem) bytes.
"""
def _make(common_name="test.example.com"):
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
subject = issuer = x509.Name(
[x509.NameAttribute(NameOID.COMMON_NAME, common_name)]
)
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.datetime.now(datetime.timezone.utc))
.not_valid_after(
datetime.datetime.now(datetime.timezone.utc)
+ datetime.timedelta(days=365)
)
.sign(key, hashes.SHA256())
)
cert_pem = cert.public_bytes(serialization.Encoding.PEM)
key_pem = key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.NoEncryption(),
)
return cert_pem, key_pem
return _make
# ============================================
# Resource Fixtures with Cleanup
# ============================================
@pytest.fixture
def test_bucket(s3_client, unique_name):
"""Create and cleanup a test S3 bucket."""
bucket_name = f"test-bucket-{unique_name}"
s3_client.create_bucket(Bucket=bucket_name)
yield bucket_name
# Cleanup: empty and delete bucket
try:
paginator = s3_client.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket=bucket_name):
if "Contents" in page:
for obj in page["Contents"]:
s3_client.delete_object(Bucket=bucket_name, Key=obj["Key"])
s3_client.delete_bucket(Bucket=bucket_name)
except ClientError as e:
logger.warning("Failed to clean up S3 bucket %s: %s", bucket_name, e)
@pytest.fixture
def test_queue(sqs_client, unique_name):
"""Create and cleanup a test SQS queue."""
queue_name = f"test-queue-{unique_name}"
response = sqs_client.create_queue(QueueName=queue_name)
queue_url = response["QueueUrl"]
yield queue_url
# Cleanup
try:
sqs_client.delete_queue(QueueUrl=queue_url)
except ClientError as e:
logger.warning("Failed to clean up SQS queue %s: %s", queue_url, e)
@pytest.fixture
def test_topic(sns_client, unique_name):
"""Create and cleanup a test SNS topic."""
topic_name = f"test-topic-{unique_name}"
response = sns_client.create_topic(Name=topic_name)
topic_arn = response["TopicArn"]
yield topic_arn
# Cleanup
try:
sns_client.delete_topic(TopicArn=topic_arn)
except ClientError as e:
logger.warning("Failed to clean up SNS topic %s: %s", topic_arn, e)
@pytest.fixture
def test_table(dynamodb_client, unique_name):
"""Create and cleanup a test DynamoDB table."""
table_name = f"test-table-{unique_name}"
dynamodb_client.create_table(
TableName=table_name,
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
# Wait for table to be active
waiter = dynamodb_client.get_waiter("table_exists")
waiter.wait(TableName=table_name, WaiterConfig={"Delay": 1, "MaxAttempts": 30})
yield table_name
# Cleanup
try:
dynamodb_client.delete_table(TableName=table_name)
except ClientError as e:
logger.warning("Failed to clean up DynamoDB table %s: %s", table_name, e)