<commit_before><?php

/**
 * IdP implementation for SAML 2.0 protocol.
 *
 * @package simpleSAMLphp
 * @version $Id$
 */
class sspmod_saml_IdP_SAML2 {

	/**
	 * Send a response to the SP.
	 *
	 * @param array $state  The authentication state.
	 */
	public static function sendResponse(array $state) {
		assert('isset($state["Attributes"])');
		assert('isset($state["SPMetadata"])');
		assert('isset($state["saml:ConsumerURL"])');
		assert('array_key_exists("saml:RequestId", $state)'); // Can be NULL.
		assert('array_key_exists("saml:RelayState", $state)'); // Can be NULL.

		$spMetadata = $state["SPMetadata"];
		$spEntityId = $spMetadata['entityid'];
		$spMetadata = SimpleSAML_Configuration::loadFromArray($spMetadata,
			'$metadata[' . var_export($spEntityId, TRUE) . ']');

		SimpleSAML_Logger::info('Sending SAML 2.0 Response to ' . var_export($spEntityId, TRUE));

		$requestId = $state['saml:RequestId'];
		$relayState = $state['saml:RelayState'];
		$consumerURL = $state['saml:ConsumerURL'];
		$protocolBinding = $state['saml:Binding'];

		$idp = SimpleSAML_IdP::getByState($state);

		$idpMetadata = $idp->getConfig();

		$assertion = self::buildAssertion($idpMetadata, $spMetadata, $state);
		$assertion->setInResponseTo($requestId);
		
		if (isset($state['saml:AuthenticatingAuthority'])) {
			$assertion->setAuthenticatingAuthority($state['saml:AuthenticatingAuthority']);
		}

		/* Create the session association (for logout). */
		$association = array(
			'id' => 'saml:' . $spEntityId,
			'Handler' => 'sspmod_saml_IdP_SAML2',
			'Expires' => $assertion->getSessionNotOnOrAfter(),
			'saml:entityID' => $spEntityId,
			'saml:NameID' => $assertion->getNameId(),
			'saml:SessionIndex' => $assertion->getSessionIndex(),
		);

		/* Maybe encrypt the assertion. */
		$assertion = self::encryptAssertion($idpMetadata, $spMetadata, $assertion);

		/* Create the response. */
		$ar = self::buildResponse($idpMetadata, $spMetadata, $consumerURL);
		$ar->setInResponseTo($requestId);
		$ar->setRelayState($relayState);
		$ar->setAssertions(array($assertion));

		/* Register the session association with the IdP. */
		$idp->addAssociation($association);

		/* Send the response. */
		$binding = SAML2_Binding::getBinding($protocolBinding);
		$binding->setDestination(sspmod_saml_Message::getDebugDestination());
		$binding->send($ar);
	}


	/**
	 * Handle authentication error.
	 *
	 * SimpleSAML_Error_Exception $exception  The exception.
	 * @param array $state  The error state.
	 */
	public static function handleAuthError(SimpleSAML_Error_Exception $exception, array $state) {
		assert('isset($state["SPMetadata"])');
		assert('isset($state["saml:ConsumerURL"])');
		assert('array_key_exists("saml:RequestId", $state)'); // Can be NULL.
		assert('array_key_exists("saml:RelayState", $state)'); // Can be NULL.

		$spMetadata = $state["SPMetadata"];
		$spEntityId = $spMetadata['entityid'];
		$spMetadata = SimpleSAML_Configuration::loadFromArray($spMetadata,
			'$metadata[' . var_export($spEntityId, TRUE) . ']');

		$requestId = $state['saml:RequestId'];
		$relayState = $state['saml:RelayState'];
		$consumerURL = $state['saml:ConsumerURL'];
		$protocolBinding = $state['saml:Binding'];

		$idp = SimpleSAML_IdP::getByState($state);

		$idpMetadata = $idp->getConfig();

		$error = sspmod_saml_Error::fromException($exception);

		SimpleSAML_Logger::warning('Returning error to sp: ' . var_export($spEntityId, TRUE));
		$error->logWarning();

		$ar = self::buildResponse($idpMetadata, $spMetadata, $consumerURL);
		$ar->setInResponseTo($requestId);
		$ar->setRelayState($relayState);

		$ar->setStatus(array(
			'Code' => $error->getStatus(),
			'SubCode' => $error->getSubStatus(),
			'Message' => $error->getStatusMessage(),
		));

		$binding = SAML2_Binding::getBinding($protocolBinding);
		$binding->setDestination(sspmod_saml_Message::getDebugDestination());
		$binding->send($ar);
	}


