From c8108833209731962344a81f08fc87c988ff2fc5 Mon Sep 17 00:00:00 2001
From: Michael Simon <simon@kit.edu>
Date: Mon, 23 Sep 2024 09:09:05 +0200
Subject: [PATCH] ISSUE-196 refactor classes

change AQ attribute source to work with AA and not only with IDPs
---
 .../saml/SamlAttributeQueryService.java       |  75 ++++++++
 .../sec/Saml2AttributeQueryHandler.java       | 177 +-----------------
 .../saml/idp/AttributeAuthorityService.java   | 159 ++++++++++++++++
 .../sp/as/AttributeQueryAttributeSource.java  |  13 +-
 .../service/saml/AttributeQueryHelper.java    |   8 +-
 5 files changed, 254 insertions(+), 178 deletions(-)
 create mode 100644 bwreg-service/src/main/java/edu/kit/scc/webreg/service/saml/SamlAttributeQueryService.java
 create mode 100644 regapp-saml-idp/src/main/java/edu/kit/scc/webreg/saml/idp/AttributeAuthorityService.java

diff --git a/bwreg-service/src/main/java/edu/kit/scc/webreg/service/saml/SamlAttributeQueryService.java b/bwreg-service/src/main/java/edu/kit/scc/webreg/service/saml/SamlAttributeQueryService.java
new file mode 100644
index 000000000..12fb79aa0
--- /dev/null
+++ b/bwreg-service/src/main/java/edu/kit/scc/webreg/service/saml/SamlAttributeQueryService.java
@@ -0,0 +1,75 @@
+package edu.kit.scc.webreg.service.saml;
+
+import java.io.IOException;
+import java.io.Serializable;
+
+import org.opensaml.messaging.decoder.MessageDecodingException;
+import org.opensaml.saml.saml2.core.AttributeQuery;
+import org.opensaml.saml.saml2.core.StatusCode;
+import org.opensaml.soap.soap11.Envelope;
+import org.slf4j.Logger;
+
+import edu.kit.scc.webreg.annotations.RetryTransaction;
+import edu.kit.scc.webreg.entity.SamlAAConfigurationEntity;
+import edu.kit.scc.webreg.saml.idp.AttributeAuthorityService;
+import edu.kit.scc.webreg.service.saml.exc.SamlAuthenticationException;
+import jakarta.ejb.Stateless;
+import jakarta.ejb.TransactionManagement;
+import jakarta.ejb.TransactionManagementType;
+import jakarta.inject.Inject;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import net.shibboleth.shared.component.ComponentInitializationException;
+
+@Stateless
+@TransactionManagement(TransactionManagementType.BEAN)
+public class SamlAttributeQueryService implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+
+	@Inject
+	private Logger logger;
+
+	@Inject
+	private AttributeAuthorityService aaService;
+	
+	@Inject
+	private Saml2DecoderService saml2DecoderService;
+
+	@Inject
+	private SamlHelper samlHelper;
+
+	@RetryTransaction
+	public void consumeAttributeQuery(HttpServletRequest request, HttpServletResponse response,
+			SamlAAConfigurationEntity aaConfig) throws IOException {
+		logger.debug("Consuming SAML AttributeQuery");
+
+		try {
+			AttributeQuery query = saml2DecoderService.decodeAttributeQuery(request);
+			logger.debug("SAML AttributeQuery decoded");
+
+			Envelope envelope = aaService.processAttributeQuery(aaConfig, query);
+
+			response.getWriter().print(samlHelper.marshal(envelope));
+
+		} catch (MessageDecodingException e) {
+			logger.info("Could not execute AttributeQuery: {}", e.getMessage());
+			sendErrorResponse(response, StatusCode.REQUEST_DENIED, e.getMessage());
+		} catch (SecurityException e) {
+			logger.info("Could not execute AttributeQuery: {}", e.getMessage());
+			sendErrorResponse(response, StatusCode.REQUEST_DENIED, e.getMessage());
+		} catch (SamlAuthenticationException e) {
+			logger.info("Could not execute AttributeQuery: {}", e.getMessage());
+			sendErrorResponse(response, StatusCode.REQUEST_DENIED, e.getMessage());
+		} catch (ComponentInitializationException e) {
+			logger.info("Could not execute AttributeQuery: {}", e.getMessage());
+			sendErrorResponse(response, StatusCode.REQUEST_DENIED, e.getMessage());
+		}
+	}
+	
+	private void sendErrorResponse(HttpServletResponse response, String statusCodeString, String messageString)
+			throws IOException {
+		Envelope envelope = aaService.buildErrorResponse(statusCodeString, messageString);
+		response.getWriter().print(samlHelper.marshal(envelope));
+	}
+}
diff --git a/bwreg-webapp/src/main/java/edu/kit/scc/webreg/sec/Saml2AttributeQueryHandler.java b/bwreg-webapp/src/main/java/edu/kit/scc/webreg/sec/Saml2AttributeQueryHandler.java
index 046540caa..38ee079c4 100644
--- a/bwreg-webapp/src/main/java/edu/kit/scc/webreg/sec/Saml2AttributeQueryHandler.java
+++ b/bwreg-webapp/src/main/java/edu/kit/scc/webreg/sec/Saml2AttributeQueryHandler.java
@@ -11,39 +11,12 @@
 package edu.kit.scc.webreg.sec;
 
 import java.io.IOException;
