16552: Nginx listens on all interfaces, not just loopback.
[arvados.git] / lib / boot / nginx.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package boot
6
7 import (
8         "context"
9         "fmt"
10         "io/ioutil"
11         "net"
12         "net/url"
13         "os"
14         "os/exec"
15         "path/filepath"
16         "regexp"
17         "strings"
18
19         "git.arvados.org/arvados.git/sdk/go/arvados"
20 )
21
22 // Run an Nginx process that proxies the supervisor's configured
23 // ExternalURLs to the appropriate InternalURLs.
24 type runNginx struct{}
25
26 func (runNginx) String() string {
27         return "nginx"
28 }
29
30 func (runNginx) Run(ctx context.Context, fail func(error), super *Supervisor) error {
31         err := super.wait(ctx, createCertificates{})
32         if err != nil {
33                 return err
34         }
35         vars := map[string]string{
36                 "LISTENHOST":       "0.0.0.0",
37                 "UPSTREAMHOST":     super.ListenHost,
38                 "SSLCERT":          filepath.Join(super.tempdir, "server.crt"),
39                 "SSLKEY":           filepath.Join(super.tempdir, "server.key"),
40                 "ACCESSLOG":        filepath.Join(super.tempdir, "nginx_access.log"),
41                 "ERRORLOG":         filepath.Join(super.tempdir, "nginx_error.log"),
42                 "TMPDIR":           super.wwwtempdir,
43                 "ARVADOS_API_HOST": super.cluster.Services.Controller.ExternalURL.Host,
44         }
45         u := url.URL(super.cluster.Services.Controller.ExternalURL)
46         ctrlHost := u.Hostname()
47         if strings.HasPrefix(super.cluster.TLS.Certificate, "file:/") && strings.HasPrefix(super.cluster.TLS.Key, "file:/") {
48                 vars["SSLCERT"] = filepath.Clean(super.cluster.TLS.Certificate[5:])
49                 vars["SSLKEY"] = filepath.Clean(super.cluster.TLS.Key[5:])
50         } else if f, err := os.Open("/var/lib/acme/live/" + ctrlHost + "/privkey"); err == nil {
51                 f.Close()
52                 vars["SSLCERT"] = "/var/lib/acme/live/" + ctrlHost + "/cert"
53                 vars["SSLKEY"] = "/var/lib/acme/live/" + ctrlHost + "/privkey"
54         }
55         for _, cmpt := range []struct {
56                 varname string
57                 svc     arvados.Service
58         }{
59                 {"CONTROLLER", super.cluster.Services.Controller},
60                 {"KEEPWEB", super.cluster.Services.WebDAV},
61                 {"KEEPWEBDL", super.cluster.Services.WebDAVDownload},
62                 {"KEEPPROXY", super.cluster.Services.Keepproxy},
63                 {"GIT", super.cluster.Services.GitHTTP},
64                 {"HEALTH", super.cluster.Services.Health},
65                 {"WORKBENCH1", super.cluster.Services.Workbench1},
66                 {"WORKBENCH2", super.cluster.Services.Workbench2},
67                 {"WS", super.cluster.Services.Websocket},
68         } {
69                 var host, port string
70                 if len(cmpt.svc.InternalURLs) == 0 {
71                         // We won't run this service, but we need an
72                         // upstream port to write in our templated
73                         // nginx config. Choose a port that will
74                         // return 502 Bad Gateway.
75                         port = "9"
76                 } else if host, port, err = internalPort(cmpt.svc); err != nil {
77                         return fmt.Errorf("%s internal port: %w (%v)", cmpt.varname, err, cmpt.svc)
78                 } else if ok, err := addrIsLocal(net.JoinHostPort(host, port)); !ok || err != nil {
79                         return fmt.Errorf("%s addrIsLocal() failed for host %q port %q: %v", cmpt.varname, host, port, err)
80                 }
81                 vars[cmpt.varname+"PORT"] = port
82
83                 port, err = externalPort(cmpt.svc)
84                 if err != nil {
85                         return fmt.Errorf("%s external port: %w (%v)", cmpt.varname, err, cmpt.svc)
86                 }
87                 listenAddr := net.JoinHostPort(super.ListenHost, port)
88                 if ok, err := addrIsLocal(listenAddr); !ok || err != nil {
89                         return fmt.Errorf("%s addrIsLocal(%q) failed: %w", cmpt.varname, listenAddr, err)
90                 }
91                 vars[cmpt.varname+"SSLPORT"] = port
92         }
93         var conftemplate string
94         if super.ClusterType == "production" {
95                 conftemplate = "/var/lib/arvados/share/nginx.conf"
96         } else {
97                 conftemplate = filepath.Join(super.SourcePath, "sdk", "python", "tests", "nginx.conf")
98         }
99         tmpl, err := ioutil.ReadFile(conftemplate)
100         if err != nil {
101                 return err
102         }
103         conf := regexp.MustCompile(`{{.*?}}`).ReplaceAllStringFunc(string(tmpl), func(src string) string {
104                 if len(src) < 4 {
105                         return src
106                 }
107                 return vars[src[2:len(src)-2]]
108         })
109         conffile := filepath.Join(super.tempdir, "nginx.conf")
110         err = ioutil.WriteFile(conffile, []byte(conf), 0755)
111         if err != nil {
112                 return err
113         }
114         nginx := "nginx"
115         if _, err := exec.LookPath(nginx); err != nil {
116                 for _, dir := range []string{"/sbin", "/usr/sbin", "/usr/local/sbin"} {
117                         if _, err = os.Stat(dir + "/nginx"); err == nil {
118                                 nginx = dir + "/nginx"
119                                 break
120                         }
121                 }
122         }
123
124         configs := "error_log stderr info; "
125         configs += "pid " + filepath.Join(super.wwwtempdir, "nginx.pid") + "; "
126         configs += "user www-data; "
127
128         super.waitShutdown.Add(1)
129         go func() {
130                 defer super.waitShutdown.Done()
131                 fail(super.RunProgram(ctx, ".", runOptions{}, nginx, "-g", configs, "-c", conffile))
132         }()
133         // Choose one of the ports where Nginx should listen, and wait
134         // here until we can connect. If ExternalURL is https://foo
135         // (with no port) then we connect to "foo:https"
136         testurl := url.URL(super.cluster.Services.Controller.ExternalURL)
137         if testurl.Port() == "" {
138                 testurl.Host = net.JoinHostPort(testurl.Host, testurl.Scheme)
139         }
140         return waitForConnect(ctx, testurl.Host)
141 }