1
0
forked from baron/baron-sso

테넌트 접속 제한 백엔드 로직 수정

This commit is contained in:
2026-04-28 09:55:37 +09:00
parent 3f85f6cfe3
commit 367368805a
6 changed files with 107 additions and 61 deletions

View File

@@ -5132,10 +5132,8 @@ func (h *AuthHandler) GetConsentRequest(c *fiber.Ctx) error {
) )
profile, err := h.resolveCurrentProfile(c) profile, err := h.resolveCurrentProfile(c)
if err == nil && profile != nil { if tenantErr := enforceClientTenantAccess(c, consentRequest.Client, profile, err); tenantErr != nil {
if !isClientTenantAccessAllowed(profile, consentRequest.Client) { return tenantErr
return tenantNotAllowedError(c)
}
} }
// [New] 로컬 DB에서 기존 동의 내역 확인 (강제 자동 승인 전략) // [New] 로컬 DB에서 기존 동의 내역 확인 (강제 자동 승인 전략)
@@ -5344,10 +5342,8 @@ func (h *AuthHandler) AcceptConsentRequest(c *fiber.Ctx) error {
consentRequest.RequestedScope = mergeRequestedScopesWithClientRequirements(consentRequest.Client, consentRequest.RequestedScope) consentRequest.RequestedScope = mergeRequestedScopesWithClientRequirements(consentRequest.Client, consentRequest.RequestedScope)
profile, err := h.resolveCurrentProfile(c) profile, err := h.resolveCurrentProfile(c)
if err == nil && profile != nil { if tenantErr := enforceClientTenantAccess(c, consentRequest.Client, profile, err); tenantErr != nil {
if !isClientTenantAccessAllowed(profile, consentRequest.Client) { return tenantErr
return tenantNotAllowedError(c)
}
} }
// 3. Hydra에 승인 요청 // 3. Hydra에 승인 요청
@@ -5489,10 +5485,8 @@ func (h *AuthHandler) AcceptOidcLoginRequest(c *fiber.Ctx) error {
profile, err := h.resolveCurrentProfile(c) profile, err := h.resolveCurrentProfile(c)
if loginReq != nil { if loginReq != nil {
if err == nil && profile != nil { if tenantErr := enforceClientTenantAccess(c, loginReq.Client, profile, err); tenantErr != nil {
if !isClientTenantAccessAllowed(profile, loginReq.Client) { return tenantErr
return tenantNotAllowedError(c)
}
} }
} }

View File

@@ -82,6 +82,7 @@ func TestGetConsentRequest_AddsMandatoryTenantScope(t *testing.T) {
"client_name": "Test App", "client_name": "Test App",
"metadata": map[string]any{ "metadata": map[string]any{
"tenant_access_restricted": true, "tenant_access_restricted": true,
"allowed_tenants": []string{"tenant-allow"},
"structured_scopes": []map[string]any{ "structured_scopes": []map[string]any{
{"name": "openid", "mandatory": true}, {"name": "openid", "mandatory": true},
{"name": "tenant", "mandatory": true, "locked": true}, {"name": "tenant", "mandatory": true, "locked": true},
@@ -108,6 +109,8 @@ func TestGetConsentRequest_AddsMandatoryTenantScope(t *testing.T) {
app := newConsentTestApp(h) app := newConsentTestApp(h)
req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/consent?consent_challenge=challenge-tenant-scope", nil) req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/consent?consent_challenge=challenge-tenant-scope", nil)
req.Header.Set("X-Mock-Role", "user")
req.Header.Set("X-Tenant-ID", "tenant-allow")
resp, err := app.Test(req) resp, err := app.Test(req)
assert.NoError(t, err) assert.NoError(t, err)
@@ -270,6 +273,7 @@ func TestAcceptConsentRequest_EnforcesMandatoryTenantScope(t *testing.T) {
"metadata": map[string]any{ "metadata": map[string]any{
"tenant_id": "tenant-abc", "tenant_id": "tenant-abc",
"tenant_access_restricted": true, "tenant_access_restricted": true,
"allowed_tenants": []string{"tenant-abc"},
"structured_scopes": []map[string]any{ "structured_scopes": []map[string]any{
{"name": "openid", "mandatory": true}, {"name": "openid", "mandatory": true},
{"name": "tenant", "mandatory": true, "locked": true}, {"name": "tenant", "mandatory": true, "locked": true},
@@ -327,6 +331,8 @@ func TestAcceptConsentRequest_EnforcesMandatoryTenantScope(t *testing.T) {
}) })
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/consent/accept", bytes.NewReader(body)) req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/consent/accept", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Mock-Role", "user")
req.Header.Set("X-Tenant-ID", "tenant-abc")
resp, err := app.Test(req) resp, err := app.Test(req)
assert.NoError(t, err) assert.NoError(t, err)

View File

@@ -144,6 +144,19 @@ func isClientTenantAccessAllowed(profile *domain.UserProfileResponse, client dom
return clientTenantAccessAllowed(profile, client) return clientTenantAccessAllowed(profile, client)
} }
func enforceClientTenantAccess(c *fiber.Ctx, client domain.HydraClient, profile *domain.UserProfileResponse, resolveErr error) error {
if !clientTenantAccessRestricted(client.Metadata) {
return nil
}
if resolveErr != nil || profile == nil {
return tenantNotAllowedError(c)
}
if !clientTenantAccessAllowed(profile, client) {
return tenantNotAllowedError(c)
}
return nil
}
type clientStructuredScope struct { type clientStructuredScope struct {
Name string `json:"name"` Name string `json:"name"`
Mandatory bool `json:"mandatory"` Mandatory bool `json:"mandatory"`

View File

@@ -181,37 +181,27 @@ func TestGetConsentRequest_DeniesTenantAccess(t *testing.T) {
} }
app := fiber.New() app := fiber.New()
tenantID := "tenant-a"
app.Use(func(c *fiber.Ctx) error {
c.Locals("user_profile", &domain.UserProfileResponse{
ID: "user-123",
Role: domain.RoleUser,
TenantID: &tenantID,
})
return c.Next()
})
app.Get("/api/v1/auth/consent", h.GetConsentRequest) app.Get("/api/v1/auth/consent", h.GetConsentRequest)
req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/consent?consent_challenge=challenge-tenant", nil) req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/consent?consent_challenge=challenge-tenant", nil)
req.Header.Set("Cookie", "ory_kratos_session=session-1") req.Header.Set("X-Mock-Role", "user")
req.Header.Set("X-Tenant-ID", "tenant-a")
resp, err := app.Test(req) resp, err := app.Test(req)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, http.StatusForbidden, resp.StatusCode) assert.Equal(t, http.StatusForbidden, resp.StatusCode)
bodyBytes, _ := io.ReadAll(resp.Body)
var body map[string]any
assert.NoError(t, json.Unmarshal(bodyBytes, &body))
assert.Equal(t, "tenant_not_allowed", body["code"])
} }
func TestAcceptOidcLoginRequest_DeniesTenantAccess(t *testing.T) { func TestGetConsentRequest_DeniesRestrictedClientWhenProfileResolutionFails(t *testing.T) {
acceptCalled := false
transport := roundTripFunc(func(r *http.Request) (*http.Response, error) { transport := roundTripFunc(func(r *http.Request) (*http.Response, error) {
switch { switch {
case r.URL.Path == "/oauth2/auth/requests/login" && r.URL.Query().Get("login_challenge") == "login-tenant": case r.URL.Path == "/oauth2/auth/requests/consent" && r.URL.Query().Get("consent_challenge") == "challenge-profile-missing":
return httpJSONAny(r, http.StatusOK, map[string]any{ return httpJSONAny(r, http.StatusOK, map[string]any{
"challenge": "login-tenant", "challenge": "challenge-profile-missing",
"subject": "user-123", "requested_scope": []string{"openid", "profile"},
"skip": false,
"subject": "user-123",
"client": map[string]any{ "client": map[string]any{
"client_id": "client-tenant", "client_id": "client-tenant",
"metadata": map[string]any{ "metadata": map[string]any{
@@ -220,15 +210,10 @@ func TestAcceptOidcLoginRequest_DeniesTenantAccess(t *testing.T) {
}, },
}, },
}), nil }), nil
case r.URL.Host == "kratos.test" && r.URL.Path == "/sessions/whoami": case r.URL.Path == "/oauth2/auth/requests/consent/accept":
acceptCalled = true
return httpJSONAny(r, http.StatusOK, map[string]any{ return httpJSONAny(r, http.StatusOK, map[string]any{
"identity": map[string]any{ "redirect_to": "http://rp/cb",
"id": "user-123",
"traits": map[string]any{
"email": "user@test.com",
"tenant_id": "tenant-a",
},
},
}), nil }), nil
default: default:
return httpJSONAny(r, http.StatusNotFound, nil), nil return httpJSONAny(r, http.StatusNotFound, nil), nil
@@ -247,33 +232,50 @@ func TestAcceptOidcLoginRequest_DeniesTenantAccess(t *testing.T) {
AdminURL: "http://hydra.test", AdminURL: "http://hydra.test",
HTTPClient: client, HTTPClient: client,
}, },
ConsentRepo: &mockConsentRepo{
consents: []domain.ClientConsent{
{
ClientID: "client-tenant",
Subject: "user-123",
GrantedScopes: []string{"openid", "profile"},
},
},
},
} }
app := fiber.New() app := fiber.New()
tenantID := "tenant-a" app.Get("/api/v1/auth/consent", h.GetConsentRequest)
app.Use(func(c *fiber.Ctx) error {
c.Locals("user_profile", &domain.UserProfileResponse{
ID: "user-123",
Role: domain.RoleUser,
TenantID: &tenantID,
})
return c.Next()
})
app.Post("/api/v1/auth/oidc/login/accept", h.AcceptOidcLoginRequest)
reqBody, _ := json.Marshal(map[string]any{ req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/consent?consent_challenge=challenge-profile-missing", nil)
"login_challenge": "login-tenant", req.Header.Set("Cookie", "ory_kratos_session=invalid-session")
})
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oidc/login/accept", bytes.NewReader(reqBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Cookie", "ory_kratos_session=session-1")
resp, err := app.Test(req) resp, err := app.Test(req)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, http.StatusForbidden, resp.StatusCode) assert.Equal(t, http.StatusForbidden, resp.StatusCode)
assert.False(t, acceptCalled)
bodyBytes, _ := io.ReadAll(resp.Body) }
var body map[string]any
assert.NoError(t, json.Unmarshal(bodyBytes, &body)) func TestAcceptOidcLoginRequest_DeniesTenantAccess(t *testing.T) {
assert.Equal(t, "tenant_not_allowed", body["code"]) app := fiber.New()
app.Get("/deny", func(c *fiber.Ctx) error {
tenantID := "tenant-a"
profile := &domain.UserProfileResponse{
ID: "user-123",
Role: domain.RoleUser,
TenantID: &tenantID,
}
client := domain.HydraClient{
ClientID: "client-tenant",
Metadata: map[string]any{
"tenant_access_restricted": true,
"allowed_tenants": []string{"tenant-b"},
},
}
return enforceClientTenantAccess(c, client, profile, nil)
})
req := httptest.NewRequest(http.MethodGet, "/deny", nil)
resp, err := app.Test(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
} }

View File

@@ -29,7 +29,7 @@ func NewClientConsentRepository(db *gorm.DB) ClientConsentRepository {
func (r *clientConsentRepo) Find(ctx context.Context, clientID, subject string) (*domain.ClientConsent, error) { func (r *clientConsentRepo) Find(ctx context.Context, clientID, subject string) (*domain.ClientConsent, error) {
var consent domain.ClientConsent var consent domain.ClientConsent
err := r.db.WithContext(ctx).Unscoped(). err := r.db.WithContext(ctx).
Where("client_id = ? AND subject = ?", clientID, subject). Where("client_id = ? AND subject = ?", clientID, subject).
First(&consent).Error First(&consent).Error
if err != nil { if err != nil {

View File

@@ -0,0 +1,31 @@
package repository
import (
"baron-sso-backend/internal/domain"
"context"
"testing"
"github.com/lib/pq"
"github.com/stretchr/testify/assert"
)
func TestClientConsentRepository_Find_IgnoresSoftDeletedConsent(t *testing.T) {
repo := NewClientConsentRepository(testDB)
ctx := context.Background()
consent := &domain.ClientConsent{
ClientID: "client-soft-delete",
Subject: "user-soft-delete",
GrantedScopes: pq.StringArray{"openid", "profile"},
}
err := repo.Upsert(ctx, consent)
assert.NoError(t, err)
err = repo.Delete(ctx, consent.Subject, consent.ClientID)
assert.NoError(t, err)
found, err := repo.Find(ctx, consent.ClientID, consent.Subject)
assert.NoError(t, err)
assert.Nil(t, found)
}