-import java.time.Instant;
-
-import org.opensaml.core.xml.XMLObject;
-import org.opensaml.core.xml.XMLObjectBuilderFactory;
-import org.opensaml.core.xml.schema.XSString;
-import org.opensaml.messaging.decoder.MessageDecodingException;
-import org.opensaml.saml.saml2.core.Assertion;
-import org.opensaml.saml.saml2.core.Attribute;
-import org.opensaml.saml.saml2.core.AttributeQuery;
-import org.opensaml.saml.saml2.core.AttributeStatement;
-import org.opensaml.saml.saml2.core.AttributeValue;
-import org.opensaml.saml.saml2.core.Issuer;
-import org.opensaml.saml.saml2.core.NameID;
-import org.opensaml.saml.saml2.core.Response;
-import org.opensaml.saml.saml2.core.Status;
-import org.opensaml.saml.saml2.core.StatusCode;
-import org.opensaml.saml.saml2.core.StatusMessage;
-import org.opensaml.saml.saml2.metadata.EntityDescriptor;
-import org.opensaml.soap.soap11.Body;
-import org.opensaml.soap.soap11.Envelope;
+
 import org.slf4j.Logger;
 
 import edu.kit.scc.webreg.entity.SamlAAConfigurationEntity;
-import edu.kit.scc.webreg.entity.SamlSpMetadataEntity;
-import edu.kit.scc.webreg.entity.UserEntity;
 import edu.kit.scc.webreg.service.SamlAAConfigurationService;
-import edu.kit.scc.webreg.service.SamlSpMetadataService;
-import edu.kit.scc.webreg.service.UserService;
-import edu.kit.scc.webreg.service.saml.Saml2DecoderService;
-import edu.kit.scc.webreg.service.saml.Saml2ResponseValidationService;
-import edu.kit.scc.webreg.service.saml.SamlHelper;
-import edu.kit.scc.webreg.service.saml.SsoHelper;
-import edu.kit.scc.webreg.service.saml.exc.SamlAuthenticationException;
+import edu.kit.scc.webreg.service.saml.SamlAttributeQueryService;
 import jakarta.inject.Inject;
 import jakarta.inject.Named;
 import jakarta.servlet.Servlet;
@@ -54,7 +27,6 @@ import jakarta.servlet.ServletResponse;
 import jakarta.servlet.annotation.WebServlet;
 import jakarta.servlet.http.HttpServletRequest;
 import jakarta.servlet.http.HttpServletResponse;
