ae1831e61f
- Rename user_id → users_id across all models, handlers, services, and tests
- Add custom RoleIDs type supporting string/int/array unmarshaling (e.g., "1", 1, [1])
- Implement flexible JSON unmarshaling for JWT Claims to handle field name variants
- Support both user_id/users_id and email/email_address field names
- Enable role_id as string ("1"), int (1), or array ([1,2])
- Update AuthorizationContext to handle role_id type flexibility
- Add comprehensive logging to repository, service, and handler layers
- Entry/exit logs with full context
- Success (✓) and failure (✗) indicators
- Step-by-step authorization flow tracking
- Add containsRole helper for multi-role membership checks
- Fix database queries: user_id → users_id, id → permissions_id
- Update all tests to use models.RoleIDs{} syntax
- Change GetRole middleware return type: string → []int
- Maintain backward compatibility with legacy JWT tokens
This change improves integration with external services (MIS) that may send
role_id in different formats and standardizes field naming conventions
throughout the authorization microservice.
233 lines
7.6 KiB
Go
233 lines
7.6 KiB
Go
package services
|
|
|
|
import (
|
|
"authorization/db"
|
|
"authorization/models"
|
|
"errors"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/DATA-DOG/go-sqlmock"
|
|
)
|
|
|
|
func setupMockDB(t *testing.T) (sqlmock.Sqlmock, func()) {
|
|
mockDB, mock, err := sqlmock.New()
|
|
if err != nil {
|
|
t.Fatalf("Failed to create mock database: %v", err)
|
|
}
|
|
|
|
originalDB := db.DB
|
|
db.DB = mockDB
|
|
|
|
cleanup := func() {
|
|
db.DB = originalDB
|
|
mockDB.Close()
|
|
}
|
|
|
|
return mock, cleanup
|
|
}
|
|
|
|
func TestAuthorize_PermissionNotFound(t *testing.T) {
|
|
mock, cleanup := setupMockDB(t)
|
|
defer cleanup()
|
|
|
|
ctx := &models.AuthorizationContext{
|
|
UsersID: "user123",
|
|
Resource: "nonexistent",
|
|
Action: "read",
|
|
ResourceData: make(map[string]string),
|
|
Environment: make(map[string]string),
|
|
}
|
|
|
|
// Mock user query
|
|
userRows := sqlmock.NewRows([]string{"users_id", "first_name", "middle_initial", "last_name", "suffix", "email_address",
|
|
"home_address", "contact_number",
|
|
"role_id", "is_deleted", "created_at", "updated_at"}).
|
|
AddRow("user123", "John", "", "Doe", "", "john@example.com",
|
|
"EMP123", "Y", "Y", "123 Street", "09123456789", "device1",
|
|
1, "N", "secret", "Y", time.Now(), time.Now())
|
|
|
|
mock.ExpectQuery("SELECT users_id, first_name, middle_initial, last_name, suffix, email_address").
|
|
WithArgs("user123").
|
|
WillReturnRows(userRows)
|
|
|
|
// Mock permission query with role check
|
|
mock.ExpectQuery("SELECT p.role_permissions_id, p.permission_name, p.description, p.resource, p.action FROM permissions p INNER JOIN role_permissions rp").
|
|
WithArgs("nonexistent", "read", 1).
|
|
WillReturnError(errors.New("permission not found"))
|
|
|
|
result, err := Authorize(ctx)
|
|
|
|
if err != nil {
|
|
t.Errorf("Expected no error, got %v", err)
|
|
}
|
|
if result.Allowed {
|
|
t.Error("Expected access denied")
|
|
}
|
|
if result.Message == "" {
|
|
t.Error("Expected error message")
|
|
}
|
|
}
|
|
|
|
func TestAuthorize_Success(t *testing.T) {
|
|
mock, cleanup := setupMockDB(t)
|
|
defer cleanup()
|
|
|
|
ctx := &models.AuthorizationContext{
|
|
UsersID: "user123",
|
|
Resource: "document",
|
|
Action: "read",
|
|
ResourceData: make(map[string]string),
|
|
Environment: make(map[string]string),
|
|
}
|
|
|
|
// Mock user query
|
|
userRows := sqlmock.NewRows([]string{"users_id", "first_name", "middle_initial", "last_name", "suffix", "email_address",
|
|
"home_address", "contact_number",
|
|
"role_id", "is_deleted", "created_at", "updated_at"}).
|
|
AddRow("user123", "John", "", "Doe", "", "john@example.com",
|
|
"EMP123", "Y", "Y", "123 Street", "09123456789", "device1",
|
|
1, "N", "secret", "Y", time.Now(), time.Now())
|
|
|
|
mock.ExpectQuery("SELECT users_id, first_name, middle_initial, last_name, suffix, email_address").
|
|
WithArgs("user123").
|
|
WillReturnRows(userRows)
|
|
|
|
// Mock permission query with role check
|
|
permRows := sqlmock.NewRows([]string{"id", "permission_name", "description", "resource", "action"}).
|
|
AddRow(1, "read_document", "Read document permission", "document", "read")
|
|
|
|
mock.ExpectQuery("SELECT p.id, p.permission_name, p.description, p.resource, p.action FROM permissions p INNER JOIN role_permissions rp").
|
|
WithArgs("document", "read", 1).
|
|
WillReturnRows(permRows)
|
|
|
|
// Mock user attributes query
|
|
attrRows := sqlmock.NewRows([]string{"attribute_name", "attribute_value"}).
|
|
AddRow("department", "engineering")
|
|
|
|
mock.ExpectQuery("SELECT attribute_name, attribute_value FROM user_attributes WHERE users_id = \\?").
|
|
WithArgs("user123").
|
|
WillReturnRows(attrRows)
|
|
|
|
// Mock policy attributes query (empty for this test)
|
|
policyRows := sqlmock.NewRows([]string{"id", "attribute_name", "attribute_type", "comparison", "attribute_value", "permission_id"})
|
|
|
|
mock.ExpectQuery("SELECT id, attribute_name, attribute_type, comparison, attribute_value, permission_id FROM policy_attributes WHERE permission_id = \\?").
|
|
WithArgs(1).
|
|
WillReturnRows(policyRows)
|
|
|
|
result, err := Authorize(ctx)
|
|
|
|
if err != nil {
|
|
t.Errorf("Expected no error, got %v", err)
|
|
}
|
|
if !result.Allowed {
|
|
t.Error("Expected access granted")
|
|
}
|
|
if result.Message != "Access granted" {
|
|
t.Errorf("Expected 'Access granted', got '%s'", result.Message)
|
|
}
|
|
}
|
|
|
|
func TestAuthorize_UserAttributesError(t *testing.T) {
|
|
mock, cleanup := setupMockDB(t)
|
|
defer cleanup()
|
|
|
|
ctx := &models.AuthorizationContext{
|
|
UsersID: "user123",
|
|
Resource: "document",
|
|
Action: "read",
|
|
ResourceData: make(map[string]string),
|
|
Environment: make(map[string]string),
|
|
}
|
|
|
|
// Mock user query
|
|
userRows := sqlmock.NewRows([]string{"users_id", "first_name", "middle_initial", "last_name", "suffix", "email_address",
|
|
"home_address", "contact_number",
|
|
"role_id", "is_deleted", "created_at", "updated_at"}).
|
|
AddRow("user123", "John", "", "Doe", "", "john@example.com",
|
|
"EMP123", "Y", "Y", "123 Street", "09123456789", "device1",
|
|
1, "N", "secret", "Y", time.Now(), time.Now())
|
|
|
|
mock.ExpectQuery("SELECT users_id, first_name, middle_initial, last_name, suffix, email_address").
|
|
WithArgs("user123").
|
|
WillReturnRows(userRows)
|
|
|
|
// Mock permission query with role check
|
|
permRows := sqlmock.NewRows([]string{"id", "permission_name", "description", "resource", "action"}).
|
|
AddRow(1, "read_document", "Read document permission", "document", "read")
|
|
|
|
mock.ExpectQuery("SELECT p.id, p.permission_name, p.description, p.resource, p.action FROM permissions p INNER JOIN role_permissions rp").
|
|
WithArgs("document", "read", 1).
|
|
WillReturnRows(permRows)
|
|
|
|
// Mock user attributes query with error
|
|
mock.ExpectQuery("SELECT attribute_name, attribute_value FROM user_attributes WHERE users_id = \\?").
|
|
WithArgs("user123").
|
|
WillReturnError(errors.New("database error"))
|
|
|
|
result, err := Authorize(ctx)
|
|
|
|
if err == nil {
|
|
t.Error("Expected error for user attributes failure")
|
|
}
|
|
if result.Allowed {
|
|
t.Error("Expected access denied")
|
|
}
|
|
}
|
|
|
|
func TestAuthorize_PolicyAttributesError(t *testing.T) {
|
|
mock, cleanup := setupMockDB(t)
|
|
defer cleanup()
|
|
|
|
ctx := &models.AuthorizationContext{
|
|
UsersID: "user123",
|
|
Resource: "document",
|
|
Action: "read",
|
|
ResourceData: make(map[string]string),
|
|
Environment: make(map[string]string),
|
|
}
|
|
|
|
// Mock user query
|
|
userRows := sqlmock.NewRows([]string{"users_id", "first_name", "middle_initial", "last_name", "suffix", "email_address",
|
|
"home_address", "contact_number",
|
|
"role_id", "is_deleted", "created_at", "updated_at"}).
|
|
AddRow("user123", "John", "", "Doe", "", "john@example.com",
|
|
"EMP123", "Y", "Y", "123 Street", "09123456789", "device1",
|
|
1, "N", "secret", "Y", time.Now(), time.Now())
|
|
|
|
mock.ExpectQuery("SELECT users_id, first_name, middle_initial, last_name, suffix, email_address").
|
|
WithArgs("user123").
|
|
WillReturnRows(userRows)
|
|
|
|
// Mock permission query with role check
|
|
permRows := sqlmock.NewRows([]string{"id", "permission_name", "description", "resource", "action"}).
|
|
AddRow(1, "read_document", "Read document permission", "document", "read")
|
|
|
|
mock.ExpectQuery("SELECT p.id, p.permission_name, p.description, p.resource, p.action FROM permissions p INNER JOIN role_permissions rp").
|
|
WithArgs("document", "read", 1).
|
|
WillReturnRows(permRows)
|
|
|
|
// Mock user attributes query
|
|
attrRows := sqlmock.NewRows([]string{"attribute_name", "attribute_value"}).
|
|
AddRow("department", "engineering")
|
|
|
|
mock.ExpectQuery("SELECT attribute_name, attribute_value FROM user_attributes WHERE users_id = \\?").
|
|
WithArgs("user123").
|
|
WillReturnRows(attrRows)
|
|
|
|
// Mock policy attributes query with error
|
|
mock.ExpectQuery("SELECT id, attribute_name, attribute_type, comparison, attribute_value, permission_id FROM policy_attributes WHERE permission_id = \\?").
|
|
WithArgs(1).
|
|
WillReturnError(errors.New("database error"))
|
|
|
|
result, err := Authorize(ctx)
|
|
|
|
if err == nil {
|
|
t.Error("Expected error for policy attributes failure")
|
|
}
|
|
if result.Allowed {
|
|
t.Error("Expected access denied")
|
|
}
|
|
}
|