Caddy module to require at-proto authentication and restrict routes to DIDs
1package caddyatprotoauth
2
3import (
4 "encoding/json"
5 "fmt"
6 "net/http"
7 "net/url"
8 "time"
9
10 "github.com/caddyserver/caddy/v2"
11 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
12 "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
13 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
14 "go.uber.org/zap"
15 "tangled.org/vvill.dev/caddy-atproto-auth/internal/oauth"
16 "tangled.org/vvill.dev/caddy-atproto-auth/internal/resolver"
17 "tangled.org/vvill.dev/caddy-atproto-auth/internal/session"
18 "tangled.org/vvill.dev/caddy-atproto-auth/internal/ui"
19)
20
21func init() {
22 caddy.RegisterModule(Gate{})
23 httpcaddyfile.RegisterHandlerDirective("atproto_gate", parseCaddyfileGate)
24}
25
26// Gate acts as a middleware that guards endpoints
27// and validates the session cookie.
28type Gate struct {
29 Allow []string `json:"allow,omitempty"`
30 Domain string `json:"domain,omitempty"` // Public domain for standalone mode (e.g. app.example.com)
31 PortalURL string `json:"portal_url,omitempty"` // URL of the central auth portal if NOT in standalone mode
32 UI ui.Config `json:"ui,omitempty"` // Custom UI configuration
33
34 // Dependencies
35 app *App
36 resolver *resolver.Resolver
37 sessions *session.Manager
38 oauth *oauth.Manager
39 renderer *ui.Renderer
40 logger *zap.Logger
41}
42
43// CaddyModule returns the Caddy module information.
44func (Gate) CaddyModule() caddy.ModuleInfo {
45 return caddy.ModuleInfo{
46 ID: "http.handlers.atproto_gate",
47 New: func() caddy.Module { return new(Gate) },
48 }
49}
50
51// Provision sets up the module.
52func (g *Gate) Provision(ctx caddy.Context) error {
53 g.logger = ctx.Logger()
54
55 // 1. Get Global App
56 app, err := ctx.App("atproto")
57 if err != nil {
58 return fmt.Errorf("getting atproto app: %w", err)
59 }
60 g.app = app.(*App)
61
62 // 2. Initialize Session Manager (using global secret)
63 if g.app.CookieSecret == "" {
64 return fmt.Errorf("global atproto cookie_secret is required")
65 }
66 g.sessions = session.NewManager(g.app.CookieSecret)
67
68 // 3. Initialize Identity Resolver
69 g.resolver = resolver.New()
70
71 // 4. Initialize UI Renderer
72 renderer, err := ui.NewRenderer(g.UI)
73 if err != nil {
74 return fmt.Errorf("failed to init ui renderer: %w", err)
75 }
76 g.renderer = renderer
77
78 // 5. Initialize OAuth Manager (if domain set for standalone mode)
79 if g.Domain != "" {
80 clientID := fmt.Sprintf("https://%s/.well-known/oauth-client-metadata.json", g.Domain)
81 callbackURL := fmt.Sprintf("https://%s/callback", g.Domain)
82
83 mgr, err := oauth.NewManager(g.app.Store, clientID, callbackURL)
84 if err != nil {
85 return fmt.Errorf("failed to init oauth manager: %w", err)
86 }
87 g.oauth = mgr
88 }
89
90 return nil
91}
92
93// Validate checks that the configuration is valid.
94func (g *Gate) Validate() error {
95 if len(g.Allow) == 0 {
96 return fmt.Errorf("atproto_gate requires at least one 'allow' entry")
97 }
98 return nil
99}
100
101// UnmarshalCaddyfile implements caddyfile.Unmarshaler.
102func (g *Gate) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
103 for d.Next() {
104 for nesting := d.Nesting(); d.NextBlock(nesting); {
105 switch d.Val() {
106 case "allow":
107 g.Allow = append(g.Allow, d.RemainingArgs()...)
108 case "domain":
109 if !d.NextArg() {
110 return d.ArgErr()
111 }
112 g.Domain = d.Val()
113 case "portal_url":
114 if !d.NextArg() {
115 return d.ArgErr()
116 }
117 g.PortalURL = d.Val()
118 case "ui":
119 for nesting := d.Nesting(); d.NextBlock(nesting); {
120 switch d.Val() {
121 case "login_template":
122 if !d.NextArg() {
123 return d.ArgErr()
124 }
125 g.UI.LoginTemplatePath = d.Val()
126 case "forbidden_template":
127 if !d.NextArg() {
128 return d.ArgErr()
129 }
130 g.UI.ForbiddenTemplatePath = d.Val()
131 default:
132 return d.Errf("unrecognized subdirective '%s'", d.Val())
133 }
134 }
135 default:
136 return d.Errf("unrecognized subdirective '%s'", d.Val())
137 }
138 }
139 }
140 return nil
141}
142
143// parseCaddyfileGate parses the atproto_gate directive from a Caddyfile.
144func parseCaddyfileGate(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
145 var g Gate
146 err := g.UnmarshalCaddyfile(h.Dispenser)
147 return &g, err
148}
149
150// ServeHTTP implements caddyhttp.MiddlewareHandler.
151func (g *Gate) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
152 // If in Standalone Mode, handle OAuth paths
153 if g.oauth != nil {
154 if r.URL.Path == "/.well-known/oauth-client-metadata.json" {
155 meta, err := g.oauth.GetClientMetadata()
156 if err != nil {
157 return caddyhttp.Error(http.StatusInternalServerError, err)
158 }
159 w.Header().Set("Content-Type", "application/json")
160 return json.NewEncoder(w).Encode(meta)
161 }
162 if r.URL.Path == "/callback" {
163 // Process callback
164 sessionData, handle, err := g.oauth.ProcessCallback(r.Context(), r.URL.Query())
165 if err != nil {
166 return caddyhttp.Error(http.StatusBadRequest, err)
167 }
168
169 // Create Session Cookie
170 cookie, err := g.sessions.CreateCookie(
171 sessionData.AccountDID,
172 handle,
173 24*7*time.Hour,
174 g.Domain,
175 )
176 if err != nil {
177 return caddyhttp.Error(http.StatusInternalServerError, err)
178 }
179
180 http.SetCookie(w, cookie)
181 http.Redirect(w, r, "/", http.StatusFound)
182 return nil
183 }
184 }
185
186 // 1. Verify stateless cookie here
187 sess, err := g.sessions.VerifyCookie(r)
188 if err == session.ErrExpired {
189 // Attempt transparent refresh if we are in a mode that supports it.
190 // We need an OAuth manager to refresh.
191 // If Standalone, g.oauth is set.
192 // If Auth Hub, g.oauth is nil in Gate. Gate relies on Portal.
193 // However, Gate and Portal SHARE the same DB (g.app.Store).
194 // We can spin up a temporary OAuth manager or use a shared one if we had config.
195 // But Gate in Hub mode doesn't know ClientID/CallbackURL.
196 // Wait, the Refresh Token is bound to the ClientID.
197 // If Gate is just a gate, it can't refresh on behalf of the Portal unless it acts AS the Portal client.
198
199 // For Standalone mode, we can refresh.
200 if g.oauth != nil && sess != nil {
201 clientSession, err := g.oauth.ResumeSession(r.Context(), sess.DID)
202 if err == nil {
203 // Refresh tokens
204 if _, err := clientSession.RefreshTokens(r.Context()); err == nil {
205 // Success! Update cookie.
206 // We need to extend expiration.
207 cookie, err := g.sessions.CreateCookie(
208 clientSession.Data.AccountDID,
209 sess.Handle, // Keep handle from old cookie or lookup
210 24*7*time.Hour,
211 g.Domain,
212 )
213 if err == nil {
214 http.SetCookie(w, cookie)
215 // Proceed as authorized
216 r.Header.Set("X-Atproto-Did", sess.DID)
217 r.Header.Set("X-Atproto-Handle", sess.Handle)
218 return next.ServeHTTP(w, r)
219 }
220 }
221 }
222 // If refresh failed, fall through to re-login logic
223 }
224 } else if err == nil {
225 // Session valid!
226 // Check authorization against allowlist
227 allowed := false
228 for _, allow := range g.Allow {
229 if allow == sess.DID || allow == sess.Handle {
230 allowed = true
231 break
232 }
233 }
234
235 if allowed {
236 // Inject headers
237 r.Header.Set("X-Atproto-Did", sess.DID)
238 r.Header.Set("X-Atproto-Handle", sess.Handle)
239 return next.ServeHTTP(w, r)
240 }
241
242 // Authenticated but not authorized
243 w.Header().Set("Content-Type", "text/html; charset=utf-8")
244 w.WriteHeader(http.StatusForbidden)
245 if err := g.renderer.RenderForbidden(w, ui.ForbiddenData{
246 AppName: g.Domain,
247 DID: sess.DID,
248 Handle: sess.Handle,
249 }); err != nil {
250 g.logger.Error("failed to render forbidden page", zap.Error(err))
251 }
252 return nil
253 }
254
255 // 2. If invalid/missing, initiate redirect to PDS or Auth Hub
256 // If standalone mode (g.oauth != nil), we can initiate flow here?
257 // But which identity? We need to prompt user for handle.
258 // So we should redirect to a login page or show a simple form.
259 // For simplicity, let's just 401 and tell user to go to /login (which we handle if standalone?)
260 // Wait, we didn't add /login handler to Gate yet.
261 // If standalone, Gate should act as Portal.
262 // Let's implement a simple /login handler in Gate if oauth is enabled.
263
264 if g.oauth != nil {
265 if r.URL.Path == "/login" {
266 if r.Method == "POST" {
267 handle := r.FormValue("handle")
268 // Strip leading @ if present
269 if len(handle) > 0 && handle[0] == '@' {
270 handle = handle[1:]
271 }
272
273 redirectURI, err := g.oauth.StartAuthFlow(r.Context(), handle)
274 if err != nil {
275 // Render error on login page instead of raw JSON
276 w.Header().Set("Content-Type", "text/html; charset=utf-8")
277 // We return 400 Bad Request
278 w.WriteHeader(http.StatusBadRequest)
279 if renderErr := g.renderer.RenderLogin(w, ui.LoginData{
280 AppName: g.Domain,
281 Redirect: "/",
282 Error: fmt.Sprintf("Authentication failed: %v", err),
283 }); renderErr != nil {
284 g.logger.Error("failed to render login error", zap.Error(renderErr))
285 }
286 return nil
287 }
288 http.Redirect(w, r, redirectURI, http.StatusFound)
289 return nil
290 }
291 // Show login form
292 w.Header().Set("Content-Type", "text/html; charset=utf-8")
293 if err := g.renderer.RenderLogin(w, ui.LoginData{
294 AppName: g.Domain,
295 Redirect: "/",
296 }); err != nil {
297 g.logger.Error("failed to render login page", zap.Error(err))
298 return caddyhttp.Error(http.StatusInternalServerError, err)
299 }
300 return nil
301 }
302 // Redirect to /login
303 http.Redirect(w, r, "/login", http.StatusFound)
304 return nil
305 }
306
307 // If NOT standalone (Auth Hub mode), redirect to the central Auth Portal if configured.
308 if g.PortalURL != "" {
309 // Construct redirect URL: ${PortalURL}/login?redirect_uri=${CurrentURL}
310 // We need to encode the current URL as a query param.
311 // NOTE: Assuming https for now, Caddy usually knows scheme but r.URL.Scheme might be empty.
312 scheme := "https"
313 if r.TLS == nil {
314 scheme = "http"
315 }
316 host := r.Host
317 currentURL := fmt.Sprintf("%s://%s%s", scheme, host, r.URL.RequestURI())
318
319 portalLogin := fmt.Sprintf("%s/login?redirect_to=%s", g.PortalURL, url.QueryEscape(currentURL))
320 http.Redirect(w, r, portalLogin, http.StatusFound)
321 return nil
322 }
323
324 // Fallback: 401
325 return caddyhttp.Error(http.StatusUnauthorized, fmt.Errorf("unauthorized"))
326}
327
328// Interface guards
329var (
330 _ caddy.Provisioner = (*Gate)(nil)
331 _ caddy.Validator = (*Gate)(nil)
332 _ caddyhttp.MiddlewareHandler = (*Gate)(nil)
333 _ caddyfile.Unmarshaler = (*Gate)(nil)
334)