Improve third-party storage access detection and cookie fallback

This commit is contained in:
Jon Koops 2023-05-23 11:42:34 +02:00 committed by Pedro Igor
parent b958d8b205
commit 98e5e9799b
4 changed files with 118 additions and 126 deletions

View file

@ -1,29 +1,58 @@
<!DOCTYPE html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
</head> </head>
<body> <body>
<script> <script type="module">
if ("hasStorageAccess" in document) { // Check if the browser has granted us access to 3rd-party storage (such as cookies).
checkStorageAccess(); if (await hasStorageAccess()) {
// If so, signal support to the page embedding this iframe.
window.parent.postMessage("supported", "*");
} else { } else {
placeTestCookie(); // Otherwise, attempt to place a test cookie to verify support.
attemptWithTestCookie();
} }
function checkStorageAccess() { // See: https://developer.mozilla.org/en-US/docs/Web/API/Storage_Access_API/Using
document.hasStorageAccess().then(function (hasAccess) { async function hasStorageAccess() {
window.parent.postMessage( // If the Storage Access API is not implemented, assume we don't have access.
hasAccess ? "supported" : "unsupported", if (!("hasStorageAccess" in document)) {
"*" return false;
); }
const hasAccess = await document.hasStorageAccess();
// If we have access to unpartitioned cookies, signal support.
if (hasAccess) {
return true;
}
// Otherwise, check whether unpartitioned cookie access has been granted to another same-site embed.
const permission = await navigator.permissions.query({
name: "storage-access",
}); });
// If not, signal that there is no support.
if (permission.state !== "granted") {
return false;
}
// Otherwise, call requestStorageAccess() without a user interaction, and it should resolve automatically.
// But just to be sure, handle a possible exception in case this behavior changes in the future.
try {
await document.requestStorageAccess();
return true;
} catch (error) {
return false;
}
} }
function placeTestCookie() { function attemptWithTestCookie() {
document.cookie = // Place a cookie to test whether we can access cookies from 3rd-party storage.
"KEYCLOAK_3P_COOKIE_SAMESITE=supported; Max-Age=60; SameSite=None; Secure"; document.cookie = "KEYCLOAK_3P_COOKIE_SAMESITE=supported; Max-Age=60; SameSite=None; Secure";
document.cookie = "KEYCLOAK_3P_COOKIE=supported; Max-Age=60"; document.cookie = "KEYCLOAK_3P_COOKIE=supported; Max-Age=60";
// Then redirect to the page where we will read these cookies to confirm this.
window.location = "step2.html"; window.location = "step2.html";
} }
</script> </script>

View file

@ -1,17 +1,20 @@
<!DOCTYPE html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
</head> </head>
<body> <body>
<script> <script type="module">
var hasAccess = document.cookie.indexOf("KEYCLOAK_3P_COOKIE") !== -1; // Check if the previously placed cookies exist to detect support for 3rd-party access.
const hasAccess = document.cookie.includes("KEYCLOAK_3P_COOKIE");
// If so, clear the cookies, so they can no longer be used.
if (hasAccess) { if (hasAccess) {
document.cookie = "KEYCLOAK_3P_COOKIE_SAMESITE=; Max-Age=0"; document.cookie = "KEYCLOAK_3P_COOKIE_SAMESITE=; Max-Age=0";
document.cookie = "KEYCLOAK_3P_COOKIE=; Max-Age=0"; document.cookie = "KEYCLOAK_3P_COOKIE=; Max-Age=0";
} }
// Signal 3rd-party access support to the page embedding this iframe.
window.parent.postMessage(hasAccess ? "supported" : "unsupported", "*"); window.parent.postMessage(hasAccess ? "supported" : "unsupported", "*");
</script> </script>
</body> </body>

View file

