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 == nil {
189 // Session valid!
190 // Check authorization against allowlist
191 allowed := false
192 for _, allow := range g.Allow {
193 if allow == sess.DID || allow == sess.Handle {
194 allowed = true
195 break
196 }
197 }
198
199 if allowed {
200 // Inject headers
201 r.Header.Set("X-Atproto-Did", sess.DID)
202 r.Header.Set("X-Atproto-Handle", sess.Handle)
203 return next.ServeHTTP(w, r)
204 }
205
206 // Authenticated but not authorized
207 w.Header().Set("Content-Type", "text/html; charset=utf-8")
208 w.WriteHeader(http.StatusForbidden)
209 if err := g.renderer.RenderForbidden(w, ui.ForbiddenData{
210 AppName: g.Domain,
211 DID: sess.DID,
212 Handle: sess.Handle,
213 }); err != nil {
214 g.logger.Error("failed to render forbidden page", zap.Error(err))
215 }
216 return nil
217 }
218
219 // 2. If invalid/missing, initiate redirect to PDS or Auth Hub
220 // If standalone mode (g.oauth != nil), we can initiate flow here?
221 // But which identity? We need to prompt user for handle.
222 // So we should redirect to a login page or show a simple form.
223 // For simplicity, let's just 401 and tell user to go to /login (which we handle if standalone?)
224 // Wait, we didn't add /login handler to Gate yet.
225 // If standalone, Gate should act as Portal.
226 // Let's implement a simple /login handler in Gate if oauth is enabled.
227
228 if g.oauth != nil {
229 if r.URL.Path == "/login" {
230 if r.Method == "POST" {
231 handle := r.FormValue("handle")
232 redirectURI, err := g.oauth.StartAuthFlow(r.Context(), handle)
233 if err != nil {
234 return caddyhttp.Error(http.StatusBadRequest, err)
235 }
236 http.Redirect(w, r, redirectURI, http.StatusFound)
237 return nil
238 }
239 // Show login form
240 w.Header().Set("Content-Type", "text/html; charset=utf-8")
241 if err := g.renderer.RenderLogin(w, ui.LoginData{
242 AppName: g.Domain,
243 Redirect: "/",
244 }); err != nil {
245 g.logger.Error("failed to render login page", zap.Error(err))
246 return caddyhttp.Error(http.StatusInternalServerError, err)
247 }
248 return nil
249 }
250 // Redirect to /login
251 http.Redirect(w, r, "/login", http.StatusFound)
252 return nil
253 }
254
255 // If NOT standalone (Auth Hub mode), redirect to the central Auth Portal if configured.
256 if g.PortalURL != "" {
257 // Construct redirect URL: ${PortalURL}/login?redirect_uri=${CurrentURL}
258 // We need to encode the current URL as a query param.
259 // NOTE: Assuming https for now, Caddy usually knows scheme but r.URL.Scheme might be empty.
260 scheme := "https"
261 if r.TLS == nil {
262 scheme = "http"
263 }
264 host := r.Host
265 currentURL := fmt.Sprintf("%s://%s%s", scheme, host, r.URL.RequestURI())
266
267 portalLogin := fmt.Sprintf("%s/login?redirect_to=%s", g.PortalURL, url.QueryEscape(currentURL))
268 http.Redirect(w, r, portalLogin, http.StatusFound)
269 return nil
270 }
271
272 // Fallback: 401
273 return caddyhttp.Error(http.StatusUnauthorized, fmt.Errorf("unauthorized"))
274}
275
276// Interface guards
277var (
278 _ caddy.Provisioner = (*Gate)(nil)
279 _ caddy.Validator = (*Gate)(nil)
280 _ caddyhttp.MiddlewareHandler = (*Gate)(nil)
281 _ caddyfile.Unmarshaler = (*Gate)(nil)
282)