1
0
forked from baron/baron-sso

Merge branch 'dev' into feature/af-issue363

This commit is contained in:
2026-03-18 09:05:23 +09:00
35 changed files with 2225 additions and 317 deletions

View File

@@ -9,6 +9,7 @@
"lint": "biome check .",
"preview": "vite preview",
"test": "playwright test",
"test:roles": "playwright test tests/devfront-role-switch-report.spec.ts",
"test:ui": "playwright test --ui"
},
"dependencies": {

View File

@@ -8,6 +8,7 @@ import ClientConsentsPage from "../features/clients/ClientConsentsPage";
import ClientDetailsPage from "../features/clients/ClientDetailsPage";
import ClientGeneralPage from "../features/clients/ClientGeneralPage";
import ClientsPage from "../features/clients/ClientsPage";
import ProfilePage from "../features/profile/ProfilePage";
export const router = createBrowserRouter(
[
@@ -33,6 +34,7 @@ export const router = createBrowserRouter(
{ path: "clients/:id/consents", element: <ClientConsentsPage /> },
{ path: "clients/:id/settings", element: <ClientGeneralPage /> },
{ path: "audit-logs", element: <AuditLogsPage /> },
{ path: "profile", element: <ProfilePage /> },
],
},
],

View File

@@ -1,3 +1,4 @@
import { useQuery } from "@tanstack/react-query";
import {
BadgeCheck,
LogOut,
@@ -5,13 +6,17 @@ import {
NotebookTabs,
ShieldHalf,
Sun,
User as UserIcon,
} from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useAuth } from "react-oidc-context";
import { NavLink, Outlet, useNavigate } from "react-router-dom";
import { t } from "../../lib/i18n";
import { resolveProfileRole } from "../../lib/role";
import LanguageSelector from "../common/LanguageSelector";
import { Toaster } from "../ui/toaster";
import { Badge } from "../ui/badge";
import { fetchMe } from "../../features/auth/authApi";
const navItems = [
{
@@ -40,6 +45,13 @@ function AppLayout() {
const [isRefreshingSession, setIsRefreshingSession] = useState(false);
const [nowMs, setNowMs] = useState(() => Date.now());
const hasAccessToken = Boolean(auth.user?.access_token);
const { data: profile } = useQuery({
queryKey: ["userMe"],
queryFn: fetchMe,
enabled: hasAccessToken,
});
const handleLogout = () => {
if (window.confirm(t("msg.dev.logout_confirm", "로그아웃 하시겠습니까?"))) {
auth.removeUser();
@@ -96,6 +108,18 @@ function AppLayout() {
auth.user?.profile?.email?.toString().trim() ||
t("ui.dev.profile.unknown_email", "unknown@example.com");
const profileInitial = profileName.charAt(0).toUpperCase();
const currentRole = resolveProfileRole(
auth.user?.profile as Record<string, unknown> | undefined,
);
// Use profile.role from API if available, otherwise fallback to local role
const displayRoleKey = profile?.role || currentRole;
const isDevConsoleAllowed = [
"super_admin",
"tenant_admin",
"rp_admin",
].includes(currentRole);
const expiresAtSec = auth.user?.expires_at;
const remainingMs =
typeof expiresAtSec === "number" ? expiresAtSec * 1000 - nowMs : null;
@@ -191,23 +215,24 @@ function AppLayout() {
</span>
</div>
<div className="flex flex-col gap-1">
{navItems.map(({ labelKey, labelFallback, to, icon: Icon }) => (
<NavLink
key={to}
to={to}
className={({ isActive }) =>
[
"flex items-center gap-3 rounded-xl px-3 py-3 text-sm transition",
isActive
? "bg-primary/10 text-primary shadow-[0_12px_40px_rgba(54,211,153,0.18)]"
: "text-muted-foreground hover:bg-muted/10 hover:text-foreground",
].join(" ")
}
>
<Icon size={18} />
<span>{t(labelKey, labelFallback)}</span>
</NavLink>
))}
{isDevConsoleAllowed &&
navItems.map(({ labelKey, labelFallback, to, icon: Icon }) => (
<NavLink
key={to}
to={to}
className={({ isActive }) =>
[
"flex items-center gap-3 rounded-xl px-3 py-3 text-sm transition",
isActive
? "bg-primary/10 text-primary shadow-[0_12px_40px_rgba(54,211,153,0.18)]"
: "text-muted-foreground hover:bg-muted/10 hover:text-foreground",
].join(" ")
}
>
<Icon size={18} />
<span>{t(labelKey, labelFallback)}</span>
</NavLink>
))}
</div>
</nav>
</div>
@@ -296,14 +321,41 @@ function AppLayout() {
<p className="text-xs uppercase tracking-[0.16em] text-muted-foreground">
{t("ui.dev.profile.menu_title", "Account")}
</p>
<div className="mt-2 rounded-lg border border-border px-3 py-2">
<p className="truncate text-sm font-semibold text-foreground">
{profileName}
</p>
<p className="truncate text-xs text-muted-foreground">
{profileEmail}
</p>
<div className="mt-2 rounded-lg border border-border px-3 py-3 flex flex-col gap-2">
<div>
<p className="truncate text-sm font-semibold text-foreground">
{profileName}
</p>
<p className="truncate text-xs text-muted-foreground">
{profileEmail}
</p>
</div>
<div className="flex items-center pt-1">
<Badge
variant="outline"
className="text-[10px] px-2 py-0"
>
{t(
`ui.common.role.${displayRoleKey}`,
displayRoleKey.toUpperCase(),
)}
</Badge>
</div>
</div>
<button
type="button"
role="menuitem"
className="mt-2 w-full flex items-center gap-2 rounded-lg border border-border px-3 py-2 text-left text-sm text-foreground transition hover:bg-muted/20"
onClick={() => {
navigate("/profile");
setIsProfileMenuOpen(false);
}}
>
<UserIcon size={16} className="text-muted-foreground" />
<span>{t("ui.dev.profile.title", "내 정보")}</span>
</button>
<button
type="button"
role="menuitem"

View File

@@ -1,5 +1,7 @@
import { useAuth } from "react-oidc-context";
import { Navigate, Outlet } from "react-router-dom";
import { t } from "../../lib/i18n";
import { resolveProfileRole } from "../../lib/role";
export default function AuthGuard() {
const auth = useAuth();
@@ -16,5 +18,39 @@ export default function AuthGuard() {
return <Navigate to="/login" replace />;
}
const normalizedRole = resolveProfileRole(
auth.user?.profile as Record<string, unknown> | undefined,
);
const isTenantMember =
normalizedRole === "user" || normalizedRole === "tenant_member";
if (isTenantMember) {
return (
<div className="min-h-screen grid place-items-center bg-background text-foreground p-6">
<div className="max-w-lg w-full rounded-xl border border-border bg-card p-6 space-y-4">
<h1 className="text-xl font-semibold">
{t("msg.dev.auth.access_denied_title", "접근 권한이 없습니다.")}
</h1>
<p className="text-sm text-muted-foreground">
{t(
"msg.dev.auth.access_denied_description",
"DevFront는 관리자 전용 화면입니다. 권한이 필요하면 관리자에게 요청해 주세요.",
)}
</p>
<button
type="button"
className="inline-flex items-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90"
onClick={() => {
auth.removeUser();
window.location.href = "/login";
}}
>
{t("ui.common.back_to_login", "로그인으로 돌아가기")}
</button>
</div>
</div>
);
}
return <Outlet />;
}

View File

@@ -356,7 +356,7 @@ function ClientConsentsPage() {
<div className="flex justify-end">
<Button
variant="link"
variant="ghost"
size="sm"
className="text-xs text-muted-foreground p-0 h-auto"
onClick={() => {

View File

@@ -262,7 +262,7 @@ function ClientsPage() {
</select>
</div>
<Button
variant="link"
variant="ghost"
size="sm"
className="text-xs text-muted-foreground ml-auto"
onClick={() => {
@@ -291,7 +291,7 @@ function ClientsPage() {
item.tone === "up"
? "success"
: item.tone === "down"
? "destructive"
? "warning"
: "muted"
}
className={cn(

View File

@@ -0,0 +1,216 @@
import { useQuery } from "@tanstack/react-query";
import {
User,
Shield,
Briefcase,
Mail,
Fingerprint,
Building2,
} from "lucide-react";
import { useState } from "react";
import { useAuth } from "react-oidc-context";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "../../components/ui/card";
import { fetchMe } from "../auth/authApi";
import { t } from "../../lib/i18n";
function ProfilePage() {
const auth = useAuth();
const hasAccessToken = Boolean(auth.user?.access_token);
const {
data: profile,
isLoading,
error,
} = useQuery({
queryKey: ["userMe"],
queryFn: fetchMe,
enabled: hasAccessToken,
});
const [activeTab, setActiveTab] = useState<"basic" | "role">("basic");
if (isLoading) {
return (
<div className="p-8 text-center">
{t("ui.dev.profile.loading", "Loading profile...")}
</div>
);
}
if (error || !profile) {
return (
<div className="p-8 text-center text-red-500">
{t("ui.dev.profile.error", "Failed to load profile information.")}
</div>
);
}
// Fallback to token information if API data is incomplete
const displayTenant =
profile.tenant?.name ||
profile.tenantId ||
auth.user?.profile?.tenant_id?.toString() ||
"-";
const displayCompanyCode =
profile.companyCode || auth.user?.profile?.companyCode?.toString() || "-";
return (
<div className="space-y-6 max-w-4xl mx-auto">
<div>
<h1 className="text-3xl font-black tracking-tight">
{t("ui.dev.profile.title", "내 정보")}
</h1>
<p className="text-muted-foreground mt-2">
{t(
"ui.dev.profile.subtitle",
"사용자 상세 정보 및 할당된 역할(Role)을 확인합니다.",
)}
</p>
</div>
<div className="flex space-x-1 border-b border-border pb-px">
<button
type="button"
onClick={() => setActiveTab("basic")}
className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
activeTab === "basic"
? "border-primary text-primary"
: "border-transparent text-muted-foreground hover:text-foreground hover:border-border"
}`}
>
{t("ui.dev.profile.tab.basic", "기본 정보")}
</button>
<button
type="button"
onClick={() => setActiveTab("role")}
className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
activeTab === "role"
? "border-primary text-primary"
: "border-transparent text-muted-foreground hover:text-foreground hover:border-border"
}`}
>
{t("ui.dev.profile.tab.role", "권한 및 역할")}
</button>
</div>
<div className="pt-4">
{activeTab === "basic" && (
<div className="grid gap-6 md:grid-cols-2">
<Card className="glass-panel">
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<User className="h-5 w-5 text-primary" />
{t("ui.dev.profile.basic.title", "사용자 정보")}
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-1">
<p className="text-sm font-medium text-muted-foreground flex items-center gap-2">
<Fingerprint className="h-4 w-4" />
{t("ui.dev.profile.basic.id", "User ID")}
</p>
<p className="text-sm break-all font-mono bg-muted/50 p-2 rounded-md">
{profile.id}
</p>
</div>
<div className="space-y-1">
<p className="text-sm font-medium text-muted-foreground flex items-center gap-2">
<User className="h-4 w-4" />
{t("ui.dev.profile.basic.name", "Name")}
</p>
<p className="text-sm">{profile.name}</p>
</div>
<div className="space-y-1">
<p className="text-sm font-medium text-muted-foreground flex items-center gap-2">
<Mail className="h-4 w-4" />
{t("ui.dev.profile.basic.email", "Email")}
</p>
<p className="text-sm">{profile.email}</p>
</div>
<div className="space-y-1">
<p className="text-sm font-medium text-muted-foreground flex items-center gap-2">
<Briefcase className="h-4 w-4" />
{t("ui.dev.profile.basic.phone", "Phone")}
</p>
<p className="text-sm">{profile.phone || "-"}</p>
</div>
</CardContent>
</Card>
<Card className="glass-panel">
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Building2 className="h-5 w-5 text-primary" />
{t("ui.dev.profile.org.title", "조직 정보")}
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-1">
<p className="text-sm font-medium text-muted-foreground">
{t("ui.dev.profile.org.tenant", "테넌트")}
</p>
<p className="text-sm">{displayTenant}</p>
</div>
<div className="space-y-1">
<p className="text-sm font-medium text-muted-foreground">
{t("ui.dev.profile.org.company_code", "회사 코드")}
</p>
<p className="text-sm">{displayCompanyCode}</p>
</div>
</CardContent>
</Card>
</div>
)}
{activeTab === "role" && (
<Card className="glass-panel">
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Shield className="h-5 w-5 text-primary" />
{t("ui.dev.profile.role.title", "시스템 역할")}
</CardTitle>
<CardDescription>
{t(
"ui.dev.profile.role.description",
"현재 계정에 부여된 권한 등급입니다.",
)}
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center gap-4 bg-muted/30 p-4 rounded-lg border border-border">
<div className="h-12 w-12 rounded-full bg-primary/20 flex items-center justify-center text-primary shrink-0">
<Briefcase className="h-6 w-6" />
</div>
<div className="flex flex-col gap-1 w-full">
<p className="text-sm text-muted-foreground font-medium uppercase tracking-wider">
{t("ui.dev.profile.role.current", "Current Role")}
</p>
<p className="text-xl font-bold mt-1">
{t(
`ui.common.role.${profile.role}`,
profile.role.toUpperCase(),
)}
</p>
<p className="mt-1 text-sm text-muted-foreground">
{t(
`ui.dev.profile.role.desc_${profile.role}`,
"시스템 역할에 대한 설명이 제공되지 않았습니다.",
)}
</p>
</div>
</div>
</CardContent>
</Card>
)}
</div>
</div>
);
}
export default ProfilePage;

27
devfront/src/lib/role.ts Normal file
View File

@@ -0,0 +1,27 @@
export function normalizeRole(rawRole: unknown): string {
if (typeof rawRole !== "string") return "";
const role = rawRole.trim().toLowerCase();
if (role === "tenant_member") return "user";
if (role === "admin") return "tenant_admin";
if (role === "superadmin") return "super_admin";
if (role === "tenantadmin") return "tenant_admin";
if (role === "rpadmin") return "rp_admin";
return role;
}
export function resolveProfileRole(
profile: Record<string, unknown> | undefined,
) {
if (!profile) return "";
const candidates = [
profile.role,
profile.grade,
profile["custom:role"],
profile["custom:grade"],
];
for (const candidate of candidates) {
const normalized = normalizeRole(candidate);
if (normalized) return normalized;
}
return "";
}

View File

@@ -313,6 +313,10 @@ unknown_error = "unknown error"
[msg.dev]
logout_confirm = "Are you sure you want to log out?"
[msg.dev.auth]
access_denied_description = "DevFront is for administrators only. Request access from your administrator."
access_denied_title = "Access denied."
[msg.dev.audit]
empty = "No audit logs found."
forbidden = "You do not have permission to view audit logs. Please request access from an administrator."
@@ -1140,6 +1144,7 @@ all = "All"
admin_only = "Admin Only"
assign = "Assign"
back = "Back"
back_to_login = "Back to login"
cancel = "Cancel"
change_file = "Change File"
clear_search = "Clear Search"
@@ -1657,3 +1662,51 @@ verify = "Verify"
[ui.userfront.signup.success]
action = "Action"
[ui.dev.profile]
unknown_name = "Unknown User"
unknown_email = "unknown@example.com"
menu_aria = "Open account menu"
menu_title = "Account"
title = "Profile"
subtitle = "View user details and assigned roles."
loading = "Loading profile..."
error = "Failed to load profile."
[ui.dev.profile.tab]
basic = "Basic Info"
role = "Roles & Permissions"
[ui.dev.profile.basic]
title = "User Info"
id = "User ID"
name = "Name"
email = "Email"
phone = "Phone Number"
[ui.dev.profile.org]
title = "Organization Info"
tenant = "Tenant"
company_code = "Company Code"
[ui.dev.profile.role]
title = "System Role"
description = "The permission level granted to this account."
current = "Current Role"
desc_super_admin = "Can manage all tenants and applications system-wide without restriction."
desc_tenant_admin = "Can manage all applications within their assigned tenant."
desc_rp_admin = "Can view and manage only assigned/linked applications."
desc_user = "Standard application access. DevFront access is denied."
desc_tenant_member = "Standard application access. DevFront access is denied."
[ui.admin.nav]
api_keys = "API Keys"
audit_logs = "Audit Logs"
auth_guard = "Auth Guard"
logout = "Logout"
overview = "Overview"
relying_parties = "Apps (RP)"
tenant_dashboard = "Tenant Dashboard"
user_groups = "User Groups"
tenants = "Tenants"
users = "Users"

View File

@@ -313,6 +313,10 @@ unknown_error = "알 수 없는 오류"
[msg.dev]
logout_confirm = "로그아웃 하시겠습니까?"
[msg.dev.auth]
access_denied_description = "DevFront는 관리자 전용 화면입니다. 권한이 필요하면 관리자에게 요청해 주세요."
access_denied_title = "접근 권한이 없습니다."
[msg.dev.audit]
empty = "조회된 감사 로그가 없습니다."
forbidden = "감사 로그를 조회할 권한이 없습니다. 관리자에게 권한을 요청해주세요."
@@ -1140,6 +1144,7 @@ all = "전체"
admin_only = "관리자 전용"
assign = "할당"
back = "돌아가기"
back_to_login = "로그인으로 돌아가기"
cancel = "취소"
change_file = "파일 변경"
clear_search = "검색 초기화"
@@ -1653,3 +1658,51 @@ verify = "본인인증"
[ui.userfront.signup.success]
action = "로그인하기"
[ui.admin.nav]
api_keys = "API 키"
audit_logs = "감사 로그"
auth_guard = "인증 가드"
logout = "로그아웃"
overview = "개요"
relying_parties = "애플리케이션(RP)"
tenant_dashboard = "테넌트 대시보드"
user_groups = "유저 그룹"
tenants = "테넌트"
users = "사용자"
[ui.dev.profile]
unknown_name = "알 수 없는 사용자"
unknown_email = "unknown@example.com"
menu_aria = "계정 메뉴 열기"
menu_title = "Account"
title = "내 정보"
subtitle = "사용자 상세 정보 및 할당된 역할(Role)을 확인합니다."
loading = "프로필 정보를 불러오는 중..."
error = "프로필 정보를 불러오지 못했습니다."
[ui.dev.profile.tab]
basic = "기본 정보"
role = "권한 및 역할"
[ui.dev.profile.basic]
title = "사용자 정보"
id = "사용자 ID"
name = "이름"
email = "이메일"
phone = "전화번호"
[ui.dev.profile.org]
title = "조직 정보"
tenant = "테넌트"
company_code = "회사 코드"
[ui.dev.profile.role]
title = "시스템 역할"
description = "현재 계정에 부여된 권한 등급입니다."
current = "현재 역할"
desc_super_admin = "전체 시스템의 모든 테넌트와 모든 앱을 제한 없이 관리할 수 있습니다."
desc_tenant_admin = "본인이 속한 테넌트(조직/회사) 하위의 모든 앱을 관리할 수 있습니다."
desc_rp_admin = "본인에게 할당된 연동 앱(Client)만 확인 및 관리할 수 있습니다."
desc_user = "기본 앱 이용 권한을 가지며, DevFront 접근은 차단됩니다."
desc_tenant_member = "기본 앱 이용 권한을 가지며, DevFront 접근은 차단됩니다."

View File

@@ -313,6 +313,10 @@ unknown_error = ""
[msg.dev]
logout_confirm = ""
[msg.dev.auth]
access_denied_description = ""
access_denied_title = ""
[msg.dev.audit]
empty = ""
forbidden = ""
@@ -1140,6 +1144,7 @@ all = ""
admin_only = ""
assign = ""
back = ""
back_to_login = ""
cancel = ""
change_file = ""
clear_search = ""
@@ -1653,3 +1658,39 @@ verify = ""
[ui.userfront.signup.success]
action = ""
[ui.dev.profile]
unknown_name = ""
unknown_email = ""
menu_aria = ""
menu_title = ""
title = ""
subtitle = ""
loading = ""
error = ""
[ui.dev.profile.tab]
basic = ""
role = ""
[ui.dev.profile.basic]
title = ""
id = ""
name = ""
email = ""
phone = ""
[ui.dev.profile.org]
title = ""
tenant = ""
company_code = ""
[ui.dev.profile.role]
title = ""
description = ""
current = ""
desc_super_admin = ""
desc_tenant_admin = ""
desc_rp_admin = ""
desc_user = ""
desc_tenant_member = ""

View File

@@ -0,0 +1,112 @@
import { expect, test } from "@playwright/test";
import {
type AuditLog,
type Consent,
installDevApiMock,
makeClient,
seedAuth,
} from "./helpers/devfront-fixtures";
test.describe("DevFront audit logs", () => {
test.beforeEach(async ({ page }) => {
page.on("dialog", async (dialog) => {
await dialog.accept();
});
await seedAuth(page);
});
test("filtering and cursor pagination", async ({ page }) => {
const state = {
clients: [makeClient("client-audit", { name: "Audit app" })],
consents: [] as Consent[],
auditLogsByCursor: {
"": {
items: [
{
event_id: "evt-1",
timestamp: "2026-03-03T09:00:00.000Z",
user_id: "actor-a",
event_type: "CLIENT_UPDATE",
status: "success",
ip_address: "127.0.0.1",
user_agent: "playwright",
details: JSON.stringify({
action: "UPDATE_CLIENT",
target_id: "client-audit",
tenant_id: "tenant-a",
}),
},
],
next_cursor: "cursor-2",
},
"cursor-2": {
items: [
{
event_id: "evt-2",
timestamp: "2026-03-03T09:01:00.000Z",
user_id: "actor-b",
event_type: "CLIENT_ROTATE_SECRET",
status: "success",
ip_address: "127.0.0.1",
user_agent: "playwright",
details: JSON.stringify({
action: "ROTATE_SECRET",
target_id: "client-audit",
tenant_id: "tenant-a",
}),
},
],
},
},
};
await installDevApiMock(page, state);
await page.goto("/audit-logs");
await expect(page.getByText("UPDATE_CLIENT")).toBeVisible();
await page
.getByPlaceholder(/Client ID로 필터|Filter by Client ID/i)
.fill("client-audit");
await page
.getByPlaceholder(/액션으로 필터|Filter by Action/i)
.fill("ROTATE_SECRET");
await page.getByRole("button", { name: /더 보기|Load more/i }).click();
await expect(page.getByText("ROTATE_SECRET")).toBeVisible();
});
test("realtime create/update actions should be visible", async ({ page }) => {
const state = {
clients: [makeClient("client-realtime", { name: "Realtime app" })],
consents: [] as Consent[],
auditLogs: [] as AuditLog[],
auditLogsByCursor: undefined,
};
await installDevApiMock(page, state);
await page.goto("/clients/new");
await page
.getByPlaceholder("My Awesome Application")
.fill("Realtime New App");
await page
.getByPlaceholder(/https:\/\/app\.example\.com\/callback/i)
.fill("https://realtime.example.com/callback");
await page.getByRole("button", { name: /앱 생성|Create/i }).click();
await expect.poll(() => state.auditLogs.length).toBeGreaterThanOrEqual(1);
await page.goto("/clients/client-realtime/settings");
await page
.getByPlaceholder("My Awesome Application")
.fill("Realtime Updated");
await page.getByRole("button", { name: /^저장$|^Save$/i }).click();
await expect.poll(() => state.auditLogs.length).toBeGreaterThanOrEqual(2);
await page.goto("/audit-logs");
await expect(page.getByText("CREATE_CLIENT")).toBeVisible({
timeout: 30000,
});
await expect(page.getByText("UPDATE_CLIENT")).toBeVisible({
timeout: 30000,
});
});
});

View File

@@ -0,0 +1,121 @@
import { expect, test } from "@playwright/test";
import {
type ClientStatus,
type Consent,
installDevApiMock,
makeClient,
seedAuth,
} from "./helpers/devfront-fixtures";
test.describe("DevFront clients lifecycle", () => {
test.beforeEach(async ({ page }) => {
page.on("dialog", async (dialog) => {
await dialog.accept();
});
await seedAuth(page);
});
test("create, update status, and delete", async ({ page }) => {
const state = {
clients: [makeClient("existing-client", { name: "Existing app" })],
consents: [] as Consent[],
updatedStatus: "active" as ClientStatus,
auditLogsByCursor: undefined,
onUpdateStatus(status: ClientStatus) {
this.updatedStatus = status;
},
};
await installDevApiMock(page, state);
await page.goto("/clients");
await expect(page.getByText("Existing app")).toBeVisible();
await page
.getByRole("button", { name: /연동 앱 추가|새 클라이언트|Create/i })
.click();
await expect(page).toHaveURL(/\/clients\/new$/);
await page
.getByPlaceholder("My Awesome Application")
.fill("Playwright Created App");
await page
.getByPlaceholder(/https:\/\/app\.example\.com\/callback/i)
.fill("https://playwright.example.com/callback");
await page
.getByRole("button", { name: /앱 생성|클라이언트 생성|Create/i })
.click();
await expect(page).toHaveURL(/\/clients\/client-2\/settings$/);
await expect(
page.getByRole("heading", {
name: /연동 앱 설정|클라이언트 설정|Client Settings/i,
}),
).toBeVisible();
await page.getByRole("button", { name: /비활성|Inactive/i }).click();
await page.getByRole("button", { name: /^저장$|^Save$/i }).click();
await expect.poll(() => state.updatedStatus).toBe("inactive");
await page.getByRole("button", { name: /삭제|Delete/i }).click();
await expect(page).toHaveURL(/\/clients$/);
await expect(page.getByText("Playwright Created App")).not.toBeVisible();
});
test("rotate secret shows new value", async ({ page }) => {
let rotatedSecret = "";
const state = {
clients: [makeClient("client-rotate", { name: "Rotate app" })],
consents: [] as Consent[],
auditLogsByCursor: undefined,
onRotateSecret(newSecret: string) {
rotatedSecret = newSecret;
},
};
await installDevApiMock(page, state);
await page.goto("/clients/client-rotate");
await expect(
page.getByRole("heading", { name: "Rotate app", exact: true }),
).toBeVisible();
await page.getByTitle(/비밀키 재발급|Rotate/i).click();
await expect.poll(() => rotatedSecret).toBe("client-rotate-rotated-secret");
await expect(page.getByText("client-rotate-rotated-secret")).toBeVisible();
});
test("update name and redirect URI should be persisted", async ({ page }) => {
const state = {
clients: [
makeClient("client-edit", {
name: "Before Name",
redirectUris: ["https://before.example.com/callback"],
}),
],
consents: [] as Consent[],
auditLogsByCursor: undefined,
};
await installDevApiMock(page, state);
await page.goto("/clients/client-edit/settings");
await page.getByPlaceholder("My Awesome Application").fill("After Name");
await page.getByRole("button", { name: /^저장$|^Save$/i }).click();
await expect.poll(() => state.clients[0]?.name).toBe("After Name");
await page.goto("/clients/client-edit");
await page
.getByRole("textbox", { name: /인증 콜백 URL|Callback/i })
.fill("https://after.example.com/callback");
await page
.getByRole("button", { name: /Redirect URIs 저장|Save/i })
.click();
await expect
.poll(() => state.clients[0]?.redirectUris[0])
.toBe("https://after.example.com/callback");
await page.reload();
await expect(
page.getByRole("textbox", { name: /인증 콜백 URL|Callback/i }),
).toHaveValue(/https:\/\/after\.example\.com\/callback/);
});
});

View File

@@ -0,0 +1,45 @@
import { expect, test } from "@playwright/test";
import {
installDevApiMock,
makeClient,
seedAuth,
type Consent,
} from "./helpers/devfront-fixtures";
test.describe("DevFront consents", () => {
test.beforeEach(async ({ page }) => {
page.on("dialog", async (dialog) => {
await dialog.accept();
});
await seedAuth(page);
});
test("consent list and revoke flow", async ({ page }) => {
const state = {
clients: [makeClient("client-consent", { name: "Consent app" })],
consents: [
{
subject: "user-1",
userName: "Alice",
clientId: "client-consent",
clientName: "Consent app",
grantedScopes: ["openid", "profile"],
authenticatedAt: "2026-03-03T08:00:00.000Z",
createdAt: "2026-03-02T08:00:00.000Z",
status: "active",
tenantId: "tenant-a",
tenantName: "Tenant A",
},
] as Consent[],
auditLogsByCursor: undefined,
};
await installDevApiMock(page, state);
await page.goto("/clients/client-consent/consents");
await expect(page.getByText("Alice")).toBeVisible();
await expect(page.getByText("Tenant A")).toBeVisible();
await page.getByRole("button", { name: /권한 철회|Revoke/i }).click();
await expect(page.getByText(/Revoked|철회/i).first()).toBeVisible();
});
});

View File

@@ -0,0 +1,155 @@
import { expect, test } from "@playwright/test";
import {
type AuditLog,
type Consent,
installDevApiMock,
makeClient,
seedAuth,
} from "./helpers/devfront-fixtures";
import { captureEvidence } from "./helpers/evidence";
test.describe("DevFront role report", () => {
test.beforeEach(async ({ page }) => {
page.on("dialog", async (dialog) => {
await dialog.accept();
});
});
test("user(tenant_member) is blocked with 안내 문구", async ({
page,
}, testInfo) => {
await seedAuth(page, "user");
await installDevApiMock(page, {
clients: [],
consents: [] as Consent[],
auditLogs: [] as AuditLog[],
});
await page.goto("/clients");
await expect(
page.getByText(/관리자 전용 화면|administrator only/i),
).toBeVisible();
await captureEvidence(page, testInfo, "role-user-blocked");
});
test("rp_admin sees only assigned Gitea app and its logs", async ({
page,
}, testInfo) => {
await seedAuth(page, "rp_admin");
const state = {
clients: [makeClient("gitea-client", { name: "Gitea" })],
consents: [] as Consent[],
auditLogs: [
{
event_id: "evt-rp-1",
timestamp: "2026-03-04T01:00:00.000Z",
user_id: "rp-admin-user",
event_type: "CLIENT_UPDATE",
status: "success" as const,
ip_address: "127.0.0.1",
user_agent: "playwright",
details: JSON.stringify({
action: "UPDATE_CLIENT",
target_id: "gitea-client",
tenant_id: "tenant-a",
}),
},
] as AuditLog[],
};
await installDevApiMock(page, state);
await page.goto("/clients");
await expect(page.getByRole("link", { name: /Gitea/ })).toBeVisible();
await expect(page.getByText("gitea-client")).toBeVisible();
await captureEvidence(page, testInfo, "role-rp-admin-clients");
await page.goto("/audit-logs");
await expect(page.getByText("UPDATE_CLIENT")).toBeVisible();
await expect(page.getByText("gitea-client")).toBeVisible();
await captureEvidence(page, testInfo, "role-rp-admin-audit");
});
test("tenant_admin can manage tenant apps and see tenant logs", async ({
page,
}, testInfo) => {
await seedAuth(page, "tenant_admin");
const state = {
clients: [
makeClient("tenant-a-app-1", { name: "Tenant A CRM" }),
makeClient("tenant-a-app-2", { name: "Tenant A ERP" }),
],
consents: [] as Consent[],
auditLogs: [] as AuditLog[],
auditLogsByCursor: undefined,
};
await installDevApiMock(page, state);
await page.goto("/clients");
await expect(page.getByText("Tenant A CRM")).toBeVisible();
await expect(page.getByText("Tenant A ERP")).toBeVisible();
await captureEvidence(page, testInfo, "role-tenant-admin-clients");
await page.goto("/clients/tenant-a-app-1/settings");
await page
.getByPlaceholder("My Awesome Application")
.fill("Tenant A CRM Updated");
const updatePromise = page.waitForResponse(
(r) =>
r.url().includes("/api/v1/dev/clients") &&
r.request().method() === "PUT",
);
await page.getByRole("button", { name: /^저장$|^Save$/i }).click();
await updatePromise;
await page.goto("/audit-logs");
await expect(page.getByText("UPDATE_CLIENT")).toBeVisible({
timeout: 30000,
});
await expect(page.getByText("tenant-a-app-1")).toBeVisible();
await captureEvidence(page, testInfo, "role-tenant-admin-audit");
});
test("super_admin sees all and can generate log entries", async ({
page,
}, testInfo) => {
await seedAuth(page, "super_admin");
const state = {
clients: [
makeClient("tenant-a-app", { name: "Tenant A App" }),
makeClient("tenant-b-app", { name: "Tenant B App" }),
],
consents: [] as Consent[],
auditLogs: [] as AuditLog[],
auditLogsByCursor: undefined,
};
await installDevApiMock(page, state);
await page.goto("/clients");
await expect(page.getByText("Tenant A App")).toBeVisible();
await expect(page.getByText("Tenant B App")).toBeVisible();
await captureEvidence(page, testInfo, "role-super-admin-clients");
await page.goto("/clients/new");
await page
.getByPlaceholder("My Awesome Application")
.fill("Super Admin Created App");
await page
.getByPlaceholder(/https:\/\/app\.example\.com\/callback/i)
.fill("https://super-admin.example.com/callback");
const createPromise = page.waitForResponse(
(r) =>
r.url().includes("/api/v1/dev/clients") &&
r.request().method() === "POST",
);
await page.getByRole("button", { name: /앱 생성|Create/i }).click();
await createPromise;
await page.goto("/audit-logs");
await expect(page.getByText("CREATE_CLIENT")).toBeVisible({
timeout: 30000,
});
await captureEvidence(page, testInfo, "role-super-admin-audit");
});
});

View File

@@ -0,0 +1,60 @@
import { expect, test } from "@playwright/test";
import {
type Consent,
installDevApiMock,
makeClient,
seedAuth,
} from "./helpers/devfront-fixtures";
test.describe("DevFront security and isolation", () => {
test.beforeEach(async ({ page }) => {
page.on("dialog", async (dialog) => {
await dialog.accept();
});
await seedAuth(page);
});
test("tenant isolation: forbidden client shows blocked error", async ({
page,
}) => {
const state = {
clients: [makeClient("tenant-a-client", { name: "Tenant A app" })],
consents: [] as Consent[],
auditLogsByCursor: undefined,
};
await installDevApiMock(page, state);
await page.goto("/clients/tenant-b-client");
await expect(page.getByText(/Error loading client|조회/i)).toBeVisible();
});
test("RBAC: non-AppManager user should not see private apps", async ({
page,
}) => {
const state = {
clients: [
makeClient("pkce-client", {
name: "PKCE only app",
type: "pkce",
}),
],
consents: [] as Consent[],
auditLogsByCursor: undefined,
};
await installDevApiMock(page, state);
await page.goto("/clients");
await expect(page.getByText("PKCE only app")).toBeVisible();
await expect(page.getByText("Server side App")).not.toBeVisible();
});
test("tenant_member user is blocked at AuthGuard", async ({ page }) => {
await seedAuth(page, "tenant_member");
await page.goto("/clients");
await expect(
page.getByText(/DevFront는 관리자 전용 화면입니다|administrator access/i),
).toBeVisible();
await expect(page).toHaveURL(/\/clients$/);
});
});

View File

@@ -0,0 +1,375 @@
import type { Page, Route } from "@playwright/test";
export type ClientStatus = "active" | "inactive";
export type ClientType = "private" | "pkce";
export type Client = {
id: string;
name: string;
type: ClientType;
status: ClientStatus;
redirectUris: string[];
scopes: string[];
createdAt: string;
clientSecret?: string;
metadata?: Record<string, unknown>;
};
export type Consent = {
subject: string;
userName: string;
clientId: string;
clientName: string;
grantedScopes: string[];
authenticatedAt?: string;
createdAt: string;
deletedAt?: string;
status: "active" | "revoked";
tenantId: string;
tenantName: string;
};
export type AuditLog = {
event_id: string;
timestamp: string;
user_id: string;
event_type: string;
status: "success" | "failure";
ip_address: string;
user_agent: string;
details: string;
};
export type DevApiMockState = {
clients: Client[];
consents: Consent[];
auditLogsByCursor?: Record<
string,
{ items: AuditLog[]; next_cursor?: string }
>;
auditLogs?: AuditLog[];
onUpdateStatus?: (status: ClientStatus) => void;
onRotateSecret?: (newSecret: string) => void;
};
export function makeClient(
id: string,
overrides: Partial<Client> = {},
): Client {
return {
id,
name: `${id} app`,
type: "private",
status: "active",
redirectUris: [`https://${id}.example.com/callback`],
scopes: ["openid", "profile", "email"],
createdAt: "2026-03-03T00:00:00.000Z",
clientSecret: `${id}-secret`,
metadata: {},
...overrides,
};
}
export async function seedAuth(page: Page, role?: string) {
const nowInSeconds = Math.floor(Date.now() / 1000);
await page.addInitScript(
({ issuedAt, injectedRole }) => {
const mockOidcUser = {
id_token: "playwright-id-token",
session_state: "playwright-session",
access_token: "playwright-access-token",
refresh_token: "playwright-refresh-token",
token_type: "Bearer",
scope: "openid profile email",
profile: {
sub: "playwright-user",
email: "playwright@example.com",
name: "Playwright User",
...(injectedRole ? { role: injectedRole } : {}),
},
expires_at: issuedAt + 3600,
};
window.localStorage.setItem(
"oidc.user:http://localhost:5000/oidc:devfront",
JSON.stringify(mockOidcUser),
);
window.localStorage.setItem(
"oidc.user:http://localhost:5000/oidc/:devfront",
JSON.stringify(mockOidcUser),
);
window.localStorage.setItem("dev_tenant_id", "tenant-a");
},
{ issuedAt: nowInSeconds, injectedRole: role ?? "" },
);
}
function json(route: Route, payload: unknown, status = 200) {
return route.fulfill({
status,
contentType: "application/json",
body: JSON.stringify(payload),
});
}
function parseClientId(pathname: string): string {
const parts = pathname.split("/").filter(Boolean);
return parts[parts.length - 1] ?? "";
}
export async function installDevApiMock(page: Page, state: DevApiMockState) {
const appendAuditLog = (
eventType: string,
action: string,
targetId: string,
status: "success" | "failure" = "success",
) => {
if (!state.auditLogs) return;
state.auditLogs.unshift({
event_id: `evt-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`,
timestamp: new Date().toISOString(),
user_id: "playwright-user",
event_type: eventType,
status,
ip_address: "127.0.0.1",
user_agent: "playwright",
details: JSON.stringify({
action,
target_id: targetId,
tenant_id: "tenant-a",
}),
});
};
await page.route("**/api/v1/dev/**", async (route) => {
const request = route.request();
const url = new URL(request.url());
const { pathname, searchParams } = url;
const method = request.method();
if (pathname === "/api/v1/dev/stats" && method === "GET") {
const total = state.clients.length;
return json(route, {
total_clients: total,
active_sessions: Math.max(1, total),
auth_failures_24h: 0,
});
}
if (pathname === "/api/v1/dev/clients" && method === "GET") {
return json(route, {
items: state.clients.map((client) => ({
id: client.id,
name: client.name,
type: client.type,
status: client.status,
createdAt: client.createdAt,
redirectUris: client.redirectUris,
scopes: client.scopes,
})),
limit: 50,
offset: 0,
});
}
if (pathname === "/api/v1/dev/clients" && method === "POST") {
const payload = (request.postDataJSON() as {
name?: string;
type?: ClientType;
status?: ClientStatus;
redirectUris?: string[];
scopes?: string[];
metadata?: Record<string, unknown>;
}) || { name: "created app" };
const created = makeClient(`client-${state.clients.length + 1}`, {
name: payload.name ?? "created app",
type: payload.type ?? "private",
status: payload.status ?? "active",
redirectUris: payload.redirectUris ?? [],
scopes: payload.scopes ?? ["openid"],
metadata: payload.metadata ?? {},
});
state.clients.push(created);
appendAuditLog("CLIENT_CREATE", "CREATE_CLIENT", created.id);
return json(route, {
client: created,
endpoints: {
discovery: "https://issuer/.well-known/openid-configuration",
issuer: "https://issuer",
authorization: "https://issuer/oauth2/auth",
token: "https://issuer/oauth2/token",
userinfo: "https://issuer/userinfo",
},
});
}
if (
pathname.startsWith("/api/v1/dev/clients/") &&
pathname.endsWith("/status") &&
method === "PATCH"
) {
const clientId = pathname.split("/")[5] ?? "";
const payload = request.postDataJSON() as { status: ClientStatus };
const found = state.clients.find((client) => client.id === clientId);
if (!found) return json(route, { error: "not found" }, 404);
found.status = payload.status;
appendAuditLog("CLIENT_UPDATE_STATUS", "UPDATE_CLIENT_STATUS", clientId);
state.onUpdateStatus?.(payload.status);
return json(route, {
client: found,
endpoints: {
discovery: "https://issuer/.well-known/openid-configuration",
issuer: "https://issuer",
authorization: "https://issuer/oauth2/auth",
token: "https://issuer/oauth2/token",
userinfo: "https://issuer/userinfo",
},
});
}
if (
pathname.startsWith("/api/v1/dev/clients/") &&
pathname.endsWith("/secret/rotate") &&
method === "POST"
) {
const clientId = pathname.split("/")[5] ?? "";
const found = state.clients.find((client) => client.id === clientId);
if (!found) return json(route, { error: "not found" }, 404);
found.clientSecret = `${clientId}-rotated-secret`;
appendAuditLog("CLIENT_ROTATE_SECRET", "ROTATE_SECRET", clientId);
state.onRotateSecret?.(found.clientSecret);
return json(route, {
client: found,
endpoints: {
discovery: "https://issuer/.well-known/openid-configuration",
issuer: "https://issuer",
authorization: "https://issuer/oauth2/auth",
token: "https://issuer/oauth2/token",
userinfo: "https://issuer/userinfo",
},
});
}
if (pathname.startsWith("/api/v1/dev/clients/") && method === "PUT") {
const clientId = parseClientId(pathname);
const payload = (request.postDataJSON() as {
name?: string;
type?: ClientType;
scopes?: string[];
redirectUris?: string[];
metadata?: Record<string, unknown>;
}) || { name: "updated app" };
const found = state.clients.find((client) => client.id === clientId);
if (!found) return json(route, { error: "not found" }, 404);
if (payload.name) found.name = payload.name;
if (payload.type) found.type = payload.type;
if (payload.scopes) found.scopes = payload.scopes;
if (payload.redirectUris) found.redirectUris = payload.redirectUris;
if (payload.metadata) found.metadata = payload.metadata;
appendAuditLog("CLIENT_UPDATE", "UPDATE_CLIENT", clientId);
return json(route, {
client: found,
endpoints: {
discovery: "https://issuer/.well-known/openid-configuration",
issuer: "https://issuer",
authorization: "https://issuer/oauth2/auth",
token: "https://issuer/oauth2/token",
userinfo: "https://issuer/userinfo",
},
});
}
if (pathname.startsWith("/api/v1/dev/clients/") && method === "DELETE") {
const clientId = parseClientId(pathname);
state.clients = state.clients.filter((client) => client.id !== clientId);
appendAuditLog("CLIENT_DELETE", "DELETE_CLIENT", clientId);
return route.fulfill({ status: 204 });
}
if (pathname.startsWith("/api/v1/dev/clients/") && method === "GET") {
const clientId = parseClientId(pathname);
const found = state.clients.find((client) => client.id === clientId);
if (!found) return json(route, { error: "forbidden" }, 403);
return json(route, {
client: found,
endpoints: {
discovery: "https://issuer/.well-known/openid-configuration",
issuer: "https://issuer",
authorization: "https://issuer/oauth2/auth",
token: "https://issuer/oauth2/token",
userinfo: "https://issuer/userinfo",
},
});
}
if (pathname === "/api/v1/dev/consents" && method === "GET") {
const subject = searchParams.get("subject") || "";
const clientId = searchParams.get("client_id") || "";
const status = searchParams.get("status") || "";
const items = state.consents.filter((row) => {
const matchesSubject =
!subject ||
row.subject.includes(subject) ||
row.userName.includes(subject);
const matchesClientId = !clientId || row.clientId === clientId;
const matchesStatus = !status || row.status === status;
return matchesSubject && matchesClientId && matchesStatus;
});
return json(route, { items });
}
if (pathname === "/api/v1/dev/consents" && method === "DELETE") {
const subject = searchParams.get("subject") || "";
const clientId = searchParams.get("client_id") || "";
const target = state.consents.find(
(row) => row.subject === subject && row.clientId === clientId,
);
if (target) {
target.status = "revoked";
target.deletedAt = "2026-03-03T10:00:00.000Z";
}
return route.fulfill({ status: 204 });
}
if (pathname === "/api/v1/dev/audit-logs" && method === "GET") {
if (state.auditLogsByCursor) {
const cursor = searchParams.get("cursor") || "";
const pageSet = state.auditLogsByCursor[cursor] ?? { items: [] };
return json(route, {
items: pageSet.items,
limit: 50,
cursor: cursor || undefined,
next_cursor: pageSet.next_cursor,
});
}
if (state.auditLogs) {
const action = searchParams.get("action") || "";
const clientId = searchParams.get("client_id") || "";
const status = searchParams.get("status") || "";
const filtered = state.auditLogs.filter((item) => {
let parsedDetails: { action?: string; target_id?: string } = {};
try {
parsedDetails = JSON.parse(item.details) as {
action?: string;
target_id?: string;
};
} catch {}
const matchesAction = !action || parsedDetails.action === action;
const matchesClient =
!clientId || parsedDetails.target_id === clientId;
const matchesStatus = !status || item.status === status;
return matchesAction && matchesClient && matchesStatus;
});
return json(route, { items: filtered, limit: 50 });
}
return json(route, { items: [], limit: 50 });
}
return json(route, { error: `Unhandled ${method} ${pathname}` }, 404);
});
}

View File

@@ -0,0 +1,24 @@
import type { Page, TestInfo } from "@playwright/test";
function safeName(name: string): string {
return name
.trim()
.toLowerCase()
.replace(/[^a-z0-9-_]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "");
}
export async function captureEvidence(
page: Page,
testInfo: TestInfo,
name: string,
) {
const filename = `${safeName(name)}.png`;
const fullPath = testInfo.outputPath(filename);
await page.screenshot({ path: fullPath, fullPage: true });
await testInfo.attach(name, {
path: fullPath,
contentType: "image/png",
});
}