package security import ( "context" "crypto/tls" "encoding/json" "fmt" "io" "log/slog" "net" "net/http" "net/http/httputil" "net/url" "os" "strings" "time" ) type Rule struct { Identity string `json:"identity"` Methods []string `json:"methods"` Prefixes []string `json:"prefixes"` } type Listener struct { Listen string `json:"listen"` Target string `json:"target"` Raw bool `json:"raw"` Identities []string `json:"identities"` Rules []Rule `json:"rules"` } // The plaintext upstream is always loopback in the SAME network namespace. // Services have no native listener on the container network or published port. func Gateway(ctx context.Context, path string) error { b, e := os.ReadFile(path) if e != nil { return e } var configs []Listener if e = json.Unmarshal(b, &configs); e != nil { return e } errors := make(chan error, len(configs)) for _, cfg := range configs { cfg := cfg host, _, e := net.SplitHostPort(cfg.Target) if e != nil || host != "127.0.0.1" { return fmt.Errorf("gateway upstream must be loopback") } tc, e := ServerTLS(cfg.Identities) if e != nil { return e } ln, e := tls.Listen("tcp", cfg.Listen, tc) if e != nil { return e } go func() { <-ctx.Done(); ln.Close() }() if cfg.Raw { go func() { for { c, e := ln.Accept() if e != nil { errors <- e return } go func() { defer c.Close() c.SetDeadline(time.Now().Add(30 * time.Second)) if e := c.(*tls.Conn).Handshake(); e != nil { return } up, e := net.DialTimeout("tcp", cfg.Target, time.Second) if e != nil { return } defer up.Close() up.SetDeadline(time.Now().Add(30 * time.Second)) go io.Copy(up, c) io.Copy(c, up) }() } }() continue } u, _ := url.Parse("http://" + cfg.Target) proxy := httputil.NewSingleHostReverseProxy(u) proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) { http.Error(w, "upstream unavailable", 503) } handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if len(cfg.Rules) > 0 { allowed := false for _, rule := range cfg.Rules { if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 { continue } identity := false for _, san := range r.TLS.PeerCertificates[0].DNSNames { if san == rule.Identity+".client.lab" { identity = true } } method := false for _, v := range rule.Methods { if v == r.Method { method = true } } if identity && method { for _, p := range rule.Prefixes { if strings.HasPrefix(r.URL.Path, p) { allowed = true } } } } if !allowed { http.Error(w, "service action forbidden", 403) return } } proxy.ServeHTTP(w, r) }) srv := &http.Server{Handler: AuthorizeHTTP(tc, handler), ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 35 * time.Second, WriteTimeout: 35 * time.Second, IdleTimeout: 2 * time.Second, MaxHeaderBytes: 16 << 10, ErrorLog: slog.NewLogLogger(slog.NewTextHandler(io.Discard, nil), slog.LevelError)} go func() { errors <- srv.Serve(ln) }() } select { case <-ctx.Done(): return nil case e := <-errors: return e } }