forked from baron/baron-sso
342 lines
11 KiB
Go
342 lines
11 KiB
Go
package handler
|
|
|
|
import (
|
|
"baron-sso-backend/internal/service"
|
|
"bytes"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/mock"
|
|
)
|
|
|
|
// --- Test Helpers ---
|
|
|
|
func newConsentTestApp(h *AuthHandler) *fiber.App {
|
|
app := fiber.New()
|
|
app.Get("/api/v1/auth/consent", h.GetConsentRequest)
|
|
app.Post("/api/v1/auth/consent/accept", h.AcceptConsentRequest)
|
|
return app
|
|
}
|
|
|
|
// --- Tests ---
|
|
|
|
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{}{
|
|
"challenge": "challenge-123",
|
|
"requested_scope": []string{"openid", "profile"},
|
|
"skip": false,
|
|
"subject": "user-123",
|
|
"client": map[string]interface{}{
|
|
"client_id": "client-app",
|
|
"client_name": "Test App",
|
|
},
|
|
}), nil
|
|
}
|
|
return httpResponse(r, http.StatusNotFound, "not found"), nil
|
|
})
|
|
|
|
client := &http.Client{Transport: transport}
|
|
|
|
origDefault := http.DefaultClient
|
|
http.DefaultClient = client
|
|
defer func() { http.DefaultClient = origDefault }()
|
|
|
|
h := &AuthHandler{
|
|
Hydra: &service.HydraAdminService{
|
|
AdminURL: "http://hydra.test",
|
|
HTTPClient: client,
|
|
},
|
|
}
|
|
app := newConsentTestApp(h)
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/consent?consent_challenge=challenge-123", nil)
|
|
resp, err := app.Test(req)
|
|
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
|
|
|
var body map[string]interface{}
|
|
json.NewDecoder(resp.Body).Decode(&body)
|
|
|
|
assert.Equal(t, "challenge-123", body["challenge"])
|
|
assert.Equal(t, false, body["skip"])
|
|
}
|
|
|
|
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{}{
|
|
"challenge": "challenge-tenant-scope",
|
|
"requested_scope": []string{"openid", "profile"},
|
|
"skip": false,
|
|
"subject": "user-123",
|
|
"client": map[string]interface{}{
|
|
"client_id": "client-app",
|
|
"client_name": "Test App",
|
|
"metadata": map[string]any{
|
|
"tenant_access_restricted": true,
|
|
"allowed_tenants": []string{"tenant-allow"},
|
|
"structured_scopes": []map[string]any{
|
|
{"name": "openid", "mandatory": true},
|
|
{"name": "tenant", "mandatory": true, "locked": true},
|
|
{"name": "profile", "mandatory": false},
|
|
},
|
|
},
|
|
},
|
|
}), nil
|
|
}
|
|
return httpResponse(r, http.StatusNotFound, "not found"), nil
|
|
})
|
|
|
|
client := &http.Client{Transport: transport}
|
|
origDefault := http.DefaultClient
|
|
http.DefaultClient = client
|
|
defer func() { http.DefaultClient = origDefault }()
|
|
|
|
h := &AuthHandler{
|
|
Hydra: &service.HydraAdminService{
|
|
AdminURL: "http://hydra.test",
|
|
HTTPClient: client,
|
|
},
|
|
}
|
|
app := newConsentTestApp(h)
|
|
|
|
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)
|
|
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
|
|
|
var body map[string]interface{}
|
|
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, true, tenantDetail["mandatory"])
|
|
}
|
|
|
|
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{}{
|
|
"challenge": "challenge-skip",
|
|
"requested_scope": []string{"openid"},
|
|
"skip": true,
|
|
"subject": "user-123",
|
|
"client": map[string]interface{}{
|
|
"client_id": "client-app",
|
|
},
|
|
}), nil
|
|
}
|
|
// Kratos: Get Identity
|
|
if r.URL.Path == "/admin/identities/user-123" {
|
|
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
|
"id": "user-123",
|
|
"traits": map[string]interface{}{
|
|
"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{}{
|
|
"redirect_to": "http://rp/cb",
|
|
}), nil
|
|
}
|
|
return httpResponse(r, http.StatusNotFound, "not found"), nil
|
|
})
|
|
|
|
client := &http.Client{Transport: transport}
|
|
origDefault := http.DefaultClient
|
|
http.DefaultClient = client
|
|
defer func() { http.DefaultClient = origDefault }()
|
|
|
|
consentRepo := &mockConsentRepo{}
|
|
|
|
h := &AuthHandler{
|
|
Hydra: &service.HydraAdminService{
|
|
AdminURL: "http://hydra.test",
|
|
HTTPClient: client,
|
|
},
|
|
KratosAdmin: new(MockKratosAdminService), // Reusing MockKratosAdminService if defined or use MockKratosAdminServiceShared
|
|
ConsentRepo: consentRepo,
|
|
}
|
|
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
|
|
ID: "user-123",
|
|
Traits: map[string]interface{}{
|
|
"email": "user@test.com",
|
|
},
|
|
}, nil)
|
|
|
|
app := newConsentTestApp(h)
|
|
req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/consent?consent_challenge=challenge-skip", nil)
|
|
|
|
resp, err := app.Test(req)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
|
|
|
var body map[string]interface{}
|
|
json.NewDecoder(resp.Body).Decode(&body)
|
|
assert.Equal(t, "http://rp/cb", body["redirectTo"])
|
|
}
|
|
|
|
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{}{
|
|
"challenge": "challenge-accept",
|
|
"requested_scope": []string{"openid", "profile"},
|
|
"subject": "user-123",
|
|
"client": map[string]interface{}{
|
|
"client_id": "client-app",
|
|
},
|
|
}), nil
|
|
}
|
|
if r.URL.Path == "/admin/identities/user-123" {
|
|
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
|
"id": "user-123",
|
|
"traits": map[string]interface{}{
|
|
"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{}{
|
|
"redirect_to": "http://rp/cb",
|
|
}), nil
|
|
}
|
|
return httpResponse(r, http.StatusNotFound, "not found"), nil
|
|
})
|
|
|
|
client := &http.Client{Transport: transport}
|
|
origDefault := http.DefaultClient
|
|
http.DefaultClient = client
|
|
defer func() { http.DefaultClient = origDefault }()
|
|
|
|
auditRepo := &mockAuditRepo{}
|
|
consentRepo := &mockConsentRepo{}
|
|
|
|
h := &AuthHandler{
|
|
Hydra: &service.HydraAdminService{
|
|
AdminURL: "http://hydra.test",
|
|
HTTPClient: client,
|
|
},
|
|
KratosAdmin: new(MockKratosAdminService),
|
|
AuditRepo: auditRepo,
|
|
ConsentRepo: consentRepo,
|
|
}
|
|
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
|
|
ID: "user-123",
|
|
Traits: map[string]interface{}{
|
|
"email": "user@test.com",
|
|
},
|
|
}, nil)
|
|
|
|
app := newConsentTestApp(h)
|
|
|
|
body, _ := json.Marshal(map[string]interface{}{
|
|
"consent_challenge": "challenge-accept",
|
|
"grant_scope": []string{"openid"},
|
|
})
|
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/consent/accept", bytes.NewReader(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := app.Test(req)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
|
|
|
assert.Equal(t, 1, len(auditRepo.logs))
|
|
}
|
|
|
|
func TestAcceptConsentRequest_EnforcesMandatoryTenantScope(t *testing.T) {
|
|
var capturedGrantScopes []string
|
|
|
|
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{}{
|
|
"challenge": "challenge-tenant-accept",
|
|
"requested_scope": []string{"openid", "profile"},
|
|
"subject": "user-123",
|
|
"client": map[string]interface{}{
|
|
"client_id": "client-app",
|
|
"metadata": map[string]any{
|
|
"tenant_id": "tenant-abc",
|
|
"tenant_access_restricted": true,
|
|
"allowed_tenants": []string{"tenant-abc"},
|
|
"structured_scopes": []map[string]any{
|
|
{"name": "openid", "mandatory": true},
|
|
{"name": "tenant", "mandatory": true, "locked": true},
|
|
{"name": "profile", "mandatory": false},
|
|
},
|
|
},
|
|
},
|
|
}), nil
|
|
}
|
|
if r.URL.Path == "/admin/identities/user-123" {
|
|
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
|
"id": "user-123",
|
|
"traits": map[string]interface{}{
|
|
"email": "user@test.com",
|
|
},
|
|
}), nil
|
|
}
|
|
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{}) {
|
|
capturedGrantScopes = append(capturedGrantScopes, scope.(string))
|
|
}
|
|
return httpJSONAny(r, http.StatusOK, map[string]interface{}{
|
|
"redirect_to": "http://rp/cb",
|
|
}), nil
|
|
}
|
|
return httpResponse(r, http.StatusNotFound, "not found"), nil
|
|
})
|
|
|
|
client := &http.Client{Transport: transport}
|
|
origDefault := http.DefaultClient
|
|
http.DefaultClient = client
|
|
defer func() { http.DefaultClient = origDefault }()
|
|
|
|
h := &AuthHandler{
|
|
Hydra: &service.HydraAdminService{
|
|
AdminURL: "http://hydra.test",
|
|
HTTPClient: client,
|
|
},
|
|
KratosAdmin: new(MockKratosAdminService),
|
|
}
|
|
h.KratosAdmin.(*MockKratosAdminService).On("GetIdentity", mock.Anything, "user-123").Return(&service.KratosIdentity{
|
|
ID: "user-123",
|
|
Traits: map[string]interface{}{
|
|
"email": "user@test.com",
|
|
},
|
|
}, nil)
|
|
|
|
app := newConsentTestApp(h)
|
|
|
|
body, _ := json.Marshal(map[string]interface{}{
|
|
"consent_challenge": "challenge-tenant-accept",
|
|
"grant_scope": []string{"openid", "profile"},
|
|
})
|
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/consent/accept", bytes.NewReader(body))
|
|
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)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
|
assert.Equal(t, []string{"openid", "tenant", "profile"}, capturedGrantScopes)
|
|
}
|