Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f077e5038e | ||
|
|
e4eb7e54f7 | ||
|
|
bdde0feb86 | ||
|
|
3da8e609ae | ||
|
|
ed064473dc | ||
|
|
a84f7d50a1 |
@@ -0,0 +1,18 @@
|
||||
# Federated account key: `sub`, not email
|
||||
|
||||
외부 IdP의 email은 표시·연락 속성이지 계정 식별자나 자동 연결 증명이 아니다.
|
||||
Keycloak의 federated identity는 provider alias와 provider user ID(`sub`)를
|
||||
로컬 사용자에 연결한다.
|
||||
|
||||
정책:
|
||||
|
||||
- 신규 identity의 email이 기존 로컬 계정과 충돌하면 기존 계정의 인증을 다시
|
||||
요구하는 기본 First Broker Login flow를 사용한다.
|
||||
- `Automatically Set Existing User`를 production flow에 넣지 않는다.
|
||||
- upstream email 변경은 같은 `sub`의 계정 귀속을 바꾸지 않는다.
|
||||
- 마지막 로그인 수단을 unlink하는 UI에서는 먼저 다른 인증 수단을 등록하도록
|
||||
안내한다.
|
||||
|
||||
`verify-account-linking-sub-vs-email.sh`는 mock IdP 사용자의 email을 실제로
|
||||
변경하고 다시 로그인한다. 로컬 사용자 ID가 유지되고 federated `userId`가
|
||||
upstream `sub`와 같은지 확인한 후 원래 email을 복구한다.
|
||||
@@ -0,0 +1,18 @@
|
||||
# Google claim-to-role mapping
|
||||
|
||||
`hd=example.test`인 upstream OIDC identity에는 Keycloak realm role
|
||||
`employee-role`을 부여한다. 매핑 키는 email이 아니라 Google subject이며,
|
||||
role 조건에 쓰는 `hd` claim은 mock provider와 실제 Google provider에서 같은
|
||||
계약을 사용한다.
|
||||
|
||||
Realm import는 `oidc-role-idp-mapper`를 선언한다. 실제 Google 설정 스크립트도
|
||||
같은 mapper를 upsert한다. 따라서 재실행해도 mapper가 중복되지 않는다.
|
||||
|
||||
검증:
|
||||
|
||||
```sh
|
||||
./scripts/verify-google-claim-to-role.sh
|
||||
```
|
||||
|
||||
검증기는 mock Google 로그인, Authorization Code + PKCE 교환, 최종 Keycloak
|
||||
access token의 `realm_access.roles`를 차례로 확인한다.
|
||||
@@ -0,0 +1,24 @@
|
||||
# Google redirect URI policy
|
||||
|
||||
Google에 등록하는 redirect URI는 애플리케이션 SPA callback이 아니라 Keycloak
|
||||
broker endpoint다.
|
||||
|
||||
```text
|
||||
https://auth.example.test/realms/keycloak-patterns/broker/google/endpoint
|
||||
```
|
||||
|
||||
규칙:
|
||||
|
||||
- production URI는 HTTPS와 고정된 public Keycloak origin을 사용한다.
|
||||
- wildcard, path prefix, 임시 tunnel hostname을 production OAuth client에
|
||||
등록하지 않는다.
|
||||
- 개발·스테이징·운영은 Google OAuth client를 분리한다.
|
||||
- reverse proxy가 있더라도 Google이 보는 URI와 Keycloak이 생성하는 URI가
|
||||
byte-for-byte 같아야 한다.
|
||||
- `configure-google-idp.sh`가 출력하는 URI를 Google Console의 Authorized
|
||||
redirect URI와 대조한다.
|
||||
|
||||
```sh
|
||||
PUBLIC_KEYCLOAK_URL=https://auth.example.test \
|
||||
./scripts/verify-google-redirect-uri-policy.sh
|
||||
```
|
||||
@@ -0,0 +1,68 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { chromium } from "playwright-core";
|
||||
|
||||
const keycloakUrl = process.env.KEYCLOAK_URL ?? "http://localhost:8080";
|
||||
const password = process.env.MOCK_GOOGLE_USER_PASSWORD;
|
||||
assert.ok(password);
|
||||
|
||||
const verifier = randomBytes(48).toString("base64url");
|
||||
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
||||
const redirectUri = "http://localhost:8088/";
|
||||
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.CHROME_BIN ?? "/usr/bin/google-chrome",
|
||||
headless: true,
|
||||
args: ["--no-sandbox"],
|
||||
});
|
||||
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
const authorizationUrl = new URL(
|
||||
`${keycloakUrl}/realms/keycloak-patterns/protocol/openid-connect/auth`,
|
||||
);
|
||||
authorizationUrl.search = new URLSearchParams({
|
||||
client_id: "spa-public",
|
||||
redirect_uri: redirectUri,
|
||||
response_type: "code",
|
||||
scope: "openid profile email",
|
||||
state: crypto.randomUUID(),
|
||||
nonce: crypto.randomUUID(),
|
||||
code_challenge: challenge,
|
||||
code_challenge_method: "S256",
|
||||
kc_idp_hint: "mock-google",
|
||||
prompt: "login",
|
||||
});
|
||||
|
||||
await page.goto(authorizationUrl.toString());
|
||||
await page.waitForURL(/\/realms\/mock-google\//u);
|
||||
await page.locator("#username").fill("mock-new-user");
|
||||
await page.locator("#password").fill(password);
|
||||
await page.locator("#kc-login").click();
|
||||
await page.waitForURL(/localhost:8088\/\?.*code=/u);
|
||||
|
||||
const code = new URL(page.url()).searchParams.get("code");
|
||||
assert.ok(code);
|
||||
const response = await fetch(
|
||||
`${keycloakUrl}/realms/keycloak-patterns/protocol/openid-connect/token`,
|
||||
{
|
||||
method: "POST",
|
||||
body: new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
client_id: "spa-public",
|
||||
redirect_uri: redirectUri,
|
||||
code,
|
||||
code_verifier: verifier,
|
||||
}),
|
||||
},
|
||||
);
|
||||
assert.equal(response.status, 200);
|
||||
const tokens = await response.json();
|
||||
const payload = JSON.parse(
|
||||
Buffer.from(tokens.access_token.split(".")[1], "base64url").toString(),
|
||||
);
|
||||
assert.ok(payload.realm_access.roles.includes("employee-role"));
|
||||
console.log("Claim-to-role verified: hd=example.test -> employee-role");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -5,7 +5,9 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test:first-broker": "node first-broker-login.mjs",
|
||||
"test:claim-mapping": "node claim-mapping.mjs"
|
||||
"test:claim-mapping": "node claim-mapping.mjs",
|
||||
"test:claim-to-role": "node claim-to-role.mjs",
|
||||
"test:sub-vs-email": "node sub-vs-email.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"playwright-core": "1.55.1"
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { chromium } from "playwright-core";
|
||||
|
||||
const baseUrl = process.env.KEYCLOAK_URL ?? "http://localhost:8080";
|
||||
const adminUsername = process.env.KC_BOOTSTRAP_ADMIN_USERNAME;
|
||||
const adminPassword = process.env.KC_BOOTSTRAP_ADMIN_PASSWORD;
|
||||
const mockPassword = process.env.MOCK_GOOGLE_USER_PASSWORD;
|
||||
assert.ok(adminUsername && adminPassword && mockPassword);
|
||||
|
||||
async function adminToken() {
|
||||
const response = await fetch(
|
||||
`${baseUrl}/realms/master/protocol/openid-connect/token`,
|
||||
{
|
||||
method: "POST",
|
||||
body: new URLSearchParams({
|
||||
client_id: "admin-cli",
|
||||
grant_type: "password",
|
||||
username: adminUsername,
|
||||
password: adminPassword,
|
||||
}),
|
||||
},
|
||||
);
|
||||
assert.equal(response.status, 200);
|
||||
return (await response.json()).access_token;
|
||||
}
|
||||
|
||||
async function adminJson(token, path, init = {}) {
|
||||
const response = await fetch(`${baseUrl}/admin/realms/${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
...(init.body ? { "Content-Type": "application/json" } : {}),
|
||||
},
|
||||
});
|
||||
assert.ok(response.ok, `${init.method ?? "GET"} ${path}: ${response.status}`);
|
||||
return response.status === 204 ? undefined : response.json();
|
||||
}
|
||||
|
||||
async function users(token, realm, query) {
|
||||
return adminJson(token, `${realm}/users?${new URLSearchParams(query)}`);
|
||||
}
|
||||
|
||||
async function brokerLogin(browser) {
|
||||
const page = await browser.newPage();
|
||||
const url = new URL(
|
||||
`${baseUrl}/realms/keycloak-patterns/protocol/openid-connect/auth`,
|
||||
);
|
||||
url.search = new URLSearchParams({
|
||||
client_id: "spa-public",
|
||||
redirect_uri: "http://localhost:8088/",
|
||||
response_type: "code",
|
||||
scope: "openid profile email",
|
||||
state: crypto.randomUUID(),
|
||||
nonce: crypto.randomUUID(),
|
||||
code_challenge: "K2qUEfBl-nQvF2gB4dNxC2zYVwZc1CVnZb5CsX2L7fI",
|
||||
code_challenge_method: "S256",
|
||||
kc_idp_hint: "mock-google",
|
||||
prompt: "login",
|
||||
});
|
||||
await page.goto(url.toString());
|
||||
await page.waitForURL(/\/realms\/mock-google\//u);
|
||||
await page.locator("#username").fill("mock-new-user");
|
||||
await page.locator("#password").fill(mockPassword);
|
||||
await page.locator("#kc-login").click();
|
||||
await page.waitForURL(/localhost:8088\/\?.*code=/u);
|
||||
await page.close();
|
||||
}
|
||||
|
||||
const token = await adminToken();
|
||||
const mockUsers = await users(token, "mock-google", {
|
||||
username: "mock-new-user",
|
||||
exact: "true",
|
||||
});
|
||||
assert.equal(mockUsers.length, 1);
|
||||
const mockUser = await adminJson(
|
||||
token,
|
||||
`mock-google/users/${mockUsers[0].id}`,
|
||||
);
|
||||
const originalEmail = mockUser.email;
|
||||
const changedEmail = "broker-renamed-user@example.test";
|
||||
|
||||
for (const existing of await users(token, "keycloak-patterns", {
|
||||
username: `mock-google.${mockUser.id}`,
|
||||
exact: "true",
|
||||
})) {
|
||||
await adminJson(token, `keycloak-patterns/users/${existing.id}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
}
|
||||
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.CHROME_BIN ?? "/usr/bin/google-chrome",
|
||||
headless: true,
|
||||
args: ["--no-sandbox"],
|
||||
});
|
||||
|
||||
try {
|
||||
await brokerLogin(browser);
|
||||
const before = await users(token, "keycloak-patterns", {
|
||||
username: `mock-google.${mockUser.id}`,
|
||||
exact: "true",
|
||||
});
|
||||
assert.equal(before.length, 1);
|
||||
const localUserId = before[0].id;
|
||||
const identities = await adminJson(
|
||||
token,
|
||||
`keycloak-patterns/users/${localUserId}/federated-identity`,
|
||||
);
|
||||
assert.equal(identities[0].userId, mockUser.id);
|
||||
|
||||
await adminJson(token, `mock-google/users/${mockUser.id}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ ...mockUser, email: changedEmail }),
|
||||
});
|
||||
await brokerLogin(browser);
|
||||
|
||||
const after = await users(token, "keycloak-patterns", {
|
||||
username: `mock-google.${mockUser.id}`,
|
||||
exact: "true",
|
||||
});
|
||||
assert.equal(after.length, 1);
|
||||
assert.equal(after[0].id, localUserId);
|
||||
console.log(
|
||||
"Federated identity verified: provider sub stayed linked while upstream email changed",
|
||||
);
|
||||
} finally {
|
||||
await adminJson(token, `mock-google/users/${mockUser.id}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ ...mockUser, email: originalEmail }),
|
||||
});
|
||||
await browser.close();
|
||||
}
|
||||
@@ -24,6 +24,10 @@
|
||||
{
|
||||
"name": "user-role",
|
||||
"description": "Regular authenticated user role"
|
||||
},
|
||||
{
|
||||
"name": "employee-role",
|
||||
"description": "Assigned to brokered identities whose hosted-domain claim is example.test"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -213,6 +217,17 @@
|
||||
"claim": "hd",
|
||||
"user.attribute": "hd"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "mock-google-example-domain-role",
|
||||
"identityProviderAlias": "mock-google",
|
||||
"identityProviderMapper": "oidc-role-idp-mapper",
|
||||
"config": {
|
||||
"syncMode": "INHERIT",
|
||||
"claim": "hd",
|
||||
"claim.value": "example.test",
|
||||
"role": "employee-role"
|
||||
}
|
||||
}
|
||||
],
|
||||
"users": [
|
||||
|
||||
@@ -144,6 +144,10 @@ upsert_mapper \
|
||||
"google-hosted-domain" \
|
||||
"oidc-user-attribute-idp-mapper" \
|
||||
'{"syncMode":"INHERIT","claim":"hd","user.attribute":"hd"}'
|
||||
upsert_mapper \
|
||||
"google-example-domain-role" \
|
||||
"oidc-role-idp-mapper" \
|
||||
'{"syncMode":"INHERIT","claim":"hd","claim.value":"example.test","role":"employee-role"}'
|
||||
|
||||
echo "Google Identity Provider $action for realm '$realm'"
|
||||
echo "Register this exact Google redirect URI:"
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
|
||||
set -a
|
||||
. ./.env
|
||||
set +a
|
||||
|
||||
./scripts/set-first-broker-login-mode.sh secure
|
||||
cd google-e2e
|
||||
npm install --ignore-scripts
|
||||
npm run test:sub-vs-email
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
|
||||
set -a
|
||||
. ./.env
|
||||
set +a
|
||||
|
||||
./scripts/configure-broker-user-profile.sh >/dev/null
|
||||
./scripts/set-first-broker-login-mode.sh secure
|
||||
|
||||
docker compose exec -T keycloak \
|
||||
/opt/keycloak/bin/kcadm.sh create roles -r keycloak-patterns \
|
||||
-s name=employee-role \
|
||||
-s 'description=Assigned from the upstream hd claim' >/dev/null 2>&1 || true
|
||||
|
||||
cd google-e2e
|
||||
npm install --ignore-scripts
|
||||
npm run test:claim-to-role
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
|
||||
realm="${KEYCLOAK_REALM:-keycloak-patterns}"
|
||||
public_keycloak_url="${PUBLIC_KEYCLOAK_URL:-https://auth.example.test}"
|
||||
expected="$public_keycloak_url/realms/$realm/broker/google/endpoint"
|
||||
|
||||
case "$public_keycloak_url" in
|
||||
https://*) ;;
|
||||
*)
|
||||
echo "PUBLIC_KEYCLOAK_URL must use https outside the local mock environment" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
case "$public_keycloak_url" in
|
||||
*\** | */)
|
||||
echo "PUBLIC_KEYCLOAK_URL must be an exact origin without wildcard/trailing slash" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
test "$expected" = "https://auth.example.test/realms/keycloak-patterns/broker/google/endpoint"
|
||||
echo "Google redirect URI policy verified: $expected"
|
||||
Reference in New Issue
Block a user