<?php

use RobRichards\XMLSecLibs\XMLSecurityKey;
use RobRichards\XMLSecLibs\XMLSecurityDSig;

require_once __DIR__ . '/vendor/autoload.php';


session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


if (!isset($_SESSION['user'])) {
    header('Location: login.php');
    exit;
}

// Load your IdP private key and certificate
$privateKey = file_get_contents('private_key.pem');
$certificate = file_get_contents('certificate.pem');

// Function to sign XML
function signXML($xml, $privateKey, $certificate) {
    $dom = new DOMDocument();
    $dom->loadXML($xml);
    
    $objDSig = new XMLSecurityDSig();
    $objDSig->setCanonicalMethod(XMLSecurityDSig::EXC_C14N);
    $objDSig->addReference(
        $dom, 
        XMLSecurityDSig::SHA256, 
        ['http://www.w3.org/2000/09/xmldsig#enveloped-signature']
    );
    
    $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, array('type'=>'private'));
    $objKey->loadKey($privateKey);
    
    $objDSig->sign($objKey);
    $objDSig->add509Cert($certificate);
    $objDSig->appendSignature($dom->documentElement);
    
    return $dom->saveXML();
}

// Create a simple SAML response
$now = time();
$notBefore = $now - 300;
$notOnOrAfter = $now + 300;

$samlResponse = <<<XML
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
                xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
                ID="_" Version="2.0"
                IssueInstant="{$now}"
                Destination="https://us-east-1.signin.aws.amazon.com/platform/saml/acs/bcc03dc7-250f-467c-87b7-1d93e2b13158">
    <saml:Issuer>https://your-idp-entity-id.com</saml:Issuer>
    <saml:Assertion xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xmlns:xs="http://www.w3.org/2001/XMLSchema"
                    ID="_" Version="2.0"
                    IssueInstant="{$now}">
        <saml:Issuer>https://your-idp-entity-id.com</saml:Issuer>
        <saml:Subject>
            <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">{$_SESSION['user']}</saml:NameID>
            <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
                <saml:SubjectConfirmationData NotOnOrAfter="{$notOnOrAfter}"
                                              Recipient="https://us-east-1.signin.aws.amazon.com/platform/saml/acs/bcc03dc7-250f-467c-87b7-1d93e2b13158"/>
            </saml:SubjectConfirmation>
        </saml:Subject>
        <saml:Conditions NotBefore="{$notBefore}" NotOnOrAfter="{$notOnOrAfter}">
            <saml:AudienceRestriction>
                <saml:Audience>urn:amazon:webservices</saml:Audience>
            </saml:AudienceRestriction>
        </saml:Conditions>
        <saml:AuthnStatement AuthnInstant="{$now}">
            <saml:AuthnContext>
                <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>
            </saml:AuthnContext>
        </saml:AuthnStatement>
    </saml:Assertion>
</samlp:Response>
XML;


// Sign the SAML response
$signedResponse = signXML($samlResponse, $privateKey, $certificate);

// Encode the signed response
$encodedResponse = base64_encode($signedResponse);

// Redirect to AWS with the SAML response
?>
<!DOCTYPE html>
<html>
<head>
    <title>Redirecting to AWS</title>
</head>
<body onload="document.forms[0].submit()">
    <form method="post" action="https://us-east-1.signin.aws.amazon.com/platform/saml/acs/bcc03dc7-250f-467c-87b7-1d93e2b13158">
        <input type="hidden" name="SAMLResponse" value="<?php echo htmlspecialchars($encodedResponse); ?>">
        <noscript>
            <p>JavaScript is disabled. Click the button below to continue:</p>
            <input type="submit" value="Continue to AWS">
        </noscript>
    </form>
</body>
</html>