8000 Add an Amazon SES email sender using the SES v2 API and IAM credentials by lorexoff · Pull Request #52361 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/documentation/release_notes/topics/26_8_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ When upgrading {project_name} with large database tables, index creation was pre

For installation instructions, see the link:{operatorguide_link}[{operatorguide_name}].

== Amazon SES email sender

{project_name} can now send its email through the Amazon SES API instead of the SES SMTP interface. The SMTP route requires a dedicated SES SMTP username and password derived from a long-lived IAM user secret, stored in the realm; the API route signs the request with the AWS credentials the server already has, including an assumed role on EKS, ECS or EC2.

Enable it with `--spi-email-sender--provider=aws-ses`. The realm's existing email settings — sender, display name, reply-to — keep their meaning, and the message sent is the one {project_name} already composed. For details, see the link:{adminguide_link}#amazon-ses-api[{adminguide_name}].

= Themes

== Redesigned identity provider buttons on the login page
Expand Down
63 changes: 63 additions & 0 deletions docs/documentation/server_admin/topics/realms/email.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,67 @@ This feature is not yet supported by {project_name}, because Google does not all
XOAUTH2 is not supported by the AWS-SMTP service.
The AWS-service requires the use of a password.

If {project_name} runs on AWS, <<amazon-ses-api,sending through the Amazon SES API>> avoids that password entirely.

[[amazon-ses-api]]
== Sending email through the Amazon SES API

Amazon SES also exposes an HTTPS API, and {project_name} ships an email sender that uses it. Compared with the SMTP interface, it authenticates with ordinary AWS credentials — an IAM role where the deployment has one — instead of a dedicated SES SMTP username and password stored in the realm.

The message itself is unchanged: it is composed exactly as the SMTP sender composes it, from the same realm email settings, and handed to SES as a raw MIME message.

NOTE: This section has been contributed by the Keycloak community. As the Keycloak core team does not have means to test third-party providers, it is provided as-is. If you find this documentation outdated or incomplete, please contribute to improve it.

=== Enabling it

[source,bash]
----
bin/kc.sh start --spi-email-sender--provider=aws-ses --spi-email-sender--aws-ses--region=eu-central-1
----

The provider selection is a build-time option, so it takes effect through {project_name}'s build step, not through a restart alone. The corresponding environment variables are `KC_SPI_EMAIL_SENDER__PROVIDER` and `KC_SPI_EMAIL_SENDER__AWS_SES__REGION`.

The legacy single-dash spelling (`--spi-email-sender-provider`, `KC_SPI_EMAIL_SENDER_PROVIDER`) is still accepted and is the only form older servers understand, which is why it is the spelling the provider's own error messages use.

=== Configuration

|===
|Option |Environment fallback |Default |Description

|`--spi-email-sender--aws-ses--region`
|`AWS_REGION`, `AWS_DEFAULT_REGION`
|_required_
|Region of the verified SES identity. SES identities are per region, and a send from a different region is denied rather than redirected.
Comment thread
Copilot marked this conversation as resolved.
Resolved

|`--spi-email-sender--aws-ses--endpoint`
|`AWS_ENDPOINT_URL_SESV2`, `AWS_ENDPOINT_URL`
|`https://email.<region>.amazonaws.com`
|Overrides the endpoint, for a VPC endpoint or a FIPS endpoint.

|`--spi-email-sender--aws-ses--configuration-set`
|
|
|SES configuration set to send through, which is how bounce, complaint and open events are published.

|`--spi-email-sender--aws-ses--connect-timeout`
|
|`10000`
|Milliseconds. The realm's own connection timeout, when set, takes precedence.

|`--spi-email-sender--aws-ses--read-timeout`
|
|`10000`
|Milliseconds. The realm's own timeout, when set, takes precedence.
|===

There is no option for credentials. They are resolved in the order the AWS SDKs use — JVM system properties, environment variables, a web identity token (EKS IRSA), the shared AWS config files, container credentials (ECS and EKS Pod Identity), and finally the EC2 instance metadata service. Shared profiles are read for static keys only: a profile that delegates through `role_arn`, `credential_process` or SSO is skipped rather than resolved. Temporary credentials are refreshed before they expire. On a server that is not on AWS, set `AWS_EC2_METADATA_DISABLED=true` to skip the metadata probe.

The sending principal needs `ses:SendEmail` on the sending identity. A policy written for the SMTP interface grants `ses:SendRawEmail`, which is the action for the v1 API and does not authorize the v2 `SendEmail` operation — such a policy has to be updated, and keeping the old action alongside the new one is what preserves the ability to switch back to SMTP. Because {project_name} only ever sends from the realm's configured *From* address, the policy can be narrowed with a `ses:FromAddress` condition.

=== What the realm still controls

*From*, *From Display Name*, *Reply To*, *Reply To Display Name* and the two timeouts keep their meaning. *Envelope From* is mapped to the SES feedback-forwarding address, which routes bounces and complaints; the SMTP envelope sender itself is fixed by the sending identity's MAIL FROM domain and cannot be set per message over the API. The SMTP host, port and credentials are ignored, since no SMTP connection is made.

An internationalised domain is converted to its ASCII form, as the SMTP sender does. A non-ASCII local part needs the SMTPUTF8 extension, which Amazon SES does not implement, and is rejected before the message is sent.

endif::[]
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright 2026 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.keycloak.email.aws;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