	/**
	 * Receive an authentication request.
	 *
	 * @param SimpleSAML_IdP $idp  The IdP we are receiving it for.
	 */
	public static function receiveAuthnRequest(SimpleSAML_IdP $idp) {

		$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
		$idpMetadata = $idp->getConfig();

		$supportedBindings = array(SAML2_Const::BINDING_HTTP_POST);
		if ($idpMetadata->getBoolean('saml20.sendartifact', FALSE)) {
			$supportedBindings[] = SAML2_Const::BINDING_HTTP_ARTIFACT;
		}

		if (isset($_REQUEST['spentityid'])) {
			/* IdP initiated authentication. */

			if (isset($_REQUEST['cookieTime'])) {
				$cookieTime = (int)$_REQUEST['cookieTime'];
				if ($cookieTime + 5 > time()) {
					/*
					 * Less than five seconds has passed since we were
					 * here the last time. Cookies are probably disabled.
					 */
					SimpleSAML_Utilities::checkCookie(SimpleSAML_Utilities::selfURL());
				}
			}

			$spEntityId = (string)$_REQUEST['spentityid'];
			$spMetadata = $metadata->getMetaDataConfig($spEntityId, 'saml20-sp-remote');

			if (isset($_REQUEST['RelayState'])) {
				$relayState = (string)$_REQUEST['RelayState'];
			} else {
				$relayState = NULL;
			}

			if (isset($_REQUEST['binding'])){
				$protocolBinding = (string)$_REQUEST['binding'];
			} else {
				$protocolBinding = NULL;
			}

			if (isset($_REQUEST['NameIDFormat'])) {
				$nameIDFormat = (string)$_REQUEST['NameIDFormat'];
			} else {
				$nameIDFormat = NULL;
			}

			$requestId = NULL;
			$IDPList = array();
			$forceAuthn = FALSE;
			$isPassive = FALSE;
			$consumerURL = NULL;

			SimpleSAML_Logger::info('SAML2.0 - IdP.SSOService: IdP initiated authentication: '. var_export($spEntityId, TRUE));

		} else {

			$binding = SAML2_Binding::getCurrentBinding();
			$request = $binding->receive();

			if (!($request instanceof SAML2_AuthnRequest)) {
				throw new SimpleSAML_Error_BadRequest('Message received on authentication request endpoint wasn\'t an authentication request.');
			}<commit_msg>IdP/SAML2: Avoid unset-variable warnings during IdP-initiated SSO.<commit_after><?php

/**
 * IdP implementation for SAML 2.0 protocol.
 *
 * @package simpleSAMLphp
 * @version $Id$
 */
class sspmod_saml_IdP_SAML2 {

	/**
	 * Send a response to the SP.
	 *
	 * @param array $state  The authentication state.
	 */
	public static function sendResponse(array $state) {
		assert('isset($state["Attributes"])');
		assert('isset($state["SPMetadata"])');
		assert('isset($state["saml:ConsumerURL"])');
		assert('array_key_exists("saml:RequestId", $state)'); // Can be NULL.
		assert('array_key_exists("saml:RelayState", $state)'); // Can be NULL.

		$spMetadata = $state["SPMetadata"];
		$spEntityId = $spMetadata['entityid'];
		$spMetadata = SimpleSAML_Configuration::loadFromArray($spMetadata,
			'$metadata[' . var_export($spEntityId, TRUE) . ']');

		SimpleSAML_Logger::info('Sending SAML 2.0 Response to ' . var_export($spEntityId, TRUE));

		$requestId = $state['saml:RequestId'];
		$relayState = $state['saml:RelayState'];
		$consumerURL = $state['saml:ConsumerURL'];
		$protocolBinding = $state['saml:Binding'];

		$idp = SimpleSAML_IdP::getByState($state);

		$idpMetadata = $idp->getConfig();

		$assertion = self::buildAssertion($idpMetadata, $spMetadata, $state);
		$assertion->setInResponseTo($requestId);
		
		if (isset($state['saml:AuthenticatingAuthority'])) {
			$assertion->setAuthenticatingAuthority($state['saml:AuthenticatingAuthority']);
		}

		/* Create the session association (for logout). */
		$association = array(
			'id' => 'saml:' . $spEntityId,
			'Handler' => 'sspmod_saml_IdP_SAML2',
			'Expires' => $assertion->getSessionNotOnOrAfter(),
			'saml:entityID' => $spEntityId,
			'saml:NameID' => $assertion->getNameId(),
			'saml:SessionIndex' => $assertion->getSessionIndex(),
		);

		/* Maybe encrypt the assertion. */
		$assertion = self::encryptAssertion($idpMetadata, $spMetadata, $assertion);

		/* Create the response. */
		$ar = self::buildResponse($idpMetadata, $spMetadata, $consumerURL);
		$ar->setInResponseTo($requestId);
		$ar->setRelayState($relayState);
		$ar->setAssertions(array($assertion));

		/* Register the session association with the IdP. */
		$idp->addAssociation($association);

		/* Send the response. */
		$binding = SAML2_Binding::getBinding($protocolBinding);
		$binding->setDestination(sspmod_saml_Message::getDebugDestination());
		$binding->send($ar);
	}


	/**
	 * Handle authentication error.
	 *
	 * SimpleSAML_Error_Exception $exception  The exception.
	 * @param array $state  The error state.
	 */
	public static function handleAuthError(SimpleSAML_Error_Exception $exception, array $state) {
		assert('isset($state["SPMetadata"])');
		assert('isset($state["saml:ConsumerURL"])');
		assert('array_key_exists("saml:RequestId", $state)'); // Can be NULL.
		assert('array_key_exists("saml:RelayState", $state)'); // Can be NULL.

		$spMetadata = $state["SPMetadata"];
		$spEntityId = $spMetadata['entityid'];
		$spMetadata = SimpleSAML_Configuration::loadFromArray($spMetadata,
			'$metadata[' . var_export($spEntityId, TRUE) . ']');

		$requestId = $state['saml:RequestId'];
		$relayState = $state['saml:RelayState'];
		$consumerURL = $state['saml:ConsumerURL'];
		$protocolBinding = $state['saml:Binding'];

		$idp = SimpleSAML_IdP::getByState($state);

		$idpMetadata = $idp->getConfig();

		$error = sspmod_saml_Error::fromException($exception);

		SimpleSAML_Logger::warning('Returning error to sp: ' . var_export($spEntityId, TRUE));
		$error->logWarning();

		$ar = self::buildResponse($idpMetadata, $spMetadata, $consumerURL);
		$ar->setInResponseTo($requestId);
		$ar->setRelayState($relayState);

		$ar->setStatus(array(
			'Code' => $error->getStatus(),
			'SubCode' => $error->getSubStatus(),
			'Message' => $error->getStatusMessage(),
		));

		$binding = SAML2_Binding::getBinding($protocolBinding);
		$binding->setDestination(sspmod_saml_Message::getDebugDestination());
		$binding->send($ar);
	}


	/**
	 * Receive an authentication request.
	 *
	 * @param SimpleSAML_IdP $idp  The IdP we are receiving it for.
	 */
	public static function receiveAuthnRequest(SimpleSAML_IdP $idp) {

		$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
		$idpMetadata = $idp->getConfig();

		$supportedBindings = array(SAML2_Const::BINDING_HTTP_POST);
		if ($idpMetadata->getBoolean('saml20.sendartifact', FALSE)) {
			$supportedBindings[] = SAML2_Const::BINDING_HTTP_ARTIFACT;
		}

		if (isset($_REQUEST['spentityid'])) {
			/* IdP initiated authentication. */

			if (isset($_REQUEST['cookieTime'])) {
				$cookieTime = (int)$_REQUEST['cookieTime'];
				if ($cookieTime + 5 > time()) {
					/*
					 * Less than five seconds has passed since we were
					 * here the last time. Cookies are probably disabled.
					 */
					SimpleSAML_Utilities::checkCookie(SimpleSAML_Utilities::selfURL());
				}
			}

			$spEntityId = (string)$_REQUEST['spentityid'];
			$spMetadata = $metadata->getMetaDataConfig($spEntityId, 'saml20-sp-remote');

			if (isset($_REQUEST['RelayState'])) {
				$relayState = (string)$_REQUEST['RelayState'];
			} else {
				$relayState = NULL;
			}

			if (isset($_REQUEST['binding'])){
				$protocolBinding = (string)$_REQUEST['binding'];
			} else {
				$protocolBinding = NULL;
			}

			if (isset($_REQUEST['NameIDFormat'])) {
				$nameIDFormat = (string)$_REQUEST['NameIDFormat'];
			} else {
				$nameIDFormat = NULL;
			}

			$requestId = NULL;
			$IDPList = array();
			$ProxyCount = NULL;
			$RequesterID = NULL;
			$forceAuthn = FALSE;
			$isPassive = FALSE;
			$consumerURL = NULL;

			SimpleSAML_Logger::info('SAML2.0 - IdP.SSOService: IdP initiated authentication: '. var_export($spEntityId, TRUE));

		} else {

			$binding = SAML2_Binding::getCurrentBinding();
			$request = $binding->receive();

			if (!($request instanceof SAML2_AuthnRequest)) {
				throw new SimpleSAML_Error_BadRequest('Message received on authentication request endpoint wasn\'t an authentication request.');
			}
{'fraction_non_alphanumeric': 0.16711431928823234, 'fraction_numerical': 0.0032734597951989256, 'mean_word_length': 5.069791136016302, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 75, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '946380', 'n_tokens_mistral': 4420, 'n_tokens_neox': 3843, 'n_words': 684}