Set X-Tailscale-* headers when copy_headers argument passed in the Caddyfile

This commit is contained in:
akp 2024-10-10 00:29:00 +01:00
parent 8dc2e083f3
commit 842a867d21
No known key found for this signature in database
GPG key ID: CF8D58F3DEB20755
2 changed files with 55 additions and 12 deletions

View file

@ -1,32 +1,73 @@
package caddy_tailscale
import (
"encoding/json"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/caddyserver/caddy/v2/modules/caddyhttp/caddyauth"
"github.com/caddyserver/caddy/v2/modules/caddyhttp/headers"
"net/http"
)
const directiveName = "tailscale_auth"
func init() {
httpcaddyfile.RegisterHandlerDirective(directiveName, parseCaddyfile)
httpcaddyfile.RegisterDirectiveOrder(directiveName, httpcaddyfile.After, "basic_auth")
httpcaddyfile.RegisterDirective("tailscale_auth", parseCaddyfileTSAuth)
httpcaddyfile.RegisterDirectiveOrder("tailscale_auth", httpcaddyfile.After, "basic_auth")
}
// parseCaddyfile sets up the handler from Caddyfile tokens. Syntax:
// parseCaddyfileTSAuth sets up the handler from Caddyfile tokens. Syntax:
//
// tailscale_auth
//
// See also for further examples: https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/caddyauth/caddyfile.go
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
func parseCaddyfileTSAuth(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) {
h.Next() // consume directive name
ta := new(TailscaleAuth)
return caddyauth.Authentication{
ProvidersRaw: caddy.ModuleMap{
"tailscale": caddyconfig.JSON(ta, nil),
handlers := []json.RawMessage{
caddyconfig.JSONModuleObject(
caddyauth.Authentication{
ProvidersRaw: caddy.ModuleMap{
"tailscale": caddyconfig.JSON(new(TailscaleAuth), nil),
},
},
"handler",
"authentication",
nil,
),
}
if h.Next() {
if h.Val() == "set_headers" {
handlers = append(handlers, caddyconfig.JSONModuleObject(
&headers.Handler{
Request: &headers.HeaderOps{
Set: http.Header{
"X-Tailscale-ID": []string{"{http.auth.user.id}"},
"X-Tailscale-Display-Name": []string{"{http.auth.user.display_name}"},
"X-Tailscale-Login-Name": []string{"{http.auth.user.login_name}"},
},
},
},
"handler",
"headers",
nil,
))
} else {
return nil, h.Errf("unknown argument %#v", h.ValRaw())
}
}
if h.NextArg() {
return nil, h.Err("too many arguments")
}
return []httpcaddyfile.ConfigValue{
{
Class: "route",
Value: caddyhttp.Route{
HandlersRaw: handlers,
},
},
}, nil
}

View file

@ -44,7 +44,9 @@ func (ta *TailscaleAuth) Authenticate(wr http.ResponseWriter, req *http.Request)
},
}
return user, false, nil
wr.Header().Add("x-tailscale-login-name", whois.UserProfile.LoginName)
return user, true, nil
}
var (