1
0
forked from baron/baron-sso

merge: integrate origin dev into dev

Includes Worksmobile SSOT sync comparison updates, UUID import conflict resolution, and Playwright route mock stabilization.
This commit is contained in:
2026-06-01 17:48:39 +09:00
91 changed files with 2173 additions and 1268 deletions

View File

@@ -302,22 +302,6 @@ export function UserBulkUploadModal({
});
};
const downloadTemplate = () => {
const headers =
"email,sub_email,name,phone,role,tenant_slug,department,grade,position,jobTitle,employee_id,tenant_slug1,department1,grade1,position1,jobTitle1,employee_id1";
const example =
"user1@example.com,sub1@test.com;sub2@test.com,홍길동,010-1234-5678,user,tenant-slug,개발팀,수석,팀장,프론트엔드,EMP001,second-tenant,센터,책임,,Architecture,EMP002";
const blob = new Blob([`${headers}\n${example}`], {
type: "text/csv;charset=utf-8;",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "user_bulk_template.csv";
a.click();
URL.revokeObjectURL(url);
};
const reset = () => {
setFile(null);
setPreviewData([]);
@@ -420,7 +404,7 @@ export function UserBulkUploadModal({
<Button
variant="ghost"
size="sm"
onClick={downloadTemplate}
onClick={downloadUserTemplate}
className="gap-2"
>
<Download size={14} />
@@ -626,15 +610,71 @@ export function UserBulkUploadModal({
) : (
<div className="space-y-4 py-4">
<div className="flex items-center gap-4 p-4 rounded-lg bg-muted/30 border">
<div className="flex-1 text-center">
<div className="text-2xl font-bold text-green-600">
{successCount}
</div>
<div className="text-xs text-muted-foreground uppercase">
{t("ui.common.success", "성공")}
</div>
</div>
<div className="w-px h-10 bg-border" />
{results.some((r) => r.success && r.status === "created") && (
<>
<div className="flex-1 text-center">
<div className="text-2xl font-bold text-green-600">
{
results.filter(
(r) => r.success && r.status === "created",
).length
}
</div>
<div className="text-xs text-muted-foreground uppercase">
{t("ui.common.status.new", "신규")}
</div>
</div>
<div className="w-px h-10 bg-border" />
</>
)}
{results.some((r) => r.success && r.status === "updated") && (
<>
<div className="flex-1 text-center">
<div className="text-2xl font-bold text-blue-600">
{
results.filter(
(r) => r.success && r.status === "updated",
).length
}
</div>
<div className="text-xs text-muted-foreground uppercase">
{t("ui.common.status.updated", "수정")}
</div>
</div>
<div className="w-px h-10 bg-border" />
</>
)}
{results.some((r) => r.success && r.status === "unchanged") && (
<>
<div className="flex-1 text-center">
<div className="text-2xl font-bold text-slate-500">
{
results.filter(
(r) => r.success && r.status === "unchanged",
).length
}
</div>
<div className="text-xs text-muted-foreground uppercase">
{t("ui.common.status.unchanged", "동일")}
</div>
</div>
<div className="w-px h-10 bg-border" />
</>
)}
{!results.some((r) => r.success && r.status) &&
successCount > 0 && (
<>
<div className="flex-1 text-center">
<div className="text-2xl font-bold text-green-600">
{successCount}
</div>
<div className="text-xs text-muted-foreground uppercase">
{t("ui.common.success", "성공")}
</div>
</div>
<div className="w-px h-10 bg-border" />
</>
)}
<div className="flex-1 text-center">
<div className="text-2xl font-bold text-destructive">
{failCount}
@@ -664,7 +704,60 @@ export function UserBulkUploadModal({
/>
)}
<div className="flex-1 min-w-0">
<div className="font-medium truncate">{r.email}</div>
<div className="flex items-center gap-2">
<div className="font-medium truncate">{r.email}</div>
{r.success && r.status === "created" && (
<span className="px-1.5 py-0.5 rounded-full bg-green-100 text-green-700 text-[10px] font-bold">
{t("ui.common.status.new", "신규")}
</span>
)}
{r.success && r.status === "updated" && (
<span className="px-1.5 py-0.5 rounded-full bg-blue-100 text-blue-700 text-[10px] font-bold">
{t("ui.common.status.updated", "수정")}
</span>
)}
{r.success && r.status === "unchanged" && (
<span className="px-1.5 py-0.5 rounded-full bg-slate-100 text-slate-600 text-[10px] font-bold">
{t("ui.common.status.unchanged", "동일")}
</span>
)}
{r.success && !r.status && (
<span className="px-1.5 py-0.5 rounded-full bg-green-100 text-green-700 text-[10px] font-bold">
{t("ui.common.success", "성공")}
</span>
)}
</div>
{r.success && r.status === "updated" && (
<div className="mt-1 text-[10px] text-muted-foreground flex flex-wrap gap-1 items-center">
<span className="font-medium">
{t(
"ui.admin.users.bulk.modified_fields",
"수정 항목:",
)}
</span>
{r.modifiedFields &&
r.modifiedFields.length > 0 &&
r.modifiedFields.map((field) => (
<span
key={field}
className="px-1 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100"
>
{t(
`ui.admin.users.field.${field.toLowerCase()}`,
field,
)}
</span>
))}
</div>
)}
{r.success && r.status === "unchanged" && (
<div className="mt-1 text-[10px] text-muted-foreground italic">
{t(
"ui.admin.users.bulk.no_changes",
"기존 데이터와 동일 (변경 사항 없음)",
)}
</div>
)}
{!r.success && (
<div className="text-xs text-destructive">
{r.message}

View File

@@ -97,7 +97,7 @@ test@test.com,Test,local-tenant-id,missing-slug,Missing Tenant,COMPANY,parent-sl
});
});
it("should preserve exported user_id for UUID based restore", () => {
it("should ignore exported user_id during user CSV import", () => {
const csv = `user_id,email,name,tenant_id,tenant_slug
9f8cc1b1-af8d-45d4-946c-924a529c2556,restore@test.com,Restore User,tenant-id,restore-tenant`;
@@ -105,12 +105,13 @@ test@test.com,Test,local-tenant-id,missing-slug,Missing Tenant,COMPANY,parent-sl
expect(result).toHaveLength(1);
expect(result[0]).toMatchObject({
userId: "9f8cc1b1-af8d-45d4-946c-924a529c2556",
email: "restore@test.com",
name: "Restore User",
tenantId: "tenant-id",
tenantSlug: "restore-tenant",
});
expect(result[0]).not.toHaveProperty("id");
expect(result[0]).not.toHaveProperty("uuid");
});
it("should parse one nullable additional appointment from numbered columns", () => {

View File

@@ -28,9 +28,7 @@ export function parseUserCSV(text: string): BulkUserItem[] {
const value = values[index];
if (value === undefined || value === "") continue;
if (header === "user_id") {
item.userId = value;
} else if (header === "email") {
if (header === "email") {
item.email = value;
} else if (header === "name") {
item.name = value;

View File

@@ -726,7 +726,6 @@ export type BulkUserAppointment = {
};
export type BulkUserItem = {
userId?: string;
email: string;
loginId?: string;
name: string;
@@ -764,6 +763,7 @@ export type BulkUserResult = {
success: boolean;
message?: string;
userId?: string;
modifiedFields?: string[];
};
export type BulkUserResponse = {

View File

@@ -112,7 +112,7 @@ test.describe("Users Bulk Upload Secondary Emails", () => {
await page.getByTestId("bulk-start-btn").click();
await expect(page.getByText(/성공|Success/i)).toBeVisible();
await expect(page.getByText(/성공|Success/i).first()).toBeVisible();
expect(bulkPayload).not.toBeNull();
expect(bulkPayload.users).toHaveLength(1);

View File

@@ -0,0 +1,139 @@
import { expect, test } from "@playwright/test";
test.describe("Users Bulk Upload UUID Import Policy", () => {
test.beforeEach(async ({ page }) => {
await page.addInitScript(() => {
window.localStorage.setItem("locale", "ko");
window.localStorage.setItem("admin_session", "fake-token");
(
window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean }
)._IS_TEST_MODE = true;
const authority = "http://localhost:5000/oidc";
const client_id = "adminfront";
const key = `oidc.user:${authority}:${client_id}`;
const authData = {
access_token: "fake-token",
token_type: "Bearer",
profile: { sub: "admin-user", name: "Admin", role: "super_admin" },
expires_at: Math.floor(Date.now() / 1000) + 36000,
};
window.localStorage.setItem(key, JSON.stringify(authData));
});
await page.route("**/api/v1/**", async (route) => {
const url = route.request().url();
const headers = { "Access-Control-Allow-Origin": "*" };
if (url.includes("/user/me")) {
return route.fulfill({
json: {
id: "admin-user",
name: "Admin",
role: "super_admin",
manageableTenants: [],
},
headers,
});
}
if (url.includes("/admin/users") && !url.includes("/bulk")) {
return route.fulfill({
json: { items: [], total: 0, limit: 50, offset: 0 },
headers,
});
}
if (url.includes("/admin/tenants")) {
return route.fulfill({
json: { items: [], total: 0, limit: 100, offset: 0 },
headers,
});
}
return route.fulfill({ json: { items: [], total: 0 }, headers });
});
await page.route("**/oidc/**", async (route) => {
await route.fulfill({ json: { issuer: "http://localhost:5000/oidc" } });
});
});
test("should not include exported user_id or uuid in bulk upload payload", async ({
page,
}) => {
let bulkPayload = "";
const testUuid = "550e8400-e29b-41d4-a716-446655440000";
await page.route("**/api/v1/admin/users/bulk", async (route) => {
bulkPayload = route.request().postData() ?? "";
return route.fulfill({
json: {
results: [
{ email: "uuid@test.com", success: true, userId: "kratos-id" },
],
},
headers: { "Access-Control-Allow-Origin": "*" },
});
});
await page.goto("/users");
await page.getByTestId("user-data-mgmt-btn").click();
await page
.getByRole("menuitem", { name: /일괄 임포트|Bulk Import/i })
.click();
await page.locator('input[type="file"]').setInputFiles({
name: "users_uuid.csv",
mimeType: "text/csv",
buffer: Buffer.from(
`user_id,email,name,uuid\n${testUuid},uuid@test.com,UUID User,${testUuid}\n`,
),
});
await page.getByTestId("bulk-start-btn").click();
await expect(page.getByText("uuid@test.com")).toBeVisible();
const payload = JSON.parse(bulkPayload);
expect(payload.users[0]).not.toHaveProperty("userId");
expect(payload.users[0]).not.toHaveProperty("uuid");
expect(payload.users[0]).not.toHaveProperty("id");
});
test("should treat id column as login id, not UUID import", async ({
page,
}) => {
let bulkPayload = "";
const testUuid = "550e8400-e29b-41d4-a716-446655440001";
await page.route("**/api/v1/admin/users/bulk", async (route) => {
bulkPayload = route.request().postData() ?? "";
return route.fulfill({
json: {
results: [
{ email: "id-uuid@test.com", success: true, userId: "kratos-id" },
],
},
headers: { "Access-Control-Allow-Origin": "*" },
});
});
await page.goto("/users");
await page.getByTestId("user-data-mgmt-btn").click();
await page
.getByRole("menuitem", { name: /일괄 임포트|Bulk Import/i })
.click();
await page.locator('input[type="file"]').setInputFiles({
name: "users_id.csv",
mimeType: "text/csv",
buffer: Buffer.from(
`email,name,id\nid-uuid@test.com,ID UUID User,${testUuid}\n`,
),
});
await page.getByTestId("bulk-start-btn").click();
const payload = JSON.parse(bulkPayload);
expect(payload.users[0]).not.toHaveProperty("uuid");
expect(payload.users[0].loginId).toBe(testUuid);
expect(payload.users[0].metadata.naverworks_id).toBe(testUuid);
});
});

View File

@@ -94,6 +94,15 @@ test.describe("Worksmobile tenant management", () => {
});
}
if (
url.pathname.endsWith(
"/admin/tenants/hanmac-family-id/worksmobile/credential-batches",
) &&
method === "GET"
) {
return route.fulfill({ json: [], headers });
}
if (
url.pathname.endsWith(
"/admin/tenants/hanmac-family-id/worksmobile/comparison",
@@ -361,6 +370,15 @@ test.describe("Worksmobile tenant management", () => {
});
}
if (
url.pathname.endsWith(
"/admin/tenants/hanmac-family-id/worksmobile/credential-batches",
) &&
method === "GET"
) {
return route.fulfill({ json: [], headers });
}
if (
url.pathname.endsWith(
"/admin/tenants/hanmac-family-id/worksmobile/comparison",
@@ -467,6 +485,15 @@ test.describe("Worksmobile tenant management", () => {
});
}
if (
url.pathname.endsWith(
"/admin/tenants/hanmac-family-id/worksmobile/credential-batches",
) &&
method === "GET"
) {
return route.fulfill({ json: [], headers });
}
if (
url.pathname.endsWith(
"/admin/tenants/hanmac-family-id/worksmobile/comparison",
@@ -614,6 +641,30 @@ test.describe("Worksmobile tenant management", () => {
});
}
if (
url.pathname.endsWith(
"/admin/tenants/hanmac-family-id/worksmobile/credential-batches",
) &&
method === "GET"
) {
return route.fulfill({
json: [
{
batchId: "batch-1",
operation: "worksmobile_user_sync",
userCount: 1,
processedCount: 1,
pendingCount: 0,
processingCount: 0,
failedCount: 0,
hasPasswords: true,
createdAt: "2026-05-01T00:00:00Z",
},
],
headers,
});
}
if (
url.pathname.endsWith(
"/admin/tenants/hanmac-family-id/worksmobile/comparison",
@@ -691,7 +742,9 @@ test.describe("Worksmobile tenant management", () => {
await expect(page.getByText("Worksmobile 연동")).toBeVisible();
const download = page.waitForEvent("download");
await page.getByRole("button", { name: "초기 비밀번호 CSV" }).click();
await page
.getByRole("button", { name: "batch-1 비밀번호 CSV 다운로드" })
.click();
const passwordCsv = await download;
expect(passwordCsv.suggestedFilename()).toBe("worksmobile-passwords.csv");
const passwordCsvPath = await passwordCsv.path();

View File

@@ -110,7 +110,7 @@ func (m *e2eMockKratosAdminService) ListIdentities(ctx context.Context) ([]servi
return nil, nil
}
func (m *e2eMockKratosAdminService) UpdateIdentity(ctx context.Context, identityID string, traits map[string]interface{}, state string) (*service.KratosIdentity, error) {
func (m *e2eMockKratosAdminService) UpdateIdentity(ctx context.Context, identityID string, traits map[string]any, state string) (*service.KratosIdentity, error) {
return nil, nil
}
@@ -325,7 +325,7 @@ func runHeadlessPasswordLoginE2ERequest(
Client: domain.HydraClient{
ClientID: "headless-login-client",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",

View File

@@ -459,7 +459,7 @@ func main() {
app.Use(cors.New(cors.Config{
AllowOriginsFunc: func(origin string) bool {
// 1. Check static allowed list
for _, allowed := range strings.Split(allowedOrigins, ",") {
for allowed := range strings.SplitSeq(allowedOrigins, ",") {
if origin == strings.TrimSpace(allowed) {
return true
}
@@ -860,9 +860,9 @@ func main() {
// Client Logging Route (Standardized & Flattened)
api.Post("/client-log", func(c *fiber.Ctx) error {
type LogReq struct {
Level string `json:"level"`
Message string `json:"message"`
Data map[string]interface{} `json:"data,omitempty"`
Level string `json:"level"`
Message string `json:"message"`
Data map[string]any `json:"data,omitempty"`
}
var req LogReq
if err := c.BodyParser(&req); err != nil {

View File

@@ -136,7 +136,7 @@ func buildSuperAdminBrokerUser(email, name string) *domain.BrokerUser {
Email: email,
Name: name,
PhoneNumber: "",
Attributes: map[string]interface{}{
Attributes: map[string]any{
"department": "Admin",
"affiliationType": "internal",
"grade": "",
@@ -170,7 +170,7 @@ func (s *gormSuperAdminStore) CreateUser(ctx context.Context, user *domain.User)
}
func (s *gormSuperAdminStore) UpdateUserSuperAdmin(ctx context.Context, userID string, name string) (*domain.User, error) {
updates := map[string]interface{}{
updates := map[string]any{
"role": domain.RoleSuperAdmin,
"status": domain.UserStatusActive,
"updated_at": time.Now(),

View File

@@ -31,7 +31,7 @@ func SeedAdminIdentity(idp domain.IdentityProvider) (string, error) {
Email: adminEmail,
Name: adminName,
PhoneNumber: "",
Attributes: map[string]interface{}{
Attributes: map[string]any{
"department": "Admin",
"affiliationType": "internal",
"grade": "",
@@ -44,7 +44,7 @@ func SeedAdminIdentity(idp domain.IdentityProvider) (string, error) {
var err error
var identityID string
for i := 0; i < maxRetries; i++ {
for i := range maxRetries {
identityID, err = idp.CreateUser(user, adminPassword)
if err == nil {
slog.Info("[Bootstrap] Admin identity created in IDP", "email", adminEmail, "idp", idp.Name(), "id", identityID)

View File

@@ -54,7 +54,7 @@ func SyncAdminRole(db *gorm.DB, kratosID string) error {
}
// Update role if needed
updates := map[string]interface{}{}
updates := map[string]any{}
if user.Role != domain.RoleSuperAdmin {
updates["role"] = domain.RoleSuperAdmin
}

View File

@@ -98,15 +98,15 @@ var hanmacInitialRomanization = []string{
func SplitEmailDomain(email string) (string, string, error) {
normalized := strings.ToLower(strings.TrimSpace(email))
at := strings.Index(normalized, "@")
if at < 0 {
before, after, ok := strings.Cut(normalized, "@")
if !ok {
return "", "", errors.New("email must contain @")
}
if strings.Count(normalized, "@") != 1 {
return "", "", errors.New("email must contain one @")
}
localPart := strings.TrimSpace(normalized[:at])
domainPart := strings.TrimSpace(normalized[at+1:])
localPart := strings.TrimSpace(before)
domainPart := strings.TrimSpace(after)
if domainPart == "" || !strings.Contains(domainPart, ".") {
return "", "", errors.New("email domain is invalid")
}

View File

@@ -19,21 +19,21 @@ const (
)
type HydraClient struct {
ClientID string `json:"client_id"`
ClientName string `json:"client_name,omitempty"`
ClientSecret string `json:"client_secret,omitempty"` // Added
ClientURI string `json:"client_uri,omitempty"`
RedirectURIs []string `json:"redirect_uris,omitempty"`
GrantTypes []string `json:"grant_types,omitempty"`
ResponseTypes []string `json:"response_types,omitempty"`
Scope string `json:"scope,omitempty"`
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
SkipConsent *bool `json:"skip_consent,omitempty"`
JWKSUri string `json:"jwks_uri,omitempty"`
JWKS interface{} `json:"jwks,omitempty"`
BackChannelLogoutURI string `json:"backchannel_logout_uri,omitempty"`
BackChannelLogoutSessionRequired *bool `json:"backchannel_logout_session_required,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
ClientID string `json:"client_id"`
ClientName string `json:"client_name,omitempty"`
ClientSecret string `json:"client_secret,omitempty"` // Added
ClientURI string `json:"client_uri,omitempty"`
RedirectURIs []string `json:"redirect_uris,omitempty"`
GrantTypes []string `json:"grant_types,omitempty"`
ResponseTypes []string `json:"response_types,omitempty"`
Scope string `json:"scope,omitempty"`
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
SkipConsent *bool `json:"skip_consent,omitempty"`
JWKSUri string `json:"jwks_uri,omitempty"`
JWKS any `json:"jwks,omitempty"`
BackChannelLogoutURI string `json:"backchannel_logout_uri,omitempty"`
BackChannelLogoutSessionRequired *bool `json:"backchannel_logout_session_required,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
func (c *HydraClient) SupportsHeadlessLogin() bool {
@@ -65,7 +65,7 @@ func (c *HydraClient) HeadlessJWKSURI() string {
return strings.TrimSpace(c.JWKSUri)
}
func (c *HydraClient) HeadlessJWKS() interface{} {
func (c *HydraClient) HeadlessJWKS() any {
if c.Metadata != nil {
if value, ok := c.Metadata[MetadataHeadlessJWKS]; ok && value != nil {
return value
@@ -140,6 +140,6 @@ type HydraConsentSession struct {
AuthenticatedAt *time.Time `json:"authenticated_at,omitempty"`
RequestedAt *time.Time `json:"requested_at,omitempty"`
HandledAt *time.Time `json:"handled_at,omitempty"`
Client HydraClient `json:"client,omitempty"`
Client HydraClient `json:"client"`
ConsentRequest *HydraConsentRequest `json:"consent_request,omitempty"`
}

View File

@@ -20,7 +20,7 @@ type BrokerUser struct {
PhoneNumber string `json:"phone_number"`
// Attributes stores custom user attributes.
// The "required_keys" tag specifies which keys MUST be present in the IDP's schema support.
Attributes map[string]interface{} `json:"attributes" required_keys:"grade,department"`
Attributes map[string]any `json:"attributes" required_keys:"grade,department"`
}
// IDPMetadata represents the schema capabilities of an Identity Provider.

View File

@@ -2,6 +2,7 @@ package domain
import (
"fmt"
"slices"
"strings"
"time"
@@ -208,10 +209,8 @@ func ValidateLoginID(loginID string, emails []string, phone string) error {
reserved := []string{"admin", "system", "root", "master", "superuser", "guest", "operator"}
lowerID := strings.ToLower(loginID)
for _, r := range reserved {
if lowerID == r {
return fmt.Errorf("reserved ID cannot be used")
}
if slices.Contains(reserved, lowerID) {
return fmt.Errorf("reserved ID cannot be used")
}
return nil

View File

@@ -26,7 +26,7 @@ func TestApiKeyHandler_CreateApiKey(t *testing.T) {
app.Post("/api-keys", h.CreateApiKey)
input := map[string]interface{}{
input := map[string]any{
"name": "M2M Test",
"scopes": []string{"read", "write"},
}
@@ -47,7 +47,7 @@ func TestApiKeyHandler_Validation(t *testing.T) {
app.Post("/api-keys", h.CreateApiKey)
// Missing name
input := map[string]interface{}{
input := map[string]any{
"scopes": []string{"read"},
}
body, _ := json.Marshal(input)
@@ -65,7 +65,7 @@ func TestApiKeyHandler_UpdateApiKeyScopesRequiresDatabase(t *testing.T) {
app.Patch("/api-keys/:id", h.UpdateApiKey)
body, _ := json.Marshal(map[string]interface{}{
body, _ := json.Marshal(map[string]any{
"scopes": []string{"org-context:read"},
})
req := httptest.NewRequest("PATCH", "/api-keys/api-key-id", bytes.NewReader(body))

View File

@@ -16,11 +16,13 @@ import (
"fmt"
"io"
"log/slog"
"maps"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"slices"
"sort"
"strconv"
"strings"
@@ -601,7 +603,7 @@ func (h *AuthHandler) GetActiveTenants(c *fiber.Ctx) error {
email := c.Query("email")
if email == "" {
// No email provided, return empty list (Security policy)
return c.JSON([]interface{}{})
return c.JSON([]any{})
}
// 1. Verify Verification Status in Redis
@@ -615,7 +617,7 @@ func (h *AuthHandler) GetActiveTenants(c *fiber.Ctx) error {
// 2. Extract domain from verified email
parts := strings.Split(email, "@")
if len(parts) != 2 {
return c.JSON([]interface{}{})
return c.JSON([]any{})
}
domainName := parts[1]
@@ -623,7 +625,7 @@ func (h *AuthHandler) GetActiveTenants(c *fiber.Ctx) error {
isInternal, _ := h.isAffiliateTenant(c.Context(), domainName)
if !isInternal {
// If not an affiliate email, do not show any tenants
return c.JSON([]interface{}{})
return c.JSON([]any{})
}
// 3. List and Filter Tenants
@@ -785,7 +787,7 @@ func (h *AuthHandler) Signup(c *fiber.Ctx) error {
slog.Info("[Signup] Phone normalization", "raw", req.Phone, "normalized", normalizedPhone)
// IDP에 전달할 BrokerUser 스키마 구성
attributes := map[string]interface{}{
attributes := map[string]any{
"department": req.Department,
"affiliationType": req.AffiliationType,
"grade": "",
@@ -854,9 +856,7 @@ func (h *AuthHandler) Signup(c *fiber.Ctx) error {
// Merge metadata
localUser.Metadata = make(domain.JSONMap)
for k, v := range req.Metadata {
localUser.Metadata[k] = v
}
maps.Copy(localUser.Metadata, req.Metadata)
if h.UserRepo != nil {
go func(u *domain.User, ids []domain.UserLoginID) {
@@ -915,7 +915,7 @@ func (h *AuthHandler) getBearerToken(c *fiber.Ctx) string {
}
func firstForwardedValue(raw string) string {
for _, part := range strings.Split(raw, ",") {
for part := range strings.SplitSeq(raw, ",") {
value := strings.TrimSpace(part)
if value != "" {
return value
@@ -925,8 +925,8 @@ func firstForwardedValue(raw string) string {
}
func forwardedDirective(raw, key string) string {
for _, group := range strings.Split(raw, ",") {
for _, directive := range strings.Split(group, ";") {
for group := range strings.SplitSeq(raw, ",") {
for directive := range strings.SplitSeq(group, ";") {
pair := strings.SplitN(strings.TrimSpace(directive), "=", 2)
if len(pair) != 2 {
continue
@@ -1075,9 +1075,9 @@ func (h *AuthHandler) GetTenantInfo(c *fiber.Ctx) error {
if loginIdField, ok := tenant.Config["loginIdField"].(string); ok && loginIdField != "" {
res["loginIdField"] = loginIdField
// Find label in userSchema
if schema, ok := tenant.Config["userSchema"].([]interface{}); ok {
if schema, ok := tenant.Config["userSchema"].([]any); ok {
for _, field := range schema {
if f, ok := field.(map[string]interface{}); ok {
if f, ok := field.(map[string]any); ok {
if f["key"] == loginIdField {
res["loginIdLabel"] = f["label"]
break
@@ -1215,9 +1215,7 @@ func buildOidcClaimsFromTraits(traits map[string]any, scopes []string, tenantID
if includeTenantDetails {
// tenant 스코프가 있을 때만 대표소속 namespace metadata를 top-level claim으로 펼칩니다.
if namespaced, ok := traits[tenantID].(map[string]any); ok {
for k, v := range namespaced {
claims[k] = v
}
maps.Copy(claims, namespaced)
}
}
}
@@ -1570,7 +1568,7 @@ func tenantClaimAncestorSummaries(ancestors []*domain.Tenant) []map[string]any {
return items
}
func applyConfiguredIDTokenClaims(baseClaims map[string]any, metadata map[string]interface{}) map[string]any {
func applyConfiguredIDTokenClaims(baseClaims map[string]any, metadata map[string]any) map[string]any {
if baseClaims == nil {
baseClaims = map[string]any{}
}
@@ -1670,7 +1668,7 @@ func (h *AuthHandler) withRPProfileClaims(ctx context.Context, claims map[string
claims["rp_profiles"] = append(existing, profile)
return claims
}
if existing, ok := claims["rp_profiles"].([]interface{}); ok {
if existing, ok := claims["rp_profiles"].([]any); ok {
claims["rp_profiles"] = append(existing, profile)
return claims
}
@@ -1678,7 +1676,7 @@ func (h *AuthHandler) withRPProfileClaims(ctx context.Context, claims map[string
return claims
}
func extractClaimEnabledCustomUserSchemaKeys(metadata map[string]interface{}) []string {
func extractClaimEnabledCustomUserSchemaKeys(metadata map[string]any) []string {
if metadata == nil {
return nil
}
@@ -1687,12 +1685,12 @@ func extractClaimEnabledCustomUserSchemaKeys(metadata map[string]interface{}) []
return nil
}
var items []interface{}
var items []any
switch schema := rawSchema.(type) {
case []interface{}:
case []any:
items = schema
case []map[string]interface{}:
items = make([]interface{}, 0, len(schema))
case []map[string]any:
items = make([]any, 0, len(schema))
for _, item := range schema {
items = append(items, item)
}
@@ -1703,7 +1701,7 @@ func extractClaimEnabledCustomUserSchemaKeys(metadata map[string]interface{}) []
keys := make([]string, 0, len(items))
seen := make(map[string]struct{})
for _, item := range items {
field, ok := item.(map[string]interface{})
field, ok := item.(map[string]any)
if !ok {
if typed, typedOK := item.(map[string]any); typedOK {
field = typed
@@ -4275,11 +4273,11 @@ func (h *AuthHandler) ScanQRLogin(c *fiber.Ctx) error {
}
type kratosCourierRequest struct {
Recipient string `json:"recipient"`
TemplateType string `json:"template_type"`
TemplateData map[string]interface{} `json:"template_data"`
Subject string `json:"subject"`
Body string `json:"body"`
Recipient string `json:"recipient"`
TemplateType string `json:"template_type"`
TemplateData map[string]any `json:"template_data"`
Subject string `json:"subject"`
Body string `json:"body"`
}
// HandleKratosCourierRelay - Kratos courier HTTP 요청을 받아 메일/SMS 발송으로 변환합니다.
@@ -4604,7 +4602,7 @@ func (h *AuthHandler) isSmsCodeOnly(loginID string) bool {
func (h *AuthHandler) generateShortCode(code string) string {
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i := 0; i < 10; i++ {
for range 10 {
b := make([]byte, 2)
if _, err := crand.Read(b); err != nil {
break
@@ -4646,7 +4644,7 @@ func firstNonEmpty(values ...string) string {
return ""
}
func extractFirstString(data map[string]interface{}, keys ...string) string {
func extractFirstString(data map[string]any, keys ...string) string {
if data == nil {
return ""
}
@@ -5229,10 +5227,7 @@ func (h *AuthHandler) GetAuthTimeline(c *fiber.Ctx) error {
}
candidates := buildLoginCandidates(profile)
fetchLimit := limit * 10
if fetchLimit < limit {
fetchLimit = limit
}
fetchLimit := max(limit*10, limit)
if fetchLimit > 500 {
fetchLimit = 500
}
@@ -5805,9 +5800,9 @@ func (h *AuthHandler) ListLinkedRps(c *fiber.Ctx) error {
}
for _, log := range auditLogs {
var details struct {
ClientID string `json:"client_id"`
ClientName string `json:"client_name"`
Scopes interface{} `json:"scopes"`
ClientID string `json:"client_id"`
ClientName string `json:"client_name"`
Scopes any `json:"scopes"`
}
// 로그 Details 파싱
if err := json.Unmarshal([]byte(log.Details), &details); err != nil {
@@ -5824,7 +5819,7 @@ func (h *AuthHandler) ListLinkedRps(c *fiber.Ctx) error {
// 스코프 추출 (consent.granted인 경우)
scopes := []string{}
if sList, ok := details.Scopes.([]interface{}); ok {
if sList, ok := details.Scopes.([]any); ok {
for _, s := range sList {
if str, ok := s.(string); ok {
scopes = append(scopes, str)
@@ -5927,7 +5922,7 @@ func (h *AuthHandler) RevokeLinkedRp(c *fiber.Ctx) error {
}
if h.AuditRepo != nil {
detailsMap := map[string]interface{}{
detailsMap := map[string]any{
"client_id": clientID,
}
detailsBytes, _ := json.Marshal(detailsMap)
@@ -6085,7 +6080,7 @@ func (h *AuthHandler) GetConsentRequest(c *fiber.Ctx) error {
}
if h.AuditRepo != nil {
detailsMap := map[string]interface{}{
detailsMap := map[string]any{
"client_id": consentRequest.Client.ClientID,
"scopes": consentRequest.RequestedScope,
"client_name": consentRequest.Client.ClientName,
@@ -6135,12 +6130,12 @@ func (h *AuthHandler) GetConsentRequest(c *fiber.Ctx) error {
// structured_scopes 파싱 및 scope_details 생성
if metadata := consentRequest.Client.Metadata; metadata != nil {
if rawScopes, ok := metadata["structured_scopes"]; ok {
scopeDetails := make(map[string]map[string]interface{})
scopeDetails := make(map[string]map[string]any)
// JSON 언마샬링 등을 통해 map[string]interface{} 또는 []interface{}로 들어옴
// 안전하게 처리
rawBytes, _ := json.Marshal(rawScopes)
var scopesList []map[string]interface{}
var scopesList []map[string]any
if err := json.Unmarshal(rawBytes, &scopesList); err == nil {
for _, item := range scopesList {
name, _ := item["name"].(string)
@@ -6150,7 +6145,7 @@ func (h *AuthHandler) GetConsentRequest(c *fiber.Ctx) error {
desc, _ := item["description"].(string)
mandatory, _ := item["mandatory"].(bool)
scopeDetails[name] = map[string]interface{}{
scopeDetails[name] = map[string]any{
"description": desc,
"mandatory": mandatory,
}
@@ -6280,7 +6275,7 @@ func (h *AuthHandler) AcceptConsentRequest(c *fiber.Ctx) error {
}
if h.AuditRepo != nil {
detailsMap := map[string]interface{}{
detailsMap := map[string]any{
"client_id": consentRequest.Client.ClientID,
"scopes": consentRequest.RequestedScope,
"client_name": consentRequest.Client.ClientName,
@@ -6618,7 +6613,7 @@ func appendLoginIDsFromValues(subjects []string, email string, phone string) []s
return subjects
}
func appendLoginIDsFromTraits(subjects []string, traits map[string]interface{}) []string {
func appendLoginIDsFromTraits(subjects []string, traits map[string]any) []string {
if traits == nil {
return subjects
}
@@ -7235,7 +7230,7 @@ func (h *AuthHandler) resolveKratosLoginID(token string) (string, error) {
return loginID, nil
}
func pickLoginIDFromTraits(traits map[string]interface{}) string {
func pickLoginIDFromTraits(traits map[string]any) string {
if traits == nil {
return ""
}
@@ -7409,12 +7404,12 @@ func extractLoginIDFromClaims(claims map[string]any) string {
return ""
}
func (h *AuthHandler) getKratosIdentity(sessionToken string) (string, map[string]interface{}, string, error) {
func (h *AuthHandler) getKratosIdentity(sessionToken string) (string, map[string]any, string, error) {
identityID, traits, _, usedID, err := h.getKratosIdentityWithSession(sessionToken)
return identityID, traits, usedID, err
}
func (h *AuthHandler) getKratosIdentityWithSession(sessionToken string) (string, map[string]interface{}, string, string, error) {
func (h *AuthHandler) getKratosIdentityWithSession(sessionToken string) (string, map[string]any, string, string, error) {
kratosURL := strings.TrimRight(os.Getenv("KRATOS_PUBLIC_URL"), "/")
if kratosURL == "" {
kratosURL = "http://kratos:4433"
@@ -7442,8 +7437,8 @@ func (h *AuthHandler) getKratosIdentityWithSession(sessionToken string) (string,
Identifier string `json:"identifier"`
} `json:"authentication_methods"`
Identity struct {
ID string `json:"id"`
Traits map[string]interface{} `json:"traits"`
ID string `json:"id"`
Traits map[string]any `json:"traits"`
} `json:"identity"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
@@ -7501,7 +7496,7 @@ func (h *AuthHandler) issueKratosSession(ctx context.Context, identityID string)
kratosAdminURL = "http://kratos:4434"
}
payload := map[string]interface{}{
payload := map[string]any{
"identity_id": identityID,
}
body, _ := json.Marshal(payload)
@@ -7534,12 +7529,12 @@ func (h *AuthHandler) issueKratosSession(ctx context.Context, identityID string)
return parsed.SessionToken, nil
}
func (h *AuthHandler) getKratosIdentityWithCookie(cookie string) (string, map[string]interface{}, string, error) {
func (h *AuthHandler) getKratosIdentityWithCookie(cookie string) (string, map[string]any, string, error) {
identityID, traits, _, usedID, err := h.getKratosIdentityWithCookieAndSession(cookie)
return identityID, traits, usedID, err
}
func (h *AuthHandler) getKratosIdentityWithCookieAndSession(cookie string) (string, map[string]interface{}, string, string, error) {
func (h *AuthHandler) getKratosIdentityWithCookieAndSession(cookie string) (string, map[string]any, string, string, error) {
kratosURL := strings.TrimRight(os.Getenv("KRATOS_PUBLIC_URL"), "/")
if kratosURL == "" {
kratosURL = "http://kratos:4433"
@@ -7567,8 +7562,8 @@ func (h *AuthHandler) getKratosIdentityWithCookieAndSession(cookie string) (stri
Identifier string `json:"identifier"`
} `json:"authentication_methods"`
Identity struct {
ID string `json:"id"`
Traits map[string]interface{} `json:"traits"`
ID string `json:"id"`
Traits map[string]any `json:"traits"`
} `json:"identity"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
@@ -7616,13 +7611,13 @@ func (h *AuthHandler) getKratosSessionIDWithCookie(cookie string) (string, error
return result.ID, nil
}
func (h *AuthHandler) updateKratosIdentity(identityID string, traits map[string]interface{}) error {
func (h *AuthHandler) updateKratosIdentity(identityID string, traits map[string]any) error {
kratosAdminURL := strings.TrimRight(os.Getenv("KRATOS_ADMIN_URL"), "/")
if kratosAdminURL == "" {
kratosAdminURL = "http://kratos:4434"
}
payload := map[string]interface{}{
payload := map[string]any{
"schema_id": "default",
"traits": traits,
}
@@ -7681,7 +7676,7 @@ func (h *AuthHandler) getHydraProfile(ctx context.Context, token string) (*domai
return h.mapKratosIdentityToProfile(identity.ID, identity.Traits), nil
}
func (h *AuthHandler) mapKratosIdentityToProfile(identityID string, traits map[string]interface{}) *domain.UserProfileResponse {
func (h *AuthHandler) mapKratosIdentityToProfile(identityID string, traits map[string]any) *domain.UserProfileResponse {
email, _ := traits["email"].(string)
name, _ := traits["name"].(string)
phone, _ := traits["phone_number"].(string)
@@ -7723,7 +7718,7 @@ func (h *AuthHandler) mapKratosIdentityToProfile(identityID string, traits map[s
return profile
}
func (h *AuthHandler) mapKratosTraitsToLocalUser(identityID string, traits map[string]interface{}, existing *domain.User) *domain.User {
func (h *AuthHandler) mapKratosTraitsToLocalUser(identityID string, traits map[string]any, existing *domain.User) *domain.User {
now := time.Now()
localUser := &domain.User{
ID: identityID,
@@ -7810,7 +7805,7 @@ func (h *AuthHandler) mapKratosTraitsToLocalUser(identityID string, traits map[s
return localUser
}
func (h *AuthHandler) syncUpdatedKratosUserReadModel(ctx context.Context, identityID string, traits map[string]interface{}) error {
func (h *AuthHandler) syncUpdatedKratosUserReadModel(ctx context.Context, identityID string, traits map[string]any) error {
if h == nil || h.UserRepo == nil {
return nil
}
@@ -7880,7 +7875,7 @@ func (h *AuthHandler) UpdateMe(c *fiber.Ctx) error {
var (
identityID string
traits map[string]interface{}
traits map[string]any
err error
)
if token != "" {
@@ -7929,10 +7924,8 @@ func (h *AuthHandler) UpdateMe(c *fiber.Ctx) error {
if _, isCore := map[string]bool{"email": true, "phone_number": true, "name": true, "department": true, "grade": true, "companyCode": true, "affiliationType": true, "id": true, "role": true, "tenant_id": true}[k]; !isCore {
// [Fix] Support merging namespaced metadata maps
if incomingMap, ok := v.(map[string]any); ok {
if existingMap, ok := traits[k].(map[string]interface{}); ok {
for subK, subV := range incomingMap {
existingMap[subK] = subV
}
if existingMap, ok := traits[k].(map[string]any); ok {
maps.Copy(existingMap, incomingMap)
traits[k] = existingMap
} else {
traits[k] = incomingMap
@@ -8129,7 +8122,7 @@ func (h *AuthHandler) VerifyUpdateCode(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"success": true})
}
func hydraClientStatus(metadata map[string]interface{}) string {
func hydraClientStatus(metadata map[string]any) string {
if metadata == nil {
return "active"
}
@@ -8142,7 +8135,7 @@ func hydraClientStatus(metadata map[string]interface{}) string {
return "active"
}
func extractHydraClientLogo(metadata map[string]interface{}) string {
func extractHydraClientLogo(metadata map[string]any) string {
if metadata == nil {
return ""
}
@@ -8198,7 +8191,7 @@ func resolveLinkedRPURL(clientID string, clientURI string, redirectURIs []string
return ""
}
func resolveLinkedRPAutoLoginSupported(clientID string, metadata map[string]interface{}) bool {
func resolveLinkedRPAutoLoginSupported(clientID string, metadata map[string]any) bool {
if readMetadataBoolValue(metadata, domain.MetadataAutoLoginSupported) {
return true
}
@@ -8210,7 +8203,7 @@ func resolveLinkedRPAutoLoginSupported(clientID string, metadata map[string]inte
}
}
func resolveLinkedRPAutoLoginURL(clientID string, metadata map[string]interface{}) string {
func resolveLinkedRPAutoLoginURL(clientID string, metadata map[string]any) string {
clientID = strings.TrimSpace(clientID)
if metadataURL := readMetadataStringValue(metadata, domain.MetadataAutoLoginURL); metadataURL != "" {
if clientID == "orgfront" {
@@ -8253,7 +8246,7 @@ func ensureOrgfrontAutoLoginURL(rawURL string) string {
return parsed.String()
}
func resolveLinkedRPInitURL(clientID string, metadata map[string]interface{}) string {
func resolveLinkedRPInitURL(clientID string, metadata map[string]any) string {
if !resolveLinkedRPAutoLoginSupported(clientID, metadata) {
return ""
}
@@ -8548,7 +8541,7 @@ func (h *AuthHandler) ListRpHistory(c *fiber.Ctx) error {
ts := log.Timestamp
item.LastApprovedAt = &ts
if scopesRaw, ok := details["scopes"].([]interface{}); ok {
if scopesRaw, ok := details["scopes"].([]any); ok {
scopes := make([]string, 0, len(scopesRaw))
for _, s := range scopesRaw {
if str, ok := s.(string); ok {
@@ -8811,7 +8804,7 @@ func extractStringLikeValue(raw any) string {
}
}
func extractHydraSessionID(ext map[string]interface{}) string {
func extractHydraSessionID(ext map[string]any) string {
if len(ext) == 0 {
return ""
}
@@ -8886,13 +8879,7 @@ func (h *AuthHandler) loadSessionClientBindings(ctx context.Context, userID stri
}
existing := bindings[sessionID]
seen := false
for _, candidate := range existing {
if candidate == clientID {
seen = true
break
}
}
seen := slices.Contains(existing, clientID)
if !seen {
bindings[sessionID] = append(existing, clientID)
}

View File

@@ -16,6 +16,7 @@ import (
"github.com/gofiber/fiber/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"gorm.io/gorm"
)
// --- Async Test Mocks ---
@@ -133,6 +134,10 @@ func (m *AsyncMockUserRepo) CountByCompanyCodes(ctx context.Context, codes []str
return nil, nil
}
func (m *AsyncMockUserRepo) DB() *gorm.DB {
return nil
}
func (m *AsyncMockUserRepo) UpdateUserLoginIDs(ctx context.Context, userID string, loginIDs []domain.UserLoginID) error {
return nil
}

View File

@@ -22,8 +22,8 @@ func TestRevokeLinkedRp_Success(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
// 1. Kratos whoami
if r.URL.Path == "/sessions/whoami" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"identity": map[string]interface{}{"id": "user-123"},
return httpJSONAny(r, http.StatusOK, map[string]any{
"identity": map[string]any{"id": "user-123"},
}), nil
}
// 2. Hydra Revoke
@@ -75,15 +75,15 @@ func TestRevokeLinkedRp_SendsBackchannelLogoutTokenWhenConfigured(t *testing.T)
var receivedBody string
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/sessions/whoami" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"identity": map[string]interface{}{"id": "user-123"},
return httpJSONAny(r, http.StatusOK, map[string]any{
"identity": map[string]any{"id": "user-123"},
}), nil
}
if r.URL.Host == "hydra.test" && r.Method == http.MethodDelete && r.URL.Path == "/oauth2/auth/sessions/consent" {
return httpResponse(r, http.StatusNoContent, ""), nil
}
if r.URL.Host == "hydra.test" && r.Method == http.MethodGet && r.URL.Path == "/clients/app-1" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "app-1",
"backchannel_logout_uri": "https://rp.example.com/backchannel-logout",
}), nil
@@ -158,8 +158,8 @@ func TestListRpHistory_Aggregation(t *testing.T) {
app.Get("/api/v1/user/rp/history", h.ListRpHistory)
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"identity": map[string]interface{}{"id": "user-123"},
return httpJSONAny(r, http.StatusOK, map[string]any{
"identity": map[string]any{"id": "user-123"},
}), nil
})
http.DefaultClient = &http.Client{Transport: transport}

View File

@@ -39,11 +39,11 @@ func (m *MockKratosAdminServiceForConsent) ListIdentities(ctx context.Context) (
return nil, nil
}
func (m *MockKratosAdminServiceForConsent) UpdateIdentity(ctx context.Context, identityID string, traits map[string]interface{}, state string) (*service.KratosIdentity, error) {
func (m *MockKratosAdminServiceForConsent) UpdateIdentity(ctx context.Context, identityID string, traits map[string]any, state string) (*service.KratosIdentity, error) {
return nil, nil
}
func (m *MockKratosAdminServiceForConsent) CreateIdentity(ctx context.Context, traits map[string]interface{}) (*service.KratosIdentity, error) {
func (m *MockKratosAdminServiceForConsent) CreateIdentity(ctx context.Context, traits map[string]any) (*service.KratosIdentity, error) {
return nil, nil
}
@@ -146,12 +146,12 @@ func TestGetConsentRequest_Normal(t *testing.T) {
// Mock Hydra transport
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-123" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"challenge": "challenge-123",
"requested_scope": []string{"openid", "profile"},
"skip": false,
"subject": "user-123",
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "client-app",
"client_name": "Test App",
},
@@ -180,7 +180,7 @@ func TestGetConsentRequest_Normal(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var body map[string]interface{}
var body map[string]any
json.NewDecoder(resp.Body).Decode(&body)
assert.Equal(t, "challenge-123", body["challenge"])
@@ -190,12 +190,12 @@ func TestGetConsentRequest_Normal(t *testing.T) {
func TestGetConsentRequest_AddsMandatoryTenantScope(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-tenant-scope" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"challenge": "challenge-tenant-scope",
"requested_scope": []string{"openid", "profile"},
"skip": false,
"subject": "user-123",
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "client-app",
"client_name": "Test App",
"metadata": map[string]any{
@@ -224,7 +224,7 @@ func TestGetConsentRequest_AddsMandatoryTenantScope(t *testing.T) {
// Mock profile resolution to allow tenant access
mockKratosAdmin.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
ID: "user-123",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@example.com",
},
}, nil)
@@ -259,12 +259,12 @@ func TestGetConsentRequest_AddsMandatoryTenantScope(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var body map[string]interface{}
var body map[string]any
json.NewDecoder(resp.Body).Decode(&body)
assert.Equal(t, []interface{}{"openid", "tenant", "profile"}, body["requested_scope"])
scopeDetails := body["scope_details"].(map[string]interface{})
tenantDetail := scopeDetails["tenant"].(map[string]interface{})
assert.Equal(t, []any{"openid", "tenant", "profile"}, body["requested_scope"])
scopeDetails := body["scope_details"].(map[string]any)
tenantDetail := scopeDetails["tenant"].(map[string]any)
assert.Equal(t, true, tenantDetail["mandatory"])
}
@@ -272,28 +272,28 @@ func TestGetConsentRequest_Skip_AutoAccept(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
// Hydra: Get Consent Request
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-skip" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"challenge": "challenge-skip",
"requested_scope": []string{"openid"},
"skip": true,
"subject": "user-123",
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "client-app",
},
}), nil
}
// Kratos: Get Identity
if r.URL.Path == "/admin/identities/user-123" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"id": "user-123",
"traits": map[string]interface{}{
"traits": map[string]any{
"email": "user@test.com",
},
}), nil
}
// Hydra: Accept Consent Request
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-skip" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"redirect_to": "http://rp/cb",
}), nil
}
@@ -320,7 +320,7 @@ func TestGetConsentRequest_Skip_AutoAccept(t *testing.T) {
}
mockKratosAdmin.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
ID: "user-123",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
},
}, nil)
@@ -332,7 +332,7 @@ func TestGetConsentRequest_Skip_AutoAccept(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var body map[string]interface{}
var body map[string]any
json.NewDecoder(resp.Body).Decode(&body)
assert.Equal(t, "http://rp/cb", body["redirectTo"])
assert.Equal(t, 1, len(rpUsageSink.events))
@@ -345,26 +345,26 @@ func TestGetConsentRequest_Skip_AutoAccept(t *testing.T) {
func TestAcceptConsentRequest_Normal(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-accept" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"challenge": "challenge-accept",
"requested_scope": []string{"openid", "profile"},
"subject": "user-123",
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "client-app",
"client_name": "Test App",
},
}), nil
}
if r.URL.Path == "/admin/identities/user-123" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"id": "user-123",
"traits": map[string]interface{}{
"traits": map[string]any{
"email": "user@test.com",
},
}), nil
}
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-accept" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"redirect_to": "http://rp/cb",
}), nil
}
@@ -393,14 +393,14 @@ func TestAcceptConsentRequest_Normal(t *testing.T) {
}
mockKratosAdmin.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
ID: "user-123",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
},
}, nil)
app := newConsentTestApp(h)
body, _ := json.Marshal(map[string]interface{}{
body, _ := json.Marshal(map[string]any{
"consent_challenge": "challenge-accept",
"grant_scope": []string{"openid"},
})
@@ -419,7 +419,7 @@ func TestAcceptConsentRequest_Normal(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, "client-app", auditDetails["client_id"])
assert.Equal(t, "Test App", auditDetails["client_name"])
assert.Equal(t, []interface{}{"openid"}, auditDetails["scopes"])
assert.Equal(t, []any{"openid"}, auditDetails["scopes"])
assert.Equal(t, 1, len(rpUsageSink.events))
assert.Equal(t, domain.RPUsageEventTypeAuthorizationGranted, rpUsageSink.events[0].EventType)
assert.Equal(t, "user-123", rpUsageSink.events[0].Subject)
@@ -436,11 +436,11 @@ func TestAcceptConsentRequest_EnforcesMandatoryTenantScope(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-tenant-accept" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"challenge": "challenge-tenant-accept",
"requested_scope": []string{"openid", "profile"},
"subject": "user-123",
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "client-app",
"metadata": map[string]any{
"tenant_id": "tenant-abc",
@@ -456,9 +456,9 @@ func TestAcceptConsentRequest_EnforcesMandatoryTenantScope(t *testing.T) {
}), nil
}
if r.URL.Path == "/admin/identities/user-123" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"id": "user-123",
"traits": map[string]interface{}{
"traits": map[string]any{
"email": "user@test.com",
},
}), nil
@@ -466,10 +466,10 @@ func TestAcceptConsentRequest_EnforcesMandatoryTenantScope(t *testing.T) {
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-tenant-accept" {
var payload map[string]any
assert.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
for _, scope := range payload["grant_scope"].([]interface{}) {
for _, scope := range payload["grant_scope"].([]any) {
capturedGrantScopes = append(capturedGrantScopes, scope.(string))
}
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"redirect_to": "http://rp/cb",
}), nil
}
@@ -492,14 +492,14 @@ func TestAcceptConsentRequest_EnforcesMandatoryTenantScope(t *testing.T) {
}
mockKratosAdmin.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
ID: "user-123",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
},
}, nil)
app := newConsentTestApp(h)
body, _ := json.Marshal(map[string]interface{}{
body, _ := json.Marshal(map[string]any{
"consent_challenge": "challenge-tenant-accept",
"grant_scope": []string{"openid", "profile"},
})

View File

@@ -17,15 +17,15 @@ import (
)
func TestBuildOidcClaimsFromTraits_DynamicClaims(t *testing.T) {
traits := map[string]interface{}{
traits := map[string]any{
"email": "user@baron.com",
"name": "홍길동",
"tenant_id": "primary-tenant-999", // Added primary tenant
"tenant-1": map[string]interface{}{
"tenant-1": map[string]any{
"department": "개발팀",
"grade": "선임",
},
"tenant-2": map[string]interface{}{
"tenant-2": map[string]any{
"department": "재무팀",
"grade": "팀장",
},
@@ -130,18 +130,18 @@ func TestRepresentativeTenantIDFromTraits(t *testing.T) {
}
func TestAcceptConsentRequest_DynamicClaims(t *testing.T) {
var capturedClaims map[string]interface{}
var capturedClaims map[string]any
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
// Hydra: Get Consent Request
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-dynamic" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"challenge": "challenge-dynamic",
"requested_scope": []string{"openid", "profile", "tenant"},
"subject": "user-123",
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "client-app",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"tenant_id": "tenant-abc",
},
},
@@ -149,12 +149,12 @@ func TestAcceptConsentRequest_DynamicClaims(t *testing.T) {
}
// Kratos: Get Identity
if r.URL.Path == "/admin/identities/user-123" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"id": "user-123",
"traits": map[string]interface{}{
"traits": map[string]any{
"email": "user@test.com",
"name": "Test User",
"tenant-abc": map[string]interface{}{
"tenant-abc": map[string]any{
"department": "Innovation",
"position": "Architect",
},
@@ -165,13 +165,13 @@ func TestAcceptConsentRequest_DynamicClaims(t *testing.T) {
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-dynamic" {
// Capture the claims sent to Hydra
body, _ := io.ReadAll(r.Body)
var acceptReq map[string]interface{}
var acceptReq map[string]any
json.Unmarshal(body, &acceptReq)
if session, ok := acceptReq["session"].(map[string]interface{}); ok {
capturedClaims = session["id_token"].(map[string]interface{})
if session, ok := acceptReq["session"].(map[string]any); ok {
capturedClaims = session["id_token"].(map[string]any)
}
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"redirect_to": "http://rp/cb",
}), nil
}
@@ -192,10 +192,10 @@ func TestAcceptConsentRequest_DynamicClaims(t *testing.T) {
}
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
ID: "user-123",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
"name": "Test User",
"tenant-abc": map[string]interface{}{
"tenant-abc": map[string]any{
"department": "Innovation",
"position": "Architect",
},
@@ -205,7 +205,7 @@ func TestAcceptConsentRequest_DynamicClaims(t *testing.T) {
app := fiber.New()
app.Post("/api/v1/auth/consent/accept", h.AcceptConsentRequest)
reqBody, _ := json.Marshal(map[string]interface{}{
reqBody, _ := json.Marshal(map[string]any{
"consent_challenge": "challenge-dynamic",
"grant_scope": []string{"openid", "profile", "tenant"},
})
@@ -225,20 +225,20 @@ func TestAcceptConsentRequest_DynamicClaims(t *testing.T) {
}
func TestAcceptConsentRequest_UsesRepresentativeTenantIDInsteadOfClientTenantContext(t *testing.T) {
var capturedClaims map[string]interface{}
var capturedClaims map[string]any
representativeTenantID := "01970f0a-5c28-74d8-a73a-f6e9e9a7b210"
rpContextTenantID := "01970f0b-3448-7bb8-bdc7-16b6a1d2e661"
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-representative-tenant" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"challenge": "challenge-representative-tenant",
"requested_scope": []string{"openid", "profile", "tenant"},
"subject": "user-representative",
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "client-app",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"tenant_id": rpContextTenantID,
},
},
@@ -246,13 +246,13 @@ func TestAcceptConsentRequest_UsesRepresentativeTenantIDInsteadOfClientTenantCon
}
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-representative-tenant" {
body, _ := io.ReadAll(r.Body)
var acceptReq map[string]interface{}
var acceptReq map[string]any
json.Unmarshal(body, &acceptReq)
if session, ok := acceptReq["session"].(map[string]interface{}); ok {
capturedClaims = session["id_token"].(map[string]interface{})
if session, ok := acceptReq["session"].(map[string]any); ok {
capturedClaims = session["id_token"].(map[string]any)
}
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"redirect_to": "http://rp/cb",
}), nil
}
@@ -269,12 +269,12 @@ func TestAcceptConsentRequest_UsesRepresentativeTenantIDInsteadOfClientTenantCon
}
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-representative").Return(&service.KratosIdentity{
ID: "user-representative",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
"name": "Test User",
"additionalAppointments": []interface{}{
map[string]interface{}{"tenantId": representativeTenantID, "isPrimary": true},
map[string]interface{}{"tenantId": rpContextTenantID},
"additionalAppointments": []any{
map[string]any{"tenantId": representativeTenantID, "isPrimary": true},
map[string]any{"tenantId": rpContextTenantID},
},
},
}, nil)
@@ -282,7 +282,7 @@ func TestAcceptConsentRequest_UsesRepresentativeTenantIDInsteadOfClientTenantCon
app := fiber.New()
app.Post("/api/v1/auth/consent/accept", h.AcceptConsentRequest)
reqBody, _ := json.Marshal(map[string]interface{}{
reqBody, _ := json.Marshal(map[string]any{
"consent_challenge": "challenge-representative-tenant",
"grant_scope": []string{"openid", "profile"},
})
@@ -301,7 +301,7 @@ func TestAcceptConsentRequest_UsesRepresentativeTenantIDInsteadOfClientTenantCon
}
func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.T) {
var capturedClaims map[string]interface{}
var capturedClaims map[string]any
deptID := "01970f0a-5c28-74d8-a73a-f6e9e9a7b210"
secondDeptID := "01970f0b-3448-7bb8-bdc7-16b6a1d2e661"
companyID := "01970f08-91da-7286-bd19-882fb98d1f2c"
@@ -309,13 +309,13 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-hanmac-tenant-claim" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"challenge": "challenge-hanmac-tenant-claim",
"requested_scope": []string{"openid", "profile", "tenant"},
"subject": "user-hanmac",
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "hanmac-rp",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"tenant_id": deptID,
},
},
@@ -323,13 +323,13 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
}
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-hanmac-tenant-claim" {
body, _ := io.ReadAll(r.Body)
var acceptReq map[string]interface{}
var acceptReq map[string]any
json.Unmarshal(body, &acceptReq)
if session, ok := acceptReq["session"].(map[string]interface{}); ok {
capturedClaims = session["id_token"].(map[string]interface{})
if session, ok := acceptReq["session"].(map[string]any); ok {
capturedClaims = session["id_token"].(map[string]any)
}
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"redirect_to": "http://rp/cb",
}), nil
}
@@ -346,11 +346,11 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
}
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-hanmac").Return(&service.KratosIdentity{
ID: "user-hanmac",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "hanmac-user@example.com",
"name": "한맥 사용자",
"additionalAppointments": []interface{}{
map[string]interface{}{
"additionalAppointments": []any{
map[string]any{
"tenantId": deptID,
"isPrimary": true,
"isOwner": true,
@@ -358,7 +358,7 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
"jobTitle": "기술기획",
"position": "팀장",
},
map[string]interface{}{
map[string]any{
"tenantId": secondDeptID,
"isPrimary": false,
"isOwner": false,
@@ -404,7 +404,7 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
app := fiber.New()
app.Post("/api/v1/auth/consent/accept", h.AcceptConsentRequest)
reqBody, _ := json.Marshal(map[string]interface{}{
reqBody, _ := json.Marshal(map[string]any{
"consent_challenge": "challenge-hanmac-tenant-claim",
"grant_scope": []string{"openid", "profile", "tenant"},
})
@@ -416,10 +416,10 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.NotNil(t, capturedClaims)
assert.Equal(t, []interface{}{deptID}, capturedClaims["lead_tenants"])
assert.ElementsMatch(t, []interface{}{deptID, secondDeptID}, capturedClaims["joined_tenants"])
tenants := capturedClaims["tenants"].(map[string]interface{})
dept := tenants[deptID].(map[string]interface{})
assert.Equal(t, []any{deptID}, capturedClaims["lead_tenants"])
assert.ElementsMatch(t, []any{deptID, secondDeptID}, capturedClaims["joined_tenants"])
tenants := capturedClaims["tenants"].(map[string]any)
dept := tenants[deptID].(map[string]any)
assert.Equal(t, true, dept["lead"])
assert.Equal(t, true, dept["representative"])
assert.Equal(t, "책임", dept["grade"])
@@ -428,21 +428,21 @@ func TestAcceptConsentRequest_IncludesHanmacFamilyTenantClaimDetails(t *testing.
assert.Equal(t, companyID, dept["parentTenantId"])
assert.NotContains(t, dept, "parentTenant")
ancestors := dept["ancestors"].([]interface{})
ancestors := dept["ancestors"].([]any)
assert.Len(t, ancestors, 2)
companyAncestor := ancestors[0].(map[string]interface{})
companyAncestor := ancestors[0].(map[string]any)
assert.Equal(t, companyID, companyAncestor["id"])
assert.Equal(t, "hanmac", companyAncestor["slug"])
assert.Equal(t, rootID, companyAncestor["parentTenantId"])
assert.NotContains(t, companyAncestor, "parentTenant")
rootAncestor := ancestors[1].(map[string]interface{})
rootAncestor := ancestors[1].(map[string]any)
assert.Equal(t, rootID, rootAncestor["id"])
assert.Equal(t, "hanmac-family", rootAncestor["slug"])
assert.Contains(t, rootAncestor, "parentTenantId")
assert.Nil(t, rootAncestor["parentTenantId"])
assert.NotContains(t, rootAncestor, "parentTenant")
secondDept := tenants[secondDeptID].(map[string]interface{})
secondDept := tenants[secondDeptID].(map[string]any)
assert.Equal(t, false, secondDept["lead"])
assert.Equal(t, false, secondDept["representative"])
assert.Equal(t, "선임", secondDept["grade"])
@@ -512,18 +512,18 @@ func TestWithHanmacFamilyTenantClaims_DefaultClaimsOnlyWithoutTenantScope(t *tes
}
func TestAcceptConsentRequest_IncludesRPProfileClaims(t *testing.T) {
var capturedClaims map[string]interface{}
var capturedClaims map[string]any
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-rp-profile" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"challenge": "challenge-rp-profile",
"requested_scope": []string{"openid", "profile", "tenant"},
"subject": "user-123",
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "client-app",
"metadata": map[string]interface{}{
"customUserSchema": []map[string]interface{}{
"metadata": map[string]any{
"customUserSchema": []map[string]any{
{
"key": "approvalLevel",
"label": "승인 등급",
@@ -543,13 +543,13 @@ func TestAcceptConsentRequest_IncludesRPProfileClaims(t *testing.T) {
}
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-rp-profile" {
body, _ := io.ReadAll(r.Body)
var acceptReq map[string]interface{}
var acceptReq map[string]any
json.Unmarshal(body, &acceptReq)
if session, ok := acceptReq["session"].(map[string]interface{}); ok {
capturedClaims = session["id_token"].(map[string]interface{})
if session, ok := acceptReq["session"].(map[string]any); ok {
capturedClaims = session["id_token"].(map[string]any)
}
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"redirect_to": "http://rp/cb",
}), nil
}
@@ -566,7 +566,7 @@ func TestAcceptConsentRequest_IncludesRPProfileClaims(t *testing.T) {
}
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
ID: "user-123",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
"name": "Test User",
},
@@ -585,7 +585,7 @@ func TestAcceptConsentRequest_IncludesRPProfileClaims(t *testing.T) {
app := fiber.New()
app.Post("/api/v1/auth/consent/accept", h.AcceptConsentRequest)
reqBody, _ := json.Marshal(map[string]interface{}{
reqBody, _ := json.Marshal(map[string]any{
"consent_challenge": "challenge-rp-profile",
"grant_scope": []string{"openid", "profile"},
})
@@ -597,31 +597,31 @@ func TestAcceptConsentRequest_IncludesRPProfileClaims(t *testing.T) {
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.NotNil(t, capturedClaims)
rpProfiles, ok := capturedClaims["rp_profiles"].([]interface{})
rpProfiles, ok := capturedClaims["rp_profiles"].([]any)
assert.True(t, ok)
assert.Len(t, rpProfiles, 1)
profile := rpProfiles[0].(map[string]interface{})
profile := rpProfiles[0].(map[string]any)
assert.Equal(t, "client-app", profile["client_id"])
fields := profile["fields"].(map[string]interface{})
fields := profile["fields"].(map[string]any)
assert.Equal(t, "A", fields["approvalLevel"])
assert.NotContains(t, fields, "internalMemo")
repo.AssertExpectations(t)
}
func TestGetConsentRequest_Skip_DynamicClaims(t *testing.T) {
var capturedClaims map[string]interface{}
var capturedClaims map[string]any
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
// Hydra: Get Consent Request
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-skip-dynamic" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"challenge": "challenge-skip-dynamic",
"requested_scope": []string{"openid", "profile", "tenant"},
"skip": true,
"subject": "user-456",
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "skip-app",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"tenant_id": "tenant-xyz",
},
},
@@ -629,11 +629,11 @@ func TestGetConsentRequest_Skip_DynamicClaims(t *testing.T) {
}
// Kratos: Get Identity
if r.URL.Path == "/admin/identities/user-456" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"id": "user-456",
"traits": map[string]interface{}{
"traits": map[string]any{
"email": "skip@test.com",
"tenant-xyz": map[string]interface{}{
"tenant-xyz": map[string]any{
"department": "Security",
"position": "Officer",
},
@@ -644,13 +644,13 @@ func TestGetConsentRequest_Skip_DynamicClaims(t *testing.T) {
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-skip-dynamic" {
// Capture the claims sent to Hydra
body, _ := io.ReadAll(r.Body)
var acceptReq map[string]interface{}
var acceptReq map[string]any
json.Unmarshal(body, &acceptReq)
if session, ok := acceptReq["session"].(map[string]interface{}); ok {
capturedClaims = session["id_token"].(map[string]interface{})
if session, ok := acceptReq["session"].(map[string]any); ok {
capturedClaims = session["id_token"].(map[string]any)
}
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"redirect_to": "http://rp/cb",
}), nil
}
@@ -671,9 +671,9 @@ func TestGetConsentRequest_Skip_DynamicClaims(t *testing.T) {
}
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-456").Return(&service.KratosIdentity{
ID: "user-456",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "skip@test.com",
"tenant-xyz": map[string]interface{}{
"tenant-xyz": map[string]any{
"department": "Security",
"position": "Officer",
},
@@ -697,19 +697,19 @@ func TestGetConsentRequest_Skip_DynamicClaims(t *testing.T) {
}
func TestAcceptConsentRequest_AppliesConfiguredIDTokenClaims(t *testing.T) {
var capturedClaims map[string]interface{}
var capturedClaims map[string]any
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-configured-claims" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"challenge": "challenge-configured-claims",
"requested_scope": []string{"openid", "profile"},
"subject": "user-789",
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "client-configured-claims",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"tenant_id": "tenant-claims",
"id_token_claims": []map[string]interface{}{
"id_token_claims": []map[string]any{
{
"namespace": "top_level",
"key": "locale",
@@ -741,13 +741,13 @@ func TestAcceptConsentRequest_AppliesConfiguredIDTokenClaims(t *testing.T) {
}
if r.URL.Path == "/oauth2/auth/requests/consent/accept" && r.URL.Query().Get("consent_challenge") == "challenge-configured-claims" {
body, _ := io.ReadAll(r.Body)
var acceptReq map[string]interface{}
var acceptReq map[string]any
json.Unmarshal(body, &acceptReq)
if session, ok := acceptReq["session"].(map[string]interface{}); ok {
capturedClaims = session["id_token"].(map[string]interface{})
if session, ok := acceptReq["session"].(map[string]any); ok {
capturedClaims = session["id_token"].(map[string]any)
}
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"redirect_to": "http://rp/cb",
}), nil
}
@@ -768,10 +768,10 @@ func TestAcceptConsentRequest_AppliesConfiguredIDTokenClaims(t *testing.T) {
}
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-789").Return(&service.KratosIdentity{
ID: "user-789",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "real-user@example.com",
"name": "Configured User",
"tenant-claims": map[string]interface{}{
"tenant-claims": map[string]any{
"department": "Platform",
},
},
@@ -780,7 +780,7 @@ func TestAcceptConsentRequest_AppliesConfiguredIDTokenClaims(t *testing.T) {
app := fiber.New()
app.Post("/api/v1/auth/consent/accept", h.AcceptConsentRequest)
reqBody, _ := json.Marshal(map[string]interface{}{
reqBody, _ := json.Marshal(map[string]any{
"consent_challenge": "challenge-configured-claims",
"grant_scope": []string{"openid", "profile"},
})
@@ -796,9 +796,9 @@ func TestAcceptConsentRequest_AppliesConfiguredIDTokenClaims(t *testing.T) {
assert.Equal(t, "ko-KR", capturedClaims["locale"])
assert.Equal(t, "tenant-claims", capturedClaims["tenant_id"])
rpClaims, ok := capturedClaims["rp_claims"].(map[string]interface{})
rpClaims, ok := capturedClaims["rp_claims"].(map[string]any)
if assert.True(t, ok) {
assert.Equal(t, float64(2), rpClaims["tier"])
assert.Equal(t, []interface{}{"sso", "claims"}, rpClaims["features"])
assert.Equal(t, []any{"sso", "claims"}, rpClaims["features"])
}
}

View File

@@ -61,12 +61,12 @@ func newKratosWhoamiTestServer(t *testing.T, identityID string) *httptest.Server
http.Error(w, "missing session", http.StatusUnauthorized)
return
}
_ = json.NewEncoder(w).Encode(map[string]interface{}{
_ = json.NewEncoder(w).Encode(map[string]any{
"id": "session-123",
"authenticated_at": "2026-05-21T00:00:00Z",
"identity": map[string]interface{}{
"identity": map[string]any{
"id": identityID,
"traits": map[string]interface{}{
"traits": map[string]any{
"email": "user@example.com",
},
},
@@ -113,7 +113,7 @@ func TestEnchantedLinkFlow_Email_Success(t *testing.T) {
assert.Equal(t, http.StatusOK, resp.StatusCode)
var initResp map[string]interface{}
var initResp map[string]any
json.NewDecoder(resp.Body).Decode(&initResp)
pendingRef := initResp["pendingRef"].(string)
assert.NotEmpty(t, pendingRef)
@@ -129,7 +129,7 @@ func TestEnchantedLinkFlow_Email_Success(t *testing.T) {
assert.NotEmpty(t, token)
// 2. Verify Magic Link
verifyBody, _ := json.Marshal(map[string]interface{}{
verifyBody, _ := json.Marshal(map[string]any{
"token": token,
"verifyOnly": true,
})
@@ -145,7 +145,7 @@ func TestEnchantedLinkFlow_Email_Success(t *testing.T) {
resp, _ = app.Test(req, -1)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var pollResp map[string]interface{}
var pollResp map[string]any
json.NewDecoder(resp.Body).Decode(&pollResp)
assert.Equal(t, "ok", pollResp["status"])
assert.Equal(t, "valid-jwt", pollResp["sessionJwt"])
@@ -177,7 +177,7 @@ func TestEnchantedLinkFlow_Sms_Success(t *testing.T) {
assert.Equal(t, http.StatusOK, resp.StatusCode)
var initResp map[string]interface{}
var initResp map[string]any
json.NewDecoder(resp.Body).Decode(&initResp)
assert.NotEmpty(t, initResp["userCode"])
}
@@ -193,7 +193,7 @@ func TestVerifyMagicLink_VerifyOnlyWithoutSharedBrowserSessionApprovesOnly(t *te
app := fiber.New()
app.Post("/api/v1/auth/magic-link/verify", h.VerifyMagicLink)
body, _ := json.Marshal(map[string]interface{}{
body, _ := json.Marshal(map[string]any{
"token": "token-123",
"verifyOnly": true,
})
@@ -204,7 +204,7 @@ func TestVerifyMagicLink_VerifyOnlyWithoutSharedBrowserSessionApprovesOnly(t *te
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Empty(t, resp.Cookies())
var got map[string]interface{}
var got map[string]any
_ = json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, "approved", got["status"])
assert.Nil(t, got["sessionJwt"])
@@ -225,7 +225,7 @@ func TestVerifyMagicLink_VerifyOnlySharedBrowserSameSubjectApprovesOnly(t *testi
app := fiber.New()
app.Post("/api/v1/auth/magic-link/verify", h.VerifyMagicLink)
body, _ := json.Marshal(map[string]interface{}{
body, _ := json.Marshal(map[string]any{
"token": "token-123",
"verifyOnly": true,
})
@@ -237,7 +237,7 @@ func TestVerifyMagicLink_VerifyOnlySharedBrowserSameSubjectApprovesOnly(t *testi
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Empty(t, resp.Cookies())
var got map[string]interface{}
var got map[string]any
_ = json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, "approved", got["status"])
assert.Nil(t, got["sessionJwt"])
@@ -258,7 +258,7 @@ func TestVerifyMagicLink_VerifyOnlySharedBrowserDifferentSubjectApprovesOnly(t *
app := fiber.New()
app.Post("/api/v1/auth/magic-link/verify", h.VerifyMagicLink)
body, _ := json.Marshal(map[string]interface{}{
body, _ := json.Marshal(map[string]any{
"token": "token-123",
"verifyOnly": true,
})
@@ -270,7 +270,7 @@ func TestVerifyMagicLink_VerifyOnlySharedBrowserDifferentSubjectApprovesOnly(t *
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Empty(t, resp.Cookies())
var got map[string]interface{}
var got map[string]any
_ = json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, "approved", got["status"])
assert.Nil(t, got["sessionJwt"])
@@ -312,7 +312,7 @@ func TestVerifyLoginCode_VerifyOnlySharedBrowserDifferentSubjectApprovesOnly(t *
app := fiber.New()
app.Post("/api/v1/auth/login/code/verify", h.VerifyLoginCode)
body, _ := json.Marshal(map[string]interface{}{
body, _ := json.Marshal(map[string]any{
"loginId": "user@example.com",
"code": "569765",
"pendingRef": "pending-123",
@@ -326,7 +326,7 @@ func TestVerifyLoginCode_VerifyOnlySharedBrowserDifferentSubjectApprovesOnly(t *
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Empty(t, resp.Cookies())
var got map[string]interface{}
var got map[string]any
_ = json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, "approved", got["status"])
assert.Nil(t, got["sessionJwt"])
@@ -349,7 +349,7 @@ func TestVerifyLoginCode_MapsSmsPhoneBeforeFlowLookup(t *testing.T) {
app := fiber.New()
app.Post("/api/v1/auth/login/code/verify", h.VerifyLoginCode)
body, _ := json.Marshal(map[string]interface{}{
body, _ := json.Marshal(map[string]any{
"loginId": "01041585840",
"code": "569765",
"pendingRef": "pending-123",
@@ -360,7 +360,7 @@ func TestVerifyLoginCode_MapsSmsPhoneBeforeFlowLookup(t *testing.T) {
resp, _ := app.Test(req, -1)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var got map[string]interface{}
var got map[string]any
_ = json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, "approved", got["status"])
assert.Equal(t, "pending-123", got["pendingRef"])
@@ -383,7 +383,7 @@ func TestPollEnchantedLink_ExpiredToken_ReturnsCode(t *testing.T) {
assert.Equal(t, http.StatusOK, resp.StatusCode)
var got map[string]interface{}
var got map[string]any
json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, "expired_token", got["error"])
assert.Equal(t, "expired_token", got["code"])
@@ -415,7 +415,7 @@ func TestPollEnchantedLink_SharedBrowserSameSubjectIssuesSession(t *testing.T) {
resp, _ := app.Test(req, -1)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var got map[string]interface{}
var got map[string]any
_ = json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, "ok", got["status"])
assert.Equal(t, "valid-jwt", got["sessionJwt"])
@@ -447,7 +447,7 @@ func TestPollEnchantedLink_SharedBrowserDifferentSubjectConflicts(t *testing.T)
resp, _ := app.Test(req, -1)
assert.Equal(t, http.StatusConflict, resp.StatusCode)
var got map[string]interface{}
var got map[string]any
_ = json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, "session_subject_conflict", got["code"])
assert.NotContains(t, redis.data[prefixSession+"pending-123"], "valid-jwt")
@@ -481,7 +481,7 @@ func TestHeadlessLinkInit_HeadlessLoginClientSuccess(t *testing.T) {
Client: domain.HydraClient{
ClientID: "headless-login-client",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -519,7 +519,7 @@ func TestHeadlessLinkInit_HeadlessLoginClientSuccess(t *testing.T) {
assert.Equal(t, http.StatusOK, resp.StatusCode)
var got map[string]interface{}
var got map[string]any
_ = json.NewDecoder(resp.Body).Decode(&got)
assert.NotEmpty(t, got["pendingRef"])
_, hasUserCode := got["userCode"]
@@ -551,7 +551,7 @@ func TestHeadlessLinkPoll_AfterApprovalReturnsRedirect(t *testing.T) {
ClientID: "headless-login-client",
ClientName: "local-demo-rp",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -604,7 +604,7 @@ func TestHeadlessLinkPoll_AfterApprovalReturnsRedirect(t *testing.T) {
resp, _ := app.Test(req, -1)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var initResp map[string]interface{}
var initResp map[string]any
_ = json.NewDecoder(resp.Body).Decode(&initResp)
pendingRef := initResp["pendingRef"].(string)
assert.NotEmpty(t, pendingRef)
@@ -618,7 +618,7 @@ func TestHeadlessLinkPoll_AfterApprovalReturnsRedirect(t *testing.T) {
}
assert.NotEmpty(t, token)
verifyBody, _ := json.Marshal(map[string]interface{}{
verifyBody, _ := json.Marshal(map[string]any{
"token": token,
"verifyOnly": true,
})
@@ -637,7 +637,7 @@ func TestHeadlessLinkPoll_AfterApprovalReturnsRedirect(t *testing.T) {
resp, _ = app.Test(req, -1)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var pollResp map[string]interface{}
var pollResp map[string]any
_ = json.NewDecoder(resp.Body).Decode(&pollResp)
assert.Equal(t, "http://rp/cb", pollResp["redirectTo"])
assert.Equal(t, "ok", pollResp["status"])
@@ -677,7 +677,7 @@ func TestHeadlessLinkPoll_ApproverSubjectConflictBlocksMixedRP(t *testing.T) {
ClientID: "headless-login-client",
ClientName: "local-demo-rp",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -734,7 +734,7 @@ func TestHeadlessLinkPoll_ApproverSubjectConflictBlocksMixedRP(t *testing.T) {
resp, _ := app.Test(req, -1)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var initResp map[string]interface{}
var initResp map[string]any
_ = json.NewDecoder(resp.Body).Decode(&initResp)
pendingRef := initResp["pendingRef"].(string)
assert.NotEmpty(t, pendingRef)
@@ -751,7 +751,7 @@ func TestHeadlessLinkPoll_ApproverSubjectConflictBlocksMixedRP(t *testing.T) {
kratosPublic := newKratosWhoamiTestServer(t, "kratos-userfront-a")
t.Setenv("KRATOS_PUBLIC_URL", kratosPublic.URL)
verifyBody, _ := json.Marshal(map[string]interface{}{
verifyBody, _ := json.Marshal(map[string]any{
"token": token,
"verifyOnly": true,
})
@@ -773,7 +773,7 @@ func TestHeadlessLinkPoll_ApproverSubjectConflictBlocksMixedRP(t *testing.T) {
assert.Equal(t, http.StatusConflict, resp.StatusCode)
assert.False(t, acceptCalled)
assert.Empty(t, resp.Cookies())
var got map[string]interface{}
var got map[string]any
_ = json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, "oidc_subject_conflict", got["code"])
assert.Equal(t, "redirect_to_userfront_login", got["recommendedAction"])
@@ -802,7 +802,7 @@ func TestHeadlessLinkPoll_RequestCookieSubjectConflictBlocksMixedRP(t *testing.T
Client: domain.HydraClient{
ClientID: "headless-login-client",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -857,7 +857,7 @@ func TestHeadlessLinkPoll_RequestCookieSubjectConflictBlocksMixedRP(t *testing.T
resp, _ := app.Test(req, -1)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var initResp map[string]interface{}
var initResp map[string]any
_ = json.NewDecoder(resp.Body).Decode(&initResp)
pendingRef := initResp["pendingRef"].(string)
assert.NotEmpty(t, pendingRef)
@@ -871,7 +871,7 @@ func TestHeadlessLinkPoll_RequestCookieSubjectConflictBlocksMixedRP(t *testing.T
}
assert.NotEmpty(t, token)
verifyBody, _ := json.Marshal(map[string]interface{}{
verifyBody, _ := json.Marshal(map[string]any{
"token": token,
"verifyOnly": true,
})
@@ -896,7 +896,7 @@ func TestHeadlessLinkPoll_RequestCookieSubjectConflictBlocksMixedRP(t *testing.T
assert.Equal(t, http.StatusConflict, resp.StatusCode)
assert.False(t, acceptCalled)
assert.Empty(t, resp.Cookies())
var got map[string]interface{}
var got map[string]any
_ = json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, "oidc_subject_conflict", got["code"])
assert.Equal(t, "kratos-userfront-a", got["currentSubject"])

View File

@@ -32,10 +32,10 @@ func TestListLinkedRps_PriorityAndAggregation(t *testing.T) {
if r.Header.Get("X-Session-Token") == "" && r.Header.Get("Cookie") == "" {
return httpResponse(r, http.StatusUnauthorized, "unauthorized"), nil
}
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"identity": map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"identity": map[string]any{
"id": "user-123",
"traits": map[string]interface{}{
"traits": map[string]any{
"email": "user@test.com",
},
},
@@ -43,9 +43,9 @@ func TestListLinkedRps_PriorityAndAggregation(t *testing.T) {
}
case "hydra.test":
if r.URL.Path == "/oauth2/auth/sessions/consent" {
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
return httpJSONAny(r, http.StatusOK, []map[string]any{
{
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "devfront",
"client_name": "DevFront",
"redirect_uris": []string{
@@ -56,10 +56,10 @@ func TestListLinkedRps_PriorityAndAggregation(t *testing.T) {
"handled_at": time.Now().Format(time.RFC3339),
},
{
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "orgfront",
"client_name": "OrgFront",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"auto_login_supported": true,
"auto_login_url": "http://localhost:5175/login",
},
@@ -73,13 +73,13 @@ func TestListLinkedRps_PriorityAndAggregation(t *testing.T) {
}), nil
}
if r.URL.Path == "/admin/clients/client-audit" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "client-audit",
"client_name": "Audit App",
}), nil
}
if r.URL.Path == "/admin/clients/client-consent" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "client-consent",
"client_name": "Consent App",
}), nil
@@ -206,17 +206,17 @@ func TestListLinkedRps_EnrichesLogoFromHydraClientWhenConsentSessionOmitsMetadat
switch r.URL.Host {
case "kratos.test":
if r.URL.Path == "/sessions/whoami" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"identity": map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"identity": map[string]any{
"id": "user-123",
},
}), nil
}
case "hydra.test":
if r.URL.Path == "/oauth2/auth/sessions/consent" {
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
return httpJSONAny(r, http.StatusOK, []map[string]any{
{
"client": map[string]interface{}{
"client": map[string]any{
"client_id": "gitea-client",
"client_name": "Gitea",
"redirect_uris": []string{
@@ -229,13 +229,13 @@ func TestListLinkedRps_EnrichesLogoFromHydraClientWhenConsentSessionOmitsMetadat
}), nil
}
if r.URL.Path == "/clients/gitea-client" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "gitea-client",
"client_name": "Gitea",
"redirect_uris": []string{
"https://gitea.example.com/callback",
},
"metadata": map[string]interface{}{
"metadata": map[string]any{
"logo_url": "https://cdn.example.com/gitea.svg",
},
}), nil

View File

@@ -32,6 +32,7 @@ import (
"github.com/gofiber/fiber/v2"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
// --- Mocks ---
@@ -113,7 +114,7 @@ func (m *MockKratosAdminService) ListIdentities(ctx context.Context) ([]service.
return nil, nil
}
func (m *MockKratosAdminService) UpdateIdentity(ctx context.Context, identityID string, traits map[string]interface{}, state string) (*service.KratosIdentity, error) {
func (m *MockKratosAdminService) UpdateIdentity(ctx context.Context, identityID string, traits map[string]any, state string) (*service.KratosIdentity, error) {
return nil, nil
}
@@ -214,6 +215,8 @@ func (r *passwordLoginUserRepo) FindByCompanyCodes(ctx context.Context, codes []
func (r *passwordLoginUserRepo) Delete(ctx context.Context, id string) error { return nil }
func (r *passwordLoginUserRepo) DB() *gorm.DB { return nil }
func (r *passwordLoginUserRepo) UpdateUserLoginIDs(ctx context.Context, userID string, loginIDs []domain.UserLoginID) error {
return nil
}
@@ -474,7 +477,7 @@ func runHeadlessPasswordLoginWithAssertionRequest(
Client: domain.HydraClient{
ClientID: "headless-login-client",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -579,7 +582,7 @@ func runHeadlessPasswordLoginWithAssertionAndLoggerRequest(
Client: domain.HydraClient{
ClientID: "headless-login-client",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -667,7 +670,7 @@ func TestPasswordLogin_OIDC_Success(t *testing.T) {
}
json.NewEncoder(w).Encode(domain.HydraLoginRequest{
Challenge: challenge,
Client: domain.HydraClient{ClientID: "client-1", Metadata: map[string]interface{}{"status": "active"}},
Client: domain.HydraClient{ClientID: "client-1", Metadata: map[string]any{"status": "active"}},
})
case strings.Contains(r.URL.Path, "/oauth2/auth/requests/login/accept") && r.Method == http.MethodPut:
// AcceptLoginRequest
@@ -710,7 +713,7 @@ func TestPasswordLogin_OIDC_Success(t *testing.T) {
t.Fatalf("expected 200, got %d, body: %s", resp.StatusCode, string(bodyBytes))
}
var got map[string]interface{}
var got map[string]any
json.NewDecoder(resp.Body).Decode(&got)
if got["redirectTo"] != "http://rp/cb" {
t.Errorf("expected redirectTo http://rp/cb, got %v", got["redirectTo"])
@@ -738,7 +741,7 @@ func TestPasswordLogin_OIDC_AuditIncludesClientMetadata(t *testing.T) {
Client: domain.HydraClient{
ClientID: "devfront",
ClientName: "DevFront",
Metadata: map[string]interface{}{"status": "active"},
Metadata: map[string]any{"status": "active"},
},
})
case strings.Contains(r.URL.Path, "/oauth2/auth/requests/login/accept") && r.Method == http.MethodPut:
@@ -902,7 +905,7 @@ func TestHeadlessPasswordLogin_HeadlessLoginClientSuccess(t *testing.T) {
Client: domain.HydraClient{
ClientID: "headless-login-client",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -958,7 +961,7 @@ func TestHeadlessPasswordLogin_HeadlessLoginClientSuccess(t *testing.T) {
t.Fatalf("expected 200, got %d, body: %s", resp.StatusCode, string(bodyBytes))
}
var got map[string]interface{}
var got map[string]any
if err := json.NewDecoder(resp.Body).Decode(&got); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
@@ -1005,7 +1008,7 @@ func TestHeadlessPasswordLogin_OIDCSubjectConflictBlocksMixedRP(t *testing.T) {
Client: domain.HydraClient{
ClientID: "headless-login-client",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -1051,7 +1054,7 @@ func TestHeadlessPasswordLogin_OIDCSubjectConflictBlocksMixedRP(t *testing.T) {
require.Equal(t, http.StatusConflict, resp.StatusCode)
require.False(t, acceptCalled)
require.Empty(t, resp.Cookies())
var got map[string]interface{}
var got map[string]any
require.NoError(t, json.NewDecoder(resp.Body).Decode(&got))
require.Equal(t, "oidc_subject_conflict", got["code"])
require.Equal(t, "redirect_to_userfront_login", got["recommendedAction"])
@@ -1090,7 +1093,7 @@ func TestHeadlessPasswordLogin_OIDCSubjectSameAllowsMixedRP(t *testing.T) {
Client: domain.HydraClient{
ClientID: "headless-login-client",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -1134,7 +1137,7 @@ func TestHeadlessPasswordLogin_OIDCSubjectSameAllowsMixedRP(t *testing.T) {
require.Equal(t, http.StatusOK, resp.StatusCode)
require.Empty(t, resp.Cookies())
var got map[string]interface{}
var got map[string]any
require.NoError(t, json.NewDecoder(resp.Body).Decode(&got))
require.Equal(t, "http://rp/cb", got["redirectTo"])
require.Nil(t, got["sessionJwt"])
@@ -1161,7 +1164,7 @@ func TestHeadlessPasswordLogin_AuditIncludesClientMetadata(t *testing.T) {
ClientID: "headless-login-client",
ClientName: "Headless Login Portal",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -1294,7 +1297,7 @@ func TestHeadlessPasswordLogin_IgnoresInlineHeadlessJWKSWhenJWKSURIIsConfigured(
Client: domain.HydraClient{
ClientID: "headless-login-client",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -1395,7 +1398,7 @@ func TestHeadlessPasswordLogin_RefreshesJWKSWhenSignatureFailsForCachedKid(t *te
Client: domain.HydraClient{
ClientID: "headless-login-client",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -1494,7 +1497,7 @@ func TestHeadlessPasswordLogin_MissingClientAssertionRejected(t *testing.T) {
Client: domain.HydraClient{
ClientID: "headless-login-client",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -1573,7 +1576,7 @@ func TestHeadlessPasswordLogin_InvalidClientAssertionRejected(t *testing.T) {
Client: domain.HydraClient{
ClientID: "headless-login-client",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -1995,7 +1998,7 @@ func TestHeadlessPasswordLogin_HeadlessDisabledRejected(t *testing.T) {
Client: domain.HydraClient{
ClientID: "headless-login-client",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_jwks_uri": "https://rp.example.com/.well-known/jwks.json",
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -2048,7 +2051,7 @@ func TestHeadlessPasswordLogin_ClientIDMismatchRejected(t *testing.T) {
Client: domain.HydraClient{
ClientID: "other-rp",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"status": "active",
"headless_login_enabled": true,
"headless_token_endpoint_auth_method": "private_key_jwt",
@@ -2102,7 +2105,7 @@ func TestPasswordLogin_OIDC_InactiveClient(t *testing.T) {
hydraHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/oauth2/auth/requests/login") && r.Method == http.MethodGet {
json.NewEncoder(w).Encode(domain.HydraLoginRequest{
Client: domain.HydraClient{ClientID: "client-inactive", Metadata: map[string]interface{}{"status": "inactive"}},
Client: domain.HydraClient{ClientID: "client-inactive", Metadata: map[string]any{"status": "inactive"}},
})
return
}
@@ -2220,7 +2223,7 @@ func TestPasswordLogin_SharedBrowserSameSubjectAllowed(t *testing.T) {
defer resp.Body.Close()
require.Equal(t, http.StatusOK, resp.StatusCode)
var got map[string]interface{}
var got map[string]any
require.NoError(t, json.NewDecoder(resp.Body).Decode(&got))
require.Equal(t, "valid-jwt", got["sessionJwt"])
mockIdp.AssertExpectations(t)
@@ -2259,7 +2262,7 @@ func TestPasswordLogin_SharedBrowserDifferentSubjectConflicts(t *testing.T) {
defer resp.Body.Close()
require.Equal(t, http.StatusConflict, resp.StatusCode)
var got map[string]interface{}
var got map[string]any
require.NoError(t, json.NewDecoder(resp.Body).Decode(&got))
require.Equal(t, "session_subject_conflict", got["code"])
require.Empty(t, resp.Cookies())

View File

@@ -33,10 +33,10 @@ func TestAcceptOidcLoginRequest_CookieOnly(t *testing.T) {
if r.Header.Get("Cookie") == "" {
return httpResponse(r, http.StatusUnauthorized, "missing cookie"), nil
}
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"identity": map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"identity": map[string]any{
"id": "kratos-123",
"traits": map[string]interface{}{},
"traits": map[string]any{},
},
}), nil
case "hydra.test":
@@ -45,7 +45,7 @@ func TestAcceptOidcLoginRequest_CookieOnly(t *testing.T) {
}
gotChallenge = r.URL.Query().Get("login_challenge")
body, _ := io.ReadAll(r.Body)
var payload map[string]interface{}
var payload map[string]any
_ = json.Unmarshal(body, &payload)
if subject, ok := payload["subject"].(string); ok {
gotSubject = subject
@@ -117,10 +117,10 @@ func TestAcceptOidcLoginRequest_TokenFallbackToCookie(t *testing.T) {
if r.Header.Get("Cookie") == "" {
return httpResponse(r, http.StatusUnauthorized, "missing cookie"), nil
}
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"identity": map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"identity": map[string]any{
"id": "kratos-456",
"traits": map[string]interface{}{},
"traits": map[string]any{},
},
}), nil
case "hydra.test":
@@ -128,7 +128,7 @@ func TestAcceptOidcLoginRequest_TokenFallbackToCookie(t *testing.T) {
return httpResponse(r, http.StatusNotFound, "not found"), nil
}
body, _ := io.ReadAll(r.Body)
var payload map[string]interface{}
var payload map[string]any
_ = json.Unmarshal(body, &payload)
if subject, ok := payload["subject"].(string); ok {
gotSubject = subject

View File

@@ -23,10 +23,10 @@ func TestHandleKratosCourierRelay_Email(t *testing.T) {
app.Post("/api/v1/auth/kratos/courier", h.HandleKratosCourierRelay)
// Simulate Kratos Courier Request for Email
reqBody := map[string]interface{}{
reqBody := map[string]any{
"recipient": "user@example.com",
"template_type": "verification_code",
"template_data": map[string]interface{}{
"template_data": map[string]any{
"verification_code": "123456",
},
"subject": "Verify your email",
@@ -50,7 +50,7 @@ func TestVerifySignupCode_Success(t *testing.T) {
// Mock stored code in redis
// signup:email:user@test.com -> {"code":"654321", "verified":false, "expires_at":...}
state := map[string]interface{}{
state := map[string]any{
"code": "654321",
"verified": false,
"expires_at": 9999999999, // far future
@@ -71,13 +71,13 @@ func TestVerifySignupCode_Success(t *testing.T) {
resp, _ := app.Test(req, -1)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var res map[string]interface{}
var res map[string]any
json.NewDecoder(resp.Body).Decode(&res)
assert.True(t, res["success"].(bool))
// Check redis state updated to verified
val, _ := redis.Get("signup:email:user@test.com")
var updatedState map[string]interface{}
var updatedState map[string]any
json.Unmarshal([]byte(val), &updatedState)
assert.True(t, updatedState["verified"].(bool))
}
@@ -90,7 +90,7 @@ func TestVerifySignupCode_Invalid(t *testing.T) {
app := fiber.New()
app.Post("/api/v1/auth/signup/verify", h.VerifySignupCode)
stateJSON, _ := json.Marshal(map[string]interface{}{
stateJSON, _ := json.Marshal(map[string]any{
"code": "111111",
"expires_at": 9999999999,
})

View File

@@ -5,6 +5,7 @@ import (
"bytes"
"context"
"encoding/json"
"maps"
"net/http"
"net/http/httptest"
"testing"
@@ -33,7 +34,7 @@ func (r *recordingUpdateMeUserRepo) UpdateUserLoginIDs(ctx context.Context, user
func TestUpdateMe_InvalidatesProfileCacheForTokenSession(t *testing.T) {
token := "token-abc"
identityID := "user-1"
traits := map[string]interface{}{
traits := map[string]any{
"email": "qa@example.com",
"name": "QA User",
"phone_number": "+821012345678",
@@ -51,8 +52,8 @@ func TestUpdateMe_InvalidatesProfileCacheForTokenSession(t *testing.T) {
if r.Header.Get("X-Session-Token") != token {
return httpResponse(r, http.StatusUnauthorized, `{"error":"invalid token"}`), nil
}
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"identity": map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"identity": map[string]any{
"id": identityID,
"traits": traits,
},
@@ -62,14 +63,12 @@ func TestUpdateMe_InvalidatesProfileCacheForTokenSession(t *testing.T) {
r.URL.Path == "/admin/identities/"+identityID &&
r.Method == http.MethodPut:
var payload struct {
Traits map[string]interface{} `json:"traits"`
Traits map[string]any `json:"traits"`
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
return httpResponse(r, http.StatusBadRequest, `{"error":"invalid body"}`), nil
}
for k, v := range payload.Traits {
traits[k] = v
}
maps.Copy(traits, payload.Traits)
return httpResponse(r, http.StatusOK, `{"ok":true}`), nil
}
@@ -93,7 +92,7 @@ func TestUpdateMe_InvalidatesProfileCacheForTokenSession(t *testing.T) {
getResp1, err := app.Test(getReq1, -1)
require.NoError(t, err)
require.Equal(t, http.StatusOK, getResp1.StatusCode)
var profile1 map[string]interface{}
var profile1 map[string]any
require.NoError(t, json.NewDecoder(getResp1.Body).Decode(&profile1))
require.Equal(t, "Old Dept", profile1["department"])
@@ -121,7 +120,7 @@ func TestUpdateMe_InvalidatesProfileCacheForTokenSession(t *testing.T) {
getResp2, err := app.Test(getReq2, -1)
require.NoError(t, err)
require.Equal(t, http.StatusOK, getResp2.StatusCode)
var profile2 map[string]interface{}
var profile2 map[string]any
require.NoError(t, json.NewDecoder(getResp2.Body).Decode(&profile2))
require.Equal(t, "New Dept", profile2["department"])
}
@@ -129,7 +128,7 @@ func TestUpdateMe_InvalidatesProfileCacheForTokenSession(t *testing.T) {
func TestUpdateMe_SyncsLocalReadModelFields(t *testing.T) {
token := "token-sync"
identityID := "user-sync"
traits := map[string]interface{}{
traits := map[string]any{
"email": "sync@example.com",
"name": "Old Name",
"phone_number": "+821012345678",
@@ -148,8 +147,8 @@ func TestUpdateMe_SyncsLocalReadModelFields(t *testing.T) {
if r.Header.Get("X-Session-Token") != token {
return httpResponse(r, http.StatusUnauthorized, `{"error":"invalid token"}`), nil
}
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"identity": map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"identity": map[string]any{
"id": identityID,
"traits": traits,
},
@@ -159,14 +158,12 @@ func TestUpdateMe_SyncsLocalReadModelFields(t *testing.T) {
r.URL.Path == "/admin/identities/"+identityID &&
r.Method == http.MethodPut:
var payload struct {
Traits map[string]interface{} `json:"traits"`
Traits map[string]any `json:"traits"`
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
return httpResponse(r, http.StatusBadRequest, `{"error":"invalid body"}`), nil
}
for k, v := range payload.Traits {
traits[k] = v
}
maps.Copy(traits, payload.Traits)
return httpResponse(r, http.StatusOK, `{"ok":true}`), nil
}
@@ -187,7 +184,7 @@ func TestUpdateMe_SyncsLocalReadModelFields(t *testing.T) {
app := fiber.New()
app.Put("/api/v1/user/me", h.UpdateMe)
updateBody, _ := json.Marshal(map[string]interface{}{
updateBody, _ := json.Marshal(map[string]any{
"name": "New Name",
"phone": "01087654321",
"department": "New Dept",

View File

@@ -68,7 +68,7 @@ func TestQRLoginFlow_Success(t *testing.T) {
resp, _ := app.Test(req, -1)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var initResp map[string]interface{}
var initResp map[string]any
json.NewDecoder(resp.Body).Decode(&initResp)
pendingRef := initResp["pendingRef"].(string)
@@ -80,7 +80,7 @@ func TestQRLoginFlow_Success(t *testing.T) {
// Expect authorization_pending (400)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
var pollResp map[string]interface{}
var pollResp map[string]any
json.NewDecoder(resp.Body).Decode(&pollResp)
assert.Equal(t, "authorization_pending", pollResp["error"])
assert.Equal(t, "authorization_pending", pollResp["code"])
@@ -99,7 +99,7 @@ func TestQRLoginFlow_Success(t *testing.T) {
assert.Equal(t, http.StatusOK, resp.StatusCode)
var successResp map[string]interface{}
var successResp map[string]any
json.NewDecoder(resp.Body).Decode(&successResp)
assert.Equal(t, "ok", successResp["status"])
assert.Equal(t, "mock-session-jwt", successResp["sessionJwt"])
@@ -121,10 +121,10 @@ func TestScanQRLogin_Success(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/sessions/whoami" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"identity": map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"identity": map[string]any{
"id": "user-123",
"traits": map[string]interface{}{
"traits": map[string]any{
"email": "user@example.com",
},
},
@@ -153,20 +153,20 @@ func TestResolveConsentSubjects_TokenAndCookie(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Header.Get("X-Session-Token") == "token-123" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"identity": map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"identity": map[string]any{
"id": "user-token",
"traits": map[string]interface{}{
"traits": map[string]any{
"email": "token@test.com",
},
},
}), nil
}
if r.Header.Get("Cookie") == "ory_kratos_session=cookie-123" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"identity": map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"identity": map[string]any{
"id": "user-cookie",
"traits": map[string]interface{}{
"traits": map[string]any{
"email": "cookie@test.com",
"phone": "010-1234-5678",
},

View File

@@ -92,7 +92,7 @@ func TestSignup_TenantSlugValidation(t *testing.T) {
app.Post("/signup", h.Signup)
// Prepare mock state (already verified email/phone)
verifiedState, _ := json.Marshal(map[string]interface{}{
verifiedState, _ := json.Marshal(map[string]any{
"verified": true,
"expires_at": time.Now().Add(time.Hour).Unix(),
})

View File

@@ -17,9 +17,9 @@ const (
clientAllowedTenantsKey = "allowed_tenants"
)
func normalizeClientTenantAccessMetadata(metadata map[string]interface{}) (map[string]interface{}, error) {
func normalizeClientTenantAccessMetadata(metadata map[string]any) (map[string]any, error) {
if metadata == nil {
metadata = map[string]interface{}{}
metadata = map[string]any{}
}
restricted := readMetadataBoolValue(metadata, clientTenantAccessRestrictedKey)
@@ -49,7 +49,7 @@ func normalizeClientTenantAccessMetadata(metadata map[string]interface{}) (map[s
return metadata, nil
}
func clientTenantAccessRestricted(metadata map[string]interface{}) bool {
func clientTenantAccessRestricted(metadata map[string]any) bool {
if metadata == nil {
return false
}
@@ -59,7 +59,7 @@ func clientTenantAccessRestricted(metadata map[string]interface{}) bool {
return len(normalizeMetadataStringSlice(metadata[clientAllowedTenantsKey])) > 0
}
func clientAllowedTenants(metadata map[string]interface{}) []string {
func clientAllowedTenants(metadata map[string]any) []string {
if metadata == nil {
return nil
}

View File

@@ -250,7 +250,7 @@ func TestGetConsentRequest_DeniesRestrictedClientWhenProfileResolutionFails(t *t
mockKratos := new(MockKratosAdminService)
mockKratos.On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
ID: "user-123",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
"tenant_id": "tenant-a",
"companyCode": "tenant-a",

View File

@@ -7,6 +7,7 @@ import (
"encoding/json"
"io"
"net/http"
"slices"
"time"
)
@@ -94,11 +95,8 @@ func (m *mockAuditRepo) FindByUserAndEvents(ctx context.Context, userID string,
var results []domain.AuditLog
for _, log := range m.logs {
if log.UserID == userID {
for _, et := range eventTypes {
if log.EventType == et {
results = append(results, log)
break
}
if slices.Contains(eventTypes, log.EventType) {
results = append(results, log)
}
}
}

View File

@@ -14,6 +14,7 @@ import (
"fmt"
"io"
"log/slog"
"maps"
"net"
"net/http"
"net/url"
@@ -104,21 +105,21 @@ type devRPUsageDailyResponse struct {
}
type clientSummary struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Status string `json:"status"`
CreatedAt *time.Time `json:"createdAt,omitempty"`
RedirectURIs []string `json:"redirectUris"`
Scopes []string `json:"scopes"`
ClientSecret string `json:"clientSecret,omitempty"`
TokenEndpointAuthMethod string `json:"tokenEndpointAuthMethod,omitempty"`
SkipConsent bool `json:"skipConsent"`
JwksUri string `json:"jwksUri,omitempty"`
Jwks interface{} `json:"jwks,omitempty"`
BackchannelLogoutURI string `json:"backchannelLogoutUri,omitempty"`
BackchannelLogoutSessionRequired bool `json:"backchannelLogoutSessionRequired"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Status string `json:"status"`
CreatedAt *time.Time `json:"createdAt,omitempty"`
RedirectURIs []string `json:"redirectUris"`
Scopes []string `json:"scopes"`
ClientSecret string `json:"clientSecret,omitempty"`
TokenEndpointAuthMethod string `json:"tokenEndpointAuthMethod,omitempty"`
SkipConsent bool `json:"skipConsent"`
JwksUri string `json:"jwksUri,omitempty"`
Jwks any `json:"jwks,omitempty"`
BackchannelLogoutURI string `json:"backchannelLogoutUri,omitempty"`
BackchannelLogoutSessionRequired bool `json:"backchannelLogoutSessionRequired"`
Metadata map[string]any `json:"metadata,omitempty"`
}
type clientListResponse struct {
@@ -198,21 +199,21 @@ type consentListResponse struct {
}
type clientUpsertRequest struct {
ID *string `json:"id"`
Name *string `json:"name"`
Type *string `json:"type"`
Status *string `json:"status"`
RedirectURIs *[]string `json:"redirectUris"`
Scopes *[]string `json:"scopes"`
GrantTypes *[]string `json:"grantTypes"`
ResponseTypes *[]string `json:"responseTypes"`
TokenEndpointAuthMethod *string `json:"tokenEndpointAuthMethod"`
SkipConsent *bool `json:"skipConsent"`
JwksUri *string `json:"jwksUri"`
Jwks interface{} `json:"jwks"`
BackchannelLogoutURI *string `json:"backchannelLogoutUri"`
BackchannelLogoutSessionRequired *bool `json:"backchannelLogoutSessionRequired"`
Metadata *map[string]interface{} `json:"metadata"`
ID *string `json:"id"`
Name *string `json:"name"`
Type *string `json:"type"`
Status *string `json:"status"`
RedirectURIs *[]string `json:"redirectUris"`
Scopes *[]string `json:"scopes"`
GrantTypes *[]string `json:"grantTypes"`
ResponseTypes *[]string `json:"responseTypes"`
TokenEndpointAuthMethod *string `json:"tokenEndpointAuthMethod"`
SkipConsent *bool `json:"skipConsent"`
JwksUri *string `json:"jwksUri"`
Jwks any `json:"jwks"`
BackchannelLogoutURI *string `json:"backchannelLogoutUri"`
BackchannelLogoutSessionRequired *bool `json:"backchannelLogoutSessionRequired"`
Metadata *map[string]any `json:"metadata"`
}
type normalizedIDTokenClaim struct {
@@ -303,7 +304,7 @@ func tenantIDFromProfile(profile *domain.UserProfileResponse) string {
func addClientIDToSet(set map[string]struct{}, raw any) {
switch value := raw.(type) {
case string:
for _, chunk := range strings.Split(value, ",") {
for chunk := range strings.SplitSeq(value, ",") {
id := strings.TrimSpace(chunk)
if id != "" {
set[id] = struct{}{}
@@ -672,7 +673,7 @@ func isProtectedSystemClientID(clientID string) bool {
return ok
}
func tenantAccessPolicyChanged(before, after map[string]interface{}) bool {
func tenantAccessPolicyChanged(before, after map[string]any) bool {
if clientTenantAccessRestricted(before) != clientTenantAccessRestricted(after) {
return true
}
@@ -1162,7 +1163,7 @@ func extractAuthClaimsFromBearer(authHeader string) (string, string) {
}
}
var claims map[string]interface{}
var claims map[string]any
if err := json.Unmarshal(payload, &claims); err != nil {
return "", ""
}
@@ -1295,10 +1296,7 @@ func (h *DevHandler) ListClients(c *fiber.Ctx) error {
if offset > len(allItems) {
offset = len(allItems)
}
end := offset + limit
if end > len(allItems) {
end = len(allItems)
}
end := min(offset+limit, len(allItems))
items = allItems[offset:end]
if len(allItems) > end && len(items) > 0 {
lastTimestamp, lastID := clientSummaryCursorKey(items[len(items)-1])
@@ -1788,7 +1786,7 @@ func (h *DevHandler) CreateClient(c *fiber.Ctx) error {
metadata := mergeMetadata(nil, req.Metadata)
if metadata == nil {
metadata = map[string]interface{}{}
metadata = map[string]any{}
}
// [Tenant Isolation] Record owner information
@@ -1858,11 +1856,11 @@ func (h *DevHandler) CreateClient(c *fiber.Ctx) error {
ResponseTypes: responseTypes,
Scope: strings.Join(scopes, " "),
TokenEndpointAuthMethod: tokenAuthMethod,
SkipConsent: boolPtr(valueOrBool(req.SkipConsent, true)),
SkipConsent: new(valueOrBool(req.SkipConsent, true)),
JWKSUri: jwksURI,
JWKS: jwks,
BackChannelLogoutURI: backchannelLogoutURI,
BackChannelLogoutSessionRequired: boolPtr(backchannelLogoutSessionRequired),
BackChannelLogoutSessionRequired: new(backchannelLogoutSessionRequired),
Metadata: metadata,
}
@@ -2005,7 +2003,7 @@ func (h *DevHandler) UpdateClient(c *fiber.Ctx) error {
metadata := mergeMetadata(current.Metadata, req.Metadata)
if status != "" {
if metadata == nil {
metadata = map[string]interface{}{}
metadata = map[string]any{}
}
metadata["status"] = status
}
@@ -2061,11 +2059,11 @@ func (h *DevHandler) UpdateClient(c *fiber.Ctx) error {
ResponseTypes: derefSlice(req.ResponseTypes, current.ResponseTypes),
Scope: buildScope(valueOrSlice(req.Scopes, strings.Fields(current.Scope))),
TokenEndpointAuthMethod: resolvedTokenAuthMethod,
SkipConsent: boolPtr(resolvedSkipConsent),
SkipConsent: new(resolvedSkipConsent),
JWKSUri: resolvedJWKSURI,
JWKS: resolvedJWKS,
BackChannelLogoutURI: strings.TrimSpace(resolvedBackchannelLogoutURI),
BackChannelLogoutSessionRequired: boolPtr(resolvedBackchannelLogoutSessionRequired),
BackChannelLogoutSessionRequired: new(resolvedBackchannelLogoutSessionRequired),
Metadata: metadata,
}
if err := validateReservedSystemClientName(updated.ClientID, updated.ClientName); err != nil {
@@ -2359,10 +2357,7 @@ func (h *DevHandler) ListConsents(c *fiber.Ctx) error {
if offset > len(items) {
offset = len(items)
}
end := offset + limit
if end > len(items) {
end = len(items)
}
end := min(offset+limit, len(items))
pageItems := items[offset:end]
if len(items) > end && len(pageItems) > 0 {
lastTimestamp, lastID := consentSummaryCursorKey(pageItems[len(pageItems)-1])
@@ -2948,7 +2943,7 @@ func (h *DevHandler) mapClientSummary(client domain.HydraClient) clientSummary {
}
}
func readMetadataStringValue(metadata map[string]interface{}, key string) string {
func readMetadataStringValue(metadata map[string]any, key string) string {
if metadata == nil {
return ""
}
@@ -2956,7 +2951,7 @@ func readMetadataStringValue(metadata map[string]interface{}, key string) string
return strings.TrimSpace(raw)
}
func readMetadataBoolValue(metadata map[string]interface{}, key string) bool {
func readMetadataBoolValue(metadata map[string]any, key string) bool {
if metadata == nil {
return false
}
@@ -2964,7 +2959,7 @@ func readMetadataBoolValue(metadata map[string]interface{}, key string) bool {
return value
}
func readStringSliceMetadata(metadata map[string]interface{}, key string) []string {
func readStringSliceMetadata(metadata map[string]any, key string) []string {
if metadata == nil {
return nil
}
@@ -2981,7 +2976,7 @@ func readStringSliceMetadata(metadata map[string]interface{}, key string) []stri
}
}
return result
case []interface{}:
case []any:
result := make([]string, 0, len(typed))
for _, item := range typed {
if str, ok := item.(string); ok {
@@ -2996,7 +2991,7 @@ func readStringSliceMetadata(metadata map[string]interface{}, key string) []stri
}
}
func readMetadataValueOrNil(metadata map[string]interface{}, key string) interface{} {
func readMetadataValueOrNil(metadata map[string]any, key string) any {
if metadata == nil {
return nil
}
@@ -3007,9 +3002,9 @@ func readMetadataValueOrNil(metadata map[string]interface{}, key string) interfa
return value
}
func normalizeBackchannelLogoutMetadata(metadata map[string]interface{}, logoutURI string, sessionRequired bool) (map[string]interface{}, error) {
func normalizeBackchannelLogoutMetadata(metadata map[string]any, logoutURI string, sessionRequired bool) (map[string]any, error) {
if metadata == nil {
metadata = map[string]interface{}{}
metadata = map[string]any{}
}
trimmedURI := strings.TrimSpace(logoutURI)
@@ -3078,7 +3073,7 @@ func isAllowedLocalBackchannelLogoutHost(rawHost string) bool {
return !strings.Contains(host, ".")
}
func normalizeClientAutoLoginMetadata(metadata map[string]interface{}) (map[string]interface{}, error) {
func normalizeClientAutoLoginMetadata(metadata map[string]any) (map[string]any, error) {
if metadata == nil {
return metadata, nil
}
@@ -3105,11 +3100,11 @@ func normalizeClientAutoLoginMetadata(metadata map[string]interface{}) (map[stri
func normalizeHeadlessClientConfig(
tokenAuthMethod string,
jwksURI string,
jwks interface{},
metadata map[string]interface{},
) (string, string, interface{}, map[string]interface{}) {
jwks any,
metadata map[string]any,
) (string, string, any, map[string]any) {
if metadata == nil {
metadata = map[string]interface{}{}
metadata = map[string]any{}
}
delete(metadata, domain.MetadataRequestObjectSigningAlg)
@@ -3145,7 +3140,7 @@ func normalizeHeadlessClientConfig(
return tokenAuthMethod, jwksURI, jwks, metadata
}
func validateHeadlessClientInput(jwksURI string, jwks interface{}, metadata map[string]interface{}) error {
func validateHeadlessClientInput(jwksURI string, jwks any, metadata map[string]any) error {
if !readMetadataBoolValue(metadata, domain.MetadataHeadlessLoginEnabled) {
return nil
}
@@ -3164,14 +3159,14 @@ func validateHeadlessClientInput(jwksURI string, jwks interface{}, metadata map[
return nil
}
func normalizeClientTypeForHeadless(clientType string, metadata map[string]interface{}) string {
func normalizeClientTypeForHeadless(clientType string, metadata map[string]any) string {
if readMetadataBoolValue(metadata, domain.MetadataHeadlessLoginEnabled) {
return "private"
}
return clientType
}
func normalizeIDTokenClaimsMetadata(metadata map[string]interface{}) (map[string]interface{}, error) {
func normalizeIDTokenClaimsMetadata(metadata map[string]any) (map[string]any, error) {
if metadata == nil {
return nil, nil
}
@@ -3189,16 +3184,16 @@ func normalizeIDTokenClaimsMetadata(metadata map[string]interface{}) (map[string
return metadata, nil
}
func normalizeIDTokenClaims(rawClaims interface{}) ([]normalizedIDTokenClaim, error) {
rawList, ok := rawClaims.([]interface{})
func normalizeIDTokenClaims(rawClaims any) ([]normalizedIDTokenClaim, error) {
rawList, ok := rawClaims.([]any)
if !ok {
if typedList, ok := rawClaims.([]map[string]interface{}); ok {
rawList = make([]interface{}, 0, len(typedList))
if typedList, ok := rawClaims.([]map[string]any); ok {
rawList = make([]any, 0, len(typedList))
for _, item := range typedList {
rawList = append(rawList, item)
}
} else if typedList, ok := rawClaims.([]map[string]any); ok {
rawList = make([]interface{}, 0, len(typedList))
rawList = make([]any, 0, len(typedList))
for _, item := range typedList {
rawList = append(rawList, item)
}
@@ -3211,13 +3206,11 @@ func normalizeIDTokenClaims(rawClaims interface{}) ([]normalizedIDTokenClaim, er
seen := make(map[string]struct{}, len(rawList))
for _, item := range rawList {
record, ok := item.(map[string]interface{})
record, ok := item.(map[string]any)
if !ok {
if typedRecord, ok := item.(map[string]any); ok {
record = make(map[string]interface{}, len(typedRecord))
for key, value := range typedRecord {
record[key] = value
}
record = make(map[string]any, len(typedRecord))
maps.Copy(record, typedRecord)
} else {
return nil, errors.New("metadata.id_token_claims items must be objects")
}
@@ -3271,7 +3264,7 @@ func normalizeIDTokenClaims(rawClaims interface{}) ([]normalizedIDTokenClaim, er
return normalized, nil
}
func readInterfaceString(value interface{}, fallback string) string {
func readInterfaceString(value any, fallback string) string {
if value == nil {
return fallback
}
@@ -3373,8 +3366,9 @@ func valueOr(ptr *string, fallback string) string {
return *ptr
}
//go:fix inline
func boolPtr(value bool) *bool {
return &value
return new(value)
}
func valueOrBool(ptr *bool, fallback bool) bool {
@@ -3398,17 +3392,13 @@ func derefSlice(ptr *[]string, fallback []string) []string {
return *ptr
}
func mergeMetadata(current map[string]interface{}, incoming *map[string]interface{}) map[string]interface{} {
func mergeMetadata(current map[string]any, incoming *map[string]any) map[string]any {
if incoming == nil {
return current
}
merged := map[string]interface{}{}
for k, v := range current {
merged[k] = v
}
for k, v := range *incoming {
merged[k] = v
}
merged := map[string]any{}
maps.Copy(merged, current)
maps.Copy(merged, *incoming)
return merged
}
@@ -3433,9 +3423,7 @@ func (h *DevHandler) setAuditDetailsExtra(c *fiber.Ctx, extra map[string]any) {
}
if existing := c.Locals("audit_details_extra"); existing != nil {
if m, ok := existing.(map[string]any); ok {
for k, v := range extra {
m[k] = v
}
maps.Copy(m, extra)
c.Locals("audit_details_extra", m)
return
}
@@ -3494,7 +3482,7 @@ func resolveDevAuditClientID(logItem domain.AuditLog, details map[string]any) st
return resolvedID
}
func resolveStatusFromMetadata(metadata map[string]interface{}) string {
func resolveStatusFromMetadata(metadata map[string]any) string {
if metadata != nil {
if value, ok := metadata["status"].(string); ok && strings.ToLower(strings.TrimSpace(value)) == "inactive" {
return "inactive"

View File

@@ -26,18 +26,18 @@ func TestDevHandler_Isolation(t *testing.T) {
HTTPClient: &http.Client{
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodGet && r.URL.Path == "/clients" {
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
return httpJSONAny(r, http.StatusOK, []map[string]any{
{
"client_id": "client-tenant-a",
"client_name": "App Tenant A",
"token_endpoint_auth_method": "none", // PKCE
"metadata": map[string]interface{}{"tenant_id": "tenant-a"},
"metadata": map[string]any{"tenant_id": "tenant-a"},
},
{
"client_id": "client-tenant-b",
"client_name": "App Tenant B",
"token_endpoint_auth_method": "none", // PKCE
"metadata": map[string]interface{}{"tenant_id": "tenant-b"},
"metadata": map[string]any{"tenant_id": "tenant-b"},
},
}), nil
}
@@ -47,15 +47,15 @@ func TestDevHandler_Isolation(t *testing.T) {
if id == "client-tenant-b" {
tenantID = "tenant-b"
}
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": id,
"client_name": "App " + id,
"token_endpoint_auth_method": "none",
"metadata": map[string]interface{}{"tenant_id": tenantID},
"metadata": map[string]any{"tenant_id": tenantID},
}), nil
}
if r.Method == http.MethodPost && r.URL.Path == "/clients" {
var body map[string]interface{}
var body map[string]any
json.NewDecoder(r.Body).Decode(&body)
return httpJSONAny(r, http.StatusCreated, body), nil
}
@@ -205,7 +205,7 @@ func TestDevHandler_Isolation(t *testing.T) {
})
app.Put("/api/v1/dev/clients/:id", h.UpdateClient)
body, _ := json.Marshal(map[string]interface{}{
body, _ := json.Marshal(map[string]any{
"client_name": "Updated Name",
})
@@ -235,7 +235,7 @@ func TestDevHandler_Isolation(t *testing.T) {
})
app.Post("/api/v1/dev/clients", h.CreateClient)
body, _ := json.Marshal(map[string]interface{}{
body, _ := json.Marshal(map[string]any{
"client_name": "New App",
"type": "pkce",
"redirectUris": []string{"http://localhost/cb"},

View File

@@ -35,10 +35,10 @@ func (m *devMockRPUserMetadataRepo) Upsert(ctx context.Context, metadata *domain
func TestDevHandler_RPUserMetadataRoundTrip(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/clients/client-1" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "client-1",
"client_name": "Client One",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"tenant_id": "tenant-1",
},
}), nil

View File

@@ -88,7 +88,7 @@ func (m *devMockKratosAdmin) GetIdentity(ctx context.Context, identityID string)
return nil, args.Error(1)
}
func (m *devMockKratosAdmin) UpdateIdentity(ctx context.Context, identityID string, traits map[string]interface{}, state string) (*service.KratosIdentity, error) {
func (m *devMockKratosAdmin) UpdateIdentity(ctx context.Context, identityID string, traits map[string]any, state string) (*service.KratosIdentity, error) {
args := m.Called(ctx, identityID, traits, state)
if identity, ok := args.Get(0).(*service.KratosIdentity); ok {
return identity, args.Error(1)
@@ -292,9 +292,9 @@ func TestGetCurrentProfile_PreservesExistingAuditUserContext(t *testing.T) {
func TestListClients_Success(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/clients" {
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
{"client_id": "client-1", "client_name": "App One", "metadata": map[string]interface{}{"status": "active"}},
{"client_id": "client-2", "client_name": "App Two", "metadata": map[string]interface{}{"status": "inactive"}},
return httpJSONAny(r, http.StatusOK, []map[string]any{
{"client_id": "client-1", "client_name": "App One", "metadata": map[string]any{"status": "active"}},
{"client_id": "client-2", "client_name": "App Two", "metadata": map[string]any{"status": "inactive"}},
}), nil
}
return httpJSONAny(r, http.StatusNotFound, nil), nil
@@ -326,9 +326,9 @@ func TestListClients_Success(t *testing.T) {
func TestListClients_UserSeesOnlyClientsAllowedByReBAC(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/clients" {
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
{"client_id": "client-denied", "client_name": "Denied App", "metadata": map[string]interface{}{"tenant_id": "tenant-a", "status": "active"}},
{"client_id": "client-allowed", "client_name": "Allowed App", "metadata": map[string]interface{}{"tenant_id": "tenant-b", "status": "active"}},
return httpJSONAny(r, http.StatusOK, []map[string]any{
{"client_id": "client-denied", "client_name": "Denied App", "metadata": map[string]any{"tenant_id": "tenant-a", "status": "active"}},
{"client_id": "client-allowed", "client_name": "Allowed App", "metadata": map[string]any{"tenant_id": "tenant-b", "status": "active"}},
}), nil
}
return httpJSONAny(r, http.StatusNotFound, nil), nil
@@ -796,9 +796,9 @@ func TestUpdateClient_AuditDetailsIncludeGeneralSettingChanges(t *testing.T) {
func TestListClients_ProtectedSystemClientHidden(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/clients" {
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
return httpJSONAny(r, http.StatusOK, []map[string]any{
{"client_id": "oathkeeper-introspect", "client_name": "Internal Client"},
{"client_id": "client-1", "client_name": "App One", "metadata": map[string]interface{}{"status": "active"}},
{"client_id": "client-1", "client_name": "App One", "metadata": map[string]any{"status": "active"}},
}), nil
}
return httpJSONAny(r, http.StatusNotFound, nil), nil
@@ -834,12 +834,12 @@ func TestListClients_ProtectedSystemClientHidden(t *testing.T) {
func TestListClients_ReservedSystemNameAliasHidden(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/clients" {
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
{"client_id": "adminfront", "client_name": "AdminFront", "metadata": map[string]interface{}{"status": "active"}},
{"client_id": "4f2c9fd6-1111-2222-3333-444444444444", "client_name": "AdminFront", "metadata": map[string]interface{}{"status": "active"}},
{"client_id": "devfront", "client_name": "DevFront", "metadata": map[string]interface{}{"status": "active"}},
{"client_id": "7d2c9fd6-1111-2222-3333-444444444444", "client_name": "DevFront", "metadata": map[string]interface{}{"status": "active"}},
{"client_id": "client-1", "client_name": "App One", "metadata": map[string]interface{}{"status": "active"}},
return httpJSONAny(r, http.StatusOK, []map[string]any{
{"client_id": "adminfront", "client_name": "AdminFront", "metadata": map[string]any{"status": "active"}},
{"client_id": "4f2c9fd6-1111-2222-3333-444444444444", "client_name": "AdminFront", "metadata": map[string]any{"status": "active"}},
{"client_id": "devfront", "client_name": "DevFront", "metadata": map[string]any{"status": "active"}},
{"client_id": "7d2c9fd6-1111-2222-3333-444444444444", "client_name": "DevFront", "metadata": map[string]any{"status": "active"}},
{"client_id": "client-1", "client_name": "App One", "metadata": map[string]any{"status": "active"}},
}), nil
}
return httpJSONAny(r, http.StatusNotFound, nil), nil
@@ -878,10 +878,10 @@ func TestListClients_ReservedSystemNameAliasHidden(t *testing.T) {
func TestGetClient_ReservedSystemNameAliasHidden(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/clients/4f2c9fd6-1111-2222-3333-444444444444" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "4f2c9fd6-1111-2222-3333-444444444444",
"client_name": "AdminFront",
"metadata": map[string]interface{}{"status": "active"},
"metadata": map[string]any{"status": "active"},
}), nil
}
return httpJSONAny(r, http.StatusNotFound, nil), nil
@@ -910,13 +910,13 @@ func TestGetClient_ReservedSystemNameAliasHidden(t *testing.T) {
func TestUpdateClientStatus_Success(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"client_id": "client-1", "metadata": map[string]interface{}{"status": "active"},
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "client-1", "metadata": map[string]any{"status": "active"},
}), nil
}
if r.Method == http.MethodPatch && r.URL.Path == "/clients/client-1" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
"client_id": "client-1", "metadata": map[string]interface{}{"status": "inactive"},
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "client-1", "metadata": map[string]any{"status": "inactive"},
}), nil
}
return httpJSONAny(r, http.StatusNotFound, nil), nil
@@ -936,7 +936,7 @@ func TestUpdateClientStatus_Success(t *testing.T) {
})
app.Patch("/api/v1/dev/clients/:id/status", h.UpdateClientStatus)
body, _ := json.Marshal(map[string]interface{}{"status": "inactive"})
body, _ := json.Marshal(map[string]any{"status": "inactive"})
req := httptest.NewRequest(http.MethodPatch, "/api/v1/dev/clients/client-1/status", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
resp, _ := app.Test(req, -1)
@@ -950,20 +950,20 @@ func TestUpdateClientStatus_Success(t *testing.T) {
func TestUpdateClientStatus_UserAllowedByStatusPermission(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "client-1",
"client_name": "App One",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"tenant_id": "tenant-1",
"status": "active",
},
}), nil
}
if r.Method == http.MethodPatch && r.URL.Path == "/clients/client-1" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "client-1",
"client_name": "App One",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"tenant_id": "tenant-1",
"status": "inactive",
},
@@ -995,7 +995,7 @@ func TestUpdateClientStatus_UserAllowedByStatusPermission(t *testing.T) {
})
app.Patch("/api/v1/dev/clients/:id/status", h.UpdateClientStatus)
body, _ := json.Marshal(map[string]interface{}{"status": "inactive"})
body, _ := json.Marshal(map[string]any{"status": "inactive"})
req := httptest.NewRequest(http.MethodPatch, "/api/v1/dev/clients/client-1/status", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
resp, _ := app.Test(req, -1)
@@ -1010,20 +1010,20 @@ func TestUpdateClientStatus_UserAllowedByStatusPermission(t *testing.T) {
func TestUpdateClientStatus_UserAllowedByEditConfigPermission(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "client-1",
"client_name": "App One",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"tenant_id": "tenant-1",
"status": "active",
},
}), nil
}
if r.Method == http.MethodPatch && r.URL.Path == "/clients/client-1" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "client-1",
"client_name": "App One",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"tenant_id": "tenant-1",
"status": "inactive",
},
@@ -1055,7 +1055,7 @@ func TestUpdateClientStatus_UserAllowedByEditConfigPermission(t *testing.T) {
})
app.Patch("/api/v1/dev/clients/:id/status", h.UpdateClientStatus)
body, _ := json.Marshal(map[string]interface{}{"status": "inactive"})
body, _ := json.Marshal(map[string]any{"status": "inactive"})
req := httptest.NewRequest(http.MethodPatch, "/api/v1/dev/clients/client-1/status", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
resp, _ := app.Test(req, -1)
@@ -1070,7 +1070,7 @@ func TestUpdateClientStatus_UserAllowedByEditConfigPermission(t *testing.T) {
func TestUpdateClientStatus_ProtectedSystemClientForbidden(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodGet && r.URL.Path == "/clients/oathkeeper-introspect" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "oathkeeper-introspect",
}), nil
}
@@ -1091,7 +1091,7 @@ func TestUpdateClientStatus_ProtectedSystemClientForbidden(t *testing.T) {
})
app.Patch("/api/v1/dev/clients/:id/status", h.UpdateClientStatus)
body, _ := json.Marshal(map[string]interface{}{"status": "inactive"})
body, _ := json.Marshal(map[string]any{"status": "inactive"})
req := httptest.NewRequest(http.MethodPatch, "/api/v1/dev/clients/oathkeeper-introspect/status", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
resp, _ := app.Test(req, -1)
@@ -1102,7 +1102,7 @@ func TestUpdateClientStatus_ProtectedSystemClientForbidden(t *testing.T) {
func TestDeleteClient_Success(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{"client_id": "client-1"}), nil
return httpJSONAny(r, http.StatusOK, map[string]any{"client_id": "client-1"}), nil
}
if r.Method == http.MethodDelete && r.URL.Path == "/clients/client-1" {
return &http.Response{StatusCode: http.StatusNoContent, Body: http.NoBody}, nil
@@ -1142,7 +1142,7 @@ func TestDeleteClient_Success(t *testing.T) {
func TestDeleteClient_ProtectedSystemClientForbidden(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodGet && r.URL.Path == "/clients/oathkeeper-introspect" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{"client_id": "oathkeeper-introspect"}), nil
return httpJSONAny(r, http.StatusOK, map[string]any{"client_id": "oathkeeper-introspect"}), nil
}
return httpJSONAny(r, http.StatusNotFound, nil), nil
})
@@ -1172,7 +1172,7 @@ func TestDeleteClient_ProtectedSystemClientForbidden(t *testing.T) {
func TestGetClient_ProtectedSystemClientHidden(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodGet && r.URL.Path == "/clients/oathkeeper-introspect" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "oathkeeper-introspect",
"client_name": "Internal Client",
}), nil
@@ -1203,10 +1203,10 @@ func TestGetClient_ProtectedSystemClientHidden(t *testing.T) {
func TestGetClient_RPAdminAllowedByKetoViewPermission(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "client-1",
"client_name": "App One",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"tenant_id": "tenant-b",
"status": "active",
},
@@ -1248,11 +1248,11 @@ func TestGetClient_RPAdminAllowedByKetoViewPermission(t *testing.T) {
func TestGetClient_RedactsSecretWithoutViewSecretPermission(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "client-1",
"client_name": "App One",
"client_secret": "stored-secret",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"tenant_id": "tenant-1",
"status": "active",
},
@@ -1297,11 +1297,11 @@ func TestGetClient_RedactsSecretWithoutViewSecretPermission(t *testing.T) {
func TestGetClient_UserAllowedToViewSecretByPermission(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
return httpJSONAny(r, http.StatusOK, map[string]any{
"client_id": "client-1",
"client_name": "App One",
"client_secret": "stored-secret",
"metadata": map[string]interface{}{
"metadata": map[string]any{
"tenant_id": "tenant-1",
"status": "active",
},
@@ -1346,10 +1346,10 @@ func TestGetClient_UserAllowedToViewSecretByPermission(t *testing.T) {
func TestRotateClientSecret_Success(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodGet && r.URL.Path == "/clients/client-1" {
return httpJSONAny(r, http.StatusOK, map[string]interface{}{"client_id": "client-1"}), nil
return httpJSONAny(r, http.StatusOK, map[string]any{"client_id": "client-1"}), nil
}
if r.Method == http.MethodPut && r.URL.Path == "/clients/client-1" {
var body map[string]interface{}
var body map[string]any
json.NewDecoder(r.Body).Decode(&body)
return httpJSONAny(r, http.StatusOK, body), nil
}
@@ -1390,7 +1390,7 @@ func TestRotateClientSecret_Success(t *testing.T) {
func TestCreateClient_RPAdminAllowedByTenantGrantPermission(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodPost && r.URL.Path == "/clients" {
var body map[string]interface{}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
body["client_secret"] = "generated-secret"
return httpJSONAny(r, http.StatusCreated, body), nil
@@ -1443,7 +1443,7 @@ func TestCreateClient_RPAdminAllowedByTenantGrantPermission(t *testing.T) {
func TestCreateClient_ApprovedDeveloperCanCreatePrivateClient(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.Method == http.MethodPost && r.URL.Path == "/clients" {
var body map[string]interface{}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
body["client_secret"] = "generated-secret"
return httpJSONAny(r, http.StatusCreated, body), nil
@@ -1625,11 +1625,11 @@ func TestRevokeDeveloperGrantRelation_DeletesRequiredTenantRelations(t *testing.
func TestGetStats_Success(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/clients" {
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
{"client_id": "c1", "metadata": map[string]interface{}{"tenant_id": "t1"}},
{"client_id": "c2", "metadata": map[string]interface{}{"tenant_id": "t1"}},
{"client_id": "oathkeeper-introspect", "metadata": map[string]interface{}{"tenant_id": "t1"}},
{"client_id": "c3", "metadata": map[string]interface{}{"tenant_id": "t2"}},
return httpJSONAny(r, http.StatusOK, []map[string]any{
{"client_id": "c1", "metadata": map[string]any{"tenant_id": "t1"}},
{"client_id": "c2", "metadata": map[string]any{"tenant_id": "t1"}},
{"client_id": "oathkeeper-introspect", "metadata": map[string]any{"tenant_id": "t1"}},
{"client_id": "c3", "metadata": map[string]any{"tenant_id": "t2"}},
}), nil
}
return httpJSONAny(r, http.StatusNotFound, nil), nil
@@ -1693,9 +1693,9 @@ func TestGetStats_UserScopesAuditMetricsToVisibleClients(t *testing.T) {
now := time.Now()
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/clients" {
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
{"client_id": "client-owned", "metadata": map[string]interface{}{"tenant_id": "tenant-a"}},
{"client_id": "client-other", "metadata": map[string]interface{}{"tenant_id": "tenant-a"}},
return httpJSONAny(r, http.StatusOK, []map[string]any{
{"client_id": "client-owned", "metadata": map[string]any{"tenant_id": "tenant-a"}},
{"client_id": "client-other", "metadata": map[string]any{"tenant_id": "tenant-a"}},
}), nil
}
return httpJSONAny(r, http.StatusNotFound, nil), nil
@@ -1785,9 +1785,9 @@ func TestGetStats_UserScopesAuditMetricsToVisibleClients(t *testing.T) {
func TestGetRPUsageDaily_UserScopesItemsToVisibleClients(t *testing.T) {
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/clients" {
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
{"client_id": "client-owned", "client_name": "Owned App", "metadata": map[string]interface{}{"tenant_id": "tenant-a"}},
{"client_id": "client-other", "client_name": "Other App", "metadata": map[string]interface{}{"tenant_id": "tenant-a"}},
return httpJSONAny(r, http.StatusOK, []map[string]any{
{"client_id": "client-owned", "client_name": "Owned App", "metadata": map[string]any{"tenant_id": "tenant-a"}},
{"client_id": "client-other", "client_name": "Other App", "metadata": map[string]any{"tenant_id": "tenant-a"}},
}), nil
}
return httpJSONAny(r, http.StatusNotFound, nil), nil
@@ -1997,7 +1997,7 @@ func TestCreateClient_DefaultsSkipConsentToTrue(t *testing.T) {
func TestNormalizeClientAutoLoginMetadata(t *testing.T) {
t.Run("keeps supported flag and URL", func(t *testing.T) {
metadata, err := normalizeClientAutoLoginMetadata(map[string]interface{}{
metadata, err := normalizeClientAutoLoginMetadata(map[string]any{
"auto_login_supported": true,
"auto_login_url": "https://rp.example.com/login?auto=1",
})
@@ -2007,14 +2007,14 @@ func TestNormalizeClientAutoLoginMetadata(t *testing.T) {
})
t.Run("requires URL when supported", func(t *testing.T) {
_, err := normalizeClientAutoLoginMetadata(map[string]interface{}{
_, err := normalizeClientAutoLoginMetadata(map[string]any{
"auto_login_supported": true,
})
assert.Error(t, err)
})
t.Run("removes URL when unsupported", func(t *testing.T) {
metadata, err := normalizeClientAutoLoginMetadata(map[string]interface{}{
metadata, err := normalizeClientAutoLoginMetadata(map[string]any{
"auto_login_supported": false,
"auto_login_url": "https://rp.example.com/login?auto=1",
})
@@ -2293,9 +2293,9 @@ func TestCreateClient_NormalizesIDTokenClaimsMetadata(t *testing.T) {
resp, _ := app.Test(req, -1)
assert.Equal(t, http.StatusCreated, resp.StatusCode)
claims, ok := captured.Metadata[domain.MetadataIDTokenClaims].([]interface{})
claims, ok := captured.Metadata[domain.MetadataIDTokenClaims].([]any)
if assert.True(t, ok) && assert.Len(t, claims, 2) {
first, ok := claims[0].(map[string]interface{})
first, ok := claims[0].(map[string]any)
if assert.True(t, ok) {
assert.Equal(t, "top_level", first["namespace"])
assert.Equal(t, "locale", first["key"])
@@ -2305,7 +2305,7 @@ func TestCreateClient_NormalizesIDTokenClaimsMetadata(t *testing.T) {
assert.False(t, hasID)
}
second, ok := claims[1].(map[string]interface{})
second, ok := claims[1].(map[string]any)
if assert.True(t, ok) {
assert.Equal(t, "rp_claims", second["namespace"])
assert.Equal(t, "tier", second["key"])
@@ -2464,7 +2464,7 @@ func TestUpdateClient_AllowsExplicitSkipConsentFalse(t *testing.T) {
Scope: "openid profile",
TokenEndpointAuthMethod: "none",
SkipConsent: &currentSkipConsent,
Metadata: map[string]interface{}{"status": "active"},
Metadata: map[string]any{"status": "active"},
}), nil
}
if r.Method == http.MethodPut && r.URL.Path == "/clients/client-1" {
@@ -2620,7 +2620,7 @@ func TestUpdateClient_RevokesExistingConsentsWhenTenantPolicyChanges(t *testing.
ResponseTypes: []string{"code"},
Scope: "openid tenant profile email",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"tenant_access_restricted": true,
"allowed_tenants": []string{"tenant-a"},
},
@@ -2704,7 +2704,7 @@ func TestUpdateClient_DoesNotRevokeConsentsWhenTenantPolicyUnchanged(t *testing.
ResponseTypes: []string{"code"},
Scope: "openid tenant profile email",
TokenEndpointAuthMethod: "none",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"tenant_access_restricted": true,
"allowed_tenants": []string{"tenant-a"},
},
@@ -2991,9 +2991,9 @@ func TestListAuditLogs_UserAllowedByRPAuditPermission(t *testing.T) {
}
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/clients" {
return httpJSONAny(r, http.StatusOK, []map[string]interface{}{
{"client_id": "client-allowed", "client_name": "Allowed App", "metadata": map[string]interface{}{"tenant_id": "tenant-a"}},
{"client_id": "client-denied", "client_name": "Denied App", "metadata": map[string]interface{}{"tenant_id": "tenant-b"}},
return httpJSONAny(r, http.StatusOK, []map[string]any{
{"client_id": "client-allowed", "client_name": "Allowed App", "metadata": map[string]any{"tenant_id": "tenant-a"}},
{"client_id": "client-denied", "client_name": "Denied App", "metadata": map[string]any{"tenant_id": "tenant-b"}},
}), nil
}
return httpJSONAny(r, http.StatusNotFound, nil), nil
@@ -3124,7 +3124,7 @@ func TestListClientRelations_RPAdminAllowedByViewRelationshipsPermission(t *test
mockKratos := new(devMockKratosAdmin)
mockKratos.On("GetIdentity", mock.Anything, "user-2").Return(&service.KratosIdentity{
ID: "user-2",
Traits: map[string]interface{}{
Traits: map[string]any{
"name": "김용연",
"email": "kyy@example.com",
"id": "kyy01",
@@ -3195,7 +3195,7 @@ func TestListClientRelations_DedupesDuplicateRelations(t *testing.T) {
mockKratos := new(devMockKratosAdmin)
mockKratos.On("GetIdentity", mock.Anything, "user-1").Return(&service.KratosIdentity{
ID: "user-1",
Traits: map[string]interface{}{
Traits: map[string]any{
"name": "Tester",
"email": "tester@example.com",
},
@@ -3371,7 +3371,7 @@ func TestSearchUsers_RPAdminSearchByNameOrEmailWithinTenantScope(t *testing.T) {
mockKratos.On("ListIdentities", mock.Anything).Return([]service.KratosIdentity{
{
ID: "user-1",
Traits: map[string]interface{}{
Traits: map[string]any{
"name": "Alice Kim",
"email": "alice@example.com",
"id": "alice01",
@@ -3380,7 +3380,7 @@ func TestSearchUsers_RPAdminSearchByNameOrEmailWithinTenantScope(t *testing.T) {
},
{
ID: "user-2",
Traits: map[string]interface{}{
Traits: map[string]any{
"name": "Bob Lee",
"email": "bob@example.com",
"id": "bob01",
@@ -3451,7 +3451,7 @@ func TestSearchUsers_UserAllowedByRPAdminRelation(t *testing.T) {
mockKratos.On("ListIdentities", mock.Anything).Return([]service.KratosIdentity{
{
ID: "target-user",
Traits: map[string]interface{}{
Traits: map[string]any{
"name": "김용연",
"email": "kyy@example.com",
"id": "kyy01",

View File

@@ -4,6 +4,7 @@ import (
"baron-sso-backend/internal/domain"
"context"
"fmt"
"slices"
"strings"
)
@@ -235,10 +236,8 @@ func nextAvailableHanmacLocalPart(base string, usedLocalParts map[string]bool) s
}
func appendUniqueString(values []string, value string) []string {
for _, existing := range values {
if existing == value {
return values
}
if slices.Contains(values, value) {
return values
}
return append(values, value)
}

View File

@@ -13,6 +13,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"sort"
"strings"
"time"
@@ -312,10 +313,7 @@ func (h *TenantHandler) ListTenants(c *fiber.Ctx) error {
}
offset = 0
} else if offset < len(tenants) {
end := offset + limit
if end > len(tenants) {
end = len(tenants)
}
end := min(offset+limit, len(tenants))
tenants = tenants[offset:end]
if total > int64(end) && len(tenants) > 0 {
last := tenants[len(tenants)-1]
@@ -980,12 +978,8 @@ func mergeTenantCSVRecordConfig(current domain.JSONMap, record tenantCSVRecord)
}
merged := make(domain.JSONMap, len(current)+len(recordConfig))
for key, value := range current {
merged[key] = value
}
for key, value := range recordConfig {
merged[key] = value
}
maps.Copy(merged, current)
maps.Copy(merged, recordConfig)
return merged, true, nil
}

View File

@@ -107,6 +107,10 @@ type MockUserRepoForHandler struct {
deletedIDs []string
}
func (m *MockUserRepoForHandler) DB() *gorm.DB {
return nil
}
func (m *MockUserRepoForHandler) Create(ctx context.Context, user *domain.User) error { return nil }
func (m *MockUserRepoForHandler) Update(ctx context.Context, user *domain.User) error { return nil }
func (m *MockUserRepoForHandler) Delete(ctx context.Context, id string) error {
@@ -229,7 +233,7 @@ func TestTenantHandler_CreateTenant(t *testing.T) {
app.Post("/tenants", h.CreateTenant)
input := map[string]interface{}{
input := map[string]any{
"name": "Test Tenant",
"slug": "test-tenant",
"domains": []string{"test.com"},
@@ -244,7 +248,7 @@ func TestTenantHandler_CreateTenant(t *testing.T) {
resp, _ := app.Test(req)
assert.Equal(t, http.StatusCreated, resp.StatusCode)
var got map[string]interface{}
var got map[string]any
json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, "t1", got["id"])
}
@@ -1191,7 +1195,7 @@ func TestTenantHandler_ImportTenantsCSVCreatesTenant(t *testing.T) {
resp, _ := app.Test(req)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var got map[string]interface{}
var got map[string]any
json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, float64(1), got["created"])
assert.Equal(t, float64(0), got["updated"])
@@ -1246,7 +1250,7 @@ func TestTenantHandler_ImportTenantsCSVResolvesParentSlugToID(t *testing.T) {
resp, _ := app.Test(req)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var got map[string]interface{}
var got map[string]any
json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, float64(2), got["created"])
assert.Equal(t, float64(0), got["failed"])
@@ -1292,7 +1296,7 @@ func TestTenantHandler_ImportTenantsCSVDoesNotAssignCreatorAsOrganizationMember(
resp, _ := app.Test(req)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var got map[string]interface{}
var got map[string]any
json.NewDecoder(resp.Body).Decode(&got)
assert.Equal(t, float64(1), got["created"])
assert.Equal(t, float64(0), got["failed"])

View File

@@ -12,6 +12,7 @@ import (
"errors"
"fmt"
"log/slog"
"maps"
"net/http"
"net/mail"
"os"
@@ -203,7 +204,7 @@ func metadataBoolFromMap(metadata map[string]any, keys ...string) (bool, bool) {
return false, false
}
func roleFromTraits(traits map[string]interface{}) string {
func roleFromTraits(traits map[string]any) string {
if role, ok := domain.NormalizeRoleAlias(extractTraitString(traits, "role")); ok {
return role
}
@@ -221,7 +222,7 @@ func normalizeAssignableSystemRole(value string) (string, bool) {
return role, role == domain.RoleSuperAdmin || role == domain.RoleUser
}
func gradeFromTraits(traits map[string]interface{}) string {
func gradeFromTraits(traits map[string]any) string {
value := strings.TrimSpace(extractTraitString(traits, "grade"))
if value == "" {
return ""
@@ -267,7 +268,7 @@ func tenantSlugPointerFromRequest(tenantSlug *string, legacyCompanyCode *string)
return nil, nil
}
func identityTenantAccessKeys(traits map[string]interface{}) []string {
func identityTenantAccessKeys(traits map[string]any) []string {
keys := make([]string, 0, 2)
if tenantID := strings.ToLower(strings.TrimSpace(extractTraitString(traits, "tenant_id"))); tenantID != "" {
keys = append(keys, tenantID)
@@ -525,10 +526,7 @@ func (h *UserHandler) ListUsers(c *fiber.Ctx) error {
if offset > len(filtered) {
offset = len(filtered)
}
end := offset + limit
if end > len(filtered) {
end = len(filtered)
}
end := min(offset+limit, len(filtered))
pageIdentities = filtered[offset:end]
if total > int64(end) && len(pageIdentities) > 0 {
lastTimestamp, lastID := kratosIdentityCursorKey(pageIdentities[len(pageIdentities)-1])
@@ -580,11 +578,32 @@ func (h *UserHandler) GetUser(c *fiber.Ctx) error {
}
identity, err := h.KratosAdmin.GetIdentity(c.Context(), userID)
if err != nil {
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
}
if identity == nil {
return errorJSON(c, fiber.StatusNotFound, "user not found")
if err != nil || identity == nil {
// [FIX] Support fixed UUID lookup fallback
id, searchErr := h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), userID)
if searchErr == nil && id != "" {
identity, err = h.KratosAdmin.GetIdentity(c.Context(), id)
}
if err != nil || identity == nil {
// Second Fallback: By Email from local DB
if h.UserRepo != nil {
local, _ := h.UserRepo.FindByID(c.Context(), userID)
if local != nil && local.Email != "" {
id, _ = h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), local.Email)
if id != "" {
identity, err = h.KratosAdmin.GetIdentity(c.Context(), id)
}
}
}
}
if err != nil || identity == nil {
if identity == nil {
return errorJSON(c, fiber.StatusNotFound, "user not found")
}
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
}
}
// [New] Check access scope
@@ -687,7 +706,7 @@ func (h *UserHandler) CreateUser(c *fiber.Ctx) error {
role = normalizedRole
}
attributes := map[string]interface{}{
attributes := map[string]any{
"department": req.Department,
"grade": strings.TrimSpace(req.Grade),
"position": req.Position,
@@ -777,7 +796,7 @@ func (h *UserHandler) CreateUser(c *fiber.Ctx) error {
if tenantID != "" && h.TenantService != nil {
tenant, err := h.TenantService.GetTenant(c.Context(), tenantID)
if err == nil && tenant != nil {
if schema, ok := tenant.Config["userSchema"].([]interface{}); ok {
if schema, ok := tenant.Config["userSchema"].([]any); ok {
if err := h.validateMetadata(req.Metadata, schema, true); err != nil {
return errorJSON(c, fiber.StatusBadRequest, "metadata validation failed: "+err.Error())
}
@@ -853,6 +872,8 @@ func (h *UserHandler) CreateUser(c *fiber.Ctx) error {
type bulkUserItem struct {
UserID string `json:"userId"`
ID string `json:"id"`
UUID string `json:"uuid"`
Email string `json:"email"`
LoginID string `json:"loginId"`
Name string `json:"name"`
@@ -879,6 +900,7 @@ type bulkUserResult struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
UserID string `json:"userId,omitempty"`
ModifiedFields []string `json:"modifiedFields,omitempty"`
}
func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
@@ -916,7 +938,7 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
ID string
Slug string
Name string
Schema []interface{}
Schema []any
Groups []domain.UserGroup
LoginIDField string
}
@@ -930,7 +952,7 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
Slug: tenant.Slug,
Name: tenant.Name,
}
if s, ok := tenant.Config["userSchema"].([]interface{}); ok {
if s, ok := tenant.Config["userSchema"].([]any); ok {
tItem.Schema = s
}
if lf, ok := tenant.Config["loginIdField"].(string); ok {
@@ -1016,6 +1038,7 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
}
for index, item := range req.Users {
var identityID string
email := strings.TrimSpace(item.Email)
name := strings.TrimSpace(item.Name)
tenantID := strings.TrimSpace(item.TenantID)
@@ -1026,6 +1049,15 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
results = append(results, bulkUserResult{Email: email, Success: false, Message: "email and name are required"})
continue
}
if strings.TrimSpace(item.ID) != "" || strings.TrimSpace(item.UUID) != "" || strings.TrimSpace(item.UserID) != "" {
results = append(results, bulkUserResult{
Email: email,
Success: false,
Status: "blockingError",
Message: "사용자 UUID 가져오기는 지원하지 않습니다. UUID 보존 복구는 백업/복구 기능을 사용하세요.",
})
continue
}
if tenantSlugErr != nil {
results = append(results, bulkUserResult{Email: email, Success: false, Message: tenantSlugErr.Error()})
continue
@@ -1209,7 +1241,7 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
role = "user"
}
attributes := map[string]interface{}{
attributes := map[string]any{
"department": dept,
"grade": strings.TrimSpace(item.Grade),
"position": strings.TrimSpace(item.Position),
@@ -1237,7 +1269,7 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
// Collect all emails
allEmails := []string{userEmail}
if secondaryRaw, exists := item.Metadata["sub_email"]; exists {
if secondaryEmails, ok := secondaryRaw.([]interface{}); ok {
if secondaryEmails, ok := secondaryRaw.([]any); ok {
for _, se := range secondaryEmails {
if seStr, ok := se.(string); ok {
allEmails = append(allEmails, seStr)
@@ -1260,33 +1292,91 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
}
}
identityID, err := h.OryProvider.CreateUser(&domain.BrokerUser{
ID: strings.TrimSpace(item.UserID),
Email: userEmail,
Name: item.Name,
PhoneNumber: userPhone,
Attributes: attributes,
}, password)
if err != nil {
// 만약 이미 존재하는 사용자라면 로컬 DB 및 Keto 관계만 업데이트(Sync)를 시도
if strings.Contains(err.Error(), "409") || strings.Contains(err.Error(), "already exists") || strings.Contains(err.Error(), "exists already") {
identityID, err = h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), userEmail)
if err != nil || identityID == "" {
results = append(results, bulkUserResult{Email: userEmail, OriginalEmail: emailEvaluation.OriginalEmail, SuggestedEmail: emailEvaluation.SuggestedEmail, Status: "blockingError", Warnings: emailEvaluation.Warnings, Success: false, Message: "이미 다른 사용자가 해당 식별자(이메일/사번 등)를 사용 중입니다."})
resultStatus := "created"
if identityID == "" {
var err error
identityID, err = h.OryProvider.CreateUser(&domain.BrokerUser{
Email: userEmail,
Name: item.Name,
PhoneNumber: userPhone,
Attributes: attributes,
}, password)
if err != nil {
// 만약 이미 존재하는 사용자라면 로컬 DB 및 Keto 관계만 업데이트(Sync)를 시도
if strings.Contains(err.Error(), "409") || strings.Contains(err.Error(), "already exists") || strings.Contains(err.Error(), "exists already") {
identityID, err = h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), userEmail)
if err != nil || identityID == "" {
results = append(results, bulkUserResult{Email: userEmail, OriginalEmail: emailEvaluation.OriginalEmail, SuggestedEmail: emailEvaluation.SuggestedEmail, Status: "blockingError", Warnings: emailEvaluation.Warnings, Success: false, Message: "이미 다른 사용자가 해당 식별자(이메일/사번 등)를 사용 중입니다."})
continue
}
resultStatus = "updated"
slog.Info("BulkCreate: User already exists by identifier, reusing identity", "email", userEmail, "identityID", identityID)
} else {
results = append(results, bulkUserResult{Email: userEmail, OriginalEmail: emailEvaluation.OriginalEmail, SuggestedEmail: emailEvaluation.SuggestedEmail, Status: emailEvaluation.Status, Warnings: emailEvaluation.Warnings, Success: false, Message: err.Error()})
continue
}
slog.Info("BulkCreate: User already exists, syncing local DB and Keto", "email", email, "identityID", identityID)
} else {
results = append(results, bulkUserResult{Email: userEmail, OriginalEmail: emailEvaluation.OriginalEmail, SuggestedEmail: emailEvaluation.SuggestedEmail, Status: emailEvaluation.Status, Warnings: emailEvaluation.Warnings, Success: false, Message: err.Error()})
continue
resultStatus = "created"
slog.Info("BulkCreate: New identity created", "email", userEmail, "identityID", identityID)
}
}
// [CRITICAL FIX] Sync to local DB directly using current data
// Don't fetch from Kratos here as it might have propagation lag
var modifiedFields []string
isRestoration := false
if resultStatus == "updated" && identityID != "" {
existing, err := h.KratosAdmin.GetIdentity(c.Context(), identityID)
if err == nil && existing != nil {
// 1. Check for Restoration (Soft-deleted in local DB)
if h.UserRepo != nil {
var existingLocal domain.User
err := h.UserRepo.DB().Unscoped().Where("id = ?", identityID).First(&existingLocal).Error
if err == nil {
// Check if it was soft-deleted
if existingLocal.DeletedAt.Valid {
isRestoration = true
modifiedFields = append(modifiedFields, "Status")
}
}
}
// 2. Compare Traits
if name != "" && !strings.EqualFold(extractTraitString(existing.Traits, "name"), name) {
modifiedFields = append(modifiedFields, "Name")
}
if item.Phone != "" && normalizePhoneNumber(extractTraitString(existing.Traits, "phone_number")) != normalizePhoneNumber(item.Phone) {
modifiedFields = append(modifiedFields, "Phone")
}
if dept != "" && !strings.EqualFold(extractTraitString(existing.Traits, "department"), dept) {
modifiedFields = append(modifiedFields, "Department")
}
if item.Grade != "" && !strings.EqualFold(gradeFromTraits(existing.Traits), strings.TrimSpace(item.Grade)) {
modifiedFields = append(modifiedFields, "Grade")
}
if item.Position != "" && !strings.EqualFold(extractTraitString(existing.Traits, "position"), strings.TrimSpace(item.Position)) {
modifiedFields = append(modifiedFields, "Position")
}
if item.JobTitle != "" && !strings.EqualFold(extractTraitString(existing.Traits, "jobTitle"), strings.TrimSpace(item.JobTitle)) {
modifiedFields = append(modifiedFields, "JobTitle")
}
if tItem.ID != "" && extractTraitString(existing.Traits, "tenant_id") != tItem.ID {
modifiedFields = append(modifiedFields, "Tenant")
}
if role != "" && !strings.EqualFold(roleFromTraits(existing.Traits), role) {
modifiedFields = append(modifiedFields, "Role")
}
// 3. Finalize Status: If no fields actually changed, it's "unchanged"
if len(modifiedFields) == 0 && !isRestoration {
resultStatus = "unchanged"
}
}
}
targetLocalID := identityID
if h.UserRepo != nil {
localUser := &domain.User{
ID: identityID,
ID: targetLocalID,
Email: userEmail,
Name: name,
Phone: normalizePhoneNumber(item.Phone),
@@ -1305,9 +1395,7 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
// Merge metadata
localUser.Metadata = make(domain.JSONMap)
for k, v := range item.Metadata {
localUser.Metadata[k] = v
}
maps.Copy(localUser.Metadata, item.Metadata)
if err := h.UserRepo.Update(c.Context(), localUser); err != nil {
slog.Error("Failed to sync bulk user to local DB", "email", email, "error", err)
@@ -1323,9 +1411,30 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
for i := range loginIDRecords {
loginIDRecords[i].UserID = localUser.ID
}
// [FIX] Pre-check and cleanup colliding identifiers from OTHER users
for _, lid := range loginIDRecords {
var existingID domain.UserLoginID
// Search in DB (including soft-deleted) for any record with the same login_id but DIFFERENT user_id
if err := h.UserRepo.DB().Unscoped().Where("login_id = ? AND user_id != ?", lid.LoginID, localUser.ID).First(&existingID).Error; err == nil {
slog.Info("BulkCreate: Cleaning up colliding identifier from another user", "loginID", lid.LoginID, "oldUserID", existingID.UserID)
_ = h.UserRepo.DB().Unscoped().Where("login_id = ?", lid.LoginID).Delete(&domain.UserLoginID{}).Error
}
}
if err := h.UserRepo.UpdateUserLoginIDs(c.Context(), localUser.ID, loginIDRecords); err != nil {
slog.Error("Failed to update user login IDs in bulk", "userID", localUser.ID, "error", err)
markUserProjectionFailed(c.Context(), h.UserProjectionRepo, err)
results = append(results, bulkUserResult{
Email: userEmail,
OriginalEmail: emailEvaluation.OriginalEmail,
SuggestedEmail: emailEvaluation.SuggestedEmail,
Status: "blockingError",
Warnings: emailEvaluation.Warnings,
Success: false,
Message: "LoginID sync failed: " + err.Error(),
})
continue
}
if h.KetoOutboxRepo != nil {
@@ -1365,10 +1474,11 @@ func (h *UserHandler) BulkCreateUsers(c *fiber.Ctx) error {
Email: userEmail,
OriginalEmail: emailEvaluation.OriginalEmail,
SuggestedEmail: emailEvaluation.SuggestedEmail,
Status: emailEvaluation.Status,
Status: resultStatus,
Warnings: emailEvaluation.Warnings,
Success: true,
UserID: identityID,
UserID: targetLocalID,
ModifiedFields: modifiedFields,
})
}
@@ -1585,7 +1695,7 @@ func (h *UserHandler) BulkUpdateUsers(c *fiber.Ctx) error {
// Pre-fetch tenant cache if tenantSlug is being changed.
type tenantCacheItem struct {
ID string
Schema []interface{}
Schema []any
}
tenantCache := make(map[string]tenantCacheItem)
@@ -1924,7 +2034,7 @@ func (h *UserHandler) UpdateUser(c *fiber.Ctx) error {
if h.TenantService != nil {
tenant, err := h.TenantService.GetTenant(c.Context(), key)
if err == nil && tenant != nil {
if schema, ok := tenant.Config["userSchema"].([]interface{}); ok {
if schema, ok := tenant.Config["userSchema"].([]any); ok {
if subMeta, ok := val.(map[string]any); ok {
if err := h.validateMetadataWithAuth(subMeta, schema, isAdmin, false); err != nil {
return errorJSON(c, fiber.StatusBadRequest, "metadata validation failed for tenant "+tenant.Name+": "+err.Error())
@@ -1945,7 +2055,7 @@ func (h *UserHandler) UpdateUser(c *fiber.Ctx) error {
tenant, _ = h.TenantService.GetTenant(c.Context(), tenantID)
}
if tenant != nil {
if schema, ok := tenant.Config["userSchema"].([]interface{}); ok {
if schema, ok := tenant.Config["userSchema"].([]any); ok {
if err := h.validateMetadataWithAuth(req.Metadata, schema, isAdmin, false); err != nil {
return errorJSON(c, fiber.StatusBadRequest, "metadata validation failed: "+err.Error())
}
@@ -1957,7 +2067,7 @@ func (h *UserHandler) UpdateUser(c *fiber.Ctx) error {
traits := identity.Traits
if traits == nil {
traits = map[string]interface{}{}
traits = map[string]any{}
}
if req.Email != nil {
currentEmail := strings.TrimSpace(extractTraitString(traits, "email"))
@@ -2071,10 +2181,8 @@ func (h *UserHandler) UpdateUser(c *fiber.Ctx) error {
if !coreTraits[k] {
// Ensure we are merging maps (tenant namespaces) correctly, not overwriting with slices
if incomingMap, ok := v.(map[string]any); ok {
if existingMap, ok := traits[k].(map[string]interface{}); ok {
for subK, subV := range incomingMap {
existingMap[subK] = subV
}
if existingMap, ok := traits[k].(map[string]any); ok {
maps.Copy(existingMap, incomingMap)
traits[k] = existingMap
} else {
traits[k] = incomingMap // New namespace
@@ -2102,7 +2210,7 @@ func (h *UserHandler) UpdateUser(c *fiber.Ctx) error {
allEmails := []string{userEmail}
if secondaryRaw, exists := traits["sub_email"]; exists {
if secondaryEmails, ok := secondaryRaw.([]interface{}); ok {
if secondaryEmails, ok := secondaryRaw.([]any); ok {
for _, se := range secondaryEmails {
if seStr, ok := se.(string); ok {
allEmails = append(allEmails, seStr)
@@ -2241,6 +2349,8 @@ func (h *UserHandler) DeleteUser(c *fiber.Ctx) error {
return errorJSON(c, fiber.StatusBadRequest, "user id is required")
}
slog.Info("[UserHandler] Attempting to delete user", "userID", userID)
// [New] Check access scope before deletion
requester, _ := c.Locals("user_profile").(*domain.UserProfileResponse)
@@ -2271,13 +2381,40 @@ func (h *UserHandler) DeleteUser(c *fiber.Ctx) error {
}
}
actualKratosID := userID
if h.KratosAdmin != nil {
id, err := h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), userID)
if err == nil && id != "" {
actualKratosID = id
slog.Info("[UserHandler] Mapped userID to Kratos identity ID", "userID", userID, "actualKratosID", actualKratosID)
} else {
if h.UserRepo != nil {
local, err := h.UserRepo.FindByID(c.Context(), userID)
if err == nil && local != nil && local.Email != "" {
id, err := h.KratosAdmin.FindIdentityIDByIdentifier(c.Context(), local.Email)
if err == nil && id != "" {
actualKratosID = id
slog.Info("[UserHandler] Mapped userID to Kratos identity ID via email", "userID", userID, "email", local.Email, "actualKratosID", actualKratosID)
}
}
}
}
}
if err := h.enqueueDeletedUserRelyingPartyCleanup(c.Context(), requester, userID); err != nil {
slog.Error("[UserHandler] Failed to enqueue RP cleanup", "userID", userID, "error", err)
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
}
if err := h.KratosAdmin.DeleteIdentity(c.Context(), userID); err != nil {
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
if err := h.KratosAdmin.DeleteIdentity(c.Context(), actualKratosID); err != nil {
slog.Error("[UserHandler] Failed to delete Kratos identity", "userID", userID, "actualKratosID", actualKratosID, "error", err)
// If Kratos says 404, it might already be gone, so we can proceed to cleanup local DB
if !strings.Contains(err.Error(), "404") {
return errorJSON(c, fiber.StatusInternalServerError, err.Error())
}
}
slog.Info("[UserHandler] Successfully deleted Kratos identity", "userID", userID, "actualKratosID", actualKratosID)
if h.Worksmobile != nil && identity != nil {
localUser := h.mapToLocalUser(*identity)
if err := h.Worksmobile.EnqueueUserDeleteIfInScope(c.Context(), *localUser); err != nil {
@@ -2302,6 +2439,8 @@ func (h *UserHandler) DeleteUser(c *fiber.Ctx) error {
if err := h.UserRepo.Delete(context.Background(), userID); err != nil {
slog.Error("[UserHandler] Failed to delete local user read-model", "userID", userID, "error", err)
markUserProjectionFailed(context.Background(), h.UserProjectionRepo, err)
} else {
slog.Info("[UserHandler] Successfully deleted local user read-model", "userID", userID)
}
}
@@ -2430,7 +2569,7 @@ func (h *UserHandler) listDeletedUserRelyingPartyRelations(ctx context.Context,
var tuples []service.RelationTuple
var err error
for attempt := 0; attempt < 3; attempt++ {
for attempt := range 3 {
tuples, err = h.KetoService.ListRelations(ctx, "RelyingParty", "", "", subject)
if err != nil {
return nil, err
@@ -2470,6 +2609,16 @@ func (h *UserHandler) mapIdentitySummary(ctx context.Context, identity service.K
traits := identity.Traits
role := roleFromTraits(traits)
// [FIX] Prioritize Local DB ID (the fixed UUID from user)
finalID := identity.ID
email := extractTraitString(traits, "email")
if h.UserRepo != nil && email != "" {
// 1. Try finding by email first as it's a strong identifier
if local, err := h.UserRepo.FindByEmail(ctx, email); err == nil && local != nil {
finalID = local.ID
}
}
tenantID := extractTraitString(traits, "tenant_id")
tenantSlug := ""
var tenantSummary *domain.Tenant
@@ -2483,7 +2632,7 @@ func (h *UserHandler) mapIdentitySummary(ctx context.Context, identity service.K
var customLoginIDs []string
if raw, ok := traits["custom_login_ids"]; ok {
if ids, ok := raw.([]interface{}); ok {
if ids, ok := raw.([]any); ok {
for _, id := range ids {
if s, ok := id.(string); ok {
customLoginIDs = append(customLoginIDs, s)
@@ -2495,7 +2644,7 @@ func (h *UserHandler) mapIdentitySummary(ctx context.Context, identity service.K
}
summary := userSummary{
ID: identity.ID,
ID: finalID,
Email: extractTraitString(traits, "email"),
LoginID: resolvePasswordLoginID(traits),
CustomLoginIDs: customLoginIDs,
@@ -2555,8 +2704,10 @@ func (h *UserHandler) mapToLocalUser(identity service.KratosIdentity) *domain.Us
traits := identity.Traits
role := roleFromTraits(traits)
finalID := identity.ID
user := &domain.User{
ID: identity.ID,
ID: finalID,
Email: extractTraitString(traits, "email"),
Name: extractTraitString(traits, "name"),
Phone: extractTraitString(traits, "phone_number"),
@@ -2680,7 +2831,7 @@ func (h *UserHandler) syncKetoRole(ctx context.Context, userID, newRole, oldRole
}
}
func extractTraitString(traits map[string]interface{}, key string) string {
func extractTraitString(traits map[string]any, key string) string {
if traits == nil {
return ""
}
@@ -2692,12 +2843,12 @@ func extractTraitString(traits map[string]interface{}, key string) string {
return ""
}
func extractTraitStringArray(traits map[string]interface{}, key string) []string {
func extractTraitStringArray(traits map[string]any, key string) []string {
if traits == nil {
return nil
}
if raw, ok := traits[key]; ok {
if slice, ok := raw.([]interface{}); ok {
if slice, ok := raw.([]any); ok {
var result []string
for _, v := range slice {
if s, ok := v.(string); ok {
@@ -2713,10 +2864,10 @@ func extractTraitStringArray(traits map[string]interface{}, key string) []string
return nil
}
func resolvePasswordLoginID(traits map[string]interface{}) string {
func resolvePasswordLoginID(traits map[string]any) string {
// First check custom_login_ids (array)
if raw, ok := traits["custom_login_ids"]; ok {
if ids, ok := raw.([]interface{}); ok && len(ids) > 0 {
if ids, ok := raw.([]any); ok && len(ids) > 0 {
if first, ok := ids[0].(string); ok {
return first
}
@@ -2736,7 +2887,7 @@ func resolvePasswordLoginID(traits map[string]interface{}) string {
// syncCustomLoginIDs collects all fields marked as isLoginId: true from tenant schemas
// and populates traits["custom_login_ids"] and returns domain.UserLoginID records for DB.
func syncCustomLoginIDs(ctx context.Context, tenantService service.TenantService, traits map[string]interface{}, metadata map[string]any, userID string) []domain.UserLoginID {
func syncCustomLoginIDs(ctx context.Context, tenantService service.TenantService, traits map[string]any, metadata map[string]any, userID string) []domain.UserLoginID {
if tenantService == nil {
return nil
}
@@ -2769,13 +2920,13 @@ func syncCustomLoginIDs(ctx context.Context, tenantService service.TenantService
continue
}
schema, ok := tenant.Config["userSchema"].([]interface{})
schema, ok := tenant.Config["userSchema"].([]any)
if !ok {
continue
}
for _, fieldRaw := range schema {
field, ok := fieldRaw.(map[string]interface{})
field, ok := fieldRaw.(map[string]any)
if !ok {
continue
}
@@ -2794,7 +2945,7 @@ func syncCustomLoginIDs(ctx context.Context, tenantService service.TenantService
var val string
if namespaced, ok := metadata[tid].(map[string]any); ok {
val, _ = namespaced[fieldKey].(string)
} else if namespaced, ok := metadata[tid].(map[string]interface{}); ok {
} else if namespaced, ok := metadata[tid].(map[string]any); ok {
val, _ = namespaced[fieldKey].(string)
}
@@ -2804,7 +2955,7 @@ func syncCustomLoginIDs(ctx context.Context, tenantService service.TenantService
if val == "" {
// Check existing trait (namespaced)
if namespaced, ok := traits[tid].(map[string]interface{}); ok {
if namespaced, ok := traits[tid].(map[string]any); ok {
val, _ = namespaced[fieldKey].(string)
} else if namespaced, ok := traits[tid].(map[string]any); ok {
val, _ = namespaced[fieldKey].(string)
@@ -2876,13 +3027,13 @@ func isMetadataMap(value any) bool {
if _, ok := value.(map[string]any); ok {
return true
}
if _, ok := value.(map[string]interface{}); ok {
if _, ok := value.(map[string]any); ok {
return true
}
return false
}
func normalizeCustomLoginIDsTrait(traits map[string]interface{}) {
func normalizeCustomLoginIDsTrait(traits map[string]any) {
raw, exists := traits["custom_login_ids"]
if !exists {
return
@@ -2890,7 +3041,7 @@ func normalizeCustomLoginIDsTrait(traits map[string]interface{}) {
switch values := raw.(type) {
case []string:
return
case []interface{}:
case []any:
normalized := make([]string, 0, len(values))
for _, value := range values {
if text, ok := value.(string); ok && strings.TrimSpace(text) != "" {
@@ -3102,14 +3253,14 @@ func normalizePhoneNumber(phone string) string {
return normalized
}
func (h *UserHandler) validateMetadata(metadata map[string]any, schema []interface{}, checkRequired bool) error {
func (h *UserHandler) validateMetadata(metadata map[string]any, schema []any, checkRequired bool) error {
return h.validateMetadataWithAuth(metadata, schema, true, checkRequired)
}
func (h *UserHandler) validateMetadataWithAuth(metadata map[string]any, schema []interface{}, isAdmin bool, checkRequired bool) error {
schemaMap := make(map[string]map[string]interface{})
func (h *UserHandler) validateMetadataWithAuth(metadata map[string]any, schema []any, isAdmin bool, checkRequired bool) error {
schemaMap := make(map[string]map[string]any)
for _, s := range schema {
if m, ok := s.(map[string]interface{}); ok {
if m, ok := s.(map[string]any); ok {
if key, ok := m["key"].(string); ok {
schemaMap[key] = m
}

View File

@@ -45,7 +45,7 @@ func (m *MockKratosAdmin) GetIdentity(ctx context.Context, id string) (*service.
return args.Get(0).(*service.KratosIdentity), args.Error(1)
}
func (m *MockKratosAdmin) UpdateIdentity(ctx context.Context, id string, traits map[string]interface{}, state string) (*service.KratosIdentity, error) {
func (m *MockKratosAdmin) UpdateIdentity(ctx context.Context, id string, traits map[string]any, state string) (*service.KratosIdentity, error) {
args := m.Called(ctx, id, traits, state)
if args.Get(0) == nil {
return nil, args.Error(1)
@@ -445,8 +445,8 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
ID: "t-123",
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
"userSchema": []any{
map[string]any{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
},
},
}, nil).Once()
@@ -455,28 +455,32 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
ID: "t-123",
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
"userSchema": []any{
map[string]any{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
},
},
}, nil)
mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
// [FIX] Search-first diagnostic calls
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, mock.Anything).Return("", nil).Maybe()
mockOry.On("CreateUser", mock.Anything, mock.Anything).Return("u-1", nil).Twice()
payload := map[string]interface{}{
"users": []map[string]interface{}{
payload := map[string]any{
"users": []map[string]any{
{
"email": "user1@test.com",
"name": "User One",
"tenantSlug": "test-tenant",
"metadata": map[string]interface{}{"emp_id": "E001"},
"metadata": map[string]any{"emp_id": "E001"},
},
{
"email": "user2@test.com",
"name": "User Two",
"tenantSlug": "test-tenant",
"metadata": map[string]interface{}{"emp_id": "E002"},
"metadata": map[string]any{"emp_id": "E002"},
},
},
}
@@ -487,20 +491,20 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
resp, _ := app.Test(req)
assert.Equal(t, 200, resp.StatusCode)
var result map[string]interface{}
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
results := result["results"].([]interface{})
results := result["results"].([]any)
assert.Len(t, results, 2)
assert.True(t, results[0].(map[string]interface{})["success"].(bool))
assert.True(t, results[1].(map[string]interface{})["success"].(bool))
assert.True(t, results[0].(map[string]any)["success"].(bool))
assert.True(t, results[1].(map[string]any)["success"].(bool))
})
t.Run("Fail - Tenant Not Found", func(t *testing.T) {
mockTenant.On("GetTenantBySlug", mock.Anything, "wrong-tenant").Return(nil, errors.New("not found")).Once()
mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
payload := map[string]interface{}{
"users": []map[string]interface{}{
payload := map[string]any{
"users": []map[string]any{
{
"email": "fail@test.com",
"name": "Fail User",
@@ -513,12 +517,12 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
req.Header.Set("Content-Type", "application/json")
resp, _ := app.Test(req)
var result map[string]interface{}
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
results := result["results"].([]interface{})
results := result["results"].([]any)
assert.False(t, results[0].(map[string]interface{})["success"].(bool))
assert.Contains(t, results[0].(map[string]interface{})["message"].(string), "tenant not found")
assert.False(t, results[0].(map[string]any)["success"].(bool))
assert.Contains(t, results[0].(map[string]any)["message"].(string), "tenant not found")
})
t.Run("Fail - Schema Validation (Required)", func(t *testing.T) {
@@ -526,8 +530,8 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
ID: "t-123",
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
"userSchema": []any{
map[string]any{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
},
},
}, nil).Once()
@@ -536,19 +540,19 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
ID: "t-123",
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
"userSchema": []any{
map[string]any{"key": "emp_id", "label": "EmpID", "required": true, "isLoginId": true},
},
},
}, nil)
payload := map[string]interface{}{
"users": []map[string]interface{}{
payload := map[string]any{
"users": []map[string]any{
{
"email": "missing-meta@test.com",
"name": "No Meta",
"tenantSlug": "test-tenant",
"metadata": map[string]interface{}{}, // emp_id missing
"metadata": map[string]any{}, // emp_id missing
},
},
}
@@ -557,12 +561,12 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
req.Header.Set("Content-Type", "application/json")
resp, _ := app.Test(req)
var result map[string]interface{}
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
results := result["results"].([]interface{})
results := result["results"].([]any)
assert.False(t, results[0].(map[string]interface{})["success"].(bool))
assert.Contains(t, results[0].(map[string]interface{})["message"].(string), "field emp_id is required")
assert.False(t, results[0].(map[string]any)["success"].(bool))
assert.Contains(t, results[0].(map[string]any)["message"].(string), "field emp_id is required")
})
t.Run("Fail - Schema Validation (Regex)", func(t *testing.T) {
@@ -570,19 +574,19 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
ID: "t-123",
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_id", "validation": "^E[0-9]{3}$"},
"userSchema": []any{
map[string]any{"key": "emp_id", "validation": "^E[0-9]{3}$"},
},
},
}, nil).Once()
payload := map[string]interface{}{
"users": []map[string]interface{}{
payload := map[string]any{
"users": []map[string]any{
{
"email": "regex-fail@test.com",
"name": "Regex Fail",
"tenantSlug": "test-tenant",
"metadata": map[string]interface{}{"emp_id": "abc"}, // Should start with E and 3 digits
"metadata": map[string]any{"emp_id": "abc"}, // Should start with E and 3 digits
},
},
}
@@ -591,39 +595,29 @@ func TestUserHandler_BulkCreateUsers(t *testing.T) {
req.Header.Set("Content-Type", "application/json")
resp, _ := app.Test(req)
var result map[string]interface{}
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
results := result["results"].([]interface{})
results := result["results"].([]any)
assert.False(t, results[0].(map[string]interface{})["success"].(bool))
assert.Contains(t, results[0].(map[string]interface{})["message"].(string), "match validation pattern")
assert.False(t, results[0].(map[string]any)["success"].(bool))
assert.Contains(t, results[0].(map[string]any)["message"].(string), "match validation pattern")
})
}
func TestUserHandler_BulkCreateUsersPreservesRequestedUserID(t *testing.T) {
func TestUserHandler_BulkCreateUsersRejectsRequestedUserID(t *testing.T) {
app := fiber.New()
mockKratos := new(MockKratosAdmin)
mockOry := new(MockOryProvider)
mockTenant := new(MockTenantServiceForUser)
const requestedUserID = "9f8cc1b1-af8d-45d4-946c-924a529c2556"
h := &UserHandler{
KratosAdmin: mockKratos,
OryProvider: mockOry,
TenantService: mockTenant,
KratosAdmin: mockKratos,
OryProvider: mockOry,
}
app.Post("/users/bulk", h.BulkCreateUsers)
mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil)
mockTenant.On("GetTenant", mock.Anything, "tenant-123").Return(&domain.Tenant{
ID: "tenant-123",
Slug: "restore-tenant",
Config: domain.JSONMap{},
}, nil).Once()
mockOry.On("CreateUser", mock.MatchedBy(func(user *domain.BrokerUser) bool {
return user != nil && user.ID == requestedUserID && user.Email == "restore@test.com"
}), mock.Anything).Return(requestedUserID, nil).Once()
payload := map[string]any{
"users": []map[string]any{
@@ -649,9 +643,10 @@ func TestUserHandler_BulkCreateUsersPreservesRequestedUserID(t *testing.T) {
results := result["results"].([]any)
require.Len(t, results, 1)
row := results[0].(map[string]any)
assert.True(t, row["success"].(bool))
assert.Equal(t, requestedUserID, row["userId"])
assert.False(t, row["success"].(bool))
assert.Contains(t, row["message"].(string), "사용자 UUID 가져오기는 지원하지 않습니다")
mockOry.AssertExpectations(t)
mockKratos.AssertNotCalled(t, "FindIdentityIDByIdentifier", mock.Anything, mock.Anything)
}
func TestUserHandler_BulkCreateUsersRejectsDuplicateAliasEmailsInBatch(t *testing.T) {
@@ -815,20 +810,20 @@ func TestUserHandler_BulkCreateUsers_ResolvesAdditionalAppointment(t *testing.T)
metadata["employee_id"] == "EMP002"
}), mock.Anything).Return("u-appointment", nil).Once()
payload := map[string]interface{}{
"users": []map[string]interface{}{
payload := map[string]any{
"users": []map[string]any{
{
"email": "dual@test.com",
"name": "Dual User",
"tenantSlug": "test-tenant",
"metadata": map[string]interface{}{"employee_id": "EMP001"},
"additionalAppointments": []map[string]interface{}{
"metadata": map[string]any{"employee_id": "EMP001"},
"additionalAppointments": []map[string]any{
{
"tenantSlug": "second-tenant",
"department": "센터",
"grade": "수석",
"jobTitle": "Architecture",
"metadata": map[string]interface{}{"employee_id": "EMP002"},
"metadata": map[string]any{"employee_id": "EMP002"},
},
},
},
@@ -899,8 +894,8 @@ func TestUserHandler_BulkCreateUsers_AppendsEmailDomainTenantAtLowestPriority(t
appointment["sourceDomain"] == "samaneng.com"
}), mock.Anything).Return("u-domain-assigned", nil).Once()
payload := map[string]interface{}{
"users": []map[string]interface{}{
payload := map[string]any{
"users": []map[string]any{
{
"email": "user@samaneng.com",
"name": "Domain User",
@@ -915,10 +910,10 @@ func TestUserHandler_BulkCreateUsers_AppendsEmailDomainTenantAtLowestPriority(t
resp, _ := app.Test(req)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var result map[string]interface{}
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
results := result["results"].([]interface{})
assert.True(t, results[0].(map[string]interface{})["success"].(bool))
results := result["results"].([]any)
assert.True(t, results[0].(map[string]any)["success"].(bool))
mockTenant.AssertExpectations(t)
mockOry.AssertExpectations(t)
}
@@ -950,8 +945,8 @@ func TestUserHandler_BulkCreateUsers_UsesEmailDomainTenantAsPrimaryWhenExplicitT
user.Attributes["additionalAppointments"] == nil
}), mock.Anything).Return("u-domain-primary", nil).Once()
payload := map[string]interface{}{
"users": []map[string]interface{}{
payload := map[string]any{
"users": []map[string]any{
{
"email": "user@samaneng.com",
"name": "Domain Primary User",
@@ -965,10 +960,10 @@ func TestUserHandler_BulkCreateUsers_UsesEmailDomainTenantAsPrimaryWhenExplicitT
resp, _ := app.Test(req)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var result map[string]interface{}
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
results := result["results"].([]interface{})
assert.True(t, results[0].(map[string]interface{})["success"].(bool))
results := result["results"].([]any)
assert.True(t, results[0].(map[string]any)["success"].(bool))
mockTenant.AssertExpectations(t)
mockOry.AssertExpectations(t)
}
@@ -1018,9 +1013,9 @@ func TestUserHandler_ListUsersReturnsNextCursorWhenMoreRowsExist(t *testing.T) {
app.Get("/users", h.ListUsers)
mockKratos.On("ListIdentities", mock.Anything).Return([]service.KratosIdentity{
{ID: "u-3", State: "active", CreatedAt: createdAt, Traits: map[string]interface{}{"email": "c@example.com", "name": "C"}},
{ID: "u-2", State: "active", CreatedAt: createdAt.Add(-time.Minute), Traits: map[string]interface{}{"email": "b@example.com", "name": "B"}},
{ID: "u-1", State: "active", CreatedAt: createdAt.Add(-2 * time.Minute), Traits: map[string]interface{}{"email": "a@example.com", "name": "A"}},
{ID: "u-3", State: "active", CreatedAt: createdAt, Traits: map[string]any{"email": "c@example.com", "name": "C"}},
{ID: "u-2", State: "active", CreatedAt: createdAt.Add(-time.Minute), Traits: map[string]any{"email": "b@example.com", "name": "B"}},
{ID: "u-1", State: "active", CreatedAt: createdAt.Add(-2 * time.Minute), Traits: map[string]any{"email": "a@example.com", "name": "A"}},
}, nil).Once()
req := httptest.NewRequest("GET", "/users?limit=2", nil)
@@ -1080,8 +1075,8 @@ func TestUserHandler_BulkCreateUsers_HanmacEmailPolicy(t *testing.T) {
return user.Email == "cyhan2@hanmaceng.co.kr"
}), mock.Anything).Return("u-hanmac", nil).Once()
payload := map[string]interface{}{
"users": []map[string]interface{}{
payload := map[string]any{
"users": []map[string]any{
{
"email": "@hanmaceng.co.kr",
"name": "한치영",
@@ -1096,14 +1091,14 @@ func TestUserHandler_BulkCreateUsers_HanmacEmailPolicy(t *testing.T) {
resp, _ := app.Test(req)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var result map[string]interface{}
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
results := result["results"].([]interface{})
row := results[0].(map[string]interface{})
results := result["results"].([]any)
row := results[0].(map[string]any)
assert.True(t, row["success"].(bool))
assert.Equal(t, "cyhan2@hanmaceng.co.kr", row["email"])
assert.Equal(t, "@hanmaceng.co.kr", row["originalEmail"])
assert.Contains(t, row["warnings"].([]interface{}), "suggested")
assert.Contains(t, row["warnings"].([]any), "suggested")
})
t.Run("full email duplicate local part is blocking error", func(t *testing.T) {
@@ -1122,8 +1117,8 @@ func TestUserHandler_BulkCreateUsers_HanmacEmailPolicy(t *testing.T) {
mockRepo.On("FindByCompanyCodes", mock.Anything, []string{"hanmac-family", "hanmac"}).Return([]domain.User{}, nil).Once()
mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil).Once()
payload := map[string]interface{}{
"users": []map[string]interface{}{
payload := map[string]any{
"users": []map[string]any{
{
"email": "han@samaneng.com",
"name": "한치영",
@@ -1138,10 +1133,10 @@ func TestUserHandler_BulkCreateUsers_HanmacEmailPolicy(t *testing.T) {
resp, _ := app.Test(req)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var result map[string]interface{}
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
results := result["results"].([]interface{})
row := results[0].(map[string]interface{})
results := result["results"].([]any)
row := results[0].(map[string]any)
assert.False(t, row["success"].(bool))
assert.Equal(t, "blockingError", row["status"])
assert.Contains(t, row["message"].(string), "한맥가족 내에서 이미 사용 중인 이메일 ID입니다.")
@@ -1182,7 +1177,7 @@ func TestUserHandler_CreateUser_HanmacEmailPolicyBlocksDuplicateLocalPart(t *tes
}, nil).Once()
mockRepo.On("FindByCompanyCodes", mock.Anything, []string{"hanmac-family", "hanmac"}).Return([]domain.User{}, nil).Once()
payload := map[string]interface{}{
payload := map[string]any{
"email": "han@samaneng.com",
"name": "한치영",
"tenantSlug": "hanmac",
@@ -1194,7 +1189,7 @@ func TestUserHandler_CreateUser_HanmacEmailPolicyBlocksDuplicateLocalPart(t *tes
resp, _ := app.Test(req)
assert.Equal(t, http.StatusConflict, resp.StatusCode)
var result map[string]interface{}
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
assert.Contains(t, result["error"].(string), "한맥가족 내에서 이미 사용 중인 이메일 ID입니다.")
mockOry.AssertNotCalled(t, "CreateUser")
@@ -1214,12 +1209,12 @@ func TestUserHandler_BulkUpdateUsers(t *testing.T) {
t.Run("Success - Update Role and Status", func(t *testing.T) {
mockKratos.On("GetIdentity", mock.Anything, "u-1").Return(&service.KratosIdentity{
ID: "u-1", Traits: map[string]interface{}{"email": "u1@test.com", "tenant_id": "tenant-1"}, State: "active",
ID: "u-1", Traits: map[string]any{"email": "u1@test.com", "tenant_id": "tenant-1"}, State: "active",
}, nil).Once()
mockKratos.On("UpdateIdentity", mock.Anything, "u-1", mock.Anything, "inactive").Return(&service.KratosIdentity{
ID: "u-1",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "u1@test.com",
"name": "Bulk User",
"tenant_id": "tenant-1",
@@ -1228,7 +1223,7 @@ func TestUserHandler_BulkUpdateUsers(t *testing.T) {
}, nil).Once()
status := "inactive"
payload := map[string]interface{}{
payload := map[string]any{
"userIds": []string{"u-1"},
"status": &status,
}
@@ -1239,10 +1234,10 @@ func TestUserHandler_BulkUpdateUsers(t *testing.T) {
resp, _ := app.Test(req)
assert.Equal(t, 200, resp.StatusCode)
var result map[string]interface{}
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
results := result["results"].([]interface{})
assert.True(t, results[0].(map[string]interface{})["success"].(bool))
results := result["results"].([]any)
assert.True(t, results[0].(map[string]any)["success"].(bool))
assert.Len(t, worksmobile.upserts, 1)
assert.Equal(t, "u-1", worksmobile.upserts[0].ID)
assert.Equal(t, domain.UserStatusPreboarding, worksmobile.upserts[0].Status)
@@ -1250,7 +1245,7 @@ func TestUserHandler_BulkUpdateUsers(t *testing.T) {
t.Run("Fail - Super admin cannot assign tenant or RP admin roles", func(t *testing.T) {
for _, role := range []string{domain.RoleTenantAdmin, domain.RoleRPAdmin} {
payload := map[string]interface{}{
payload := map[string]any{
"userIds": []string{"u-1"},
"role": role,
}
@@ -1272,7 +1267,7 @@ func TestUserHandler_BulkUpdateUsers(t *testing.T) {
})
role := domain.RoleSuperAdmin
payload := map[string]interface{}{
payload := map[string]any{
"userIds": []string{"u-1"},
"role": &role,
}
@@ -1302,7 +1297,7 @@ func TestUserHandler_BulkDeleteUsers(t *testing.T) {
mockKratos.On("DeleteIdentity", mock.Anything, "u-1").Return(nil).Once()
mockKratos.On("DeleteIdentity", mock.Anything, "u-2").Return(nil).Once()
payload := map[string]interface{}{
payload := map[string]any{
"userIds": []string{"u-1", "u-2"},
}
body, _ := json.Marshal(payload)
@@ -1347,6 +1342,10 @@ func TestUserHandler_DeleteUserDeletesLocalReadModel(t *testing.T) {
mockOutbox.On("Create", mock.Anything, mock.MatchedBy(func(entry *domain.KetoOutbox) bool {
return entry.Namespace == "System" && entry.Object == "global" && entry.Relation == "super_admins" && entry.Subject == "User:u-1" && entry.Action == domain.KetoOutboxActionDelete
})).Return(nil).Once()
// [FIX] Diagnostic call for fixed UUID mapping
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, "u-1").Return("", nil).Maybe()
mockKratos.On("DeleteIdentity", mock.Anything, "u-1").Return(nil).Once()
req := httptest.NewRequest(http.MethodDelete, "/users/u-1", nil)
@@ -1385,7 +1384,7 @@ func TestUserHandler_BulkDeleteUsers_CleansUpRelyingPartyRelations(t *testing.T)
})).Return(nil).Once()
mockKratos.On("DeleteIdentity", mock.Anything, "u-1").Return(nil).Once()
payload := map[string]interface{}{
payload := map[string]any{
"userIds": []string{"u-1"},
}
body, _ := json.Marshal(payload)
@@ -1446,6 +1445,10 @@ func TestUserHandler_DeleteUserFallsBackToKetoOutboxWhenLiveRelationsAreEmpty(t
mockOutbox.On("Create", mock.Anything, mock.MatchedBy(func(entry *domain.KetoOutbox) bool {
return entry.Namespace == "System" && entry.Object == "global" && entry.Relation == "super_admins" && entry.Subject == "User:u-1" && entry.Action == domain.KetoOutboxActionDelete
})).Return(nil).Once()
// [FIX] Diagnostic call for fixed UUID mapping
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, "u-1").Return("", nil).Maybe()
mockKratos.On("DeleteIdentity", mock.Anything, "u-1").Return(nil).Once()
req := httptest.NewRequest(http.MethodDelete, "/users/u-1", nil)
@@ -1488,6 +1491,10 @@ func TestUserHandler_DeleteUserRecordsCascadeRelyingPartyCleanupAudit(t *testing
mockOutbox.On("Create", mock.Anything, mock.MatchedBy(func(entry *domain.KetoOutbox) bool {
return entry.Namespace == "System" && entry.Object == "global" && entry.Relation == "super_admins" && entry.Subject == "User:u-1" && entry.Action == domain.KetoOutboxActionDelete
})).Return(nil).Once()
// [FIX] Diagnostic call for fixed UUID mapping
mockKratos.On("FindIdentityIDByIdentifier", mock.Anything, "u-1").Return("", nil).Maybe()
mockKratos.On("DeleteIdentity", mock.Anything, "u-1").Return(nil).Once()
req := httptest.NewRequest(http.MethodDelete, "/users/u-1", nil)
@@ -1538,21 +1545,21 @@ func TestUserHandler_UpdateUser_AdminOnlyField(t *testing.T) {
tenantID := "t-123"
mockKratos.On("GetIdentity", mock.Anything, "u-1").Return(&service.KratosIdentity{
ID: "u-1",
Traits: map[string]interface{}{"email": "user@test.com", "tenant_id": tenantID},
Traits: map[string]any{"email": "user@test.com", "tenant_id": tenantID},
}, nil)
mockTenant.On("GetTenant", mock.Anything, tenantID).Return(&domain.Tenant{
ID: tenantID,
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "salary", "adminOnly": true},
"userSchema": []any{
map[string]any{"key": "salary", "adminOnly": true},
},
},
}, nil)
payload := map[string]interface{}{
"metadata": map[string]interface{}{"salary": 5000},
payload := map[string]any{
"metadata": map[string]any{"salary": 5000},
}
body, _ := json.Marshal(payload)
req := httptest.NewRequest("PUT", "/users/u-1", bytes.NewReader(body))
@@ -1561,7 +1568,7 @@ func TestUserHandler_UpdateUser_AdminOnlyField(t *testing.T) {
resp, _ := app.Test(req)
assert.Equal(t, 400, resp.StatusCode) // validation failed
var result map[string]interface{}
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
assert.Contains(t, result["error"].(string), "field salary is admin only")
})
@@ -1579,11 +1586,11 @@ func TestUserHandler_UpdateUser_RejectsDeprecatedAdminRoles(t *testing.T) {
for _, role := range []string{domain.RoleTenantAdmin, domain.RoleRPAdmin} {
mockKratos.On("GetIdentity", mock.Anything, "u-1").Return(&service.KratosIdentity{
ID: "u-1",
Traits: map[string]interface{}{"email": "user@test.com", "role": domain.RoleUser},
Traits: map[string]any{"email": "user@test.com", "role": domain.RoleUser},
State: "active",
}, nil).Once()
payload := map[string]interface{}{"role": role}
payload := map[string]any{"role": role}
body, _ := json.Marshal(payload)
req := httptest.NewRequest("PUT", "/users/u-1", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
@@ -1734,20 +1741,20 @@ func TestSyncCustomLoginIDs_IgnoresFlatMetadataMaps(t *testing.T) {
ID: tenantID,
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_no", "isLoginId": true},
"userSchema": []any{
map[string]any{"key": "emp_no", "isLoginId": true},
},
},
}, nil).Once()
traits := map[string]interface{}{
traits := map[string]any{
"tenant_id": tenantID,
}
metadata := map[string]any{
tenantID: map[string]interface{}{
tenantID: map[string]any{
"emp_no": "E1001",
},
"worksmobileAliasEmails": map[string]interface{}{
"worksmobileAliasEmails": map[string]any{
"0": "alias@hanmaceng.co.kr",
},
}
@@ -1779,7 +1786,7 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
userID := "u-1"
mockKratos.On("GetIdentity", mock.Anything, userID).Return(&service.KratosIdentity{
ID: userID,
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
"companyCode": "test-tenant",
"tenant_id": tenantID,
@@ -1790,8 +1797,8 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
ID: tenantID,
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_no", "label": "Employee No", "isLoginId": true},
"userSchema": []any{
map[string]any{"key": "emp_no", "label": "Employee No", "isLoginId": true},
},
},
}, nil)
@@ -1799,8 +1806,8 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
ID: tenantID,
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_no", "label": "Employee No", "isLoginId": true},
"userSchema": []any{
map[string]any{"key": "emp_no", "label": "Employee No", "isLoginId": true},
},
},
}, nil)
@@ -1808,20 +1815,20 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
mockTenant.On("ListManageableTenants", mock.Anything, userID).Return([]domain.Tenant{}, nil).Once()
// Expect traits to include 'custom_login_ids' synced from 'emp_no'
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]interface{}) bool {
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]any) bool {
ids, ok := traits["custom_login_ids"].([]string)
return ok && len(ids) > 0 && ids[0] == "E1001"
}), mock.Anything).Return(&service.KratosIdentity{
ID: userID,
Traits: map[string]interface{}{
"custom_login_ids": []interface{}{"E1001"},
Traits: map[string]any{
"custom_login_ids": []any{"E1001"},
"email": "user@test.com",
},
}, nil).Once()
payload := map[string]interface{}{
"metadata": map[string]interface{}{
tenantID: map[string]interface{}{
payload := map[string]any{
"metadata": map[string]any{
tenantID: map[string]any{
"emp_no": "E1001",
},
},
@@ -1852,12 +1859,12 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
userID := "u-2"
mockKratos.On("GetIdentity", mock.Anything, userID).Return(&service.KratosIdentity{
ID: userID,
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user2@test.com",
"companyCode": "test-tenant",
"tenant_id": tenantID,
"id": "old-id",
tenantID: map[string]interface{}{
tenantID: map[string]any{
"emp_no": "E2002",
},
},
@@ -1867,8 +1874,8 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
ID: tenantID,
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_no", "isLoginId": true},
"userSchema": []any{
map[string]any{"key": "emp_no", "isLoginId": true},
},
},
}, nil)
@@ -1876,8 +1883,8 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
ID: tenantID,
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_no", "isLoginId": true},
"userSchema": []any{
map[string]any{"key": "emp_no", "isLoginId": true},
},
},
}, nil)
@@ -1885,17 +1892,17 @@ func TestUserHandler_UpdateUser_LoginIDSync(t *testing.T) {
mockTenant.On("ListManageableTenants", mock.Anything, userID).Return([]domain.Tenant{}, nil).Once()
// Even if metadata is empty, it should sync from existing traits
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]interface{}) bool {
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]any) bool {
ids, ok := traits["custom_login_ids"].([]string)
return ok && len(ids) > 0 && ids[0] == "E2002"
}), mock.Anything).Return(&service.KratosIdentity{
ID: userID,
Traits: map[string]interface{}{
"custom_login_ids": []interface{}{"E2002"},
Traits: map[string]any{
"custom_login_ids": []any{"E2002"},
},
}, nil).Once()
payload := map[string]interface{}{
payload := map[string]any{
"name": "New Name",
}
body, _ := json.Marshal(payload)
@@ -1927,8 +1934,8 @@ func TestUserHandler_UpdateUser_PasswordUsesProvider(t *testing.T) {
userID := "u-1"
mockKratos.On("GetIdentity", mock.Anything, userID).Return(&service.KratosIdentity{
ID: userID,
Traits: map[string]interface{}{
"custom_login_ids": []interface{}{"dyddus1210"},
Traits: map[string]any{
"custom_login_ids": []any{"dyddus1210"},
"email": "dyddus1210@gmail.com",
"companyCode": "test-tenant",
"tenant_id": "t-1",
@@ -1940,8 +1947,8 @@ func TestUserHandler_UpdateUser_PasswordUsesProvider(t *testing.T) {
ID: "t-1",
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_id", "isLoginId": true},
"userSchema": []any{
map[string]any{"key": "emp_id", "isLoginId": true},
},
},
}, nil)
@@ -1949,27 +1956,27 @@ func TestUserHandler_UpdateUser_PasswordUsesProvider(t *testing.T) {
ID: "t-1",
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_id", "isLoginId": true},
"userSchema": []any{
map[string]any{"key": "emp_id", "isLoginId": true},
},
},
}, nil)
mockTenant.On("ListManageableTenants", mock.Anything, userID).Return([]domain.Tenant{}, nil).Once()
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]interface{}) bool {
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]any) bool {
ids, ok := traits["custom_login_ids"].([]string)
return ok && len(ids) > 0 && ids[0] == "dyddus1210"
}), "").Return(&service.KratosIdentity{
ID: userID,
Traits: map[string]interface{}{
"custom_login_ids": []interface{}{"dyddus1210"},
Traits: map[string]any{
"custom_login_ids": []any{"dyddus1210"},
"email": "dyddus1210@gmail.com",
},
}, nil).Once()
mockOry.On("UpdateUserPassword", "dyddus1210", "asdfzxcv1234!", (*http.Request)(nil)).Return(nil).Once()
payload := map[string]interface{}{
payload := map[string]any{
"password": "asdfzxcv1234!",
}
body, _ := json.Marshal(payload)
@@ -2001,7 +2008,7 @@ func TestUserHandler_UpdateUser_PasswordFallsBackToEmail(t *testing.T) {
userID := "u-2"
mockKratos.On("GetIdentity", mock.Anything, userID).Return(&service.KratosIdentity{
ID: userID,
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "dyddus1210@gmail.com",
"companyCode": "test-tenant",
},
@@ -2013,18 +2020,18 @@ func TestUserHandler_UpdateUser_PasswordFallsBackToEmail(t *testing.T) {
}, nil)
mockTenant.On("ListManageableTenants", mock.Anything, userID).Return([]domain.Tenant{}, nil).Once()
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]interface{}) bool {
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]any) bool {
return traits["email"] == "dyddus1210@gmail.com"
}), "").Return(&service.KratosIdentity{
ID: userID,
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "dyddus1210@gmail.com",
},
}, nil).Once()
mockOry.On("UpdateUserPassword", "dyddus1210@gmail.com", "asdfzxcv1234!", (*http.Request)(nil)).Return(nil).Once()
payload := map[string]interface{}{
payload := map[string]any{
"password": "asdfzxcv1234!",
}
body, _ := json.Marshal(payload)
@@ -2054,8 +2061,8 @@ func TestUserHandler_CreateUser_LoginIDSync(t *testing.T) {
ID: tenantID,
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_no", "label": "Employee No", "isLoginId": true},
"userSchema": []any{
map[string]any{"key": "emp_no", "label": "Employee No", "isLoginId": true},
},
},
}, nil)
@@ -2063,8 +2070,8 @@ func TestUserHandler_CreateUser_LoginIDSync(t *testing.T) {
ID: tenantID,
Slug: "test-tenant",
Config: domain.JSONMap{
"userSchema": []interface{}{
map[string]interface{}{"key": "emp_no", "label": "Employee No", "isLoginId": true},
"userSchema": []any{
map[string]any{"key": "emp_no", "label": "Employee No", "isLoginId": true},
},
},
}, nil)
@@ -2080,8 +2087,8 @@ func TestUserHandler_CreateUser_LoginIDSync(t *testing.T) {
// Mock GetIdentity after creation
mockKratos.On("GetIdentity", mock.Anything, "u-1").Return(&service.KratosIdentity{
ID: "u-1",
Traits: map[string]interface{}{
"custom_login_ids": []interface{}{"E1001"},
Traits: map[string]any{
"custom_login_ids": []any{"E1001"},
"email": "new@test.com",
"companyCode": "test-tenant",
},
@@ -2090,12 +2097,12 @@ func TestUserHandler_CreateUser_LoginIDSync(t *testing.T) {
// Mock ListManageableTenants for mapIdentitySummary
mockTenant.On("ListManageableTenants", mock.Anything, "u-1").Return([]domain.Tenant{}, nil).Once()
payload := map[string]interface{}{
payload := map[string]any{
"email": "new@test.com",
"name": "New User",
"tenantSlug": "test-tenant",
"metadata": map[string]interface{}{
tenantID: map[string]interface{}{
"metadata": map[string]any{
tenantID: map[string]any{
"emp_no": "E1001",
},
},
@@ -2146,25 +2153,25 @@ func TestUserHandler_CreateUser_UsesAdditionalAppointmentAsPrimaryTenant(t *test
}), mock.Anything).Return("u-appointment", nil).Once()
mockKratos.On("GetIdentity", mock.Anything, "u-appointment").Return(&service.KratosIdentity{
ID: "u-appointment",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "new@samaneng.com",
"name": "Appointment User",
"companyCode": "saman",
"tenant_id": tenantID,
"additionalAppointments": []interface{}{
map[string]interface{}{"tenantId": tenantID, "tenantSlug": "saman"},
"additionalAppointments": []any{
map[string]any{"tenantId": tenantID, "tenantSlug": "saman"},
},
},
State: "active",
}, nil).Once()
payload := map[string]interface{}{
payload := map[string]any{
"email": "new@samaneng.com",
"name": "Appointment User",
"additionalAppointments": []map[string]interface{}{
"additionalAppointments": []map[string]any{
{"tenantId": tenantID, "tenantSlug": "saman", "tenantName": "삼안"},
},
"metadata": map[string]interface{}{
"metadata": map[string]any{
"userType": "hanmac",
},
}
@@ -2236,7 +2243,7 @@ func TestUserHandler_CreateUser_AutoCreatesPersonalTenantWhenAssignmentMissing(t
}), mock.Anything).Return("u-personal", nil).Once()
mockKratos.On("GetIdentity", mock.Anything, "u-personal").Return(&service.KratosIdentity{
ID: "u-personal",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "personal-user@example.com",
"name": "Personal User",
"companyCode": "personal-01970f0d96667548963d2890351f03dd",
@@ -2244,7 +2251,7 @@ func TestUserHandler_CreateUser_AutoCreatesPersonalTenantWhenAssignmentMissing(t
},
State: "active",
}, nil).Once()
payload := map[string]interface{}{
payload := map[string]any{
"email": "personal-user@example.com",
"name": "Personal User",
}
@@ -2289,7 +2296,7 @@ func TestUserHandler_CreateUserAcceptsTenantSlugAndRejectsCompanyCode(t *testing
mockKratos.On("GetIdentity", mock.Anything, "user-id").Return(&service.KratosIdentity{
ID: "user-id",
State: "active",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
"name": "Test User",
"tenant_id": "tenant-id",
@@ -2326,7 +2333,7 @@ func TestUserHandler_UpdateUserAcceptsTenantSlugAndRejectsCompanyCode(t *testing
identity := &service.KratosIdentity{
ID: "user-id",
State: "active",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
"name": "Test User",
"tenant_id": "old-tenant-id",
@@ -2343,13 +2350,13 @@ func TestUserHandler_UpdateUserAcceptsTenantSlugAndRejectsCompanyCode(t *testing
Slug: "new-tenant",
Config: domain.JSONMap{},
}, nil).Once()
mockKratos.On("UpdateIdentity", mock.Anything, "user-id", mock.MatchedBy(func(traits map[string]interface{}) bool {
mockKratos.On("UpdateIdentity", mock.Anything, "user-id", mock.MatchedBy(func(traits map[string]any) bool {
_, hasCompanyCode := traits["companyCode"]
return !hasCompanyCode && traits["tenant_id"] == "new-tenant-id"
}), "").Return(&service.KratosIdentity{
ID: "user-id",
State: "active",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
"name": "Test User",
"tenant_id": "new-tenant-id",
@@ -2388,7 +2395,7 @@ func TestUserHandler_BulkUpdateUsersAcceptsTenantSlugAndRejectsCompanyCode(t *te
mockKratos.On("GetIdentity", mock.Anything, "user-id").Return(&service.KratosIdentity{
ID: "user-id",
State: "active",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
"name": "Test User",
"tenant_id": "old-tenant-id",
@@ -2399,13 +2406,13 @@ func TestUserHandler_BulkUpdateUsersAcceptsTenantSlugAndRejectsCompanyCode(t *te
ID: "new-tenant-id",
Slug: "new-tenant",
}, nil).Once()
mockKratos.On("UpdateIdentity", mock.Anything, "user-id", mock.MatchedBy(func(traits map[string]interface{}) bool {
mockKratos.On("UpdateIdentity", mock.Anything, "user-id", mock.MatchedBy(func(traits map[string]any) bool {
_, hasCompanyCode := traits["companyCode"]
return !hasCompanyCode && traits["tenant_id"] == "new-tenant-id"
}), "active").Return(&service.KratosIdentity{
ID: "user-id",
State: "active",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
"name": "Test User",
"tenant_id": "new-tenant-id",
@@ -2434,7 +2441,7 @@ func TestUserHandler_MapToLocalUserKeepsRoleAndGradeSeparate(t *testing.T) {
identity := service.KratosIdentity{
ID: "user-grade-id",
State: "active",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "grade@example.com",
"name": "Grade User",
"role": domain.RoleUser,

View File

@@ -0,0 +1,68 @@
package handler
import (
"baron-sso-backend/internal/domain"
"bytes"
"encoding/json"
"net/http/httptest"
"testing"
"github.com/gofiber/fiber/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestUserHandler_BulkCreateUsers_UUIDImportPolicy(t *testing.T) {
tests := []struct {
name string
field string
}{
{name: "id 필드 차단", field: "id"},
{name: "uuid 필드 차단", field: "uuid"},
{name: "userId 필드 차단", field: "userId"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
app := fiber.New()
mockKratos := new(MockKratosAdmin)
mockOry := new(MockOryProvider)
h := &UserHandler{
KratosAdmin: mockKratos,
OryProvider: mockOry,
}
app.Post("/users/bulk", h.BulkCreateUsers)
mockOry.On("GetPasswordPolicy").Return(&domain.PasswordPolicy{MinLength: 8}, nil).Once()
payload := map[string]any{
"users": []map[string]any{
{
"email": "uuid-import@test.com",
"name": "UUID Import User",
tt.field: "550e8400-e29b-41d4-a716-446655440000",
"metadata": map[string]any{},
},
},
}
body, _ := json.Marshal(payload)
req := httptest.NewRequest("POST", "/users/bulk", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
resp, _ := app.Test(req)
assert.Equal(t, 200, resp.StatusCode)
var result struct {
Results []bulkUserResult `json:"results"`
}
assert.NoError(t, json.NewDecoder(resp.Body).Decode(&result))
assert.Len(t, result.Results, 1)
assert.False(t, result.Results[0].Success)
assert.Contains(t, result.Results[0].Message, "사용자 UUID 가져오기는 지원하지 않습니다")
mockOry.AssertExpectations(t)
mockKratos.AssertNotCalled(t, "FindIdentityIDByIdentifier", mock.Anything, mock.Anything)
})
}
}

View File

@@ -9,6 +9,7 @@ import (
"encoding/json"
"fmt"
"io"
"maps"
"net/http"
"net/http/httptest"
"testing"
@@ -196,14 +197,10 @@ func TestGetClient_ClientSecretFallbackPaths(t *testing.T) {
})
secretRepo := &mockSecretRepo{secrets: map[string]string{}}
for k, v := range tt.initialSecrets {
secretRepo.secrets[k] = v
}
maps.Copy(secretRepo.secrets, tt.initialSecrets)
redisRepo := &mockRedisRepo{data: map[string]string{}}
for k, v := range tt.initialRedis {
redisRepo.data[k] = v
}
maps.Copy(redisRepo.data, tt.initialRedis)
h := &handler.DevHandler{
Hydra: &service.HydraAdminService{

View File

@@ -104,11 +104,11 @@ func SanitizeClientLogMessage(message string) string {
return sanitized
}
func SanitizeClientLogData(data map[string]interface{}) map[string]interface{} {
func SanitizeClientLogData(data map[string]any) map[string]any {
if len(data) == 0 {
return data
}
out := make(map[string]interface{}, len(data))
out := make(map[string]any, len(data))
for k, v := range data {
if isSensitiveClientLogKey(k) {
out[k] = "*****"
@@ -119,12 +119,12 @@ func SanitizeClientLogData(data map[string]interface{}) map[string]interface{} {
return out
}
func sanitizeClientLogValue(v interface{}) interface{} {
func sanitizeClientLogValue(v any) any {
switch val := v.(type) {
case map[string]interface{}:
case map[string]any:
return SanitizeClientLogData(val)
case []interface{}:
next := make([]interface{}, len(val))
case []any:
next := make([]any, len(val))
for i := range val {
next[i] = sanitizeClientLogValue(val[i])
}

View File

@@ -57,15 +57,15 @@ func TestShouldFilterNoisyClientInfo(t *testing.T) {
}
func TestSanitizeClientLogData(t *testing.T) {
input := map[string]interface{}{
input := map[string]any{
"token": "raw-token",
"safe": "ok",
"nested": map[string]interface{}{
"nested": map[string]any{
"new_password": "secret-1",
"path": "/ko/profile",
},
"arr": []interface{}{
map[string]interface{}{"authorization": "Bearer abc"},
"arr": []any{
map[string]any{"authorization": "Bearer abc"},
"token=abc123",
},
}
@@ -75,12 +75,12 @@ func TestSanitizeClientLogData(t *testing.T) {
assert.Equal(t, "*****", result["token"])
assert.Equal(t, "ok", result["safe"])
nested := result["nested"].(map[string]interface{})
nested := result["nested"].(map[string]any)
assert.Equal(t, "*****", nested["new_password"])
assert.Equal(t, "/ko/profile", nested["path"])
arr := result["arr"].([]interface{})
first := arr[0].(map[string]interface{})
arr := result["arr"].([]any)
first := arr[0].(map[string]any)
assert.Equal(t, "*****", first["authorization"])
assert.Equal(t, "token=*****", arr[1])
}

View File

@@ -23,7 +23,6 @@ func TestResolveBackendLogLevel_DefaultsByAppEnv(t *testing.T) {
}
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()

View File

@@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"log/slog"
"maps"
"reflect"
"sync"
"time"
@@ -28,7 +29,7 @@ func isNil(i any) bool {
return true
}
v := reflect.ValueOf(i)
return v.Kind() == reflect.Ptr && v.IsNil()
return v.Kind() == reflect.Pointer && v.IsNil()
}
// AuditMiddleware provides comprehensive audit logging for write requests by default.
@@ -153,10 +154,8 @@ func AuditMiddleware(config AuditConfig) fiber.Handler {
for key, value := range v {
details[key] = value
}
case map[string]interface{}:
for key, value := range v {
details[key] = value
}
case map[string]any:
maps.Copy(details, v)
}
}
if skipTimeline, ok := c.Locals("auth_timeline_skip").(bool); ok && skipTimeline {

View File

@@ -44,7 +44,7 @@ func (r *clientConsentRepo) Find(ctx context.Context, clientID, subject string)
func (r *clientConsentRepo) Upsert(ctx context.Context, consent *domain.ClientConsent) error {
return r.db.WithContext(ctx).Unscoped().
Where("client_id = ? AND subject = ?", consent.ClientID, consent.Subject).
Assign(map[string]interface{}{
Assign(map[string]any{
"granted_scopes": consent.GrantedScopes,
"updated_at": gorm.Expr("NOW()"),
"deleted_at": nil,

View File

@@ -70,7 +70,7 @@ func (r *ketoOutboxRepository) ListCurrentBySubject(ctx context.Context, namespa
}
func (r *ketoOutboxRepository) UpdateStatus(ctx context.Context, id string, status string, retryCount int, lastError string) error {
return r.db.WithContext(ctx).Model(&domain.KetoOutbox{}).Where("id = ?", id).Updates(map[string]interface{}{
return r.db.WithContext(ctx).Model(&domain.KetoOutbox{}).Where("id = ?", id).Updates(map[string]any{
"status": status,
"retry_count": retryCount,
"last_error": lastError,
@@ -80,7 +80,7 @@ func (r *ketoOutboxRepository) UpdateStatus(ctx context.Context, id string, stat
func (r *ketoOutboxRepository) MarkProcessed(ctx context.Context, id string) error {
now := time.Now()
return r.db.WithContext(ctx).Model(&domain.KetoOutbox{}).Where("id = ?", id).Updates(map[string]interface{}{
return r.db.WithContext(ctx).Model(&domain.KetoOutbox{}).Where("id = ?", id).Updates(map[string]any{
"status": domain.KetoOutboxStatusProcessed,
"processed_at": &now,
"updated_at": now,

View File

@@ -76,7 +76,7 @@ func (r *userProjectionRepository) CountTenantMembers(ctx context.Context, tenan
}
valuePlaceholders := make([]string, 0, len(tenants))
args := make([]interface{}, 0, len(tenants)*2)
args := make([]any, 0, len(tenants)*2)
for _, tenant := range tenants {
valuePlaceholders = append(valuePlaceholders, "(?, ?)")
args = append(args, strings.TrimSpace(tenant.ID), strings.TrimSpace(tenant.Slug))
@@ -124,6 +124,14 @@ func (r *userProjectionRepository) ReplaceAllFromKratos(ctx context.Context, use
}
if len(users) > 0 {
// [FIX] Handle email conflicts before bulk upsert
for _, u := range users {
if u.Email != "" {
// Hard-delete any record with same email but different ID to clear unique constraint
_ = tx.Unscoped().Where("email = ? AND id != ?", u.Email, u.ID).Delete(&domain.User{}).Error
}
}
if err := tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "id"}},
UpdateAll: true,

View File

@@ -24,6 +24,7 @@ type UserRepository interface {
FindByTenantIDs(ctx context.Context, tenantIDs []string) ([]domain.User, error)
FindByCompanyCodes(ctx context.Context, codes []string) ([]domain.User, error)
Delete(ctx context.Context, id string) error
DB() *gorm.DB
// Multiple identifiers support
UpdateUserLoginIDs(ctx context.Context, userID string, loginIDs []domain.UserLoginID) error
@@ -40,18 +41,27 @@ func NewUserRepository(db *gorm.DB) UserRepository {
return &userRepository{db: db}
}
func (r *userRepository) DB() *gorm.DB {
return r.db
}
func (r *userRepository) Create(ctx context.Context, user *domain.User) error {
return r.db.WithContext(ctx).Create(user).Error
}
func (r *userRepository) Update(ctx context.Context, user *domain.User) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 1. Check for email collision (including soft-deleted)
var existing domain.User
if err := tx.Unscoped().Where("email = ?", user.Email).First(&existing).Error; err == nil {
// If email exists but ID is different, we MUST clear the old one to avoid unique constraint violation
if existing.ID != user.ID {
// [Restored] Check if the existing user is archived
if strings.EqualFold(strings.TrimSpace(existing.Status), domain.UserStatusArchived) {
return fmt.Errorf("email is reserved by archived user: %s", user.Email)
}
// HARD DELETE the old record and its associated login IDs to free up the email and identifiers
if err := tx.Unscoped().Where("user_id = ?", existing.ID).Delete(&domain.UserLoginID{}).Error; err != nil {
return err
}
@@ -61,9 +71,25 @@ func (r *userRepository) Update(ctx context.Context, user *domain.User) error {
}
}
return tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "id"}},
UpdateAll: true,
// 2. Perform Upsert on the new/target ID
return tx.Unscoped().Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "id"}},
DoUpdates: clause.Assignments(map[string]any{
"email": user.Email,
"name": user.Name,
"phone": user.Phone,
"role": user.Role,
"status": user.Status,
"department": user.Department,
"grade": user.Grade,
"position": user.Position,
"job_title": user.JobTitle,
"metadata": user.Metadata,
"tenant_id": user.TenantID,
"affiliation_type": user.AffiliationType,
"updated_at": user.UpdatedAt,
"deleted_at": nil, // Ensure it's active
}),
}).Create(user).Error
})
}
@@ -222,8 +248,9 @@ func (r *userRepository) Delete(ctx context.Context, id string) error {
func (r *userRepository) UpdateUserLoginIDs(ctx context.Context, userID string, loginIDs []domain.UserLoginID) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// Delete existing login IDs for this user
if err := tx.Where("user_id = ?", userID).Delete(&domain.UserLoginID{}).Error; err != nil {
// [FIX] Use Unscoped to permanently delete existing login IDs for this user
// This prevents unique constraint violations with soft-deleted records
if err := tx.Unscoped().Where("user_id = ?", userID).Delete(&domain.UserLoginID{}).Error; err != nil {
return err
}

View File

@@ -3,16 +3,16 @@ package response
import "github.com/gofiber/fiber/v2"
type ErrorResponse struct {
Error string `json:"error"`
Code string `json:"code,omitempty"`
Details interface{} `json:"details,omitempty"`
Error string `json:"error"`
Code string `json:"code,omitempty"`
Details any `json:"details,omitempty"`
}
func Error(c *fiber.Ctx, status int, code, message string) error {
return ErrorWithDetails(c, status, code, message, nil)
}
func ErrorWithDetails(c *fiber.Ctx, status int, code, message string, details interface{}) error {
func ErrorWithDetails(c *fiber.Ctx, status int, code, message string, details any) error {
resp := ErrorResponse{
Error: message,
Code: code,

View File

@@ -36,13 +36,13 @@ func TestBackchannelLogoutService_BuildLogoutToken(t *testing.T) {
require.NoError(t, err)
var claims struct {
Issuer string `json:"iss"`
Subject string `json:"sub"`
Aud interface{} `json:"aud"`
Iat int64 `json:"iat"`
Jti string `json:"jti"`
Sid string `json:"sid"`
Events map[string]interface{} `json:"events"`
Issuer string `json:"iss"`
Subject string `json:"sub"`
Aud any `json:"aud"`
Iat int64 `json:"iat"`
Jti string `json:"jti"`
Sid string `json:"sid"`
Events map[string]any `json:"events"`
}
require.NoError(t, parsed.Claims(jwks.Keys[0].Key, &claims))
@@ -51,7 +51,7 @@ func TestBackchannelLogoutService_BuildLogoutToken(t *testing.T) {
switch aud := claims.Aud.(type) {
case string:
assert.Equal(t, "client-1", aud)
case []interface{}:
case []any:
assert.Len(t, aud, 1)
assert.Equal(t, "client-1", aud[0])
default:

View File

@@ -65,21 +65,21 @@ func (s *DeveloperService) ListRequests(ctx context.Context, userID, status stri
}
func (s *DeveloperService) ApproveRequest(ctx context.Context, id uint, adminNotes string) error {
return s.db.WithContext(ctx).Model(&domain.DeveloperRequest{}).Where("id = ?", id).Updates(map[string]interface{}{
return s.db.WithContext(ctx).Model(&domain.DeveloperRequest{}).Where("id = ?", id).Updates(map[string]any{
"status": domain.DeveloperRequestStatusApproved,
"admin_notes": adminNotes,
}).Error
}
func (s *DeveloperService) RejectRequest(ctx context.Context, id uint, adminNotes string) error {
return s.db.WithContext(ctx).Model(&domain.DeveloperRequest{}).Where("id = ?", id).Updates(map[string]interface{}{
return s.db.WithContext(ctx).Model(&domain.DeveloperRequest{}).Where("id = ?", id).Updates(map[string]any{
"status": domain.DeveloperRequestStatusRejected,
"admin_notes": adminNotes,
}).Error
}
func (s *DeveloperService) CancelApprovedRequest(ctx context.Context, id uint, adminNotes string) error {
return s.db.WithContext(ctx).Model(&domain.DeveloperRequest{}).Where("id = ?", id).Updates(map[string]interface{}{
return s.db.WithContext(ctx).Model(&domain.DeveloperRequest{}).Where("id = ?", id).Updates(map[string]any{
"status": domain.DeveloperRequestStatusCancelled,
"admin_notes": adminNotes,
}).Error

View File

@@ -309,7 +309,7 @@ func (s *HeadlessJWKSCacheService) refreshClient(ctx context.Context, client dom
updated := *previous
updated.JWKSURI = jwksURI
updated.LastCheckedAt = &now
updated.ExpiresAt = ptrTime(now.Add(s.TTL))
updated.ExpiresAt = new(now.Add(s.TTL))
updated.NextRetryAt = nil
updated.LastRefreshStatus = "success"
updated.LastError = ""
@@ -339,7 +339,7 @@ func (s *HeadlessJWKSCacheService) refreshClient(ctx context.Context, client dom
ClientID: client.ClientID,
JWKSURI: jwksURI,
CachedAt: &now,
ExpiresAt: ptrTime(now.Add(s.TTL)),
ExpiresAt: new(now.Add(s.TTL)),
LastCheckedAt: &now,
NextRetryAt: nil,
LastSuccessfulVerificationAt: previousLastVerification(previous),
@@ -379,7 +379,7 @@ func (s *HeadlessJWKSCacheService) persistRefreshFailure(client domain.HydraClie
state.ConsecutiveFailures = previous.ConsecutiveFailures + 1
}
if s.shouldBackoff(state.ConsecutiveFailures) {
state.NextRetryAt = ptrTime(now.Add(s.failureBackoffDuration()))
state.NextRetryAt = new(now.Add(s.failureBackoffDuration()))
}
_ = s.SaveState(client.ClientID, state)
return &state
@@ -480,8 +480,9 @@ func previousLastVerification(previous *domain.HeadlessJWKSCacheState) *time.Tim
return previous.LastSuccessfulVerificationAt
}
//go:fix inline
func ptrTime(value time.Time) *time.Time {
return &value
return new(value)
}
func (w *HeadlessJWKSCacheWorker) Start(ctx context.Context) {

View File

@@ -70,7 +70,7 @@ func TestHeadlessJWKSCacheService_EnsureFreshKeySet_UsesCachedJWKSWhenFresh(t *t
CachedKids: []string{"cached-key"},
CachedAt: &now,
LastCheckedAt: &now,
ExpiresAt: ptrTestTime(now.Add(30 * time.Minute)),
ExpiresAt: new(now.Add(30 * time.Minute)),
LastRefreshStatus: "success",
ConsecutiveFailures: 0,
})
@@ -114,7 +114,7 @@ func TestHeadlessJWKSCacheService_EnsureFreshKeySet_RefreshesWhenKidMissing(t *t
CachedKids: []string{"stale-key"},
CachedAt: &now,
LastCheckedAt: &now,
ExpiresAt: ptrTestTime(now.Add(30 * time.Minute)),
ExpiresAt: new(now.Add(30 * time.Minute)),
LastRefreshStatus: "success",
})
require.NoError(t, err)
@@ -181,7 +181,7 @@ func TestHeadlessJWKSCacheService_ShouldPrefetch_SkipsUntilNextRetryAt(t *testin
ClientID: "client-headless",
LastRefreshStatus: "failure",
ConsecutiveFailures: 3,
NextRetryAt: ptrTestTime(now.Add(10 * time.Minute)),
NextRetryAt: new(now.Add(10 * time.Minute)),
}
assert.False(t, cacheService.ShouldPrefetch(state, now))
@@ -216,7 +216,7 @@ func TestHeadlessJWKSCacheWorker_RunOnce_SkipsBackoffTargets(t *testing.T) {
JWKSURI: clients[1].HeadlessJWKSURI(),
LastRefreshStatus: "failure",
ConsecutiveFailures: 3,
NextRetryAt: ptrTestTime(now.Add(10 * time.Minute)),
NextRetryAt: new(now.Add(10 * time.Minute)),
}))
fetchCounts := map[string]int{}
@@ -278,7 +278,7 @@ func TestHeadlessJWKSCacheWorker_RunOnce_RetriesAfterBackoffAndClearsFailureStat
LastRefreshStatus: "failure",
LastError: "previous failure",
ConsecutiveFailures: 3,
NextRetryAt: ptrTestTime(time.Now().Add(-time.Minute)),
NextRetryAt: new(time.Now().Add(-time.Minute)),
}))
fetchCount := 0
@@ -353,7 +353,7 @@ func TestHeadlessJWKSCacheWorker_RunOnce_MixedClients(t *testing.T) {
JWKSURI: skipClient.HeadlessJWKSURI(),
LastRefreshStatus: "failure",
ConsecutiveFailures: 3,
NextRetryAt: ptrTestTime(time.Now().Add(10 * time.Minute)),
NextRetryAt: new(time.Now().Add(10 * time.Minute)),
}))
fetchCounts := map[string]int{}
@@ -416,8 +416,9 @@ func mustServiceHeadlessRSAJWK(t *testing.T, kid string) (*rsa.PrivateKey, jose.
return privateKey, jose.JSONWebKeySet{Keys: []jose.JSONWebKey{publicJWK}}
}
//go:fix inline
func ptrTestTime(value time.Time) *time.Time {
return &value
return new(value)
}
func newTestHeadlessClient(clientID, jwksURI string) domain.HydraClient {

View File

@@ -97,7 +97,7 @@ func (s *HydraAdminService) GetClient(ctx context.Context, clientID string) (*do
func (s *HydraAdminService) PatchClientStatus(ctx context.Context, clientID, status string) (*domain.HydraClient, error) {
// JSON Patch format
payload := []map[string]interface{}{
payload := []map[string]any{
{
"op": "replace",
"path": "/metadata/status",
@@ -396,7 +396,7 @@ func (s *HydraAdminService) RejectConsentRequest(ctx context.Context, challenge
return nil, err
}
payload := map[string]interface{}{
payload := map[string]any{
"error": "access_denied",
"error_description": "The user decided to reject the consent request.",
}
@@ -438,7 +438,7 @@ func (s *HydraAdminService) RejectLoginRequest(ctx context.Context, challenge, e
return nil, err
}
payload := map[string]interface{}{
payload := map[string]any{
"error": error,
"error_description": errorDescription,
}
@@ -513,7 +513,7 @@ func (s *HydraAdminService) AcceptConsentRequest(ctx context.Context, challenge
return nil, err
}
payload := map[string]interface{}{
payload := map[string]any{
"grant_scope": grantInfo.RequestedScope,
"grant_audience": grantInfo.RequestedAudience,
"remember": true,
@@ -564,7 +564,7 @@ func (s *HydraAdminService) AcceptLoginRequest(ctx context.Context, challenge st
return nil, err
}
payload := map[string]interface{}{
payload := map[string]any{
"subject": subject,
"remember": true,
"remember_for": 2592000,
@@ -600,13 +600,13 @@ func (s *HydraAdminService) AcceptLoginRequest(ctx context.Context, challenge st
}
type HydraIntrospectionResponse struct {
Active bool `json:"active"`
Subject string `json:"sub"`
ClientID string `json:"client_id"`
Scope string `json:"scope"`
ExpiresAt int64 `json:"exp"`
IssuedAt int64 `json:"iat"`
Ext map[string]interface{} `json:"ext"`
Active bool `json:"active"`
Subject string `json:"sub"`
ClientID string `json:"client_id"`
Scope string `json:"scope"`
ExpiresAt int64 `json:"exp"`
IssuedAt int64 `json:"iat"`
Ext map[string]any `json:"ext"`
}
func (s *HydraAdminService) IntrospectToken(ctx context.Context, token string) (*HydraIntrospectionResponse, error) {

View File

@@ -127,7 +127,7 @@ func TestHydraAdminService_PatchClientStatus(t *testing.T) {
assert.Equal(t, "PATCH", r.Method)
assert.Equal(t, "application/json-patch+json", r.Header.Get("Content-Type"))
var payload []map[string]interface{}
var payload []map[string]any
_ = json.NewDecoder(r.Body).Decode(&payload)
assert.Equal(t, "replace", payload[0]["op"])
assert.Equal(t, "/metadata/status", payload[0]["path"])
@@ -273,7 +273,7 @@ func TestHydraAdminService_AcceptLoginRequest(t *testing.T) {
assert.Equal(t, "/oauth2/auth/requests/login/accept", r.URL.Path)
assert.Equal(t, challenge, r.URL.Query().Get("login_challenge"))
var body map[string]interface{}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
assert.Equal(t, subject, body["subject"])

View File

@@ -110,7 +110,7 @@ func (s *ketoService) CheckPermission(ctx context.Context, subject, namespace, o
maxRetries := 5
backoff := 200 * time.Millisecond
for i := 0; i < maxRetries; i++ {
for i := range maxRetries {
req, _ := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
resp, err := s.client.Do(req)
if err == nil {
@@ -143,7 +143,7 @@ func (s *ketoService) CheckPermission(ctx context.Context, subject, namespace, o
func (s *ketoService) CreateRelation(ctx context.Context, namespace, object, relation, subject string) error {
u := fmt.Sprintf("%s/admin/relation-tuples", s.writeURL)
payload := map[string]interface{}{
payload := map[string]any{
"namespace": namespace,
"object": object,
"relation": relation,
@@ -156,7 +156,7 @@ func (s *ketoService) CreateRelation(ctx context.Context, namespace, object, rel
maxRetries := 5
backoff := 200 * time.Millisecond
for i := 0; i < maxRetries; i++ {
for i := range maxRetries {
req, _ := http.NewRequestWithContext(ctx, "PUT", u, bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
@@ -197,7 +197,7 @@ func (s *ketoService) DeleteRelation(ctx context.Context, namespace, object, rel
maxRetries := 5
backoff := 200 * time.Millisecond
for i := 0; i < maxRetries; i++ {
for i := range maxRetries {
req, _ := http.NewRequestWithContext(ctx, "DELETE", u.String(), nil)
resp, err := s.client.Do(req)
if err == nil {

View File

@@ -36,7 +36,7 @@ func TestKetoService_CreateRelation(t *testing.T) {
assert.Equal(t, "/admin/relation-tuples", r.URL.Path)
assert.Equal(t, "PUT", r.Method)
var body map[string]interface{}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
assert.Equal(t, "tenants", body["namespace"])
assert.Equal(t, "tenant1", body["object"])

View File

@@ -17,15 +17,14 @@ import (
)
type KratosIdentity struct {
ID string `json:"id"`
SchemaID string `json:"schema_id,omitempty"`
Traits map[string]interface{} `json:"traits"`
State string `json:"state,omitempty"`
MetadataAdmin interface{} `json:"metadata_admin,omitempty"`
MetadataPublic interface{} `json:"metadata_public,omitempty"`
ExternalID string `json:"external_id,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
ID string `json:"id"`
SchemaID string `json:"schema_id,omitempty"`
Traits map[string]any `json:"traits"`
State string `json:"state,omitempty"`
MetadataAdmin any `json:"metadata_admin,omitempty"`
MetadataPublic any `json:"metadata_public,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type KratosSessionDevice struct {
@@ -36,9 +35,9 @@ type KratosSessionDevice struct {
type KratosSession struct {
ID string `json:"id"`
Active bool `json:"active"`
AuthenticatedAt time.Time `json:"authenticated_at,omitempty"`
ExpiresAt time.Time `json:"expires_at,omitempty"`
IssuedAt time.Time `json:"issued_at,omitempty"`
AuthenticatedAt time.Time `json:"authenticated_at"`
ExpiresAt time.Time `json:"expires_at"`
IssuedAt time.Time `json:"issued_at"`
Identity *KratosIdentity `json:"identity,omitempty"`
Devices []KratosSessionDevice `json:"devices,omitempty"`
}
@@ -47,7 +46,7 @@ type KratosAdminService interface {
ListIdentities(ctx context.Context) ([]KratosIdentity, error)
FindIdentityIDByIdentifier(ctx context.Context, identifier string) (string, error)
GetIdentity(ctx context.Context, identityID string) (*KratosIdentity, error)
UpdateIdentity(ctx context.Context, identityID string, traits map[string]interface{}, state string) (*KratosIdentity, error)
UpdateIdentity(ctx context.Context, identityID string, traits map[string]any, state string) (*KratosIdentity, error)
UpdateIdentityPassword(ctx context.Context, identityID, newPassword string) error
DeleteIdentity(ctx context.Context, identityID string) error
CreateUser(ctx context.Context, user *domain.BrokerUser, password string) (string, error)
@@ -99,13 +98,66 @@ func (s *kratosAdminService) FindIdentityIDByIdentifier(ctx context.Context, ide
}
endpoint := strings.TrimRight(s.AdminURL, "/") + "/admin/identities"
// 1. Try credentials_identifier (Email/LoginID/Phone)
id, err := s.searchIdentities(ctx, endpoint, "credentials_identifier", identifier)
if err == nil && id != "" {
// VERIFY: Kratos sometimes ignores unknown query params and returns the first identity.
if s.verifyIdentityMatch(ctx, id, identifier) {
return id, nil
}
}
identity, err := s.GetIdentity(ctx, identifier)
if err == nil && identity != nil {
return identity.ID, nil
}
return "", nil
}
func (s *kratosAdminService) verifyIdentityMatch(ctx context.Context, id, identifier string) bool {
identity, err := s.GetIdentity(ctx, id)
if err != nil || identity == nil {
return false
}
// Exact ID match
if strings.EqualFold(identity.ID, identifier) {
return true
}
// Check traits (Email, CustomLoginIDs)
if email, ok := identity.Traits["email"].(string); ok && strings.EqualFold(email, identifier) {
return true
}
if phone, ok := identity.Traits["phone_number"].(string); ok && strings.EqualFold(phone, identifier) {
return true
}
if lids, ok := identity.Traits["custom_login_ids"].([]any); ok {
for _, lid := range lids {
if s, ok := lid.(string); ok && strings.EqualFold(s, identifier) {
return true
}
}
} else if lids, ok := identity.Traits["custom_login_ids"].([]string); ok {
for _, lid := range lids {
if strings.EqualFold(lid, identifier) {
return true
}
}
}
return false
}
func (s *kratosAdminService) searchIdentities(ctx context.Context, endpoint, key, value string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return "", err
}
query := req.URL.Query()
query.Set("credentials_identifier", identifier)
query.Set(key, value)
req.URL.RawQuery = query.Encode()
resp, err := s.httpClient().Do(req)
@@ -119,7 +171,7 @@ func (s *kratosAdminService) FindIdentityIDByIdentifier(ctx context.Context, ide
}
if resp.StatusCode >= 300 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
return "", fmt.Errorf("kratos admin search failed status=%d body=%s", resp.StatusCode, string(body))
return "", fmt.Errorf("kratos admin search by %s failed status=%d body=%s", key, resp.StatusCode, string(body))
}
var identities []struct {
@@ -162,8 +214,8 @@ func (s *kratosAdminService) GetIdentity(ctx context.Context, identityID string)
return &identity, nil
}
func (s *kratosAdminService) UpdateIdentity(ctx context.Context, identityID string, traits map[string]interface{}, state string) (*KratosIdentity, error) {
payload := map[string]interface{}{
func (s *kratosAdminService) UpdateIdentity(ctx context.Context, identityID string, traits map[string]any, state string) (*KratosIdentity, error) {
payload := map[string]any{
"schema_id": "default",
"traits": traits,
}
@@ -211,12 +263,12 @@ func (s *kratosAdminService) UpdateIdentityPassword(ctx context.Context, identit
return err
}
payload := map[string]interface{}{
payload := map[string]any{
"schema_id": identity.SchemaID,
"traits": identity.Traits,
"state": identity.State,
"credentials": map[string]interface{}{
"password": map[string]interface{}{
"credentials": map[string]any{
"password": map[string]any{
"config": map[string]string{
"hashed_password": hashedPassword,
},
@@ -235,10 +287,6 @@ func (s *kratosAdminService) UpdateIdentityPassword(ctx context.Context, identit
if identity.MetadataPublic != nil {
payload["metadata_public"] = identity.MetadataPublic
}
if identity.ExternalID != "" {
payload["external_id"] = identity.ExternalID
}
body, _ := json.Marshal(payload)
endpoint := fmt.Sprintf("%s/admin/identities/%s", strings.TrimRight(s.AdminURL, "/"), identityID)
req, err := http.NewRequestWithContext(ctx, http.MethodPut, endpoint, bytes.NewReader(body))
@@ -263,8 +311,11 @@ func (s *kratosAdminService) CreateUser(ctx context.Context, user *domain.Broker
if user == nil {
return "", fmt.Errorf("kratos admin: user payload is nil")
}
if strings.TrimSpace(user.ID) != "" {
return "", fmt.Errorf("kratos admin: requested identity id import is disabled; use backup/restore")
}
traits := map[string]interface{}{
traits := map[string]any{
"email": user.Email,
"name": user.Name,
}
@@ -278,11 +329,11 @@ func (s *kratosAdminService) CreateUser(ctx context.Context, user *domain.Broker
traits[k] = v
}
payload := map[string]interface{}{
payload := map[string]any{
"schema_id": "default",
"traits": traits,
"credentials": map[string]interface{}{
"password": map[string]interface{}{
"credentials": map[string]any{
"password": map[string]any{
"config": map[string]string{
"password": password,
},
@@ -290,10 +341,6 @@ func (s *kratosAdminService) CreateUser(ctx context.Context, user *domain.Broker
},
"state": "active",
}
if requestedID := strings.TrimSpace(user.ID); requestedID != "" {
payload["id"] = requestedID
}
body, _ := json.Marshal(payload)
endpoint := strings.TrimRight(s.AdminURL, "/") + "/admin/identities"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
@@ -319,10 +366,6 @@ func (s *kratosAdminService) CreateUser(ctx context.Context, user *domain.Broker
if err := json.NewDecoder(resp.Body).Decode(&created); err != nil {
return "", err
}
if requestedID := strings.TrimSpace(user.ID); requestedID != "" && created.ID != requestedID {
return "", fmt.Errorf("kratos admin: requested identity id was not preserved requested=%s actual=%s", requestedID, created.ID)
}
return created.ID, nil
}

View File

@@ -103,7 +103,7 @@ func (m *MockKratosAdminServiceShared) GetIdentity(ctx context.Context, identity
return args.Get(0).(*KratosIdentity), args.Error(1)
}
func (m *MockKratosAdminServiceShared) UpdateIdentity(ctx context.Context, identityID string, traits map[string]interface{}, state string) (*KratosIdentity, error) {
func (m *MockKratosAdminServiceShared) UpdateIdentity(ctx context.Context, identityID string, traits map[string]any, state string) (*KratosIdentity, error) {
args := m.Called(ctx, identityID, traits, state)
if args.Get(0) == nil {
return nil, args.Error(1)

View File

@@ -57,8 +57,10 @@ func (o *OryProvider) CreateUser(user *domain.BrokerUser, password string) (stri
if user.Email == "" || password == "" {
return "", fmt.Errorf("ory provider: email and password are required")
}
if strings.TrimSpace(user.ID) != "" {
return "", fmt.Errorf("ory provider: requested identity id import is disabled; use backup/restore")
}
// 중복 확인
existingID, err := o.findIdentityID(user.Email)
if err != nil {
return "", fmt.Errorf("ory provider: search identity failed: %w", err)
@@ -102,7 +104,7 @@ func (o *OryProvider) CreateUser(user *domain.BrokerUser, password string) (stri
}
}
traits := map[string]interface{}{
traits := map[string]any{
"email": user.Email,
"name": user.Name,
}
@@ -123,21 +125,18 @@ func (o *OryProvider) CreateUser(user *domain.BrokerUser, password string) (stri
traits[k] = v
}
payload := map[string]interface{}{
payload := map[string]any{
"schema_id": "default",
"traits": traits,
"credentials": map[string]interface{}{
"password": map[string]interface{}{
"credentials": map[string]any{
"password": map[string]any{
"config": map[string]string{
"password": password,
},
},
},
}
if requestedID := strings.TrimSpace(user.ID); requestedID != "" {
payload["id"] = requestedID
}
verifiable := []map[string]interface{}{
verifiable := []map[string]any{
{
"value": user.Email,
"verified": true,
@@ -145,14 +144,14 @@ func (o *OryProvider) CreateUser(user *domain.BrokerUser, password string) (stri
},
}
if user.PhoneNumber != "" {
verifiable = append(verifiable, map[string]interface{}{
verifiable = append(verifiable, map[string]any{
"value": user.PhoneNumber,
"verified": true,
"via": "sms",
})
}
payload["verifiable_addresses"] = verifiable
payload["recovery_addresses"] = []map[string]interface{}{
payload["recovery_addresses"] = []map[string]any{
{
"value": user.Email,
"via": "email",
@@ -182,10 +181,6 @@ func (o *OryProvider) CreateUser(user *domain.BrokerUser, password string) (stri
if err := json.NewDecoder(resp.Body).Decode(&created); err != nil {
return "", fmt.Errorf("ory provider: decode create identity response failed: %w", err)
}
if requestedID := strings.TrimSpace(user.ID); requestedID != "" && created.ID != requestedID {
return "", fmt.Errorf("ory provider: requested identity id was not preserved requested=%s actual=%s", requestedID, created.ID)
}
slog.Info("Ory identity created", "identity_id", created.ID, "email", user.Email)
return created.ID, nil
}
@@ -460,12 +455,12 @@ func (o *OryProvider) ensureCodeLoginIdentifier(loginID string) error {
existingIndex = idx
}
}
ops := make([]map[string]interface{}, 0, 2)
ops := make([]map[string]any, 0, 2)
if !exists {
ops = append(ops, map[string]interface{}{
ops = append(ops, map[string]any{
"op": "add",
"path": "/verifiable_addresses/-",
"value": map[string]interface{}{
"value": map[string]any{
"value": loginID,
"via": via,
"verified": true,
@@ -475,14 +470,14 @@ func (o *OryProvider) ensureCodeLoginIdentifier(loginID string) error {
} else {
addr := identity.VerifiableAddresses[existingIndex]
if !addr.Verified {
ops = append(ops, map[string]interface{}{
ops = append(ops, map[string]any{
"op": "replace",
"path": fmt.Sprintf("/verifiable_addresses/%d/verified", existingIndex),
"value": true,
})
}
if addr.Status != "" && addr.Status != "completed" {
ops = append(ops, map[string]interface{}{
ops = append(ops, map[string]any{
"op": "replace",
"path": fmt.Sprintf("/verifiable_addresses/%d/status", existingIndex),
"value": "completed",
@@ -526,7 +521,7 @@ func (o *OryProvider) ensureCodeLoginIdentifier(loginID string) error {
})
}
payload := map[string]interface{}{
payload := map[string]any{
"schema_id": fullIdentity.SchemaID,
"traits": fullIdentity.Traits,
"verifiable_addresses": addresses,
@@ -567,12 +562,12 @@ type kratosRecoveryAddress struct {
type kratosIdentityFull struct {
SchemaID string `json:"schema_id"`
Traits map[string]interface{} `json:"traits"`
Traits map[string]any `json:"traits"`
VerifiableAddresses []kratosVerifiableAddress `json:"verifiable_addresses"`
RecoveryAddresses []kratosRecoveryAddress `json:"recovery_addresses"`
}
func (o *OryProvider) patchIdentity(identityID string, ops []map[string]interface{}) error {
func (o *OryProvider) patchIdentity(identityID string, ops []map[string]any) error {
body, _ := json.Marshal(ops)
req, err := http.NewRequestWithContext(context.Background(), http.MethodPatch, fmt.Sprintf("%s/admin/identities/%s", o.KratosAdminURL, identityID), bytes.NewReader(body))
if err != nil {
@@ -756,12 +751,12 @@ func (o *OryProvider) UpdateUserPassword(loginID, newPassword string, r *http.Re
return fmt.Errorf("ory provider: hash password failed: %w", err)
}
payload := map[string]interface{}{
payload := map[string]any{
"schema_id": identity.SchemaID,
"traits": identity.Traits,
"state": identity.State,
"credentials": map[string]interface{}{
"password": map[string]interface{}{
"credentials": map[string]any{
"password": map[string]any{
"config": map[string]string{
"hashed_password": hashedPassword,
},
@@ -780,10 +775,6 @@ func (o *OryProvider) UpdateUserPassword(loginID, newPassword string, r *http.Re
if identity.MetadataPublic != nil {
payload["metadata_public"] = identity.MetadataPublic
}
if identity.ExternalID != "" {
payload["external_id"] = identity.ExternalID
}
body, _ := json.Marshal(payload)
req, err := http.NewRequestWithContext(context.Background(), http.MethodPut, fmt.Sprintf("%s/admin/identities/%s", o.KratosAdminURL, identityID), bytes.NewReader(body))
if err != nil {
@@ -812,6 +803,18 @@ func getenv(key, fallback string) string {
return fallback
}
// findIdentityByID: Kratos Admin API에서 ID(UUID)로 직접 조회
func (o *OryProvider) findIdentityByID(id string) (string, error) {
identity, err := o.getIdentity(id)
if err != nil {
return "", err
}
if identity != nil {
return identity.ID, nil
}
return "", nil
}
// findIdentityID: Kratos Admin API에서 credentials_identifier로 검색 후 첫 번째 identity id 반환
func (o *OryProvider) findIdentityID(loginID string) (string, error) {
u, err := url.Parse(fmt.Sprintf("%s/admin/identities", o.KratosAdminURL))
@@ -843,7 +846,8 @@ func (o *OryProvider) findIdentityID(loginID string) (string, error) {
}
var identities []struct {
ID string `json:"id"`
ID string `json:"id"`
Traits map[string]any `json:"traits"`
}
if err := json.NewDecoder(resp.Body).Decode(&identities); err != nil {
return "", fmt.Errorf("decode response failed: %w", err)
@@ -851,7 +855,30 @@ func (o *OryProvider) findIdentityID(loginID string) (string, error) {
if len(identities) == 0 {
return "", nil
}
return identities[0].ID, nil
// VERIFY: Double check traits to avoid Kratos ignoring the query param
candidate := identities[0]
if email, ok := candidate.Traits["email"].(string); ok && strings.EqualFold(email, loginID) {
return candidate.ID, nil
}
if phone, ok := candidate.Traits["phone_number"].(string); ok && strings.EqualFold(phone, loginID) {
return candidate.ID, nil
}
if lids, ok := candidate.Traits["custom_login_ids"].([]any); ok {
for _, lid := range lids {
if s, ok := lid.(string); ok && strings.EqualFold(s, loginID) {
return candidate.ID, nil
}
}
} else if lids, ok := candidate.Traits["custom_login_ids"].([]string); ok {
for _, lid := range lids {
if strings.EqualFold(lid, loginID) {
return candidate.ID, nil
}
}
}
return "", nil
}
func (o *OryProvider) getIdentity(identityID string) (*KratosIdentity, error) {

View File

@@ -36,76 +36,6 @@ type roundTripperFunc func(req *http.Request) (*http.Response, error)
func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) }
func TestCreateUserSendsRequestedIdentityID(t *testing.T) {
const requestedID = "9f8cc1b1-af8d-45d4-946c-924a529c2556"
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/admin/identities" && r.Method == http.MethodGet:
_ = json.NewEncoder(w).Encode([]map[string]string{})
return
case r.URL.Path == "/admin/identities" && r.Method == http.MethodPost:
var payload map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
t.Fatalf("failed to decode payload: %v", err)
}
if payload["id"] != requestedID {
t.Fatalf("expected id=%s, got=%v", requestedID, payload["id"])
}
_ = json.NewEncoder(w).Encode(map[string]string{"id": requestedID})
return
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
}
})
provider := &OryProvider{
KratosAdminURL: "http://kratos-admin.local",
HTTPClient: clientForHandler(handler),
}
id, err := provider.CreateUser(&domain.BrokerUser{
ID: requestedID,
Email: "restore@test.com",
Name: "Restore User",
}, "Sup3rStr0ng!Pass#2026")
if err != nil {
t.Fatalf("CreateUser returned error: %v", err)
}
if id != requestedID {
t.Fatalf("expected %s, got %s", requestedID, id)
}
}
func TestCreateUserRejectsRequestedIdentityIDMismatch(t *testing.T) {
const requestedID = "9f8cc1b1-af8d-45d4-946c-924a529c2556"
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/admin/identities" && r.Method == http.MethodGet:
_ = json.NewEncoder(w).Encode([]map[string]string{})
return
case r.URL.Path == "/admin/identities" && r.Method == http.MethodPost:
_ = json.NewEncoder(w).Encode(map[string]string{"id": "generated-id"})
return
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
}
})
provider := &OryProvider{
KratosAdminURL: "http://kratos-admin.local",
HTTPClient: clientForHandler(handler),
}
_, err := provider.CreateUser(&domain.BrokerUser{
ID: requestedID,
Email: "restore@test.com",
Name: "Restore User",
}, "Sup3rStr0ng!Pass#2026")
if err == nil || !strings.Contains(err.Error(), "requested identity id was not preserved") {
t.Fatalf("expected requested identity id mismatch error, got: %v", err)
}
}
func TestUpdateUserPassword_Success(t *testing.T) {
const (
loginID = "user@example.com"
@@ -121,19 +51,24 @@ func TestUpdateUserPassword_Success(t *testing.T) {
if got := q.Get("credentials_identifier"); got != loginID {
t.Fatalf("expected credentials_identifier=%s, got=%s", loginID, got)
}
_ = json.NewEncoder(w).Encode([]map[string]string{
{"id": identityID},
_ = json.NewEncoder(w).Encode([]map[string]any{
{
"id": identityID,
"traits": map[string]any{
"email": loginID,
},
},
})
return
}
if r.URL.Path != "/admin/identities/"+identityID {
t.Fatalf("unexpected identity lookup path: %s", r.URL.Path)
}
_ = json.NewEncoder(w).Encode(map[string]interface{}{
_ = json.NewEncoder(w).Encode(map[string]any{
"id": identityID,
"schema_id": "default",
"state": "active",
"traits": map[string]interface{}{
"traits": map[string]any{
"email": loginID,
},
})
@@ -191,17 +126,22 @@ func TestUpdateUserPassword_ServerError(t *testing.T) {
switch {
case strings.HasPrefix(r.URL.Path, "/admin/identities") && r.Method == http.MethodGet:
if r.URL.Path == "/admin/identities" {
_ = json.NewEncoder(w).Encode([]map[string]string{
{"id": "abc"},
_ = json.NewEncoder(w).Encode([]map[string]any{
{
"id": "abc",
"traits": map[string]any{
"email": "user@example.com",
},
},
})
return
}
if r.URL.Path == "/admin/identities/abc" {
_ = json.NewEncoder(w).Encode(map[string]interface{}{
_ = json.NewEncoder(w).Encode(map[string]any{
"id": "abc",
"schema_id": "default",
"state": "active",
"traits": map[string]interface{}{
"traits": map[string]any{
"email": "user@example.com",
},
})
@@ -234,8 +174,13 @@ func TestFindIdentityID_QueryEncoding(t *testing.T) {
if values.Get("credentials_identifier") != loginID {
t.Fatalf("expected credentials_identifier=%s, got=%s", loginID, values.Get("credentials_identifier"))
}
_ = json.NewEncoder(w).Encode([]map[string]string{
{"id": "id-123"},
_ = json.NewEncoder(w).Encode([]map[string]any{
{
"id": "id-123",
"traits": map[string]any{
"email": loginID,
},
},
})
})
@@ -252,3 +197,30 @@ func TestFindIdentityID_QueryEncoding(t *testing.T) {
t.Fatalf("expected id-123, got %s", id)
}
}
func TestOryProvider_CreateUser_RejectsRequestedIdentityID(t *testing.T) {
const (
email = "newuser@test.com"
name = "New User"
customUuid = "550e8400-e29b-41d4-a716-446655440000"
password = "secret123456"
)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
})
provider := &OryProvider{
KratosAdminURL: "http://kratos-admin.local",
HTTPClient: clientForHandler(handler),
}
id, err := provider.CreateUser(&domain.BrokerUser{
ID: customUuid,
Email: email,
Name: name,
}, password)
if err == nil || !strings.Contains(err.Error(), "requested identity id import is disabled") {
t.Fatalf("expected requested identity id rejection, got id=%s err=%v", id, err)
}
}

View File

@@ -100,7 +100,7 @@ func (s *relyingPartyService) enqueueDefaultRelyingPartyRelations(ctx context.Co
func (s *relyingPartyService) Create(ctx context.Context, tenantID string, client domain.HydraClient) (*domain.RelyingParty, error) {
// 1. Create Client in Hydra
if client.Metadata == nil {
client.Metadata = make(map[string]interface{})
client.Metadata = make(map[string]any)
}
client.Metadata["tenant_id"] = tenantID

View File

@@ -52,7 +52,7 @@ func TestRelyingPartyService_Create_Success(t *testing.T) {
tenantID := "tenant-1"
inputClient := domain.HydraClient{
ClientName: "Test App",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"user_id": "creator-1",
},
}
@@ -127,7 +127,7 @@ func TestRelyingPartyService_Get_Success(t *testing.T) {
_ = json.NewEncoder(w).Encode(domain.HydraClient{
ClientID: clientID,
ClientName: "Hydra Name",
Metadata: map[string]interface{}{
Metadata: map[string]any{
"tenant_id": "tenant-1",
},
})
@@ -180,7 +180,7 @@ func TestRelyingPartyService_Delete_Success(t *testing.T) {
if r.Method == http.MethodGet && strings.Contains(r.URL.Path, clientID) {
_ = json.NewEncoder(w).Encode(domain.HydraClient{
ClientID: clientID,
Metadata: map[string]interface{}{
Metadata: map[string]any{
"tenant_id": tenantID,
"user_id": "creator-1",
},

View File

@@ -8,7 +8,7 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"log/slog"
"net/http"
"os"
@@ -82,7 +82,7 @@ func (s *SmsServiceImpl) SendSms(to, content string) error {
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error reading response body: %w", err)
}

View File

@@ -336,7 +336,7 @@ func (s *tenantService) ProvisionTenantByDomain(ctx context.Context, domainName
}
for _, g := range groups {
rawConfig, ok := g.Config["autoProvisioning"].(map[string]interface{})
rawConfig, ok := g.Config["autoProvisioning"].(map[string]any)
if !ok {
continue
}
@@ -346,12 +346,12 @@ func (s *tenantService) ProvisionTenantByDomain(ctx context.Context, domainName
continue
}
mapping, ok := rawConfig["mappingRules"].(map[string]interface{})
mapping, ok := rawConfig["mappingRules"].(map[string]any)
if !ok {
continue
}
rule, ok := mapping[domainName].(map[string]interface{})
rule, ok := mapping[domainName].(map[string]any)
if !ok {
continue
}

View File

@@ -7,6 +7,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"gorm.io/gorm"
)
// --- Local Mocks to avoid collisions ---
@@ -185,6 +186,10 @@ func (m *MockUserRepoForTenant) FindTenantIDByLoginID(ctx context.Context, login
return "", nil
}
func (m *MockUserRepoForTenant) DB() *gorm.DB {
return nil
}
// --- Tests ---
func TestTenantService_RegisterTenant_AutoVerify(t *testing.T) {

View File

@@ -225,7 +225,7 @@ func (s *userGroupService) AddMember(ctx context.Context, groupID, userID string
if err == nil && identity != nil {
traits := identity.Traits
if traits == nil {
traits = make(map[string]interface{})
traits = make(map[string]any)
}
delete(traits, "companyCode")
delete(traits, "companyCodes")
@@ -349,7 +349,7 @@ func mapUserGroupKratosIdentityToLocalUser(identity KratosIdentity) *domain.User
return user
}
func userGroupTraitString(traits map[string]interface{}, key string) string {
func userGroupTraitString(traits map[string]any, key string) string {
if traits == nil {
return ""
}
@@ -363,14 +363,14 @@ func userGroupTraitString(traits map[string]interface{}, key string) string {
return fmt.Sprint(value)
}
func userGroupTraitStringArray(traits map[string]interface{}, key string) []string {
func userGroupTraitStringArray(traits map[string]any, key string) []string {
if traits == nil {
return nil
}
switch value := traits[key].(type) {
case []string:
return value
case []interface{}:
case []any:
items := make([]string, 0, len(value))
for _, item := range value {
if str, ok := item.(string); ok && str != "" {

View File

@@ -135,6 +135,10 @@ func (m *MockUserRepository) FindTenantIDByLoginID(ctx context.Context, loginID
return "", nil
}
func (m *MockUserRepository) DB() *gorm.DB {
return nil
}
type MockKetoOutboxRepository struct {
mock.Mock
}
@@ -250,7 +254,7 @@ func TestUserGroupService_AddMember(t *testing.T) {
// Mock Kratos
mockKratos.On("GetIdentity", mock.Anything, userID).Return(&KratosIdentity{
ID: userID,
Traits: map[string]interface{}{"email": "user@test.com"},
Traits: map[string]any{"email": "user@test.com"},
State: "active",
}, nil)
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.Anything, "active").Return(&KratosIdentity{}, nil)
@@ -295,18 +299,18 @@ func TestUserGroupService_AddMemberUpsertsLocalReadModelWhenMissing(t *testing.T
mockTenantRepo.On("FindByID", mock.Anything, tenantID).Return(&domain.Tenant{ID: tenantID, Slug: tenantSlug}, nil)
mockKratos.On("GetIdentity", mock.Anything, userID).Return(&KratosIdentity{
ID: userID,
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
"name": "User Test",
},
State: "active",
}, nil)
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]interface{}) bool {
mockKratos.On("UpdateIdentity", mock.Anything, userID, mock.MatchedBy(func(traits map[string]any) bool {
_, hasCompanyCode := traits["companyCode"]
return !hasCompanyCode && traits["tenant_id"] == tenantID && traits["department"] == "Sales"
}), "active").Return(&KratosIdentity{
ID: userID,
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "user@test.com",
"name": "User Test",
"tenant_id": tenantID,
@@ -402,7 +406,7 @@ func TestUserGroupService_Get_WithKratosFallback(t *testing.T) {
mockKratos.On("GetIdentity", mock.Anything, "u1").Return(&KratosIdentity{
ID: "u1",
Traits: map[string]interface{}{"name": "User One", "email": "user1@example.com"},
Traits: map[string]any{"name": "User One", "email": "user1@example.com"},
}, nil)
group, err := svc.Get(context.Background(), groupID)

View File

@@ -110,7 +110,7 @@ func MapKratosIdentityToLocalUser(identity KratosIdentity) domain.User {
return user
}
func kratosProjectionTraitString(traits map[string]interface{}, key string) string {
func kratosProjectionTraitString(traits map[string]any, key string) string {
if traits == nil {
return ""
}
@@ -124,14 +124,14 @@ func kratosProjectionTraitString(traits map[string]interface{}, key string) stri
return fmt.Sprint(value)
}
func kratosProjectionTraitStringArray(traits map[string]interface{}, key string) []string {
func kratosProjectionTraitStringArray(traits map[string]any, key string) []string {
if traits == nil {
return nil
}
switch value := traits[key].(type) {
case []string:
return value
case []interface{}:
case []any:
items := make([]string, 0, len(value))
for _, item := range value {
if str, ok := item.(string); ok && strings.TrimSpace(str) != "" {

View File

@@ -48,12 +48,12 @@ func TestUserProjectionSyncService_ReconcileReplacesProjectionFromKratos(t *test
kratos.On("ListIdentities", ctx).Return([]KratosIdentity{
{
ID: "00000000-0000-0000-0000-000000000101",
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "one@example.com",
"name": "One",
"phone_number": "+821012345678",
"companyCode": "saman",
"companyCodes": []interface{}{"saman", "group-a"},
"companyCodes": []any{"saman", "group-a"},
"tenant_id": tenantID,
"department": "DX",
"customAttr": "kept",
@@ -101,7 +101,7 @@ func TestMapKratosIdentityToLocalUserPreservesArchivedStatus(t *testing.T) {
user := MapKratosIdentityToLocalUser(KratosIdentity{
ID: "00000000-0000-0000-0000-000000000201",
State: domain.UserStatusArchived,
Traits: map[string]interface{}{
Traits: map[string]any{
"email": "archived@example.com",
"name": "Archived User",
},

View File

@@ -778,7 +778,7 @@ type WorksmobileUserPatchPayload struct {
DomainID int64 `json:"domainId"`
Email string `json:"email,omitempty"`
UserExternalKey string `json:"userExternalKey,omitempty"`
UserName WorksmobileUserName `json:"userName,omitempty"`
UserName WorksmobileUserName `json:"userName"`
CellPhone string `json:"cellPhone,omitempty"`
EmployeeNumber string `json:"employeeNumber,omitempty"`
AliasEmails []string `json:"aliasEmails,omitempty"`
@@ -797,23 +797,26 @@ type WorksmobileOrgUnitPatchPayload struct {
}
type WorksmobileRemoteUser struct {
ID string `json:"id"`
ExternalID string `json:"externalId"`
UserName string `json:"userName"`
Email string `json:"email"`
DisplayName string `json:"displayName"`
LevelID string `json:"levelId"`
LevelName string `json:"levelName"`
Task string `json:"task"`
DomainID int64 `json:"domainId"`
DomainName string `json:"domainName"`
PrimaryOrgUnitID string `json:"primaryOrgUnitId"`
PrimaryOrgUnitName string `json:"primaryOrgUnitName"`
PrimaryOrgUnitPositionID string `json:"primaryOrgUnitPositionId"`
PrimaryOrgUnitPositionName string `json:"primaryOrgUnitPositionName"`
PrimaryOrgUnitIsManager *bool `json:"primaryOrgUnitIsManager,omitempty"`
OrgUnitManagers map[string]*bool `json:"orgUnitManagers,omitempty"`
Active bool `json:"active"`
ID string `json:"id"`
ExternalID string `json:"externalId"`
UserName string `json:"userName"`
Email string `json:"email"`
DisplayName string `json:"displayName"`
CellPhone string `json:"cellPhone,omitempty"`
EmployeeNumber string `json:"employeeNumber,omitempty"`
LevelID string `json:"levelId"`
LevelName string `json:"levelName"`
Task string `json:"task"`
DomainID int64 `json:"domainId"`
DomainName string `json:"domainName"`
PrimaryOrgUnitID string `json:"primaryOrgUnitId"`
PrimaryOrgUnitName string `json:"primaryOrgUnitName"`
PrimaryOrgUnitPositionID string `json:"primaryOrgUnitPositionId"`
PrimaryOrgUnitPositionName string `json:"primaryOrgUnitPositionName"`
PrimaryOrgUnitIsManager *bool `json:"primaryOrgUnitIsManager,omitempty"`
OrgUnitManagers map[string]*bool `json:"orgUnitManagers,omitempty"`
Organizations []WorksmobileUserOrganization `json:"organizations,omitempty"`
Active bool `json:"active"`
}
type WorksmobileRemoteGroup struct {
@@ -935,10 +938,18 @@ func parseWorksmobileDirectoryUser(resource map[string]any) WorksmobileRemoteUse
UserName: email,
Email: email,
DisplayName: parseWorksmobileDirectoryUserName(resource),
LevelID: parseWorksmobileUserLevelID(resource),
LevelName: parseWorksmobileUserLevelName(resource),
Task: firstStringFromMap(resource, "task", "job", "jobDescription"),
Active: true,
CellPhone: firstStringFromMap(resource, "cellPhone", "phoneNumber", "phone", "mobile", "mobilePhone"),
EmployeeNumber: firstStringFromMap(
resource,
"employeeNumber",
"employeeNo",
"employeeId",
"employeeID",
),
LevelID: parseWorksmobileUserLevelID(resource),
LevelName: parseWorksmobileUserLevelName(resource),
Task: firstStringFromMap(resource, "task", "job", "jobDescription"),
Active: true,
}
if active, ok := resource["active"].(bool); ok {
user.Active = active
@@ -950,6 +961,7 @@ func parseWorksmobileDirectoryUser(resource map[string]any) WorksmobileRemoteUse
user.PrimaryOrgUnitPositionName = primaryOrgUnit.PositionName
user.PrimaryOrgUnitIsManager = primaryOrgUnit.IsManager
user.OrgUnitManagers = parseWorksmobileOrgUnitManagers(resource)
user.Organizations = parseWorksmobileUserOrganizations(resource)
return user
}
@@ -1072,6 +1084,84 @@ func parseWorksmobilePrimaryOrgUnitDetail(resource map[string]any) worksmobileOr
return worksmobileOrgUnitDetail{}
}
func parseWorksmobileUserOrganizations(resource map[string]any) []WorksmobileUserOrganization {
if organizations := parseWorksmobileUserOrganizationList(resource["organizations"]); len(organizations) > 0 {
return organizations
}
for key, raw := range resource {
if !strings.Contains(strings.ToLower(key), "works") {
continue
}
if values, ok := raw.(map[string]any); ok {
if organizations := parseWorksmobileUserOrganizationList(values["organizations"]); len(organizations) > 0 {
return organizations
}
}
}
return nil
}
func parseWorksmobileUserOrganizationList(raw any) []WorksmobileUserOrganization {
values, ok := raw.([]any)
if !ok {
return nil
}
organizations := make([]WorksmobileUserOrganization, 0, len(values))
for _, item := range values {
organization, ok := item.(map[string]any)
if !ok {
continue
}
orgUnits := parseWorksmobileUserOrgUnitList(organization["orgUnits"])
if len(orgUnits) == 0 {
continue
}
organizations = append(organizations, WorksmobileUserOrganization{
DomainID: int64FromMap(organization, "domainId"),
Email: firstStringFromMap(organization, "email"),
Primary: boolFromMap(organization, "primary"),
OrgUnits: orgUnits,
})
}
return organizations
}
func parseWorksmobileUserOrgUnitList(raw any) []WorksmobileUserOrgUnit {
values, ok := raw.([]any)
if !ok {
return nil
}
orgUnits := make([]WorksmobileUserOrgUnit, 0, len(values))
for _, item := range values {
orgUnit, ok := item.(map[string]any)
if !ok {
continue
}
id := firstStringFromMap(orgUnit, "orgUnitExternalKey", "externalKey")
if id != "" {
id = "externalKey:" + id
} else {
id = firstStringFromMap(orgUnit, "orgUnitId", "id", "value")
}
if id == "" {
if nested := parseWorksmobileUserOrgUnitList(orgUnit["orgUnits"]); len(nested) > 0 {
orgUnits = append(orgUnits, nested...)
}
continue
}
orgUnits = append(orgUnits, WorksmobileUserOrgUnit{
OrgUnitID: id,
Primary: boolFromMap(orgUnit, "primary"),
PositionID: firstStringFromMap(orgUnit, "positionId"),
IsManager: boolPointerFromMap(orgUnit, "isManager", "manager"),
})
if nested := parseWorksmobileUserOrgUnitList(orgUnit["orgUnits"]); len(nested) > 0 {
orgUnits = append(orgUnits, nested...)
}
}
return orgUnits
}
func parseWorksmobileOrgUnitManagers(resource map[string]any) map[string]*bool {
result := map[string]*bool{}
collectWorksmobileOrgUnitManagers(resource["organizations"], result)
@@ -1101,7 +1191,13 @@ func collectWorksmobileOrgUnitManagers(raw any, result map[string]*bool) {
if !ok {
continue
}
if id := firstStringFromMap(orgUnit, "orgUnitId", "id", "value"); id != "" {
id := firstStringFromMap(orgUnit, "orgUnitExternalKey", "externalKey")
if id != "" {
id = "externalKey:" + id
} else {
id = firstStringFromMap(orgUnit, "orgUnitId", "id", "value")
}
if id != "" {
result[id] = boolPointerFromMap(orgUnit, "isManager", "manager")
}
collectWorksmobileOrgUnitManagers(orgUnit["organizations"], result)
@@ -1194,6 +1290,19 @@ func boolFromMap(values map[string]any, key string) bool {
return value
}
func int64FromMap(values map[string]any, key string) int64 {
switch value := values[key].(type) {
case int:
return int64(value)
case int64:
return value
case float64:
return int64(value)
default:
return 0
}
}
func boolPointerFromMap(values map[string]any, keys ...string) *bool {
for _, key := range keys {
if value, ok := values[key].(bool); ok {

View File

@@ -1033,8 +1033,10 @@ func TestParseWorksmobileDirectoryUserIncludesFullNameLevelAndOrgRole(t *testing
func TestParseWorksmobileDirectoryUserIncludesAllOrgUnitManagerFlags(t *testing.T) {
user := parseWorksmobileDirectoryUser(map[string]any{
"userId": "works-user",
"email": "tester@samaneng.com",
"userId": "works-user",
"email": "tester@samaneng.com",
"cellPhone": "010-1234-5678",
"employeeNumber": "EMP001",
"userName": map[string]any{
"lastName": "홍길동",
},
@@ -1062,6 +1064,17 @@ func TestParseWorksmobileDirectoryUserIncludesAllOrgUnitManagerFlags(t *testing.
require.False(t, *user.OrgUnitManagers["externalKey:primary-org"])
require.NotNil(t, user.OrgUnitManagers["externalKey:secondary-org"])
require.True(t, *user.OrgUnitManagers["externalKey:secondary-org"])
require.Equal(t, "010-1234-5678", user.CellPhone)
require.Equal(t, "EMP001", user.EmployeeNumber)
require.Equal(t, []WorksmobileUserOrganization{
{
Primary: true,
OrgUnits: []WorksmobileUserOrgUnit{
{OrgUnitID: "externalKey:primary-org", Primary: true, IsManager: boolPtr(false)},
{OrgUnitID: "externalKey:secondary-org", Primary: false, IsManager: boolPtr(true)},
},
},
}, user.Organizations)
}
func TestParseWorksmobileDirectoryGroupExtractsMailLocalPart(t *testing.T) {
@@ -1075,6 +1088,10 @@ func TestParseWorksmobileDirectoryGroupExtractsMailLocalPart(t *testing.T) {
require.Equal(t, "tech-dev-center", group.MailLocalPart)
}
func boolPtr(value bool) *bool {
return &value
}
type fakeWorksmobileOutboxRepo struct {
recent []domain.WorksmobileOutbox
ready []domain.WorksmobileOutbox

View File

@@ -5,6 +5,7 @@ import (
"baron-sso-backend/internal/repository"
"context"
"errors"
"fmt"
"net/mail"
"os"
"sort"
@@ -1266,7 +1267,7 @@ func compareWorksmobileUsers(localUsers []domain.User, remoteUsers []Worksmobile
if !matched {
remote, matched = remoteByEmail[strings.ToLower(strings.TrimSpace(user.Email))]
}
needsUpdate := matched && worksmobileUserNeedsUpdate(user, remote)
needsUpdate := matched && worksmobileUserNeedsUpdate(user, remote, localTenants)
if matched && !includeMatched && !needsUpdate {
matchedRemoteIDs[remote.ID] = true
continue
@@ -1364,7 +1365,7 @@ func compareWorksmobileUsers(localUsers []domain.User, remoteUsers []Worksmobile
return result
}
func worksmobileUserNeedsUpdate(user domain.User, remote WorksmobileRemoteUser) bool {
func worksmobileUserNeedsUpdate(user domain.User, remote WorksmobileRemoteUser, localTenants map[string]domain.Tenant) bool {
if strings.TrimSpace(remote.ExternalID) != strings.TrimSpace(user.ID) {
return true
}
@@ -1374,12 +1375,179 @@ func worksmobileUserNeedsUpdate(user domain.User, remote WorksmobileRemoteUser)
if strings.ToLower(strings.TrimSpace(remote.Email)) != strings.ToLower(strings.TrimSpace(user.Email)) {
return true
}
if worksmobileUserPhoneNeedsUpdate(user, remote) {
return true
}
if worksmobileUserEmployeeNumberNeedsUpdate(user, remote) {
return true
}
if worksmobileUserOrganizationsNeedUpdate(user, remote, localTenants) {
return true
}
if worksmobileUserManagerNeedsUpdate(user, remote) {
return true
}
return false
}
func worksmobileUserPhoneNeedsUpdate(user domain.User, remote WorksmobileRemoteUser) bool {
localPhone := normalizeWorksmobilePhoneForCompare(user.Phone)
remotePhone := normalizeWorksmobilePhoneForCompare(remote.CellPhone)
if localPhone == "" && remotePhone == "" {
return false
}
return localPhone != remotePhone
}
func normalizeWorksmobilePhoneForCompare(value string) string {
normalized := strings.TrimSpace(value)
normalized = strings.NewReplacer("-", "", " ", "", "(", "", ")", "").Replace(normalized)
if normalized == "" {
return ""
}
if strings.HasPrefix(normalized, "010") {
return "+82" + normalized[1:]
}
if strings.HasPrefix(normalized, "82") {
return "+" + normalized
}
return normalized
}
func worksmobileUserEmployeeNumberNeedsUpdate(user domain.User, remote WorksmobileRemoteUser) bool {
localEmployeeNumber := strings.TrimSpace(metadataEmployeeNumber(user.Metadata))
remoteEmployeeNumber := strings.TrimSpace(remote.EmployeeNumber)
if localEmployeeNumber == "" && remoteEmployeeNumber == "" {
return false
}
return localEmployeeNumber != remoteEmployeeNumber
}
func worksmobileUserOrganizationsNeedUpdate(user domain.User, remote WorksmobileRemoteUser, localTenants map[string]domain.Tenant) bool {
if len(remote.Organizations) == 0 || user.TenantID == nil || localTenants == nil {
return false
}
tenantID := strings.TrimSpace(*user.TenantID)
if tenantID == "" {
return false
}
tenant, ok := localTenants[tenantID]
if !ok {
return false
}
expected, err := BuildWorksmobileUserPayloadForDomainTenants(user, tenant, localTenants, worksmobileComparisonRootConfig(localTenants))
if err != nil {
return false
}
return !worksmobileUserOrganizationsEqual(expected.Organizations, remote.Organizations)
}
func worksmobileComparisonRootConfig(localTenants map[string]domain.Tenant) domain.JSONMap {
for _, tenant := range localTenants {
if strings.TrimSpace(tenant.Slug) == HanmacFamilyTenantSlug {
return tenant.Config
}
}
return nil
}
type worksmobileComparableOrgUnit struct {
organizationPrimary bool
organizationEmail string
unitPrimary bool
positionID string
comparePosition bool
manager *bool
compareManager bool
}
func worksmobileUserOrganizationsEqual(expected []WorksmobileUserOrganization, remote []WorksmobileUserOrganization) bool {
expectedUnits := flattenExpectedWorksmobileUserOrganizations(expected)
remoteUnits := flattenRemoteWorksmobileUserOrganizations(remote)
if len(expectedUnits) != len(remoteUnits) {
return false
}
for key, expectedUnit := range expectedUnits {
remoteUnit, ok := remoteUnits[key]
if !ok {
return false
}
if expectedUnit.organizationPrimary != remoteUnit.organizationPrimary {
return false
}
if strings.ToLower(expectedUnit.organizationEmail) != strings.ToLower(remoteUnit.organizationEmail) {
return false
}
if expectedUnit.unitPrimary != remoteUnit.unitPrimary {
return false
}
if expectedUnit.comparePosition && strings.TrimSpace(expectedUnit.positionID) != strings.TrimSpace(remoteUnit.positionID) {
return false
}
if expectedUnit.compareManager && !worksmobileBoolPointersEqual(expectedUnit.manager, remoteUnit.manager) {
return false
}
}
return true
}
func flattenExpectedWorksmobileUserOrganizations(organizations []WorksmobileUserOrganization) map[string]worksmobileComparableOrgUnit {
result := map[string]worksmobileComparableOrgUnit{}
for _, organization := range organizations {
for _, orgUnit := range organization.OrgUnits {
key := worksmobileComparableOrgUnitKey(organization.DomainID, orgUnit.OrgUnitID)
if key == "" {
continue
}
result[key] = worksmobileComparableOrgUnit{
organizationPrimary: organization.Primary,
organizationEmail: strings.TrimSpace(organization.Email),
unitPrimary: orgUnit.Primary,
positionID: strings.TrimSpace(orgUnit.PositionID),
comparePosition: strings.TrimSpace(orgUnit.PositionID) != "",
manager: orgUnit.IsManager,
compareManager: orgUnit.IsManager != nil,
}
}
}
return result
}
func flattenRemoteWorksmobileUserOrganizations(organizations []WorksmobileUserOrganization) map[string]worksmobileComparableOrgUnit {
result := map[string]worksmobileComparableOrgUnit{}
for _, organization := range organizations {
for _, orgUnit := range organization.OrgUnits {
key := worksmobileComparableOrgUnitKey(organization.DomainID, orgUnit.OrgUnitID)
if key == "" {
continue
}
result[key] = worksmobileComparableOrgUnit{
organizationPrimary: organization.Primary,
organizationEmail: strings.TrimSpace(organization.Email),
unitPrimary: orgUnit.Primary,
positionID: strings.TrimSpace(orgUnit.PositionID),
manager: orgUnit.IsManager,
}
}
}
return result
}
func worksmobileComparableOrgUnitKey(domainID int64, orgUnitID string) string {
orgUnitID = strings.TrimSpace(orgUnitID)
if domainID == 0 || orgUnitID == "" {
return ""
}
return fmt.Sprintf("%d:%s", domainID, orgUnitID)
}
func worksmobileBoolPointersEqual(left, right *bool) bool {
if left == nil || right == nil {
return left == nil && right == nil
}
return *left == *right
}
func worksmobileUserManagerNeedsUpdate(user domain.User, remote WorksmobileRemoteUser) bool {
localManagers := worksmobileUserExplicitOrgUnitManagers(user)
if len(localManagers) == 0 {

View File

@@ -7,6 +7,7 @@ import (
"time"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
func TestWorksmobileSyncServiceRejectsAliasEmailAlreadyUsedByOtherUser(t *testing.T) {
@@ -1476,6 +1477,102 @@ func TestCompareWorksmobileUsersMarksSecondaryManagerChangeNeedsUpdate(t *testin
require.Equal(t, "needs_update", items[0].Status)
}
func TestCompareWorksmobileUsersMarksMissingSecondaryOrganizationNeedsUpdate(t *testing.T) {
t.Setenv("SAMAN_DOMAIN_ID", "1001")
t.Setenv("GPDTDC_DOMAIN_ID", "1003")
rootID := "tenant-root"
primaryTenantID := "tenant-saman"
gpdtdcID := "tenant-gpdtdc"
secondaryTenantID := "tenant-gpdtdc-leaf"
user := domain.User{
ID: "user-secondary-org",
Email: "secondary-org@samaneng.com",
Name: "Secondary Org User",
TenantID: &secondaryTenantID,
Status: domain.UserStatusActive,
Metadata: domain.JSONMap{
"additionalAppointments": []any{
map[string]any{
"tenantId": primaryTenantID,
"isPrimary": true,
},
map[string]any{
"tenantId": secondaryTenantID,
"isPrimary": false,
},
},
},
}
remotePrimaryManager := false
items := compareWorksmobileUsers(
[]domain.User{user},
[]WorksmobileRemoteUser{{
ID: "works-user-secondary-org",
ExternalID: user.ID,
Email: user.Email,
DisplayName: user.Name,
Organizations: []WorksmobileUserOrganization{
{
DomainID: 1001,
Email: user.Email,
Primary: true,
OrgUnits: []WorksmobileUserOrgUnit{
{
OrgUnitID: "externalKey:" + primaryTenantID,
Primary: true,
},
},
},
},
PrimaryOrgUnitID: "externalKey:" + primaryTenantID,
PrimaryOrgUnitIsManager: &remotePrimaryManager,
}},
true,
map[string]domain.Tenant{
rootID: {ID: rootID, Slug: HanmacFamilyTenantSlug, Name: "한맥가족", Type: domain.TenantTypeCompanyGroup},
primaryTenantID: {ID: primaryTenantID, Slug: "saman", Name: "삼안", Type: domain.TenantTypeCompany, ParentID: &rootID, Domains: []domain.TenantDomain{{Domain: "samaneng.com"}}},
gpdtdcID: {ID: gpdtdcID, Slug: "gpdtdc", Name: "총괄기획&기술개발센터", Type: domain.TenantTypeCompanyGroup, ParentID: &rootID},
secondaryTenantID: {ID: secondaryTenantID, Slug: "people-growth", Name: "인재성장", Type: domain.TenantTypeOrganization, ParentID: &gpdtdcID},
},
)
require.Len(t, items, 1)
require.Equal(t, "needs_update", items[0].Status)
}
func TestCompareWorksmobileUsersMarksPhoneAndEmployeeNumberChangesNeedsUpdate(t *testing.T) {
tenantID := "tenant-saman"
user := domain.User{
ID: "user-phone-employee",
Email: "phone-employee@samaneng.com",
Name: "Phone Employee User",
Phone: "010-1234-5678",
TenantID: &tenantID,
Status: domain.UserStatusActive,
Metadata: domain.JSONMap{
"employeeNumber": "EMP001",
},
}
items := compareWorksmobileUsers(
[]domain.User{user},
[]WorksmobileRemoteUser{{
ID: "works-user-phone-employee",
ExternalID: user.ID,
Email: user.Email,
DisplayName: user.Name,
CellPhone: "+821099998888",
EmployeeNumber: "EMP999",
}},
true,
map[string]domain.Tenant{
tenantID: {ID: tenantID, Name: "삼안", Type: domain.TenantTypeCompany},
},
)
require.Len(t, items, 1)
require.Equal(t, "needs_update", items[0].Status)
}
type fakeWorksmobileTenantService struct {
tenants map[string]domain.Tenant
list []domain.Tenant
@@ -1597,3 +1694,7 @@ func (f *fakeWorksmobileUserRepo) IsLoginIDTaken(ctx context.Context, loginID st
func (f *fakeWorksmobileUserRepo) FindTenantIDByLoginID(ctx context.Context, loginID string) (string, error) {
return "", nil
}
func (f *fakeWorksmobileUserRepo) DB() *gorm.DB {
return nil
}

View File

@@ -33,7 +33,7 @@ func MaskSensitiveJSON(data []byte) []byte {
return data
}
var obj interface{}
var obj any
if err := json.Unmarshal(data, &obj); err != nil {
// Not a JSON object/array, return as is
return data
@@ -48,10 +48,10 @@ func MaskSensitiveJSON(data []byte) []byte {
return result
}
func maskValue(v interface{}) interface{} {
func maskValue(v any) any {
switch val := v.(type) {
case map[string]interface{}:
newMap := make(map[string]interface{}, len(val))
case map[string]any:
newMap := make(map[string]any, len(val))
for k, v := range val {
if isSensitive(k) {
newMap[k] = "*****"
@@ -60,8 +60,8 @@ func maskValue(v interface{}) interface{} {
}
}
return newMap
case []interface{}:
newArr := make([]interface{}, len(val))
case []any:
newArr := make([]any, len(val))
for i, v := range val {
newArr[i] = maskValue(v)
}

View File

@@ -4,6 +4,8 @@ import (
"baron-sso-backend/internal/domain"
"crypto/rand"
"fmt"
"slices"
"strings"
)
const (
@@ -111,13 +113,7 @@ func GeneratePasswordWithPolicy(policy *domain.PasswordPolicy) (string, error) {
if additionalTypes > 0 {
pool := make([]string, 0, len(selected))
for _, cat := range selected {
isRequired := false
for _, req := range required {
if req == cat {
isRequired = true
break
}
}
isRequired := slices.Contains(required, cat)
if !isRequired {
pool = append(pool, cat)
}
@@ -150,12 +146,12 @@ func GeneratePasswordWithPolicy(policy *domain.PasswordPolicy) (string, error) {
passwordRunes = append(passwordRunes, ch)
}
combined := ""
var combined strings.Builder
for _, charset := range selected {
combined += charset
combined.WriteString(charset)
}
for len(passwordRunes) < minLength {
ch, err := randomChar(combined)
ch, err := randomChar(combined.String())
if err != nil {
return "", err
}

View File

@@ -8,7 +8,7 @@ import (
)
// ValidateIDPCompatibility checks if the provided IDP supports all required fields defined in the BrokerUser model.
func ValidateIDPCompatibility(brokerModel interface{}, idp domain.IdentityProvider) error {
func ValidateIDPCompatibility(brokerModel any, idp domain.IdentityProvider) error {
metadata, err := idp.GetMetadata()
if err != nil {
return fmt.Errorf("failed to fetch metadata from IDP %s: %w", idp.Name(), err)
@@ -20,12 +20,12 @@ func ValidateIDPCompatibility(brokerModel interface{}, idp domain.IdentityProvid
}
t := reflect.TypeOf(brokerModel)
if t.Kind() == reflect.Ptr {
if t.Kind() == reflect.Pointer {
t = t.Elem()
}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
for field := range t.Fields() {
field := field
// Check "required" tag
isRequired := field.Tag.Get("required") == "true"
@@ -47,8 +47,8 @@ func ValidateIDPCompatibility(brokerModel interface{}, idp domain.IdentityProvid
if fieldName == "attributes" {
reqKeys := field.Tag.Get("required_keys")
if reqKeys != "" {
keys := strings.Split(reqKeys, ",")
for _, key := range keys {
keys := strings.SplitSeq(reqKeys, ",")
for key := range keys {
key = strings.TrimSpace(key)
if !supportedMap[key] {
return fmt.Errorf("IDP %s does not support required custom attribute: %s", idp.Name(), key)

View File

@@ -188,6 +188,9 @@ active = "Active"
blocked = "Blocked"
failure = "Failure"
inactive = "Inactive"
new = "New"
ok = "Ok"
pending = "Pending"
success = "Success"
unchanged = "Unchanged"
updated = "Updated"

View File

@@ -188,6 +188,9 @@ active = "활성"
blocked = "차단됨"
failure = "실패"
inactive = "비활성"
new = "신규"
ok = "정상"
pending = "준비 중"
success = "성공"
unchanged = "동일"
updated = "수정"

View File

@@ -188,6 +188,9 @@ active = ""
blocked = ""
failure = ""
inactive = ""
new = ""
ok = ""
pending = ""
success = ""
unchanged = ""
updated = ""

View File

@@ -55,6 +55,7 @@ test.describe("DevFront relationships", () => {
] satisfies ClientRelation[],
},
auditLogsByCursor: undefined,
mockRole: "super_admin",
};
await installDevApiMock(page, state);

View File

@@ -115,8 +115,11 @@ export type DevApiMockState = {
onRotateSecret?: (newSecret: string) => void;
onRefreshHeadlessJwks?: (clientId: string) => void;
onRevokeHeadlessJwksCache?: (clientId: string) => void;
mockRole?: string;
};
const seededRoles = new WeakMap<Page, string>();
export function makeClient(
id: string,
overrides: Partial<Client> = {},
@@ -137,6 +140,7 @@ export function makeClient(
export async function seedAuth(page: Page, role?: string) {
const nowInSeconds = Math.floor(Date.now() / 1000);
seededRoles.set(page, role || "rp_admin");
await page.addInitScript(
({ issuedAt, injectedRole }) => {
@@ -225,11 +229,8 @@ function parseClientId(pathname: string): string {
}
export async function installDevApiMock(page: Page, state: DevApiMockState) {
const readMockRole = async () =>
(
(await page.evaluate(() => window.localStorage.getItem("dev_role"))) ??
"rp_admin"
).trim();
const readMockRole = () =>
(state.mockRole ?? seededRoles.get(page) ?? "rp_admin").trim();
const buildSelfConfigEditorRelation = (): ClientRelation => ({
relation: "config_editor",
@@ -250,7 +251,7 @@ export async function installDevApiMock(page: Page, state: DevApiMockState) {
return explicitRelations;
}
const role = await readMockRole();
const role = readMockRole();
if (!shouldGrantDefaultEditRelation(role)) {
return [];
}
@@ -282,9 +283,7 @@ export async function installDevApiMock(page: Page, state: DevApiMockState) {
};
await page.route("**/api/v1/user/me", async (route) => {
const storedRole =
(await page.evaluate(() => window.localStorage.getItem("dev_role"))) ??
"rp_admin";
const storedRole = readMockRole();
return json(route, {
id: "playwright-user",
loginId: "playwright@example.com",

View File

@@ -1739,6 +1739,17 @@ additional = "Additional Affiliated/Manageable Tenants"
primary = "Representative Affiliated Tenant"
title = "Affiliation & Organization Info"
[ui.admin.users.field]
department = "Department"
grade = "Grade"
jobtitle = "Job Title"
name = "Name"
phone = "Phone"
position = "Position"
role = "Role"
status = "Status"
tenant = "Tenant"
[ui.admin.users.list]
add = "User Add"
bulk_import = "Bulk Import"
@@ -2878,6 +2889,8 @@ title = "Login request status by company and app"
export = "Export"
[ui.admin.users.bulk]
modified_fields = "Modified Fields:"
no_changes = "No changes"
permission_placeholder = "Select permission"
status_placeholder = "Select status"

View File

@@ -2203,6 +2203,17 @@ additional = "추가 소속/관리 테넌트"
primary = "대표 소속 테넌트"
title = "소속 및 조직 정보"
[ui.admin.users.field]
department = "부서"
grade = "직급"
jobtitle = "직무"
name = "이름"
phone = "전화번호"
position = "직책"
role = "역할"
status = "상태"
tenant = "테넌트"
[ui.admin.users.list]
add = "사용자 추가"
bulk_import = "일괄 임포트"
@@ -3300,6 +3311,8 @@ title = "회사별 앱별 로그인 요청 현황"
export = "내보내기"
[ui.admin.users.bulk]
modified_fields = "수정 항목:"
no_changes = "변경 사항 없음"
permission_placeholder = "권한 선택"
status_placeholder = "상태 선택"

View File

@@ -1782,8 +1782,10 @@ acknowledge_warning = ""
create_missing_tenant = ""
do_move = ""
download_template = ""
modified_fields = ""
move_group = ""
move_title = ""
no_changes = ""
no_department = ""
schema_warning = ""
select_group = ""
@@ -2082,6 +2084,17 @@ additional = ""
primary = ""
title = ""
[ui.admin.users.field]
department = ""
grade = ""
jobtitle = ""
name = ""
phone = ""
position = ""
role = ""
status = ""
tenant = ""
[ui.admin.users.list]
add = ""
bulk_import = ""

View File

@@ -1,93 +0,0 @@
# 멀티 IDP 아키텍처 및 마이그레이션 전략
본 문서는 Primary IDP 변경(예: Descope → Hydra/Authentik) 시 시스템의 유연성을 보장하기 위한 아키텍처 설계 전략을 기술합니다.
## 핵심 전략
1. **Broker 패턴 고도화**: 백엔드가 모든 인증 요청을 중계하며, 클라이언트는 특정 IDP에 종속되지 않습니다.
2. **추상화 계층 (Abstraction Layer)**: 비즈니스 로직은 `IdentityProvider` 인터페이스에만 의존하며, 구체적인 구현체(Descope, Hydra 등)는 알 필요가 없습니다.
3. **식별자 분리 (Identifier Decoupling)**: 외부 IDP의 `sub` 값과 내부 시스템의 `user_id`를 분리하여 매핑합니다.
## 상세 설계
### 1. IdentityProvider 인터페이스 확장
단순 메타데이터 조회를 넘어, 인증의 핵심 라이프사이클을 모두 포함하도록 인터페이스를 확장해야 합니다.
```go
type IdentityProvider interface {
// 메타데이터 및 스키마 검증
Name() string
GetMetadata() (*IDPMetadata, error)
// 핵심 인증/인가 기능
SignUp(ctx context.Context, user *BrokerUser, password string) (*AuthResult, error)
Login(ctx context.Context, loginID, password string) (*AuthResult, error)
VerifyToken(ctx context.Context, token string) (*TokenInfo, error)
// 사용자 관리
GetUser(ctx context.Context, id string) (*BrokerUser, error)
UpdateUser(ctx context.Context, user *BrokerUser) error
DeleteUser(ctx context.Context, id string) error
}
```
### 2. Provider Factory 패턴
설정(`config.yaml` 또는 환경변수)에 따라 사용할 IDP 구현체를 런타임에 결정합니다.
```go
func NewIdentityProvider(config Config) (domain.IdentityProvider, error) {
switch config.IDPType {
case "descope":
return service.NewDescopeProvider(config.Descope)
case "hydra":
return service.NewHydraProvider(config.Hydra)
case "authentik":
return service.NewAuthentikProvider(config.Authentik)
default:
return nil, fmt.Errorf("unsupported IDP type: %s", config.IDPType)
}
}
```
### 3. 식별자 매핑 (ID Mapping)
IDP 변경 시 가장 큰 문제는 사용자 고유 ID(`sub`)가 바뀌는 것입니다. 이를 해결하기 위해 Baron SSO 내부 전용 UUID를 사용하고 매핑 테이블을 둡니다.
* **User Table (Baron Internal)**: `id` (UUID), `email`, ...
* **IDP Link Table**: `baron_user_id`, `idp_provider` (e.g., descope), `idp_subject_id` (e.g., U12345)
## 구현 예시 (Descope)
현재 단계에서 즉시 사용 가능한 `DescopeProvider`의 구현 예시입니다.
```go
// DescopeProvider는 IdentityProvider 인터페이스를 구현합니다.
type DescopeProvider struct {
Client *client.DescopeClient
}
func (d *DescopeProvider) SignUp(ctx context.Context, user *domain.BrokerUser, password string) (*domain.AuthResult, error) {
// BrokerUser를 Descope User 객체로 변환
descopeUser := &descope.User{
Name: user.Name,
Email: user.Email,
Phone: user.PhoneNumber,
CustomAttributes: user.Attributes,
}
// SDK 호출
authInfo, err := d.Client.Auth.Password().SignUp(ctx, user.Email, descopeUser, password)
if err != nil {
return nil, err\n }
// 결과 반환
return &domain.AuthResult{
UserID: authInfo.User.UserID,
Token: authInfo.SessionToken.JWT,
}, nil
}
```
## 향후 지원 후보 (Candidates)
* **Ory Hydra**: 자체적인 OAuth2/OIDC 서버 구축이 필요할 때 적합. 높은 커스터마이징 가능.
* **Authentik**: 오픈소스 IDP로, 설치형(Self-hosted) 환경에서 강력한 기능을 제공.

View File

@@ -45,10 +45,10 @@ packages:
dependency: transitive
description:
name: characters
sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803
sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b
url: "https://pub.dev"
source: hosted
version: "1.4.0"
version: "1.4.1"
cli_config:
dependency: transitive
description:
@@ -268,14 +268,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.5"
js:
dependency: transitive
description:
name: js
sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc"
url: "https://pub.dev"
source: hosted
version: "0.7.2"
leak_tracker:
dependency: transitive
description:
@@ -328,18 +320,18 @@ packages:
dependency: transitive
description:
name: matcher
sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861
url: "https://pub.dev"
source: hosted
version: "0.12.17"
version: "0.12.19"
material_color_utilities:
dependency: transitive
description:
name: material_color_utilities
sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec
sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b"
url: "https://pub.dev"
source: hosted
version: "0.11.1"
version: "0.13.0"
meta:
dependency: transitive
description:
@@ -661,26 +653,26 @@ packages:
dependency: transitive
description:
name: test
sha256: "75906bf273541b676716d1ca7627a17e4c4070a3a16272b7a3dc7da3b9f3f6b7"
sha256: "280d6d890011ca966ad08df7e8a4ddfab0fb3aa49f96ed6de56e3521347a9ae7"
url: "https://pub.dev"
source: hosted
version: "1.26.3"
version: "1.30.0"
test_api:
dependency: transitive
description:
name: test_api
sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55
sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a"
url: "https://pub.dev"
source: hosted
version: "0.7.7"
version: "0.7.10"
test_core:
dependency: transitive
description:
name: test_core
sha256: "0cc24b5ff94b38d2ae73e1eb43cc302b77964fbf67abad1e296025b78deb53d0"
sha256: "0381bd1585d1a924763c308100f2138205252fb90c9d4eeaf28489ee65ccde51"
url: "https://pub.dev"
source: hosted
version: "0.6.12"
version: "0.6.16"
toml:
dependency: "direct main"
description: