summaryrefslogtreecommitdiffhomepage
path: root/config.go
blob: e1916324eb2ce8a45cb9d61b59ae3b938eaff70a (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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package main

import (
	"fmt"
	"net/netip"
	"net/url"
	"strings"

	"github.com/hashicorp/hcl/v2/hclsimple"
)

type Config struct {
	User    string
	Servers []ServerConfig
}

type ServerConfig struct {
	Protocol        string
	Host            string
	Port            int
	RedirectToHTTPS bool
	ACMEChallenge   *ACMEChallengeConfig
	TLSCertFile     string
	TLSKeyFile      string
	Proxies         []ProxyConfig
}

type ACMEChallengeConfig struct {
	Root string
}

type ProxyConfig struct {
	Name      string
	From      ProxyFromConfig
	To        ProxyToConfig
	BasicAuth *ProxyBasicAuthConfig
}

type ProxyFromConfig struct {
	Host string
	Path string
}

type ProxyToConfig struct {
	Host string
	Port int
}

type ProxyBasicAuthConfig struct {
	Realm          string
	CredentialFile string
}

type InternalHCLConfig struct {
	User    string                    `hcl:"user,optional"`
	Servers []InternalHCLServerConfig `hcl:"server,block"`
}

type InternalHCLServerConfig struct {
	Protocol        string                           `hcl:"protocol,label"`
	Host            string                           `hcl:"host"`
	Port            int                              `hcl:"port"`
	RedirectToHTTPS bool                             `hcl:"redirect_to_https,optional"`
	ACMEChallenge   []InternalHCLACMEChallengeConfig `hcl:"acme_challenge,block"`
	TLSCertFile     string                           `hcl:"tls_cert_file,optional"`
	TLSKeyFile      string                           `hcl:"tls_key_file,optional"`
	Proxies         []InternalHCLProxyConfig         `hcl:"proxy,block"`
}

type InternalHCLACMEChallengeConfig struct {
	Root string `hcl:"root"`
}

type InternalHCLProxyConfig struct {
	Name  string                       `hcl:"name,label"`
	From  InternalHCLProxyFromConfig   `hcl:"from,block"`
	To    InternalHCLProxyToConfig     `hcl:"to,block"`
	Auths []InternalHCLProxyAuthConfig `hcl:"auth,block"`
}

type InternalHCLProxyFromConfig struct {
	Host string `hcl:"host,optional"`
	Path string `hcl:"path,optional"`
}

type InternalHCLProxyToConfig struct {
	Host string `hcl:"host"`
	Port int    `hcl:"port"`
}

type InternalHCLProxyAuthConfig struct {
	Scheme         string `hcl:"scheme,label"`
	Realm          string `hcl:"realm"`
	CredentialFile string `hcl:"credential_file"`
}

func fromHCLConfigToConfig(hclConfig *InternalHCLConfig) *Config {
	servers := make([]ServerConfig, len(hclConfig.Servers))
	for i, s := range hclConfig.Servers {
		var acmeChallenge *ACMEChallengeConfig
		if len(s.ACMEChallenge) != 0 {
			acmeChallenge = &ACMEChallengeConfig{
				Root: s.ACMEChallenge[0].Root,
			}
		}
		proxies := make([]ProxyConfig, len(s.Proxies))
		for j, p := range s.Proxies {
			var basicAuth *ProxyBasicAuthConfig
			if len(p.Auths) != 0 {
				auth := p.Auths[0]
				basicAuth = &ProxyBasicAuthConfig{
					Realm:          auth.Realm,
					CredentialFile: auth.CredentialFile,
				}
			}
			proxies[j] = ProxyConfig{
				Name: p.Name,
				From: ProxyFromConfig{
					Host: p.From.Host,
					Path: p.From.Path,
				},
				To: ProxyToConfig{
					Host: p.To.Host,
					Port: p.To.Port,
				},
				BasicAuth: basicAuth,
			}
		}
		servers[i] = ServerConfig{
			Protocol:        s.Protocol,
			Host:            s.Host,
			Port:            s.Port,
			RedirectToHTTPS: s.RedirectToHTTPS,
			ACMEChallenge:   acmeChallenge,
			TLSCertFile:     s.TLSCertFile,
			TLSKeyFile:      s.TLSKeyFile,
			Proxies:         proxies,
		}
	}

	return &Config{
		User:    hclConfig.User,
		Servers: servers,
	}
}

func LoadConfig(fileName string) (*Config, error) {
	var hclConfig InternalHCLConfig
	err := hclsimple.DecodeFile(fileName, nil, &hclConfig)
	if err != nil {
		return nil, err
	}

	if len(hclConfig.Servers) == 0 {
		return nil, fmt.Errorf("No server blocks found")
	}
	if 2 < len(hclConfig.Servers) {
		return nil, fmt.Errorf("Too many server blocks found")
	}

	var listenHTTPS = false
	var redirectToHTTPS = false
	for _, server := range hclConfig.Servers {
		if server.Protocol == "https" {
			listenHTTPS = true
		} else if server.Protocol != "http" {
			return nil, fmt.Errorf("Invalid protocol %s", server.Protocol)
		}

		_, err = netip.ParseAddr(server.Host)
		if err != nil {
			return nil, fmt.Errorf("Invalid host %s", server.Host)
		}

		if len(server.ACMEChallenge) != 0 && len(server.ACMEChallenge) != 1 {
			return nil, fmt.Errorf("Only one acme_challenge block is allowed")
		}
		if len(server.ACMEChallenge) != 0 && server.Protocol != "http" {
			return nil, fmt.Errorf("accept_acme_challenge must be on http listener")
		}

		if server.RedirectToHTTPS {
			redirectToHTTPS = true
			if server.Protocol != "http" {
				return nil, fmt.Errorf("redirect_to_https must be on http listener")
			}
			if len(server.Proxies) != 0 {
				return nil, fmt.Errorf("redirect_to_https cannot be used with proxy")
			}
		}

		if server.Protocol == "https" {
			if server.TLSCertFile == "" {
				return nil, fmt.Errorf("tls_cert_file is required for https listener")
			}
			if server.TLSKeyFile == "" {
				return nil, fmt.Errorf("tls_key_file is required for https listener")
			}
		} else {
			if server.TLSCertFile != "" {
				return nil, fmt.Errorf("tls_cert_file is only allowed for https listener")
			}
			if server.TLSKeyFile != "" {
				return nil, fmt.Errorf("tls_key_file is only allowed for https listener")
			}
		}

		for _, p := range server.Proxies {
			if p.From.Path != "" {
				if !strings.HasPrefix(p.From.Path, "/") {
					return nil, fmt.Errorf("Path must start with '/'")
				}
				if !strings.HasSuffix(p.From.Path, "/") {
					return nil, fmt.Errorf("Path must end with '/'")
				}
			}
			if p.From.Host == "" && p.From.Path == "" {
				return nil, fmt.Errorf("Either host or path must be specified")
			}
			_, err := url.Parse(fmt.Sprintf("http://%s:%d", p.To.Host, p.To.Port))
			if err != nil {
				return nil, fmt.Errorf("Invalid host or port: %s:%d", p.To.Host, p.To.Port)
			}
			if 2 <= len(p.Auths) {
				return nil, fmt.Errorf("Too many auth blocks found")
			}
			if len(p.Auths) == 1 {
				auth := p.Auths[0]
				if auth.Scheme != "basic" {
					return nil, fmt.Errorf("Only basic auth is supported")
				}
				if auth.Realm == "" {
					return nil, fmt.Errorf("realm is required")
				}
				if auth.CredentialFile == "" {
					return nil, fmt.Errorf("credential_file is required")
				}
			}
		}
	}
	if redirectToHTTPS && !listenHTTPS {
		return nil, fmt.Errorf("redirect_to_https requires https listener")
	}

	return fromHCLConfigToConfig(&hclConfig), nil
}