Skip to content

Implement SAML custom attributes support for Identity Provider #128176

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Jun 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
505f064
Implement SAML custom attributes support for Identity Provider
lloydmeta May 20, 2025
763363b
Add test for SAML custom attributes in authentication response
lloydmeta May 20, 2025
67d94ea
Add backward compatibility overload for SuccessfulAuthenticationRespo…
lloydmeta May 20, 2025
a266115
Add validation for duplicate SAML attribute keys
lloydmeta May 20, 2025
4b4b3ad
Refactor SAML attributes validation to follow standard patterns
lloydmeta May 21, 2025
4114c68
Update docs/changelog/128176.yaml
lloydmeta May 21, 2025
ae21529
Improve SAML response validation in identity provider tests
lloydmeta May 21, 2025
30a89c5
Simplify SAML attributes representation using JSON object/Map structure
lloydmeta May 21, 2025
2d10dc1
* Fix up toString dangling quote.
lloydmeta May 22, 2025
ddfa91b
Merge branch 'main' into add-arbitrary-attribute-support
lloydmeta May 22, 2025
8de83dc
Merge branch 'main' of github.com:elastic/elasticsearch into add-arbi…
lloydmeta Jun 2, 2025
be900e6
* Remove attributes from Response object.
lloydmeta Jun 2, 2025
04e8c45
* Remove friendly name.
lloydmeta Jun 2, 2025
686544f
* Cleanup serdes by using existing utils in the ES codebase
lloydmeta Jun 2, 2025
fbb5a6f
Touchup comment
lloydmeta Jun 2, 2025
a28adf3
Update x-pack/plugin/identity-provider/src/test/java/org/elasticsearc…
lloydmeta Jun 2, 2025
0c69ff5
Merge branch 'main' into add-arbitrary-attribute-support
lloydmeta Jun 2, 2025
c88a58a
Merge branch 'main' into add-arbitrary-attribute-support
tvernum Jun 3, 2025
5072c44
Add transport-version checks
tvernum Jun 3, 2025
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
5 changes: 5 additions & 0 deletions docs/changelog/128176.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pr: 128176
summary: Implement SAML custom attributes support for Identity Provider
area: Authentication
type: enhancement
issues: []
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ static TransportVersion def(int id) {
public static final TransportVersion INFERENCE_CUSTOM_SERVICE_ADDED = def(9_084_0_00);
public static final TransportVersion ESQL_LIMIT_ROW_SIZE = def(9_085_0_00);
public static final TransportVersion ESQL_REGEX_MATCH_WITH_CASE_INSENSITIVITY = def(9_086_0_00);
public static final TransportVersion IDP_CUSTOM_SAML_ATTRIBUTES = def(9_087_0_00);

/*
* STOP! READ THIS FIRST! No, really,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,38 @@
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.xcontent.ObjectPath;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.json.JsonXContent;
import org.elasticsearch.xpack.core.security.action.saml.SamlPrepareAuthenticationResponse;
import org.elasticsearch.xpack.idp.saml.sp.SamlServiceProviderIndex;
import org.junit.Before;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;

public class IdentityProviderAuthenticationIT extends IdpRestTestCase {

Expand Down Expand Up @@ -74,6 +89,81 @@ public void testRegistrationAndIdpInitiatedSso() throws Exception {
authenticateWithSamlResponse(samlResponse, null);
}

public void testCustomAttributesInIdpInitiatedSso() throws Exception {
final Map<String, Object> request = Map.ofEntries(
Map.entry("name", "Test SP With Custom Attributes"),
Map.entry("acs", SP_ACS),
Map.entry("privileges", Map.ofEntries(Map.entry("resource", SP_ENTITY_ID), Map.entry("roles", List.of("sso:(\\w+)")))),
Map.entry(
"attributes",
Map.ofEntries(
Map.entry("principal", "https://idp.test.es.elasticsearch.org/attribute/principal"),
Map.entry("name", "https://idp.test.es.elasticsearch.org/attribute/name"),
Map.entry("email", "https://idp.test.es.elasticsearch.org/attribute/email"),
Map.entry("roles", "https://idp.test.es.elasticsearch.org/attribute/roles")
)
)
);
final SamlServiceProviderIndex.DocumentVersion docVersion = createServiceProvider(SP_ENTITY_ID, request);
checkIndexDoc(docVersion);
ensureGreen(SamlServiceProviderIndex.INDEX_NAME);

// Create custom attributes
Map<String, List<String>> attributesMap = Map.of("department", List.of("engineering", "product"), "region", List.of("APJ"));

// Generate SAML response with custom attributes
final String samlResponse = generateSamlResponseWithAttributes(SP_ENTITY_ID, SP_ACS, null, attributesMap);

// Parse XML directly from samlResponse (it's not base64 encoded at this point)
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // Required for XPath
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(samlResponse)));

// Create XPath evaluator
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();

// Validate SAML Response structure
Element responseElement = (Element) xpath.evaluate("//*[local-name()='Response']", document, XPathConstants.NODE);
assertThat("SAML Response element should exist", responseElement, notNullValue());

Element assertionElement = (Element) xpath.evaluate("//*[local-name()='Assertion']", document, XPathConstants.NODE);
assertThat("SAML Assertion element should exist", assertionElement, notNullValue());

// Validate department attribute
NodeList departmentAttributes = (NodeList) xpath.evaluate(
"//*[local-name()='Attribute' and @Name='department']/*[local-name()='AttributeValue']",
document,
XPathConstants.NODESET
);

assertThat("Should have two values for department attribute", departmentAttributes.getLength(), is(2));

// Verify department values
List<String> departmentValues = new ArrayList<>();
for (int i = 0; i < departmentAttributes.getLength(); i++) {
departmentValues.add(departmentAttributes.item(i).getTextContent());
}
assertThat(
"Department attribute should contain 'engineering' and 'product'",
departmentValues,
containsInAnyOrder("engineering", "product")
);

// Validate region attribute
NodeList regionAttributes = (NodeList) xpath.evaluate(
"//*[local-name()='Attribute' and @Name='region']/*[local-name()='AttributeValue']",
document,
XPathConstants.NODESET
);

assertThat("Should have one value for region attribute", regionAttributes.getLength(), is(1));
assertThat("Region attribute should contain 'APJ'", regionAttributes.item(0).getTextContent(), equalTo("APJ"));

authenticateWithSamlResponse(samlResponse, null);
}

public void testRegistrationAndSpInitiatedSso() throws Exception {
final Map<String, Object> request = Map.ofEntries(
Map.entry("name", "Test SP"),
Expand Down Expand Up @@ -125,17 +215,37 @@ private SamlPrepareAuthenticationResponse generateSamlAuthnRequest(String realmN
}
}

private String generateSamlResponse(String entityId, String acs, @Nullable Map<String, Object> authnState) throws Exception {
private String generateSamlResponse(String entityId, String acs, @Nullable Map<String, Object> authnState) throws IOException {
return generateSamlResponseWithAttributes(entityId, acs, authnState, null);
}

private String generateSamlResponseWithAttributes(
String entityId,
String acs,
@Nullable Map<String, Object> authnState,
@Nullable Map<String, List<String>> attributes
) throws IOException {
final Request request = new Request("POST", "/_idp/saml/init");
if (authnState != null && authnState.isEmpty() == false) {
request.setJsonEntity(Strings.format("""
{"entity_id":"%s", "acs":"%s","authn_state":%s}
""", entityId, acs, Strings.toString(JsonXContent.contentBuilder().map(authnState))));
} else {
request.setJsonEntity(Strings.format("""
{"entity_id":"%s", "acs":"%s"}
""", entityId, acs));

XContentBuilder builder = JsonXContent.contentBuilder();
builder.startObject();
builder.field("entity_id", entityId);
builder.field("acs", acs);

if (authnState != null) {
builder.field("authn_state");
builder.map(authnState);
}

if (attributes != null) {
builder.field("attributes");
builder.map(attributes);
}

builder.endObject();
String jsonEntity = Strings.toString(builder);

request.setJsonEntity(jsonEntity);
request.setOptions(
RequestOptions.DEFAULT.toBuilder()
.addHeader("es-secondary-authorization", basicAuthHeaderValue("idp_user", new SecureString("idp-password".toCharArray())))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
*/
package org.elasticsearch.xpack.idp.action;

import org.elasticsearch.TransportVersions;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.LegacyActionRequest;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.xpack.idp.saml.support.SamlAuthenticationState;
import org.elasticsearch.xpack.idp.saml.support.SamlInitiateSingleSignOnAttributes;

import java.io.IOException;

Expand All @@ -22,12 +24,16 @@ public class SamlInitiateSingleSignOnRequest extends LegacyActionRequest {
private String spEntityId;
private String assertionConsumerService;
private SamlAuthenticationState samlAuthenticationState;
private SamlInitiateSingleSignOnAttributes attributes;

public SamlInitiateSingleSignOnRequest(StreamInput in) throws IOException {
super(in);
spEntityId = in.readString();
assertionConsumerService = in.readString();
samlAuthenticationState = in.readOptionalWriteable(SamlAuthenticationState::new);
if (in.getTransportVersion().onOrAfter(TransportVersions.IDP_CUSTOM_SAML_ATTRIBUTES)) {
attributes = in.readOptionalWriteable(SamlInitiateSingleSignOnAttributes::new);
}
}

public SamlInitiateSingleSignOnRequest() {}
Expand All @@ -41,6 +47,17 @@ public ActionRequestValidationException validate() {
if (Strings.isNullOrEmpty(assertionConsumerService)) {
validationException = addValidationError("acs is missing", validationException);
}

// Validate attributes if present
if (attributes != null) {
ActionRequestValidationException attributesValidationException = attributes.validate();
if (attributesValidationException != null) {
for (String error : attributesValidationException.validationErrors()) {
validationException = addValidationError(error, validationException);
}
}
}

return validationException;
}

Expand Down Expand Up @@ -68,17 +85,38 @@ public void setSamlAuthenticationState(SamlAuthenticationState samlAuthenticatio
this.samlAuthenticationState = samlAuthenticationState;
}

public SamlInitiateSingleSignOnAttributes getAttributes() {
return attributes;
}

public void setAttributes(SamlInitiateSingleSignOnAttributes attributes) {
this.attributes = attributes;
}

@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(spEntityId);
out.writeString(assertionConsumerService);
out.writeOptionalWriteable(samlAuthenticationState);
if (out.getTransportVersion().onOrAfter(TransportVersions.IDP_CUSTOM_SAML_ATTRIBUTES)) {
out.writeOptionalWriteable(attributes);
}
}

@Override
public String toString() {
return getClass().getSimpleName() + "{spEntityId='" + spEntityId + "', acs='" + assertionConsumerService + "'}";
return getClass().getSimpleName()
+ "{"
+ "spEntityId='"
+ spEntityId
+ "', "
+ "acs='"
+ assertionConsumerService
+ "', "
+ "attributes='"
+ attributes
+ "'}";
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ protected void doExecute(
identityProvider
);
try {
final Response response = builder.build(user, authenticationState);
final Response response = builder.build(user, authenticationState, request.getAttributes());
listener.onResponse(
new SamlInitiateSingleSignOnResponse(
user.getServiceProvider().getEntityId(),
Expand Down
Loading
Loading