-import net.shibboleth.shared.component.ComponentInitializationException;
 
 @Named
 @WebServlet(urlPatterns = { "/Shibboleth.sso/SAML2/AttributeQuery", "/saml/sp/attribute-query" })
@@ -64,26 +36,11 @@ public class Saml2AttributeQueryHandler implements Servlet {
 	private Logger logger;
 
 	@Inject
-	private Saml2DecoderService saml2DecoderService;
-
-	@Inject
-	private Saml2ResponseValidationService saml2ValidationService;
-
-	@Inject
-	private SamlHelper samlHelper;
-
-	@Inject
-	private SamlSpMetadataService spMetadataService;
+	private SamlAttributeQueryService aqService;
 
 	@Inject
 	private SamlAAConfigurationService aaConfigService;
 
-	@Inject
-	private UserService userService;
-
-	@Inject
-	private SsoHelper ssoHelper;
-
 	@Override
 	public void service(ServletRequest servletRequest, ServletResponse servletResponse)
 			throws ServletException, IOException {
@@ -100,7 +57,7 @@ public class Saml2AttributeQueryHandler implements Servlet {
 
 		if (aaConfig != null && aaConfig.getAq() != null && aaConfig.getAq().endsWith(context + path)) {
 			logger.debug("Executing AttributeQuery Handler for entity {}", aaConfig.getEntityId());
-			service(request, response, aaConfig);
+			aqService.consumeAttributeQuery(request, response, aaConfig);
 			return;
 		}
 
@@ -108,132 +65,6 @@ public class Saml2AttributeQueryHandler implements Servlet {
 
 	}
 
-	private void service(HttpServletRequest request, HttpServletResponse response, SamlAAConfigurationEntity aaConfig)
-			throws IOException {
-
-		logger.debug("Consuming SAML AttributeQuery");
-
-		try {
-			AttributeQuery query = saml2DecoderService.decodeAttributeQuery(request);
-			logger.debug("SAML AttributeQuery decoded");
-
-			Issuer issuer = query.getIssuer();
-			if (issuer == null || issuer.getValue() == null) {
-				throw new SamlAuthenticationException("Issuer not set");
-			}
-
-			String issuerString = issuer.getValue();
-			SamlSpMetadataEntity spEntity = spMetadataService.findByEntityId(issuerString);
-			if (spEntity == null)
-				throw new SamlAuthenticationException("Issuer metadata not in database");
-
-			EntityDescriptor spEntityDescriptor = samlHelper.unmarshal(spEntity.getEntityDescriptor(),
-					EntityDescriptor.class);
-
-			saml2ValidationService.verifyIssuer(spEntity, query);
-			saml2ValidationService.validateSpSignature(query, issuer, spEntityDescriptor);
-
-			Response samlResponse = buildSamlRespone(StatusCode.SUCCESS, null);
-			samlResponse.setIssuer(ssoHelper.buildIssuser(aaConfig.getEntityId()));
-			samlResponse.setIssueInstant(Instant.now());
-
-			if (query.getSubject() != null && query.getSubject().getNameID() != null) {
-				String nameIdValue = query.getSubject().getNameID().getValue();
-				String nameIdFormat = query.getSubject().getNameID().getFormat();
-
-				UserEntity user = userService.fetch(Long.parseLong(nameIdValue));
-				if (user != null) {
-					Assertion assertion = samlHelper.create(Assertion.class, Assertion.DEFAULT_ELEMENT_NAME);
-					assertion.setIssueInstant(Instant.now());
-					assertion.setIssuer(ssoHelper.buildIssuser(aaConfig.getEntityId()));
-					assertion.setSubject(ssoHelper.buildAQSubject(aaConfig, spEntity, nameIdValue, NameID.UNSPECIFIED,
-							query.getID()));
-					assertion.getAttributeStatements().add(buildAttributeStatement(user));
-					samlResponse.getAssertions().add(assertion);
-				}
-			}
-
-			Envelope envelope = buildSoapEnvelope(samlResponse);
-			response.getWriter().print(samlHelper.marshal(envelope));
-
-		} catch (MessageDecodingException e) {
-			logger.info("Could not execute AttributeQuery: {}", e.getMessage());
-			sendErrorResponse(response, StatusCode.REQUEST_DENIED, e.getMessage());
-		} catch (SecurityException e) {
-			logger.info("Could not execute AttributeQuery: {}", e.getMessage());
-			sendErrorResponse(response, StatusCode.REQUEST_DENIED, e.getMessage());
-		} catch (SamlAuthenticationException e) {
-			logger.info("Could not execute AttributeQuery: {}", e.getMessage());
-			sendErrorResponse(response, StatusCode.REQUEST_DENIED, e.getMessage());
-		} catch (ComponentInitializationException e) {
-			logger.info("Could not execute AttributeQuery: {}", e.getMessage());
-			sendErrorResponse(response, StatusCode.REQUEST_DENIED, e.getMessage());
-		}
-	}
-
-	private void sendErrorResponse(HttpServletResponse response, String statusCodeString, String messageString)
-			throws IOException {
-		Response samlResponse = buildSamlRespone(statusCodeString, messageString);
-
-		Envelope envelope = buildSoapEnvelope(samlResponse);
-		response.getWriter().print(samlHelper.marshal(envelope));
-	}
-
-	private Envelope buildSoapEnvelope(XMLObject xmlObject) {
-		XMLObjectBuilderFactory bf = samlHelper.getBuilderFactory();
-		Envelope envelope = (Envelope) bf.getBuilder(Envelope.DEFAULT_ELEMENT_NAME)
-				.buildObject(Envelope.DEFAULT_ELEMENT_NAME);
-		Body body = (Body) bf.getBuilder(Body.DEFAULT_ELEMENT_NAME).buildObject(Body.DEFAULT_ELEMENT_NAME);
-
-		body.getUnknownXMLObjects().add(xmlObject);
-		envelope.setBody(body);
-		return envelope;
-	}
-
-	private Response buildSamlRespone(String statusCodeString, String messageString) {
-		Response samlResponse = samlHelper.create(Response.class, Response.DEFAULT_ELEMENT_NAME);
-		samlResponse.setStatus(buildSamlStatus(statusCodeString, messageString));
-		return samlResponse;
-	}
-
-	private Status buildSamlStatus(String statusCodeString, String messageString) {
-		StatusCode statusCode = samlHelper.create(StatusCode.class, StatusCode.DEFAULT_ELEMENT_NAME);
-		statusCode.setValue(statusCodeString);
-
-		Status samlStatus = samlHelper.create(Status.class, Status.DEFAULT_ELEMENT_NAME);
-		samlStatus.setStatusCode(statusCode);
-
-		if (messageString != null) {
-			StatusMessage statusMessage = samlHelper.create(StatusMessage.class, StatusMessage.DEFAULT_ELEMENT_NAME);
-			statusMessage.setValue(messageString);
-			samlStatus.setStatusMessage(statusMessage);
-		}
-		return samlStatus;
-	}
-
-	private AttributeStatement buildAttributeStatement(UserEntity user) {
-		AttributeStatement attributeStatement = samlHelper.create(AttributeStatement.class,
-				AttributeStatement.DEFAULT_ELEMENT_NAME);
-		attributeStatement.getAttributes().add(buildAttribute("urn:oid:1.3.6.1.4.1.5923.1.1.1.6",
-				"eduPersonPrincipalName", Attribute.URI_REFERENCE, user.getEppn()));
-		return attributeStatement;
-	}
-
-	private Attribute buildAttribute(String name, String friendlyName, String nameFormat, String... values) {
-		Attribute attribute = samlHelper.create(Attribute.class, Attribute.DEFAULT_ELEMENT_NAME);
-		attribute.setName(name);
-		attribute.setFriendlyName(friendlyName);
-		attribute.setNameFormat(nameFormat);
-
-		for (String value : values) {
-			XSString xsany = samlHelper.create(XSString.class, XSString.TYPE_NAME, AttributeValue.DEFAULT_ELEMENT_NAME);
-			xsany.setValue(value);
-			attribute.getAttributeValues().add(xsany);
-		}
-
-		return attribute;
-	}
-
 	@Override
 	public void init(ServletConfig config) throws ServletException {
 
diff --git a/regapp-saml-idp/src/main/java/edu/kit/scc/webreg/saml/idp/AttributeAuthorityService.java b/regapp-saml-idp/src/main/java/edu/kit/scc/webreg/saml/idp/AttributeAuthorityService.java
new file mode 100644
index 000000000..ce8b88ac5
--- /dev/null
+++ b/regapp-saml-idp/src/main/java/edu/kit/scc/webreg/saml/idp/AttributeAuthorityService.java
@@ -0,0 +1,159 @@
+package edu.kit.scc.webreg.saml.idp;
+
+import java.time.Instant;
+
+import org.opensaml.core.xml.XMLObject;
+import org.opensaml.core.xml.XMLObjectBuilderFactory;
+import org.opensaml.core.xml.schema.XSString;
+import org.opensaml.saml.saml2.core.Assertion;
+import org.opensaml.saml.saml2.core.Attribute;
+import org.opensaml.saml.saml2.core.AttributeQuery;
+import org.opensaml.saml.saml2.core.AttributeStatement;
+import org.opensaml.saml.saml2.core.AttributeValue;
+import org.opensaml.saml.saml2.core.Issuer;
+import org.opensaml.saml.saml2.core.NameID;
+import org.opensaml.saml.saml2.core.Response;
+import org.opensaml.saml.saml2.core.Status;
+import org.opensaml.saml.saml2.core.StatusCode;
+import org.opensaml.saml.saml2.core.StatusMessage;
+import org.opensaml.saml.saml2.metadata.EntityDescriptor;
+import org.opensaml.soap.soap11.Body;
+import org.opensaml.soap.soap11.Envelope;
+import org.slf4j.Logger;
+
+import edu.kit.scc.webreg.dao.SamlSpMetadataDao;
+import edu.kit.scc.webreg.dao.UserDao;
+import edu.kit.scc.webreg.entity.SamlAAConfigurationEntity;
+import edu.kit.scc.webreg.entity.SamlSpMetadataEntity;
+import edu.kit.scc.webreg.entity.UserEntity;
+import edu.kit.scc.webreg.service.saml.Saml2ResponseValidationService;
+import edu.kit.scc.webreg.service.saml.SamlHelper;
+import edu.kit.scc.webreg.service.saml.SsoHelper;
+import edu.kit.scc.webreg.service.saml.exc.SamlAuthenticationException;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+@ApplicationScoped
+public class AttributeAuthorityService {
+
+	@Inject
+	private Logger logger;
+
+	@Inject
+	private Saml2ResponseValidationService saml2ValidationService;
+
+	@Inject
+	private SamlSpMetadataDao spMetadataDao;
+
+	@Inject
+	private UserDao userService;
+
+	@Inject
+	private SamlHelper samlHelper;
+
+	@Inject
+	private SsoHelper ssoHelper;
+
+	public Envelope processAttributeQuery(SamlAAConfigurationEntity aaConfig, AttributeQuery query) throws SamlAuthenticationException {
+		
+		logger.debug("Processing AttributeQuery");
+		
+		Issuer issuer = query.getIssuer();
+		if (issuer == null || issuer.getValue() == null) {
+			throw new SamlAuthenticationException("Issuer not set");
+		}
+
+		String issuerString = issuer.getValue();
+		SamlSpMetadataEntity spEntity = spMetadataDao.findByEntityId(issuerString);
+		if (spEntity == null)
+			throw new SamlAuthenticationException("Issuer metadata not in database");
+
+		EntityDescriptor spEntityDescriptor = samlHelper.unmarshal(spEntity.getEntityDescriptor(),
+				EntityDescriptor.class);
+
+		saml2ValidationService.verifyIssuer(spEntity, query);
+		saml2ValidationService.validateSpSignature(query, issuer, spEntityDescriptor);
+
+		Response samlResponse = buildSamlRespone(StatusCode.SUCCESS, null);
+		samlResponse.setIssuer(ssoHelper.buildIssuser(aaConfig.getEntityId()));
+		samlResponse.setIssueInstant(Instant.now());
+
+		if (query.getSubject() != null && query.getSubject().getNameID() != null) {
+			String nameIdValue = query.getSubject().getNameID().getValue();
+			String nameIdFormat = query.getSubject().getNameID().getFormat();
+
+			UserEntity user = userService.fetch(Long.parseLong(nameIdValue));
+			if (user != null) {
+				Assertion assertion = samlHelper.create(Assertion.class, Assertion.DEFAULT_ELEMENT_NAME);
+				assertion.setIssueInstant(Instant.now());
+				assertion.setIssuer(ssoHelper.buildIssuser(aaConfig.getEntityId()));
+				assertion.setSubject(ssoHelper.buildAQSubject(aaConfig, spEntity, nameIdValue, NameID.UNSPECIFIED,
+						query.getID()));
+				assertion.getAttributeStatements().add(buildAttributeStatement(user));
+				samlResponse.getAssertions().add(assertion);
+			}
+		}
+
+		return buildSoapEnvelope(samlResponse);
+	}
+	
+	public Envelope buildErrorResponse(String statusCodeString, String messageString) {
+		Response samlResponse = buildSamlRespone(statusCodeString, messageString);
+		return buildSoapEnvelope(samlResponse);
+	}
+	
+	private Response buildSamlRespone(String statusCodeString, String messageString) {
+		Response samlResponse = samlHelper.create(Response.class, Response.DEFAULT_ELEMENT_NAME);
+		samlResponse.setStatus(buildSamlStatus(statusCodeString, messageString));
+		return samlResponse;
+	}
+
+	private Status buildSamlStatus(String statusCodeString, String messageString) {
+		StatusCode statusCode = samlHelper.create(StatusCode.class, StatusCode.DEFAULT_ELEMENT_NAME);
+		statusCode.setValue(statusCodeString);
+
+		Status samlStatus = samlHelper.create(Status.class, Status.DEFAULT_ELEMENT_NAME);
+		samlStatus.setStatusCode(statusCode);
+
+		if (messageString != null) {
+			StatusMessage statusMessage = samlHelper.create(StatusMessage.class, StatusMessage.DEFAULT_ELEMENT_NAME);
+			statusMessage.setValue(messageString);
+			samlStatus.setStatusMessage(statusMessage);
+		}
+		return samlStatus;
+	}
+
+	private Envelope buildSoapEnvelope(XMLObject xmlObject) {
+		XMLObjectBuilderFactory bf = samlHelper.getBuilderFactory();
+		Envelope envelope = (Envelope) bf.getBuilder(Envelope.DEFAULT_ELEMENT_NAME)
+				.buildObject(Envelope.DEFAULT_ELEMENT_NAME);
+		Body body = (Body) bf.getBuilder(Body.DEFAULT_ELEMENT_NAME).buildObject(Body.DEFAULT_ELEMENT_NAME);
+
+		body.getUnknownXMLObjects().add(xmlObject);
+		envelope.setBody(body);
+		return envelope;
+	}
+
+	private AttributeStatement buildAttributeStatement(UserEntity user) {
+		AttributeStatement attributeStatement = samlHelper.create(AttributeStatement.class,
+				AttributeStatement.DEFAULT_ELEMENT_NAME);
+		attributeStatement.getAttributes().add(buildAttribute("urn:oid:1.3.6.1.4.1.5923.1.1.1.6",
+				"eduPersonPrincipalName", Attribute.URI_REFERENCE, user.getEppn()));
+		return attributeStatement;
+	}
+
+	private Attribute buildAttribute(String name, String friendlyName, String nameFormat, String... values) {
+		Attribute attribute = samlHelper.create(Attribute.class, Attribute.DEFAULT_ELEMENT_NAME);
+		attribute.setName(name);
+		attribute.setFriendlyName(friendlyName);
+		attribute.setNameFormat(nameFormat);
+
+		for (String value : values) {
+			XSString xsany = samlHelper.create(XSString.class, XSString.TYPE_NAME, AttributeValue.DEFAULT_ELEMENT_NAME);
+			xsany.setValue(value);
+			attribute.getAttributeValues().add(xsany);
+		}
+
+		return attribute;
+	}
+}
diff --git a/regapp-saml-sp/src/main/java/edu/kit/scc/regapp/saml/sp/as/AttributeQueryAttributeSource.java b/regapp-saml-sp/src/main/java/edu/kit/scc/regapp/saml/sp/as/AttributeQueryAttributeSource.java
index 139c172bb..70715ec60 100644
--- a/regapp-saml-sp/src/main/java/edu/kit/scc/regapp/saml/sp/as/AttributeQueryAttributeSource.java
+++ b/regapp-saml-sp/src/main/java/edu/kit/scc/regapp/saml/sp/as/AttributeQueryAttributeSource.java
@@ -15,11 +15,14 @@ import org.opensaml.saml.saml2.core.Response;
 import edu.kit.scc.webreg.as.AbstractAttributeSourceWorkflow;
 import edu.kit.scc.webreg.audit.AttributeSourceAuditor;
 import edu.kit.scc.webreg.dao.GroupDao;
+import edu.kit.scc.webreg.dao.SamlAAMetadataDao;
 import edu.kit.scc.webreg.dao.SamlIdpMetadataDao;
 import edu.kit.scc.webreg.dao.SamlSpConfigurationDao;
 import edu.kit.scc.webreg.dao.ScriptDao;
 import edu.kit.scc.webreg.dao.as.ASUserAttrValueDao;
+import edu.kit.scc.webreg.entity.SamlAAMetadataEntity;
 import edu.kit.scc.webreg.entity.SamlIdpMetadataEntity;
+import edu.kit.scc.webreg.entity.SamlMetadataEntity;
 import edu.kit.scc.webreg.entity.SamlSpConfigurationEntity;
 import edu.kit.scc.webreg.entity.ScriptEntity;
 import edu.kit.scc.webreg.entity.UserEntity;
@@ -37,6 +40,7 @@ public class AttributeQueryAttributeSource extends AbstractAttributeSourceWorkfl
 	private static final long serialVersionUID = 1L;
 
 	private SamlIdpMetadataDao idpDao;
+	private SamlAAMetadataDao aaDao;
 	private SamlSpConfigurationDao spDao;
 	private AttributeQueryHelper aqHelper;
 	private Saml2AssertionService saml2AssertionService;
@@ -47,6 +51,7 @@ public class AttributeQueryAttributeSource extends AbstractAttributeSourceWorkfl
 	public AttributeQueryAttributeSource() {
 		super();
 		idpDao = CDI.current().select(SamlIdpMetadataDao.class).get();
+		aaDao = CDI.current().select(SamlAAMetadataDao.class).get();
 		spDao = CDI.current().select(SamlSpConfigurationDao.class).get();
 		saml2AssertionService = CDI.current().select(Saml2AssertionService.class).get();
 		attrHelper = CDI.current().select(AttributeMapHelper.class).get();
@@ -75,7 +80,13 @@ public class AttributeQueryAttributeSource extends AbstractAttributeSourceWorkfl
 		UserEntity user = asUserAttr.getUser();
 
 		SamlSpConfigurationEntity spEntity = spDao.findByEntityId(spEntityId);
-		SamlIdpMetadataEntity idpEntity = idpDao.findByEntityId(aaEntityId);
+		SamlMetadataEntity idpEntity = idpDao.findByEntityId(aaEntityId);
+		if (idpEntity == null) {
+			idpEntity = aaDao.findByEntityId(aaEntityId);
+			
+			if (idpEntity == null) 
+				throw new UserUpdateException("AS is not configured correctly. IDP or AA not found: " + aaEntityId);
+		}
 
 		ScriptEntity script = scriptDao.findByName(nameIdScript);
 		if (script == null)
diff --git a/regapp-saml/src/main/java/edu/kit/scc/webreg/service/saml/AttributeQueryHelper.java b/regapp-saml/src/main/java/edu/kit/scc/webreg/service/saml/AttributeQueryHelper.java
index 5b5867674..3db6a5d33 100644
--- a/regapp-saml/src/main/java/edu/kit/scc/webreg/service/saml/AttributeQueryHelper.java
+++ b/regapp-saml/src/main/java/edu/kit/scc/webreg/service/saml/AttributeQueryHelper.java
@@ -118,7 +118,7 @@ public class AttributeQueryHelper implements Serializable {
 	@Inject
 	ApplicationConfig appConfig;
 
-	public Response query(String format, String persistentId, SamlMetadataEntity idpEntity, EntityDescriptor idpEntityDescriptor,
+	public Response query(String format, String persistentId, SamlMetadataEntity idpEntity, EntityDescriptor aaEntityDescriptor,
 			SamlSpConfigurationEntity spEntity, StringBuffer debugLog) throws Exception {
 
 		if (debugLog != null) {
@@ -126,7 +126,7 @@ public class AttributeQueryHelper implements Serializable {
 					.append(idpEntity.getEntityId()).append(" sp: ").append(spEntity.getEntityId()).append("\n");
 		}
 
-		AttributeService attributeService = metadataHelper.getAttributeService(idpEntityDescriptor);
+		AttributeService attributeService = metadataHelper.getAttributeService(aaEntityDescriptor);
 		if (attributeService == null || attributeService.getLocation() == null)
 			throw new MetadataException("No Attribute Service found for IDP " + idpEntity.getEntityId());
 
@@ -168,7 +168,7 @@ public class AttributeQueryHelper implements Serializable {
 		ssConfig.setSigningCredentials(credentialList);
 		CriteriaSet criteriaSet = new CriteriaSet();
 		criteriaSet.add(new SignatureSigningConfigurationCriterion(ssConfig));
-		criteriaSet.add(new RoleDescriptorCriterion(idpEntityDescriptor.getIDPSSODescriptor(SAMLConstants.SAML20P_NS)));
+		criteriaSet.add(new RoleDescriptorCriterion(aaEntityDescriptor.getAttributeAuthorityDescriptor(SAMLConstants.SAML20P_NS)));
 		SAMLMetadataSignatureSigningParametersResolver smsspr = new SAMLMetadataSignatureSigningParametersResolver();
 
 		SignatureSigningParameters ssp = smsspr.resolveSingle(criteriaSet);
@@ -197,7 +197,7 @@ public class AttributeQueryHelper implements Serializable {
 		SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(getRequestTimeout()).build();
 
 		Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
-				.register("https", getSSLConnectionSocketFactory(idpEntityDescriptor)).build();
+				.register("https", getSSLConnectionSocketFactory(aaEntityDescriptor)).build();
 		BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(
 				socketFactoryRegistry);
 		
-- 
GitLab