aboutsummaryrefslogtreecommitdiff
path: root/echo/echo_default.go
blob: ab163ffacd0606518885024cd804acb355a2d660 (plain)
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
package echo

import (
	"context"
	"crypto/tls"
	"fmt"
	"html/template"
	"net/http"
	"sync"

	glmw "code.crute.us/mcrute/golib/echo/middleware"
	gltls "code.crute.us/mcrute/golib/tls"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/labstack/gommon/log"
)

type EchoConfig struct {
	Debug                 bool
	BindAddress           string
	BindTLSAddress        string
	TLSCert               string
	TLSKey                string
	TrustedProxyIPRanges  []string
	TemplatePath          *string
	TemplateGlob          *string
	TemplateFunctions     template.FuncMap
	CombinedHostLogFile   string
	RedirectToWWW         bool
	ContentSecurityPolicy *glmw.ContentSecurityPolicyConfig
}

type EchoWrapper struct {
	*echo.Echo
	tlsServer   http.Server
	bindAddress string
	ocspErrors  chan gltls.OcspError
	ocspManager *gltls.OcspManager
	initDone    bool
}

// Init does "expensive" work that requires network calls but must be called
// before using the returned echo instance
func (w *EchoWrapper) Init() error {
	if err := w.ocspManager.Init(); err != nil {
		return fmt.Errorf("Error loading TLS certificates and stapling: %w", err)
	}
	w.initDone = true
	return nil
}

func (w *EchoWrapper) CachedStaticRoute(prefix, path string) {
	w.Group(prefix, glmw.CacheOneMonthMiddleware).Static("/", path)
}

func (w *EchoWrapper) OcspErrors() chan gltls.OcspError {
	return w.ocspErrors
}

func (w *EchoWrapper) RunCertificateManager(ctx context.Context, wg *sync.WaitGroup) error {
	return w.ocspManager.Run(ctx, wg)
}

func (w *EchoWrapper) run(ctx context.Context, wg *sync.WaitGroup, f func() error, sf func(context.Context) error) error {
	if !w.initDone {
		return fmt.Errorf("Echo is not initialized. Call Init()")
	}

	wg.Add(1)
	defer wg.Done()

	err := make(chan error)
	go func() { err <- f() }()
	select {
	case e := <-err:
		return e
	default:
	}

	select {
	case <-ctx.Done():
		w.Logger.Info("Shutting down web server")
		return sf(ctx)
	}
}

func (w *EchoWrapper) Serve(ctx context.Context, wg *sync.WaitGroup) error {
	return w.run(
		ctx,
		wg,
		func() error { return w.Echo.Start(w.bindAddress) },
		func(ctx context.Context) error { return w.Echo.Shutdown(ctx) },
	)
}

func (w *EchoWrapper) ServeTLS(ctx context.Context, wg *sync.WaitGroup) error {
	return w.run(
		ctx,
		wg,
		func() error { return w.tlsServer.ListenAndServeTLS("", "") },
		func(ctx context.Context) error { return w.tlsServer.Shutdown(ctx) },
	)
}

// NewDefaultEchoWithConfig builds a wrapper around an Echo instance and
// configures it in the default way that it should probably be configured in
// all cases. The struct returned from this function can be treated like a
// normal Echo instance (because, for the most part it is).
//
// Consumers must call Init() on the returned object before serving with it.
func NewDefaultEchoWithConfig(c EchoConfig) (*EchoWrapper, error) {
	var err error

	e := echo.New()
	e.Debug = c.Debug

	e.IPExtractor, err = glmw.ExtractIPFromXFFHeaders(false, c.TrustedProxyIPRanges)
	if err != nil {
		return nil, fmt.Errorf("Error building XFF IP extractor: %w", err)
	}

	// Only install template handlers if the path and glob are set
	if c.TemplatePath != nil && c.TemplateGlob != nil {
		e.HTTPErrorHandler = ErrorHandler(*c.TemplatePath, c.TemplateFunctions)

		tr, err := NewTemplateRenderer(*c.TemplatePath, *c.TemplateGlob, c.TemplateFunctions)
		if err != nil {
			return nil, fmt.Errorf("Error loading template renderer: %w", err)
		}
		e.Renderer = tr
	}

	e.Logger.SetLevel(log.INFO)
	if c.Debug {
		e.Logger.SetLevel(log.DEBUG)
	}

	if c.CombinedHostLogFile != "" {
		lc, err := NginxCombinedHostConfigToFile(c.CombinedHostLogFile)
		if err != nil {
			return nil, fmt.Errorf("Error opening log file: %w", err)
		}
		e.Use(middleware.LoggerWithConfig(lc))
	}

	cmek := make(chan gltls.OcspError)
	cm := &gltls.OcspManager{
		CertPath: c.TLSCert,
		KeyPath:  c.TLSKey,
		Errors:   cmek,
	}

	ts := http.Server{
		Addr: c.BindTLSAddress,
		TLSConfig: &tls.Config{
			MinVersion:     tls.VersionTLS12,
			GetCertificate: cm.GetCertificate,
		},
		Handler: e,
	}

	e.Use(middleware.Logger())
	e.Use(glmw.Recover())
	e.Use(middleware.HTTPSRedirect())
	if c.RedirectToWWW {
		e.Use(middleware.WWWRedirect())
	}
	e.Use(middleware.GzipWithConfig(middleware.GzipConfig{Level: 5}))
	e.Use(glmw.StrictSecure())

	if c.ContentSecurityPolicy != nil {
		e.Use(glmw.ContentSecurityPolicyWithConfig(*c.ContentSecurityPolicy))
	} else {
		return nil, fmt.Errorf("ContentSecurityPolicy is required")
	}

	return &EchoWrapper{
		Echo:        e,
		tlsServer:   ts,
		bindAddress: c.BindAddress,
		ocspErrors:  cmek,
		ocspManager: cm,
	}, nil
}