<!DOCTYPE html>
<html>
<head>
    <script src="/js-test-resources/js-test.js"></script>
    <script src="/js-test-resources/ui-helper.js"></script>
    <script src="/resourceLoadStatistics/resources/util.js"></script>
</head>
<body>
    <script>
        description("Tests that cross-origin iframe storage access is granted if the iframe is sandboxed, has the allow token, the iframe origin is a prevalent resource, the iframe origin has had user interaction, the user opts in, and the frame is the one with access.");
        jsTestIsAsync = true;

        const hostUnderTest = "localhost:8000";
        const statisticsUrl = "http://" + hostUnderTest + "/temp";

        const partitionHost = "127.0.0.1:8000";
        const thirdPartyOrigin = "http://localhost:8000";
        const resourcePath = "/storageAccess/resources";
        const thirdPartyBaseUrl = thirdPartyOrigin + resourcePath;
        const firstPartyCookieName = "firstPartyCookie";
        const subPathToSetFirstPartyCookie = "/set-cookie.py?name=" + firstPartyCookieName + "&value=value";
        const partitionedCookieName = "partitionedCookie";
        const subPathToSetPartitionedCookie = "/set-cookie.py?name=" + partitionedCookieName + "&value=value";
        const returnUrl = "http://" + partitionHost + "/storageAccess/request-and-grant-access-cross-origin-sandboxed-iframe-from-prevalent-domain-with-user-interaction-and-access-from-right-frame.html";
        const subPathToGetCookies = "/get-cookies.py?name1=" + firstPartyCookieName + "&name2=" + partitionedCookieName;

        function openIframe(url, onLoadHandler) {
            const element = document.createElement("iframe");
            element.src = url;
            if (onLoadHandler) {
                element.onload = onLoadHandler;
            }
            document.body.appendChild(element);
        }

        function receiveMessage(event) {
            if (event.origin === "http://localhost:8000") {
                if (event.data.indexOf("PASS") !== -1)
                    testPassed(event.data.replace("PASS ", ""));
                else
                    testFailed(event.data);
            } else
                testFailed("Received a message from an unexpected origin: " + event.origin);
            runTest();
        }

        function activateElement(elementId) {
            var element = document.getElementById(elementId);
            var centerX = element.offsetLeft + element.offsetWidth / 2;
            var centerY = element.offsetTop + element.offsetHeight / 2;
            UIHelper.activateAt(centerX, centerY).then(
                function () {
                    if (window.eventSender)
                        eventSender.keyDown("escape");
                    else {
                        testFailed("No eventSender.");
                        setEnableFeature(false, finishJSTest);
                    }
                },
                function () {
                    testFailed("Promise rejected.");
                    setEnableFeature(false, finishJSTest);
                }
            );
        }

        function runTest() {
            switch (document.location.hash) {
                case "#step1":
                    if (testRunner.isStatisticsPrevalentResource(statisticsUrl))
                        testFailed("Host prematurely set as prevalent resource.");
                    // Set first-party cookie for localhost.
                    document.location.href = thirdPartyBaseUrl + subPathToSetFirstPartyCookie + "#" + returnUrl + "#step2";
                    break;
                case "#step2":
                    document.location.hash = "step3";
                    // Check that the first-party cookie does get sent for localhost under 127.0.0.1.
                    openIframe(thirdPartyBaseUrl + subPathToGetCookies + "&message=Should receive first-party cookie.", runTest);
                    break;
                case "#step3":
                    document.location.hash = "step4";
                    // Set localhost as prevalent with user interaction.
                    testRunner.setStatisticsHasHadUserInteraction(statisticsUrl, true, function() {
                        if (!testRunner.isStatisticsHasHadUserInteraction(statisticsUrl))
                            testFailed("Host did not get logged for user interaction.");
                        testRunner.setStatisticsPrevalentResource(statisticsUrl, true, function() {
                            if (!testRunner.isStatisticsPrevalentResource(statisticsUrl))
                                testFailed("Host did not get set as prevalent resource.");
                            testRunner.statisticsUpdateCookieBlocking(function() {
                                // Check that the first-party cookie does not get sent for localhost under 127.0.0.1.
                                openIframe(thirdPartyBaseUrl + subPathToGetCookies + "&message=Should not receive cookies.", runTest);
                            });
                        });
                    });
                    break;
                case "#step4":
                    document.location.hash = "step5";
                    // Try to set a cookie for localhost.
                    openIframe(thirdPartyBaseUrl + subPathToSetPartitionedCookie, runTest);
                    break;
                case "#step5":
                    document.location.hash = "step6";
                    // Check that no cookie gets sent for localhost under 127.0.0.1.
                    openIframe(thirdPartyBaseUrl + subPathToGetCookies + "&message=Should not receive cookies.", runTest);
                    break;
                case "#step6":
                    document.location.hash = "step7";
                    // Set per-frame access since clearing access on cross-site navigation of the iframe requires per-frame access.
                    internals.settings.setStorageAccessAPIPerPageScopeEnabled(false);
                    // Create iframe that will request storage access.
                    let iframeElement = document.createElement("iframe");
                    iframeElement.setAttribute("sandbox", "allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-modals");
                    iframeElement.onload = function() {
                        testRunner.statisticsUpdateCookieBlocking(function() {
                            activateElement("TheIframeThatRequestsStorageAccess");
                        });
                    };
                    iframeElement.id = "TheIframeThatRequestsStorageAccess";
                    iframeElement.src = "http://localhost:8000/storageAccess/resources/request-storage-access-iframe.html?bogus#userShouldGrantAccess,userShouldBeConsulted,policyShouldGrantAccess,isNotSameOriginIframe";
                    document.body.appendChild(iframeElement);
                    break;
                case "#step7":
                    document.location.hash = "step8";
                    // Navigate the frame same-site.
                    let existingIframe1 = document.getElementById("TheIframeThatRequestsStorageAccess");
                    existingIframe1.onload = function () {
                        debug("Did navigate iframe same-site and will now check that it still has storage access.");
                        let iframe = document.getElementById("TheIframeThatRequestsStorageAccess");
                        iframe.contentWindow.postMessage("reportBackCookies", "http://localhost:8000");
                    };
                    existingIframe1.src = thirdPartyBaseUrl + subPathToGetCookies;
                    break;
                case "#step8":
                    document.location.hash = "step9";
                    // Navigate the frame cross-site. This should clear out storage access.
                    let existingIframe2 = document.getElementById("TheIframeThatRequestsStorageAccess");
                    existingIframe2.onload = runTest;
                    existingIframe2.src = "http://" + partitionHost;
                    break;
                case "#step9":
                    document.location.hash = "step10";
                    // Again open localhost in the existing frame and check that no cookie gets sent for localhost under 127.0.0.1 since it has been navigated cross-site.
                    let existingIframe3 = document.getElementById("TheIframeThatRequestsStorageAccess");
                    existingIframe3.onload = runTest;
                    existingIframe3.src = thirdPartyBaseUrl + subPathToGetCookies + "&message=After the top frame navigates the sub frame cross-site and back, the sub frame should no longer have access to cookies.";
                    break;
                case "#step10":
                    // Reset access scope.
                    internals.settings.setStorageAccessAPIPerPageScopeEnabled(true);
                    setEnableFeature(false, finishJSTest);
                    break;
            }
        }

        if (document.location.hash === "") {
            setEnableFeature(true, function() {
                if (testRunner.isStatisticsPrevalentResource(thirdPartyBaseUrl))
                    testFailed("Localhost was classified as prevalent resource before the test starts.");
                testRunner.dumpChildFramesAsText();
                document.location.hash = "step1";
            });
        }

        window.addEventListener("message", receiveMessage, false);

        runTest();
    </script>
</body>
</html>
