-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.go
More file actions
287 lines (240 loc) · 7.85 KB
/
plugin.go
File metadata and controls
287 lines (240 loc) · 7.85 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
package auth0
import (
"context"
"encoding/json"
"net/http"
"time"
rrcontext "github.com/roadrunner-server/context"
"github.com/roadrunner-server/errors"
"go.uber.org/zap"
)
const pluginName = "auth0"
// Configurer interface for configuration management
type Configurer interface {
UnmarshalKey(name string, out interface{}) error
Has(name string) bool
}
// Logger interface for logging
type Logger interface {
NamedLogger(name string) *zap.Logger
}
// Plugin represents the Auth0 middleware plugin
type Plugin struct {
log *zap.Logger
config *Config
client *Client
sessionManager *SessionManager
urlMatcher *URLMatcher
handler *Handler
// Background cleanup ticker
cleanupTicker *time.Ticker
cleanupDone chan bool
}
// Init initializes the Auth0 middleware plugin
func (p *Plugin) Init(cfg Configurer, log Logger) error {
const op = errors.Op("auth0_plugin_init")
// Check if plugin is enabled
if !cfg.Has(pluginName) {
return errors.E(op, errors.Disabled)
}
// Initialize logger
p.log = log.NamedLogger(pluginName)
// Initialize configuration
p.config = &Config{}
if err := cfg.UnmarshalKey(pluginName, p.config); err != nil {
return errors.E(op, err)
}
// Set defaults and validate
p.config.InitDefaults()
if err := p.config.Validate(); err != nil {
return errors.E(op, err)
}
// Initialize Auth0 client
client, err := NewClient(p.config)
if err != nil {
return errors.E(op, err)
}
p.client = client
// Initialize session manager
p.sessionManager = NewSessionManager(&p.config.Session)
// Initialize URL matcher
urlMatcher, err := NewURLMatcher(&p.config.Protection)
if err != nil {
return errors.E(op, err)
}
p.urlMatcher = urlMatcher
// Initialize handler
p.handler = NewHandler(client, p.sessionManager, p.config, p.log)
// Start background cleanup goroutine
p.startCleanupRoutine()
p.log.Debug("Auth0 middleware initialized",
zap.String("domain", p.config.Domain),
zap.String("protection_mode", p.config.Protection.Mode))
return nil
}
// Middleware implements the HTTP middleware interface
func (p *Plugin) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
const op = "auth0_middleware"
// Check if this is an authentication route
if p.isAuthRoute(r.URL.Path) {
p.handleAuthRoute(w, r)
return
}
// Check if URL should be protected
protection := p.urlMatcher.ShouldProtect(r.URL.Path)
if !protection.Protected {
// URL is not protected, inject unauthenticated context and continue
r = p.injectUnauthenticatedContext(r)
next.ServeHTTP(w, r)
return
}
// URL is protected, check authentication
session, err := p.sessionManager.GetSessionFromCookie(r)
if err != nil || session == nil {
p.log.Debug("unauthenticated request to protected URL",
zap.String("op", op),
zap.String("path", r.URL.Path),
zap.String("reason", protection.Reason),
zap.Error(err))
// Redirect to login
p.redirectToLogin(w, r)
return
}
// User is authenticated, inject context and continue
r = p.injectAuthenticatedContext(r, session)
p.log.Debug("authenticated request",
zap.String("op", op),
zap.String("path", r.URL.Path),
zap.String("user_id", session.UserID),
zap.String("session_id", session.ID))
next.ServeHTTP(w, r)
})
}
// Name returns the plugin name
func (p *Plugin) Name() string {
return pluginName
}
// Weight returns the middleware weight (higher weight = later in chain)
func (p *Plugin) Weight() uint {
return 100
}
// Stop gracefully stops the plugin
func (p *Plugin) Stop(ctx context.Context) error {
if p.cleanupTicker != nil {
p.cleanupTicker.Stop()
}
if p.cleanupDone != nil {
close(p.cleanupDone)
}
p.log.Info("Auth0 middleware stopped")
return nil
}
// isAuthRoute checks if the path is an authentication route
func (p *Plugin) isAuthRoute(path string) bool {
return p.urlMatcher.IsAuthRoute(path, p.config.Routes.Login) ||
p.urlMatcher.IsAuthRoute(path, p.config.Routes.Callback) ||
p.urlMatcher.IsAuthRoute(path, p.config.Routes.Logout) ||
p.urlMatcher.IsAuthRoute(path, p.config.Routes.UserInfo)
}
// handleAuthRoute handles authentication routes
func (p *Plugin) handleAuthRoute(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
switch {
case p.urlMatcher.IsAuthRoute(path, p.config.Routes.Login):
p.log.Info("routing to login handler")
p.handler.HandleLogin(w, r)
case p.urlMatcher.IsAuthRoute(path, p.config.Routes.Callback):
p.log.Info("routing to callback handler")
p.handler.HandleCallback(w, r)
case p.urlMatcher.IsAuthRoute(path, p.config.Routes.Logout):
p.log.Info("routing to logout handler")
p.handler.HandleLogout(w, r)
case p.urlMatcher.IsAuthRoute(path, p.config.Routes.UserInfo):
p.log.Info("routing to userinfo handler")
p.handler.HandleUserInfo(w, r)
default:
// This shouldn't happen, but handle gracefully
p.log.Warn("auth route matched but no handler found", zap.String("path", path))
http.NotFound(w, r)
}
}
// redirectToLogin redirects to the login route
func (p *Plugin) redirectToLogin(w http.ResponseWriter, r *http.Request) {
loginURL := p.config.Routes.Login
// Add return_to parameter if not already an auth route
if !p.isAuthRoute(r.URL.Path) {
loginURL += "?return_to=" + r.URL.Path
}
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
}
// injectAuthenticatedContext injects authenticated user context into request
// Sets a single "auth0" PSR attribute containing JSON with complete user data
func (p *Plugin) injectAuthenticatedContext(r *http.Request, session *Session) *http.Request {
// Initialize PSR attributes if not already present
ctx := r.Context()
var psrAttributes map[string][]string
if existingAttrs := ctx.Value(rrcontext.PsrContextKey); existingAttrs != nil {
if attrs, ok := existingAttrs.(map[string][]string); ok {
psrAttributes = attrs
} else {
psrAttributes = make(map[string][]string)
}
} else {
psrAttributes = make(map[string][]string)
}
// Create Auth0 data structure
auth0Data := NewAuth0Data(session)
if auth0Data != nil {
// Serialize to JSON
if auth0JSON, err := json.Marshal(auth0Data); err == nil {
p.setStringAttr(psrAttributes, "auth0", string(auth0JSON))
} else {
// Log error but continue without setting attribute
p.log.Error("failed to serialize auth0 data",
zap.String("user_id", session.UserID),
zap.Error(err))
}
}
// Set the updated PSR attributes back to context
ctx = context.WithValue(ctx, rrcontext.PsrContextKey, psrAttributes)
return r.WithContext(ctx)
}
// injectUnauthenticatedContext injects unauthenticated context into request
// For unauthenticated users, we do NOT set any auth0 attribute
// The absence of the "auth0" attribute indicates the user is not authenticated
func (p *Plugin) injectUnauthenticatedContext(r *http.Request) *http.Request {
// No need to set any attributes for unauthenticated users
// PHP application will treat absence of "auth0" attribute as guest user
return r
}
// startCleanupRoutine starts background session cleanup
func (p *Plugin) startCleanupRoutine() {
p.cleanupTicker = time.NewTicker(15 * time.Minute) // Cleanup every 15 minutes
p.cleanupDone = make(chan bool)
go func() {
for {
select {
case <-p.cleanupTicker.C:
p.sessionManager.CleanupExpiredSessions()
sessionCount := p.sessionManager.GetSessionCount()
p.log.Debug("cleaned up expired sessions",
zap.Int("active_sessions", sessionCount))
case <-p.cleanupDone:
return
}
}
}()
}
// RPC returns the RPC interface for external API access
func (p *Plugin) RPC() interface{} {
return &RPC{plugin: p}
}
// setStringAttr is a helper function to set a string attribute in PSR attributes map
func (p *Plugin) setStringAttr(attrs map[string][]string, key, value string) {
if attrs[key] == nil {
attrs[key] = []string{value}
} else {
attrs[key] = append(attrs[key], value)
}
}