-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
300 lines (262 loc) · 9.11 KB
/
auth.go
File metadata and controls
300 lines (262 loc) · 9.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package fiberoapi
import (
"errors"
"fmt"
"reflect"
"strings"
"github.com/gofiber/fiber/v2"
)
// AuthContext contains user authentication details
type AuthContext struct {
UserID string `json:"user_id"`
Roles []string `json:"roles"`
Scopes []string `json:"scopes"`
Claims map[string]interface{} `json:"claims"`
}
// ResourcePermission defines permissions on a resource
type ResourcePermission struct {
ResourceType string `json:"resource_type"`
ResourceID string `json:"resource_id"`
Actions []string `json:"actions"` // ["read", "write", "delete", "share"]
}
// AuthorizationService interface for permission checks
type AuthorizationService interface {
// Authentication
ValidateToken(token string) (*AuthContext, error)
// Global authorization (roles/scopes)
HasRole(ctx *AuthContext, role string) bool
HasScope(ctx *AuthContext, scope string) bool
// Dynamic authorization on resources
CanAccessResource(ctx *AuthContext, resourceType, resourceID, action string) (bool, error)
GetUserPermissions(ctx *AuthContext, resourceType, resourceID string) (*ResourcePermission, error)
}
// SecurityScheme for OpenAPI
type SecurityScheme struct {
Type string `json:"type" yaml:"type"`
Scheme string `json:"scheme,omitempty" yaml:"scheme,omitempty"`
BearerFormat string `json:"bearerFormat,omitempty" yaml:"bearerFormat,omitempty"`
In string `json:"in,omitempty" yaml:"in,omitempty"`
Name string `json:"name,omitempty" yaml:"name,omitempty"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
Flows map[string]interface{} `json:"flows,omitempty" yaml:"flows,omitempty"`
}
// GetAuthContext extracts the authentication context from Fiber
func GetAuthContext(c *fiber.Ctx) (*AuthContext, error) {
auth, ok := c.Locals("auth").(*AuthContext)
if !ok {
return nil, fmt.Errorf("no authentication context found")
}
return auth, nil
}
// RequireResourceAccess checks permissions in handlers
func RequireResourceAccess(c *fiber.Ctx, authService AuthorizationService, resourceType, resourceID, action string) error {
authCtx, err := GetAuthContext(c)
if err != nil {
return c.Status(401).JSON(fiber.Map{
"error": "Authentication required",
})
}
canAccess, err := authService.CanAccessResource(authCtx, resourceType, resourceID, action)
if err != nil {
return c.Status(500).JSON(fiber.Map{
"error": "Authorization check failed",
"details": err.Error(),
})
}
if !canAccess {
return c.Status(403).JSON(fiber.Map{
"error": "Insufficient permissions",
"resource": resourceType,
"action": action,
})
}
return nil
}
// BearerTokenMiddleware creates a JWT/Bearer middleware
func BearerTokenMiddleware(validator AuthorizationService) fiber.Handler {
return func(c *fiber.Ctx) error {
authHeader := c.Get("Authorization")
if authHeader == "" {
return c.Status(401).JSON(fiber.Map{
"error": "Authorization header required",
})
}
if !strings.HasPrefix(authHeader, "Bearer ") {
return c.Status(401).JSON(fiber.Map{
"error": "Bearer token required",
})
}
token := strings.TrimPrefix(authHeader, "Bearer ")
authCtx, err := validator.ValidateToken(token)
if err != nil {
return c.Status(401).JSON(fiber.Map{
"error": "Invalid token",
"details": err.Error(),
})
}
// Store auth context for later use
c.Locals("auth", authCtx)
return c.Next()
}
}
// RoleGuard middleware for role verification
func RoleGuard(validator AuthorizationService, requiredRoles ...string) fiber.Handler {
return func(c *fiber.Ctx) error {
authCtx, err := GetAuthContext(c)
if err != nil {
return c.Status(401).JSON(fiber.Map{
"error": "Authentication required",
})
}
for _, role := range requiredRoles {
if !validator.HasRole(authCtx, role) {
return c.Status(403).JSON(fiber.Map{
"error": "Insufficient permissions",
"required_role": role,
})
}
}
return c.Next()
}
}
// validateAuthorization validates permissions based on configured security schemes.
// When SecuritySchemes is empty, it falls back to Bearer-only validation for backward compatibility.
func validateAuthorization(c *fiber.Ctx, input interface{}, authService AuthorizationService, config *Config, requiredRoles []string, requireAllRoles bool) error {
if authService == nil {
if len(requiredRoles) > 0 {
return &AuthError{StatusCode: 500, Message: "authorization service not configured"}
}
return nil
}
// Backward compatibility: if no SecuritySchemes are configured,
// fall back to Bearer-only validation (original behavior).
if config == nil || len(config.SecuritySchemes) == 0 {
authCtx, err := validateBearerToken(c, authService)
if err != nil {
// Preserve typed AuthError (including 5xx) and map ScopeError to 403,
// falling back to 401 only for untyped errors.
var authErr *AuthError
if errors.As(err, &authErr) {
return err
}
var scopeErr *ScopeError
if errors.As(err, &scopeErr) {
return &AuthError{StatusCode: 403, Message: err.Error()}
}
return &AuthError{StatusCode: 401, Message: err.Error()}
}
c.Locals("auth", authCtx)
// Check roles before resource access
if err := checkRequiredRoles(authCtx, authService, requiredRoles, requireAllRoles); err != nil {
return err
}
return validateResourceAccess(c, authCtx, input, authService)
}
// Multi-scheme validation path
securityReqs := config.DefaultSecurity
if len(securityReqs) == 0 {
securityReqs = buildDefaultFromSchemes(config.SecuritySchemes)
}
// Try each security requirement (OR semantics per OpenAPI spec).
// Server configuration errors (5xx) short-circuit immediately since
// no alternative requirement can fix a misconfigured scheme.
var lastErr error
for _, requirement := range securityReqs {
authCtx, err := validateSecurityRequirement(c, requirement, config.SecuritySchemes, authService)
if err == nil {
c.Locals("auth", authCtx)
// Check roles before resource access
if err := checkRequiredRoles(authCtx, authService, requiredRoles, requireAllRoles); err != nil {
return err
}
return validateResourceAccess(c, authCtx, input, authService)
}
var authErr *AuthError
if errors.As(err, &authErr) && authErr.StatusCode >= 500 {
return err
}
lastErr = err
}
// Propagate typed errors (AuthError, ScopeError) without re-wrapping
var existingAuthErr *AuthError
if errors.As(lastErr, &existingAuthErr) {
return lastErr
}
var scopeErr *ScopeError
if errors.As(lastErr, &scopeErr) {
return &AuthError{StatusCode: 403, Message: lastErr.Error()}
}
return &AuthError{StatusCode: 401, Message: lastErr.Error()}
}
// checkRequiredRoles checks the authenticated user's roles against the required roles.
// By default (requireAll=false), the user needs at least one of the roles (OR semantics).
// When requireAll=true, the user must have all listed roles (AND semantics).
func checkRequiredRoles(authCtx *AuthContext, authService AuthorizationService, requiredRoles []string, requireAll bool) error {
if len(requiredRoles) == 0 {
return nil
}
if requireAll {
for _, role := range requiredRoles {
if !authService.HasRole(authCtx, role) {
return &AuthError{StatusCode: 403, Message: fmt.Sprintf("required role missing: %s", role)}
}
}
return nil
}
for _, role := range requiredRoles {
if authService.HasRole(authCtx, role) {
return nil
}
}
return &AuthError{StatusCode: 403, Message: fmt.Sprintf("requires one of: %s", strings.Join(requiredRoles, ", "))}
}
// validateResourceAccess validates resource access based on tags
func validateResourceAccess(c *fiber.Ctx, authCtx *AuthContext, input interface{}, authService AuthorizationService) error {
inputValue := reflect.ValueOf(input)
inputType := reflect.TypeOf(input)
if isPointerType(inputType) {
inputValue = inputValue.Elem()
inputType = inputType.Elem()
}
if inputType.Kind() != reflect.Struct {
return nil
}
for i := 0; i < inputType.NumField(); i++ {
field := inputType.Field(i)
// New tags for authorization
if resourceTag := field.Tag.Get("resource"); resourceTag != "" {
actionTag := field.Tag.Get("action")
if actionTag == "" {
actionTag = inferActionFromMethod(c.Method())
}
// Get the resource ID field value
fieldValue := inputValue.Field(i)
if fieldValue.Kind() == reflect.String {
resourceID := fieldValue.String()
canAccess, err := authService.CanAccessResource(authCtx, resourceTag, resourceID, actionTag)
if err != nil {
return &AuthError{StatusCode: 500, Message: fmt.Sprintf("authorization check failed: %v", err)}
}
if !canAccess {
return &AuthError{StatusCode: 403, Message: fmt.Sprintf("insufficient permissions for %s %s on %s", actionTag, resourceTag, resourceID)}
}
}
}
}
return nil
}
// inferActionFromMethod infers the action from the HTTP method
func inferActionFromMethod(method string) string {
switch method {
case "GET":
return "read"
case "POST":
return "create"
case "PUT", "PATCH":
return "write"
case "DELETE":
return "delete"
default:
return "read"
}
}