/**
* One outbound HTTP call, described in full before it is executed.
* <p>
* The request is a value object on purpose: SigV4 signs a byte-exact rendering of method, URI,
* headers and body, so the bytes that are signed and the bytes that reach the socket must come from
* the same immutable object. Anything that lets a layer below add or rewrite a signed header
* invalidates the signature.
*
* @param method HTTP method, uppercase
* @param uri absolute request URI; must carry no query string for SES
* @param headers headers to place on the request, insertion-ordered
* @param body request body, empty (never {@code null}) for bodyless requests
* @param connectTimeoutMillis TCP connect timeout
* @param readTimeoutMillis socket read timeout
*/
public record AwsHttpRequest(String method, URI uri, Map<String, String> headers, byte[] body,
int connectTimeoutMillis, int readTimeoutMillis) {

public static final byte[] NO_BODY = new byte[0];

public AwsHttpRequest {
headers = Collections.unmodifiableMap(new LinkedHashMap<>(headers));
body = body == null ? NO_BODY : body.clone();
}

public static AwsHttpRequest get(URI uri, Map<String, String> headers, int connectTimeoutMillis, int readTimeoutMillis) {
return new AwsHttpRequest("GET", uri, headers, NO_BODY, connectTimeoutMillis, readTimeoutMillis);
}

@Override
public byte[] body() {
return body.clone();
}

/** The body as text, for the JSON/XML responses of the credential endpoints. */
public String bodyAsString() {
return new String(body, StandardCharsets.UTF_8);
}

public AwsHttpRequest withHeaders(Map<String, String> additional) {
Map<String, String> merged = new LinkedHashMap<>(headers);
merged.putAll(additional);
return new AwsHttpRequest(method, uri, merged, body, connectTimeoutMillis, readTimeoutMillis);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright 2026 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.keycloak.email.aws;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

/**
* The response of an {@link AwsHttpTransport} exchange.
*
* @param status HTTP status code
* @param headers response headers; look them up through {@link #header(String)}, never directly —
* AWS documents {@code x-amzn-ErrorType} in one casing and sends another
* @param body response body, empty when there is none
*/
public record AwsHttpResponse(int status, Map<String, String> headers, byte[] body) {

public AwsHttpResponse {
headers = Collections.unmodifiableMap(new LinkedHashMap<>(headers));
body = body == null ? new byte[0] : body.clone();
}

@Override
public byte[] body() {
return body.clone();
}

public String bodyAsString() {
return new String(body, StandardCharsets.UTF_8);
}

public boolean isSuccessful() {
return status >= 200 && status < 300;
}

/** Case-insensitive header lookup, as HTTP requires and AWS's own casing demands. */
public String header(String name) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
if (entry.getKey().equalsIgnoreCase(name)) {
return entry.getValue();
}
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright 2026 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.keycloak.email.aws;

import java.io.IOException;

/**
* Executes an {@link AwsHttpRequest} exactly as described.
* <p>
* "Exactly" is the whole contract. An implementation must not add, remove, reorder or rewrite any
* header the caller set, must not follow redirects, and must not itself retry a request whose bytes
* already reached the wire: the first two would break the SigV4 signature, the third would send a
* transactional email twice, because SES {@code SendEmail} has no idempotency token.
* <p>
* The last one is only as strong as the client underneath. {@code KeycloakHttpTransport} runs on the
* server's shared Apache client, which installs a retry handler of its own and turns it into a
* resend-after-send when {@code spi-connections-http-client-default-max-retries} is set; that cannot
* be opted out of per request, so the factory warns at startup when it sees it.
*/
public interface AwsHttpTransport {

AwsHttpResponse exchange(AwsHttpRequest request) throws IOException;
}
56 changes: 56 additions & 0 deletions services/src/main/java/org/keycloak/email/aws/AwsRegion.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* Copyright 2026 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.keycloak.email.aws;

import java.util.regex.Pattern;

/**
* The two things this provider needs to know about an AWS region name: whether it is one, and which
* DNS suffix its partition uses.
* <p>
* Validation is not defensive programming for its own sake. A region name is interpolated into the
* hostname of the SES and STS endpoints, and both of those requests carry credentials — the STS one
* carries a service-account token in its body. A region read from the environment as
* {@code attacker.example/collect} would otherwise build
* {@code https://sts.attacker.example/collect.amazonaws.com/} and post that token to a host of
* someone else's choosing.
*/
public final class AwsRegion {

/** {@code eu-central-1}, {@code us-gov-west-1}, {@code cn-north-1} — and nothing that could smuggle a host or a path. */
private static final Pattern VALID = Pattern.compile("[a-z0-9]+(-[a-z0-9]+)+");

private static final String DEFAULT_DNS_SUFFIX = "amazonaws.com";
private static final String CHINA_DNS_SUFFIX = "amazonaws.com.cn";

private AwsRegion() {
}

public static boolean isValid(String region) {
return region != null && VALID.matcher(region).matches();
}

/**
* The DNS suffix of the region's partition. China is the partition that differs for the endpoints
* this provider builds; the AWS GovCloud and the standard partition share {@code amazonaws.com},
* and the isolated partitions are not reachable from a server that could run this code anyway.
*/
public static String dnsSuffix(String region) {
return region != null && region.startsWith("cn-") ? CHINA_DNS_SUFFIX : DEFAULT_DNS_SUFFIX;
}
}
Loading
0