Add backups, currencies and dashboard APIs, and scope access by guard_name.
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled

Web users may only CRUD their own records, operators stay in assigned branches, and admin/manager/superadmin keep full access.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
guwandykandCursor committed 2026-08-31 18:14:47 +05:00
1 parent 0d000f9af6
commit 28509eb4ca
65 files changed
+9132 -296

No files matched your search

+116 -30
View File
@@ -16,13 +16,17 @@ import (
)
const (
roleUser = "user"
roleOperator = "operator"
adminPrefix = "/api/admin"
contextRole = "role"
roleUser = "user"
roleOperator = "operator"
guardWeb = "web"
guardOperator = "operator"
guardAdmin = "admin"
adminPrefix = "/api/admin"
contextRole = "role"
contextGuard = "guard"
)
func RequirePermission(service *Service, code string) gin.HandlerFunc {
func RequirePermission(service Authorizer, code string) gin.HandlerFunc {
return func(c *gin.Context) {
rawID, exists := c.Get("id")
if !exists {
@@ -46,7 +50,7 @@ func RequirePermission(service *Service, code string) gin.HandlerFunc {
}
}
func Guard(service *Service) gin.HandlerFunc {
func Guard(service Authorizer) gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Method == http.MethodOptions || isPublicAdminPath(c.Request.URL.Path) {
c.Next()
@@ -59,26 +63,34 @@ func Guard(service *Service) gin.HandlerFunc {
return
}
code, err := service.RoleCode(c.Request.Context(), userID)
code, guardName, err := service.RoleLookup(c.Request.Context(), userID)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
guard := effectiveGuard(code, guardName)
c.Set("id", strconv.FormatInt(userID, 10))
c.Set(contextRole, code)
c.Set(contextGuard, guard)
c.Set(contextService, service)
switch code {
case roleOperator:
switch guard {
case guardOperator:
enforceOperator(c, service, userID)
return
case roleUser, "":
case guardWeb:
if code == "" {
c.Set(contextRole, roleUser)
}
if !userRoleAllows(c.Request.Method, c.Request.URL.Path) {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
scopeOwnedLists(c, userID)
if !enforceOwnWrites(c, userID) {
return
}
c.Next()
return
default:
@@ -88,7 +100,7 @@ func Guard(service *Service) gin.HandlerFunc {
}
}
func enforceOperator(c *gin.Context, service *Service, userID int64) {
func enforceOperator(c *gin.Context, service Authorizer, userID int64) {
ids, err := service.BranchIDs(c.Request.Context(), userID)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
@@ -113,6 +125,28 @@ func enforceOperator(c *gin.Context, service *Service, userID int64) {
c.Next()
}
func effectiveGuard(code, guardName string) string {
code = strings.ToLower(strings.TrimSpace(code))
guard := strings.ToLower(strings.TrimSpace(guardName))
switch code {
case "admin", "superadmin", "manager":
return guardAdmin
case roleOperator:
return guardOperator
}
switch guard {
case guardWeb, guardOperator, guardAdmin:
return guard
}
if code == roleUser || code == "" {
return guardWeb
}
return guardAdmin
}
func isPublicAdminPath(path string) bool {
switch strings.TrimSuffix(path, "/") {
case adminPrefix + "/login",
@@ -128,19 +162,31 @@ func isPublicAdminPath(path string) bool {
}
func userRoleAllows(method, path string) bool {
if method != http.MethodGet {
return false
}
rest := strings.TrimSuffix(strings.TrimPrefix(path, adminPrefix), "/")
rest := adminREST(path)
if rest == "" {
return false
}
if !strings.HasPrefix(rest, "/") {
rest = "/" + rest
}
for _, prefix := range userRolePrefixes {
if matchesPrefix(rest, userCatalogPrefixes) {
return method == http.MethodGet
}
if matchesPrefix(rest, userSelfPrefixes) {
if rest == "/profile" || strings.HasPrefix(rest, "/profile/") {
return method == http.MethodGet || method == http.MethodPut || method == http.MethodPatch
}
return method == http.MethodGet || method == http.MethodPost
}
if matchesPrefix(rest, userOwnedPrefixes) {
switch method {
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
return true
}
}
return false
}
func matchesPrefix(rest string, prefixes []string) bool {
for _, prefix := range prefixes {
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
return true
}
@@ -148,6 +194,41 @@ func userRoleAllows(method, path string) bool {
return false
}
func enforceOwnWrites(c *gin.Context, userID int64) bool {
if !matchesPrefix(adminREST(c.Request.URL.Path), userOwnedPrefixes) {
return true
}
switch c.Request.Method {
case http.MethodPost, http.MethodPut, http.MethodPatch:
default:
return true
}
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, appresult.ErrMissingParam)
return false
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
if len(bytes.TrimSpace(body)) == 0 {
return true
}
var payload map[string]interface{}
if err := json.Unmarshal(body, &payload); err != nil {
return true
}
payload["userId"] = userID
payload["user_id"] = userID
rewritten, err := json.Marshal(payload)
if err != nil {
return true
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(rewritten))
c.Request.ContentLength = int64(len(rewritten))
return true
}
func scopeOwnedLists(c *gin.Context, userID int64) {
rest := strings.TrimSuffix(strings.TrimPrefix(c.Request.URL.Path, adminPrefix), "/")
if rest == "" {
@@ -232,27 +313,28 @@ func bearerToken(header string) string {
return strings.TrimSpace(header)
}
var userRolePrefixes = []string{
"/profile",
"/cards",
"/card-orders",
"/card-pin-orders",
var userCatalogPrefixes = []string{
"/payment-cards",
"/reasons-cards",
"/visa-master-payment-orders",
"/loan-orders",
"/loan-types",
"/loans-documents",
"/loans-repayment",
"/loan-paid-off-letters",
"/currencies",
}
var userSelfPrefixes = []string{
"/profile",
"/file",
}
var userOwnedPrefixes = []string{
"/cards",
"/card-orders",
"/card-pin-orders",
"/card-rekwizit-orders",
"/visa-master-payment-orders",
"/loan-orders",
"/loans-repayment",
"/loan-paid-off-letters",
}
func operatorRoleAllows(method, path string) bool {
@@ -280,7 +362,7 @@ func operatorProfileOrFile(path string) bool {
return rest == "/profile" || rest == "/file" || strings.HasPrefix(rest, "/file/")
}
func operatorWriteAllowed(c *gin.Context, service *Service, branchIDs []int64) bool {
func operatorWriteAllowed(c *gin.Context, service Authorizer, branchIDs []int64) bool {
switch c.Request.Method {
case http.MethodPost, http.MethodPut, http.MethodPatch:
default:
@@ -345,6 +427,7 @@ var operatorWritePrefixes = []string{
"/cards",
"/card-orders",
"/card-pin-orders",
"/card-rekwizit-orders",
"/visa-master-payment-orders",
"/loan-orders",
"/loans-repayment",
@@ -354,10 +437,12 @@ var operatorWritePrefixes = []string{
var operatorGetPrefixes = []string{
"/profile",
"/file",
"/dashboard",
"/users",
"/cards",
"/card-orders",
"/card-pin-orders",
"/card-rekwizit-orders",
"/payment-cards",
"/reasons-cards",
"/visa-master-payment-orders",
@@ -368,4 +453,5 @@ var operatorGetPrefixes = []string{
"/loan-paid-off-letters",
"/provinces",
"/branches",
"/currencies",
}
+599
View File
@@ -0,0 +1,599 @@
package rbac
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
)
func TestUserRoleAllows(t *testing.T) {
tests := []struct {
method, path string
want bool
}{
{http.MethodGet, "/api/admin/currencies", true},
{http.MethodGet, "/api/admin/currencies/3", true},
{http.MethodPost, "/api/admin/currencies", false},
{http.MethodPut, "/api/admin/currencies/3", false},
{http.MethodDelete, "/api/admin/currencies/3", false},
{http.MethodGet, "/api/admin/backups", false},
{http.MethodGet, "/api/admin/backups/1", false},
{http.MethodPost, "/api/admin/backups", false},
{http.MethodGet, "/api/admin/cards", true},
{http.MethodPost, "/api/admin/cards", true},
{http.MethodPut, "/api/admin/cards/9", true},
{http.MethodDelete, "/api/admin/cards/9", true},
{http.MethodGet, "/api/admin/card-orders/9", true},
{http.MethodPost, "/api/admin/card-orders", true},
{http.MethodPut, "/api/admin/loan-orders/2", true},
{http.MethodDelete, "/api/admin/loan-orders/2", true},
{http.MethodGet, "/api/admin/card-balances", false},
{http.MethodGet, "/api/admin/profile", true},
{http.MethodPut, "/api/admin/profile", true},
{http.MethodPost, "/api/admin/file", true},
{http.MethodDelete, "/api/admin/profile", false},
{http.MethodGet, "/api/admin/users", false},
{http.MethodGet, "/api/admin/activity-logs", false},
{http.MethodGet, "/api/admin/provinces", false},
{http.MethodGet, "/api/admin/loan-types", true},
{http.MethodPost, "/api/admin/loan-types", false},
{http.MethodPost, "/api/admin/loan-orders", true},
{http.MethodGet, "/api/admin/loans-repayment", true},
{http.MethodPost, "/api/admin/loans-repayment", true},
{http.MethodDelete, "/api/admin/loan-paid-off-letters/4", true},
{http.MethodPatch, "/api/admin/cards/9", true},
}
for _, tt := range tests {
if got := userRoleAllows(tt.method, tt.path); got != tt.want {
t.Errorf("userRoleAllows(%s %s) = %v, want %v", tt.method, tt.path, got, tt.want)
}
}
}
func TestOperatorRoleAllows(t *testing.T) {
tests := []struct {
method, path string
want bool
}{
{http.MethodGet, "/api/admin/currencies", true},
{http.MethodGet, "/api/admin/currencies/1", true},
{http.MethodPost, "/api/admin/currencies", false},
{http.MethodPut, "/api/admin/currencies/1", false},
{http.MethodDelete, "/api/admin/currencies/1", false},
{http.MethodGet, "/api/admin/backups", false},
{http.MethodPost, "/api/admin/backups", false},
{http.MethodGet, "/api/admin/card-orders", true},
{http.MethodPost, "/api/admin/card-orders", true},
{http.MethodDelete, "/api/admin/card-orders/2", true},
{http.MethodGet, "/api/admin/dashboard", true},
{http.MethodGet, "/api/admin/users", true},
{http.MethodPost, "/api/admin/users", true},
{http.MethodGet, "/api/admin/activity-logs", false},
{http.MethodGet, "/api/admin/provinces", true},
{http.MethodPost, "/api/admin/provinces", false},
{http.MethodGet, "/api/admin/card-balances", false},
}
for _, tt := range tests {
if got := operatorRoleAllows(tt.method, tt.path); got != tt.want {
t.Errorf("operatorRoleAllows(%s %s) = %v, want %v", tt.method, tt.path, got, tt.want)
}
}
}
func TestUserPrefixDoesNotBleedIntoOtherModules(t *testing.T) {
if userRoleAllows(http.MethodGet, "/api/admin/card-balances") {
t.Fatal("/cards must not grant /card-balances")
}
if operatorRoleAllows(http.MethodGet, "/api/admin/card-balances") {
t.Fatal("operator /cards must not grant /card-balances")
}
}
func TestIsPublicAdminPath(t *testing.T) {
public := []string{
"/api/admin/login",
"/api/admin/token",
"/api/admin/register",
"/api/admin/register/verify",
"/api/admin/forgot-password",
"/api/admin/forgot-password/verify",
"/api/admin/login/",
}
for _, path := range public {
if !isPublicAdminPath(path) {
t.Errorf("expected public %s", path)
}
}
private := []string{"/api/admin/currencies", "/api/admin/backups", "/api/admin/users"}
for _, path := range private {
if isPublicAdminPath(path) {
t.Errorf("expected private %s", path)
}
}
}
func TestAdminREST(t *testing.T) {
if got := adminREST("/api/admin/currencies/4"); got != "/currencies/4" {
t.Fatalf("got %q", got)
}
if got := adminREST("/api/admin/currencies/"); got != "/currencies" {
t.Fatalf("got %q", got)
}
if got := adminREST("/api/admin"); got != "" {
t.Fatalf("got %q", got)
}
}
func TestScopeOwnedListsInjectsUserID(t *testing.T) {
gin.SetMode(gin.TestMode)
paths := []string{
"/api/admin/cards?page=1",
"/api/admin/loan-orders",
"/api/admin/loans-repayment",
"/api/admin/loan-paid-off-letters",
}
for _, path := range paths {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, path, nil)
scopeOwnedLists(c, 42)
if got := c.Request.URL.Query().Get("user_id"); got != "42" {
t.Errorf("%s user_id=%q", path, got)
}
}
}
func TestScopeOwnedListsSkipsReferenceData(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/api/admin/currencies", nil)
scopeOwnedLists(c, 42)
if got := c.Request.URL.Query().Get("user_id"); got != "" {
t.Fatalf("currencies must not be scoped by user_id, got %q", got)
}
}
func TestGuardMatrix(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name string
role string
branches []int64
method string
path string
want int
}{
{"user GET currencies", roleUser, nil, http.MethodGet, "/api/admin/currencies", http.StatusOK},
{"user POST currencies", roleUser, nil, http.MethodPost, "/api/admin/currencies", http.StatusForbidden},
{"user GET backups", roleUser, nil, http.MethodGet, "/api/admin/backups", http.StatusForbidden},
{"user GET cards", roleUser, nil, http.MethodGet, "/api/admin/cards", http.StatusOK},
{"user POST cards", roleUser, nil, http.MethodPost, "/api/admin/cards", http.StatusOK},
{"user PUT card-orders", roleUser, nil, http.MethodPut, "/api/admin/card-orders/3", http.StatusOK},
{"user DELETE loan-orders", roleUser, nil, http.MethodDelete, "/api/admin/loan-orders/3", http.StatusOK},
{"user PATCH cards", roleUser, nil, http.MethodPatch, "/api/admin/cards/3", http.StatusOK},
{"user POST loans-repayment", roleUser, nil, http.MethodPost, "/api/admin/loans-repayment", http.StatusOK},
{"user PUT profile", roleUser, nil, http.MethodPut, "/api/admin/profile", http.StatusOK},
{"user POST file", roleUser, nil, http.MethodPost, "/api/admin/file", http.StatusOK},
{"user GET users", roleUser, nil, http.MethodGet, "/api/admin/users", http.StatusForbidden},
{"no-role GET currencies", "", nil, http.MethodGet, "/api/admin/currencies", http.StatusOK},
{"no-role GET backups", "", nil, http.MethodGet, "/api/admin/backups", http.StatusForbidden},
{"operator GET currencies", roleOperator, []int64{1}, http.MethodGet, "/api/admin/currencies", http.StatusOK},
{"operator POST currencies", roleOperator, []int64{1}, http.MethodPost, "/api/admin/currencies", http.StatusForbidden},
{"operator GET backups", roleOperator, []int64{1}, http.MethodGet, "/api/admin/backups", http.StatusForbidden},
{"operator GET card-orders", roleOperator, []int64{1}, http.MethodGet, "/api/admin/card-orders", http.StatusOK},
{"operator POST card-orders", roleOperator, []int64{1}, http.MethodPost, "/api/admin/card-orders", http.StatusOK},
{"operator no branch GET currencies", roleOperator, nil, http.MethodGet, "/api/admin/currencies", http.StatusForbidden},
{"operator no branch GET profile", roleOperator, nil, http.MethodGet, "/api/admin/profile", http.StatusOK},
{"admin GET backups", "admin", nil, http.MethodGet, "/api/admin/backups", http.StatusOK},
{"admin POST currencies", "admin", nil, http.MethodPost, "/api/admin/currencies", http.StatusOK},
{"superadmin DELETE backups", "superadmin", nil, http.MethodDelete, "/api/admin/backups/1", http.StatusOK},
{"manager GET backups", "manager", nil, http.MethodGet, "/api/admin/backups", http.StatusOK},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
status := serveGuard(&stubAuth{role: tt.role, branches: tt.branches}, tt.method, tt.path, "7", nil)
if status != tt.want {
t.Fatalf("status=%d want=%d", status, tt.want)
}
})
}
if status := serveGuard(&stubAuth{role: "customer", guard: guardWeb}, http.MethodPost, "/api/admin/cards", "7", nil); status != http.StatusOK {
t.Fatalf("web guard custom role status=%d", status)
}
if status := serveGuard(&stubAuth{role: "customer", guard: guardWeb}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusForbidden {
t.Fatalf("web guard backups status=%d", status)
}
if status := serveGuard(&stubAuth{role: "teller", guard: guardOperator, branches: []int64{1}}, http.MethodPost, "/api/admin/card-orders", "7", nil); status != http.StatusOK {
t.Fatalf("operator guard custom role status=%d", status)
}
if status := serveGuard(&stubAuth{role: "auditor", guard: guardAdmin}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusOK {
t.Fatalf("admin guard custom role status=%d", status)
}
if status := serveGuard(&stubAuth{role: roleOperator, guard: guardAdmin, branches: []int64{1}}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusForbidden {
t.Fatalf("legacy operator+admin guard must stay operator, status=%d", status)
}
if status := serveGuard(&stubAuth{role: "superadmin", guard: guardWeb}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusOK {
t.Fatalf("superadmin code must stay admin even if guard is web, status=%d", status)
}
}
func TestGuardOptionsAndPublicSkipAuthz(t *testing.T) {
gin.SetMode(gin.TestMode)
auth := &stubAuth{role: roleUser}
if status := serveGuard(auth, http.MethodOptions, "/api/admin/backups", "7", nil); status != http.StatusOK {
t.Fatalf("OPTIONS status=%d", status)
}
if status := serveGuard(auth, http.MethodGet, "/api/admin/login", "7", nil); status != http.StatusOK {
t.Fatalf("public login status=%d", status)
}
}
func TestGuardWithoutUserPassesThrough(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(Guard(&stubAuth{role: roleUser}))
r.GET("/api/admin/backups", func(c *gin.Context) { c.Status(http.StatusOK) })
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/admin/backups", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status=%d", w.Code)
}
}
func TestGuardRoleLookupError(t *testing.T) {
gin.SetMode(gin.TestMode)
status := serveGuard(&stubAuth{roleErr: errors.New("db down")}, http.MethodGet, "/api/admin/currencies", "7", nil)
if status != http.StatusInternalServerError {
t.Fatalf("status=%d", status)
}
}
func TestOperatorWriteAllowedBranchScope(t *testing.T) {
gin.SetMode(gin.TestMode)
auth := &stubAuth{role: roleOperator, branches: []int64{1, 2}, visible: true}
allowed := serveGuard(auth, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"branchId":1}`))
if allowed != http.StatusOK {
t.Fatalf("own branch status=%d", allowed)
}
denied := serveGuard(auth, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"branchId":99}`))
if denied != http.StatusForbidden {
t.Fatalf("foreign branch status=%d", denied)
}
}
func TestOperatorWriteAllowedUserVisibility(t *testing.T) {
gin.SetMode(gin.TestMode)
okAuth := &stubAuth{role: roleOperator, branches: []int64{1}, visible: true}
if status := serveGuard(okAuth, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"userId":15}`)); status != http.StatusOK {
t.Fatalf("visible user status=%d", status)
}
hidden := &stubAuth{role: roleOperator, branches: []int64{1}, visible: false}
if status := serveGuard(hidden, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"userId":15}`)); status != http.StatusForbidden {
t.Fatalf("hidden user status=%d", status)
}
}
func TestRequirePermission(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set("id", "3")
c.Next()
})
r.GET("/x", RequirePermission(&stubAuth{perms: map[string]bool{"currencies.view": true}}, "currencies.view"), okHandler)
r.POST("/x", RequirePermission(&stubAuth{perms: map[string]bool{}}, "currencies.manage"), okHandler)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/x", nil))
if w.Code != http.StatusOK {
t.Fatalf("granted status=%d", w.Code)
}
w = httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/x", nil))
if w.Code != http.StatusForbidden {
t.Fatalf("denied status=%d", w.Code)
}
}
func TestAllowsBranchAndGuardUser(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
if !AllowsBranch(c, 1) {
t.Fatal("no scope should allow any branch")
}
if !GuardUser(c, 9) {
t.Fatal("no scope should allow any user")
}
c.Set(contextBranchIDs, []int64{1, 2})
if !AllowsBranch(c, 2) {
t.Fatal("expected branch 2 allowed")
}
if AllowsBranch(c, 9) {
t.Fatal("expected branch 9 denied")
}
c.Set(contextService, &stubAuth{visible: true})
if !GuardUser(c, 15) {
t.Fatal("expected visible user allowed")
}
c.Set(contextService, &stubAuth{visible: false})
if GuardUser(c, 15) {
t.Fatal("expected hidden user denied")
}
}
func TestBindBranchIDs(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
var dest []int64
BindBranchIDs(c, &dest)
if dest != nil {
t.Fatalf("expected empty dest, got %v", dest)
}
c.Set(contextBranchIDs, []int64{4, 5})
BindBranchIDs(c, &dest)
if len(dest) != 2 || dest[0] != 4 {
t.Fatalf("dest=%v", dest)
}
}
func TestClaimAndContextUserID(t *testing.T) {
if id, ok := claimUserID(jwt.MapClaims{"id": float64(12)}); !ok || id != 12 {
t.Fatalf("float id=%d ok=%v", id, ok)
}
if id, ok := claimUserID(jwt.MapClaims{"id": "8"}); !ok || id != 8 {
t.Fatalf("string id=%d ok=%v", id, ok)
}
if _, ok := claimUserID(jwt.MapClaims{"id": 0}); ok {
t.Fatal("zero id should fail")
}
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Set("id", "21")
if id, ok := parseContextUserID(c); !ok || id != 21 {
t.Fatalf("context id=%d ok=%v", id, ok)
}
}
func TestBearerToken(t *testing.T) {
if got := bearerToken("Bearer abc"); got != "abc" {
t.Fatalf("got %q", got)
}
if got := bearerToken("abc"); got != "abc" {
t.Fatalf("got %q", got)
}
}
func TestUserInBranchSQLIncludesNewOrderTables(t *testing.T) {
sql := UserInBranchSQL("c.user_id", 3)
for _, table := range []string{
"branch_user", "card_orders", "loan_orders", "card_pin_orders",
"card_rekwizit_orders", "visa_master_payment_orders", "loan_paid_off_letters",
} {
if !strings.Contains(sql, table) {
t.Errorf("missing %s", table)
}
}
if strings.Count(sql, "$3") != 7 {
t.Fatalf("$3 count=%d", strings.Count(sql, "$3"))
}
}
func serveGuard(auth Authorizer, method, path, userID string, body []byte) int {
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set("id", userID)
c.Next()
})
r.Use(Guard(auth))
handler := func(c *gin.Context) { c.Status(http.StatusOK) }
r.GET("/api/admin/*rest", handler)
r.POST("/api/admin/*rest", handler)
r.PUT("/api/admin/*rest", handler)
r.PATCH("/api/admin/*rest", handler)
r.DELETE("/api/admin/*rest", handler)
r.OPTIONS("/api/admin/*rest", handler)
var req *http.Request
if body != nil {
req = httptest.NewRequest(method, path, bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
} else {
req = httptest.NewRequest(method, path, nil)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w.Code
}
func okHandler(c *gin.Context) { c.Status(http.StatusOK) }
type stubAuth struct {
role string
guard string
roleErr error
branches []int64
visible bool
visibleErr error
perms map[string]bool
}
func (s *stubAuth) RoleLookup(context.Context, int64) (string, string, error) {
return s.role, s.guard, s.roleErr
}
func (s *stubAuth) BranchIDs(context.Context, int64) ([]int64, error) {
return s.branches, nil
}
func (s *stubAuth) HasPermission(_ context.Context, _ int64, code string) (bool, error) {
return s.perms[code], nil
}
func (s *stubAuth) UserVisibleInBranches(context.Context, int64, []int64) (bool, error) {
return s.visible, s.visibleErr
}
var _ Authorizer = (*stubAuth)(nil)
var _ Authorizer = (*Service)(nil)
func TestEffectiveGuard(t *testing.T) {
tests := []struct {
code, guard, want string
}{
{roleUser, guardWeb, guardWeb},
{roleOperator, guardOperator, guardOperator},
{"admin", guardAdmin, guardAdmin},
{"customer", guardWeb, guardWeb},
{"teller", guardOperator, guardOperator},
{"auditor", guardAdmin, guardAdmin},
{roleUser, "", guardWeb},
{roleOperator, "", guardOperator},
{"admin", "", guardAdmin},
{"", "", guardWeb},
{roleOperator, guardAdmin, guardOperator},
{roleOperator, guardWeb, guardOperator},
{"superadmin", guardWeb, guardAdmin},
{"admin", guardWeb, guardAdmin},
{"manager", guardOperator, guardAdmin},
}
for _, tt := range tests {
if got := effectiveGuard(tt.code, tt.guard); got != tt.want {
t.Errorf("effectiveGuard(%q, %q)=%q want %q", tt.code, tt.guard, got, tt.want)
}
}
}
func TestContainsInt64(t *testing.T) {
if !containsInt64([]int64{1, 2, 3}, 2) {
t.Fatal("expected 2")
}
if containsInt64([]int64{1, 2, 3}, 9) {
t.Fatal("did not expect 9")
}
}
func TestHasBranchScope(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
if HasBranchScope(c) {
t.Fatal("expected no scope")
}
c.Set(contextBranchIDs, []int64{1})
if !HasBranchScope(c) {
t.Fatal("expected scope")
}
}
func TestEnforceOwnWritesRewritesUserID(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set("id", "7")
c.Next()
})
r.Use(Guard(&stubAuth{role: roleUser}))
r.POST("/api/admin/cards", func(c *gin.Context) {
body, _ := io.ReadAll(c.Request.Body)
c.String(http.StatusOK, string(body))
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/admin/cards", bytes.NewReader([]byte(`{"userId":99,"number":"1"}`)))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status=%d", w.Code)
}
if !strings.Contains(w.Body.String(), `"userId":7`) {
t.Fatalf("userId not rewritten: %s", w.Body.String())
}
if !strings.Contains(w.Body.String(), `"user_id":7`) {
t.Fatalf("user_id not rewritten: %s", w.Body.String())
}
}
func TestGuardOwnedOwnScope(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
c.Set(contextRole, roleUser)
c.Set(contextGuard, guardWeb)
c.Set("id", "7")
own := int64(7)
if !GuardOwned(c, &own) {
t.Fatal("own record should pass")
}
other := int64(9)
if GuardOwned(c, &other) {
t.Fatal("foreign record should fail")
}
if GuardOwned(c, nil) {
t.Fatal("nil owner should fail")
}
if GuardUser(c, 9) {
t.Fatal("GuardUser should deny other users")
}
if !GuardUser(c, 7) {
t.Fatal("GuardUser should allow current user")
}
}
func TestSkipRecordGuard(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
if !SkipRecordGuard(c) {
t.Fatal("admin with no role/branches should skip")
}
c.Set(contextRole, roleUser)
c.Set(contextGuard, guardWeb)
if SkipRecordGuard(c) {
t.Fatal("user must not skip record guard")
}
c.Set(contextRole, roleOperator)
c.Set(contextGuard, guardOperator)
c.Set(contextBranchIDs, []int64{1})
if SkipRecordGuard(c) {
t.Fatal("operator with branches must not skip")
}
}
+50 -2
View File
@@ -27,6 +27,49 @@ func HasBranchScope(c *gin.Context) bool {
return len(BranchIDsFrom(c)) > 0
}
func RoleFrom(c *gin.Context) string {
raw, _ := c.Get(contextRole)
role, _ := raw.(string)
return role
}
func GuardFrom(c *gin.Context) string {
raw, _ := c.Get(contextGuard)
guard, _ := raw.(string)
return guard
}
func IsOwnScope(c *gin.Context) bool {
return GuardFrom(c) == guardWeb
}
func SkipRecordGuard(c *gin.Context) bool {
return !HasBranchScope(c) && !IsOwnScope(c)
}
func CurrentUserID(c *gin.Context) (int64, bool) {
return parseContextUserID(c)
}
func GuardOwned(c *gin.Context, ownerID *int64) bool {
if !IsOwnScope(c) {
return true
}
current, ok := CurrentUserID(c)
if !ok || ownerID == nil || *ownerID != current {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
return true
}
func GuardOrder(c *gin.Context, ownerID *int64, branchID int64) bool {
if IsOwnScope(c) {
return GuardOwned(c, ownerID)
}
return GuardBranch(c, branchID)
}
func AllowsBranch(c *gin.Context, branchID int64) bool {
ids := BranchIDsFrom(c)
if len(ids) == 0 {
@@ -52,6 +95,10 @@ func GuardBranch(c *gin.Context, branchID int64) bool {
}
func GuardUser(c *gin.Context, userID int64) bool {
if IsOwnScope(c) {
id := userID
return GuardOwned(c, &id)
}
ids := BranchIDsFrom(c)
if len(ids) == 0 {
return true
@@ -61,7 +108,7 @@ func GuardUser(c *gin.Context, userID int64) bool {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
service, _ := raw.(*Service)
service, _ := raw.(Authorizer)
if service == nil {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
@@ -89,9 +136,10 @@ func UserInBranchSQL(userExpr string, placeholder int) string {
OR EXISTS (SELECT 1 FROM card_orders co WHERE co.user_id = %s AND co.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM loan_orders lo WHERE lo.user_id = %s AND lo.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM card_pin_orders cpo WHERE cpo.user_id = %s AND cpo.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM card_rekwizit_orders cro WHERE cro.user_id = %s AND cro.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM visa_master_payment_orders vmo WHERE vmo.user_id = %s AND vmo.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM loan_paid_off_letters lpl WHERE lpl.user_id = %s AND lpl.branch_id = ANY($%d))
)`, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder)
)`, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder)
}
func containsInt64(ids []int64, want int64) bool {
+38 -13
View File
@@ -17,15 +17,40 @@ func NewService(client postgresql.Client) *Service {
return &Service{client: client}
}
// Authorizer is the lookup Guard, RequirePermission and GuardUser need.
type Authorizer interface {
RoleLookup(ctx context.Context, userID int64) (code, guardName string, err error)
BranchIDs(ctx context.Context, userID int64) ([]int64, error)
HasPermission(ctx context.Context, userID int64, code string) (bool, error)
UserVisibleInBranches(ctx context.Context, userID int64, branchIDs []int64) (bool, error)
}
// HasPermission checks the role's baseline grant, then lets a per-user
// permission_user override win: an explicit "deny" always wins (even over
// another allow), an explicit "allow" grants a permission the role does
// not, and no override falls back to the role.
func (s *Service) HasPermission(ctx context.Context, userID int64, code string) (bool, error) {
const query = `
SELECT EXISTS (
SELECT 1
FROM role_user ru
JOIN permission_role pr ON pr.role_id = ru.role_id
JOIN permissions p ON p.id = pr.permission_id
WHERE ru.user_id = $1 AND p.code = $2
)`
SELECT
CASE
WHEN EXISTS (
SELECT 1 FROM permission_user pu
JOIN permissions p ON p.id = pu.permission_id
WHERE pu.user_id = $1 AND p.code = $2 AND pu.effect = 'deny'
) THEN false
WHEN EXISTS (
SELECT 1 FROM permission_user pu
JOIN permissions p ON p.id = pu.permission_id
WHERE pu.user_id = $1 AND p.code = $2 AND pu.effect = 'allow'
) THEN true
ELSE EXISTS (
SELECT 1
FROM role_user ru
JOIN permission_role pr ON pr.role_id = ru.role_id
JOIN permissions p ON p.id = pr.permission_id
WHERE ru.user_id = $1 AND p.code = $2
)
END`
var granted bool
if err := s.client.QueryRow(ctx, query, userID, code).Scan(&granted); err != nil {
@@ -34,21 +59,21 @@ func (s *Service) HasPermission(ctx context.Context, userID int64, code string)
return granted, nil
}
func (s *Service) RoleCode(ctx context.Context, userID int64) (string, error) {
func (s *Service) RoleLookup(ctx context.Context, userID int64) (string, string, error) {
const query = `
SELECT r.code
SELECT r.code, r.guard_name
FROM role_user ru
JOIN roles r ON r.id = ru.role_id
WHERE ru.user_id = $1
ORDER BY ru.id
LIMIT 1`
var code string
err := s.client.QueryRow(ctx, query, userID).Scan(&code)
var code, guardName string
err := s.client.QueryRow(ctx, query, userID).Scan(&code, &guardName)
if errors.Is(err, pgx.ErrNoRows) {
return "", nil
return "", "", nil
}
return code, err
return code, guardName, err
}
func (s *Service) BranchIDs(ctx context.Context, userID int64) ([]int64, error) {