@ -1,125 +1,88 @@
<!DOCTYPE html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
</head> </head>
<body> <body>
<script> <script type="module">
var init; window.addEventListener("message", onMessage);
function checkState(clientId, origin, sessionState, callback) { async function onMessage(event) {
var cookie = getCookie(); // Filter out any events that do not match the expected format of a 2-part string split by a space.
var checkCookie = function () {
if (clientId === init.clientId && origin === init.origin) {
var c = cookie.split("/");
if (sessionState === c[2]) {
callback("unchanged");
} else {
callback("changed");
}
} else {
callback("error");
}
};
if (!init) {
var req = new XMLHttpRequest();
var url = location.href.split("?")[0] + "/init";
url += "?client_id=" + encodeURIComponent(clientId);
url += "&origin=" + encodeURIComponent(origin);
req.open("GET", url, true);
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (req.status === 204 || req.status === 1223) {
init = {
clientId: clientId,
origin: origin,
};
if (!cookie) {
if (sessionState != "") {
callback("changed");
} else {
callback("unchanged");
}
} else {
checkCookie();
}
} else {
callback("error");
}
}
};
req.send();
} else if (!cookie) {
if (sessionState != "") {
callback("changed");
} else {
callback("unchanged");
}
} else {
checkCookie();
}
}
function getCookie() {
var cookie = getCookieByName("KEYCLOAK_SESSION");
if (cookie === null) {
return getCookieByName("KEYCLOAK_SESSION_LEGACY");
}
return cookie;
}
function getCookieByName(name) {
name = name + "=";
var ca = document.cookie.split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
}
return null;
}
function receiveMessage(event) {
if (typeof event.data !== "string") { if (typeof event.data !== "string") {
return; return;
} }
var origin = event.origin; const data = event.data.split(" ");
var data = event.data.split(" ");
if (data.length != 2) { if (data.length !== 2) {
return; return;
} }
var clientId = data[0]; // Extract data from event and verify status of session.
var sessionState = data[1]; const [clientId, sessionState] = data;
const sessionStatus = await checkState(clientId, event.origin, sessionState);
function doStateCheck() { // Signal session status to the page embedding this iframe.
checkState(clientId, event.origin, sessionState, function (result) { event.source.postMessage(sessionStatus, event.origin);
event.source.postMessage(result, origin);
});
}
if (!("hasStorageAccess" in document)) {
doStateCheck();
return;
}
document.hasStorageAccess().then(function (hasAccess) {
if (!hasAccess) {
event.source.postMessage("error");
return;
}
doStateCheck();
});
} }
window.addEventListener("message", receiveMessage, false); let init;
async function checkState(clientId, origin, sessionState) {
const cookie = getSessionCookie();
// If not initialized, verify this client is allowed access with a call to the server.
if (!init) {
const url = new URL(`${location.origin}${location.pathname}/init`);
url.searchParams.set("client_id", clientId);
url.searchParams.set("origin", origin);
const response = await fetch(url);
if (!response.ok) {
return "error";
}
init = { clientId, origin };
}
// Signal a change in state if there is no cookie, and the session state is not empty.
if (!cookie) {
return sessionState !== "" ? "changed" : "unchanged";
}
// If the client and origin from the event match the verified ones from the server, signal if the cookie has changed.
if (clientId === init.clientId && origin === init.origin) {
const [, , cookieSessionState] = cookie.split("/");
return sessionState === cookieSessionState ? "unchanged" : "changed";
}
// Otherwise, if there is no match, then signal an error.
return "error";
}
function getSessionCookie() {
const cookie = getCookieByName("KEYCLOAK_SESSION");
if (cookie !== null) {
return cookie;
}
return getCookieByName("KEYCLOAK_SESSION_LEGACY");
}
function getCookieByName(name) {
const cookies = new Map();
for (const cookie of document.cookie.split(";")) {
const [key, value] = cookie.split("=").map((value) => value.trim());
cookies.set(key, value);
}
return cookies.get(name) ?? null;
}
</script> </script>
</body> </body>
</html> </html>

View file

@ -123,9 +123,6 @@ public class LoginStatusIframeEndpointTest extends AbstractKeycloakTest {
response = client.execute(get); response = client.execute(get);
assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode());
s = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
assertTrue(s.contains("function getCookie()"));
assertEquals("CP=\"This is not a P3P policy!\"", response.getFirstHeader("P3P").getValue()); assertEquals("CP=\"This is not a P3P policy!\"", response.getFirstHeader("P3P").getValue());
assertNull(response.getFirstHeader(BrowserSecurityHeaders.X_FRAME_OPTIONS.getHeaderName())); assertNull(response.getFirstHeader(BrowserSecurityHeaders.X_FRAME_OPTIONS.getHeaderName()));
assertEquals("frame-src 'self'; object-src 'none';", response.getFirstHeader(BrowserSecurityHeaders.CONTENT_SECURITY_POLICY.getHeaderName()).getValue()); assertEquals("frame-src 'self'; object-src 'none';", response.getFirstHeader(BrowserSecurityHeaders.CONTENT_SECURITY_POLICY.getHeaderName()).getValue());