| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package remotecmd |
| 18 | |
| 19 | import ( |
| 20 | "crypto/tls" |
| 21 | "encoding/json" |
| 22 | "errors" |
| 23 | "fmt" |
| 24 | "io" |
| 25 | "net" |
| 26 | "net/http" |
| 27 | "net/url" |
| 28 | "os" |
| 29 | "strings" |
| 30 | "time" |
| 31 | |
| 32 | "golang.org/x/net/http2" |
| 33 | "golang.org/x/oauth2" |
| 34 | |
| 35 | "github.com/sassoftware/relic/v7/cmdline/shared" |
| 36 | "github.com/sassoftware/relic/v7/config" |
| 37 | "github.com/sassoftware/relic/v7/internal/authmodel" |
| 38 | "github.com/sassoftware/relic/v7/internal/httperror" |
| 39 | "github.com/sassoftware/relic/v7/lib/compresshttp" |
| 40 | "github.com/sassoftware/relic/v7/lib/x509tools" |
| 41 | ) |
| 42 | |
| 43 | type ReaderGetter interface { |
| 44 | GetReader() (io.Reader, error) |
| 45 | } |
| 46 | |
| 47 | type client struct { |
| 48 | config *config.RemoteConfig |
| 49 | cli *http.Client |
| 50 | tokenSource oauth2.TokenSource |
| 51 | } |
| 52 | |
| 53 | func newClient() (*client, error) { |
| 54 | err := shared.InitClientConfig() |
| 55 | if err != nil { |
| 56 | return nil, err |
| 57 | } |
| 58 | cfg := shared.CurrentConfig.Remote |
| 59 | if cfg == nil { |
| 60 | return nil, errors.New("missing remote section in config file") |
| 61 | } else if cfg.DirectoryURL == "" { |
| 62 | if cfg.URL == "" { |
| 63 | return nil, errors.New("url or directoryUrl must be set in 'remote' section of configuration") |
| 64 | } |
| 65 | cfg.DirectoryURL = cfg.URL |
| 66 | } |
| 67 | tconf, err := makeTLSConfig(cfg) |
| 68 | if err != nil { |
| 69 | return nil, err |
| 70 | } |
| 71 | dialer := &net.Dialer{ |
| 72 | Timeout: time.Duration(cfg.ConnectTimeout) * time.Second, |
| 73 | } |
| 74 | transport := &http.Transport{TLSClientConfig: tconf, DialContext: dialer.DialContext} |
| 75 | if err := http2.ConfigureTransport(transport); err != nil { |
| 76 | return nil, err |
| 77 | } |
| 78 | client := &client{ |
| 79 | config: cfg, |
| 80 | cli: &http.Client{Transport: transport}, |
| 81 | } |
| 82 | if cfg.AccessToken != "" { |
| 83 | // static access token from environment |
| 84 | client.tokenSource = oauth2.StaticTokenSource(&oauth2.Token{AccessToken: cfg.AccessToken}) |
| 85 | } |
| 86 | if client.tokenSource == nil && tconf.GetClientCertificate == nil && !cfg.Interactive { |
| 87 | return nil, errors.New("remote.certfile and remote.keyfile must be set") |
| 88 | } |
| 89 | // in case of interactive auth, wait until we have metadata |
| 90 | return client, nil |
| 91 | } |
| 92 | |
| 93 | // Make a single API request to a named endpoint, handling directory lookup and failover automatically. |
| 94 | func CallRemote(endpoint, method string, query *url.Values, body ReaderGetter) (*http.Response, error) { |
| 95 | cli, err := newClient() |
| 96 | if err != nil { |
| 97 | return nil, err |
| 98 | } |
| 99 | cfg := shared.CurrentConfig.Remote |
| 100 | bases := []string{cfg.DirectoryURL} |
| 101 | metadata, serverEncodings, err := cli.getDirectory(cfg.DirectoryURL) |
| 102 | if err != nil { |
| 103 | return nil, err |
| 104 | } else if len(metadata.Hosts) > 0 { |
| 105 | // list of direct URLs provided |
| 106 | bases = metadata.Hosts |
| 107 | } |
| 108 | if err := cli.interactiveAuth(metadata); err != nil { |
| 109 | return nil, fmt.Errorf("configuring interactive authentication: %w", err) |
| 110 | } |
| 111 | return cli.doRequest(bases, endpoint, method, serverEncodings, query, body) |
| 112 | } |
| 113 | |
| 114 | func (cli *client) interactiveAuth(metadata *authmodel.Metadata) error { |
| 115 | if !cli.config.Interactive || cli.tokenSource != nil { |
| 116 | // not needed |
| 117 | return nil |
| 118 | } |
| 119 | for _, auth := range metadata.Auth { |
| 120 | if auth.Type != authmodel.AuthTypeAzureAD { |
| 121 | continue |
| 122 | } |
| 123 | var err error |
| 124 | cli.tokenSource, err = azureTokenSource(auth.Authority, auth.ClientID, auth.Scopes) |
| 125 | if err != nil { |
| 126 | return err |
| 127 | } |
| 128 | break |
| 129 | } |
| 130 | return nil |
| 131 | } |
| 132 | |
| 133 | // Call the configured directory URL to get a list of servers to try. |
| 134 | // callRemote() calls this automatically, use that instead. |
| 135 | func (cli *client) getDirectory(dirurl string) (*authmodel.Metadata, string, error) { |
| 136 | response, err := cli.doRequest([]string{dirurl}, "directory", "GET", "", nil, nil) |
| 137 | if err != nil { |
| 138 | return nil, "", err |
| 139 | } |
| 140 | encodings := response.Header.Get("Accept-Encoding") |
| 141 | bodybytes, err := io.ReadAll(response.Body) |
| 142 | if err != nil { |
| 143 | return nil, "", err |
| 144 | } |
| 145 | response.Body.Close() |
| 146 | m := new(authmodel.Metadata) |
| 147 | if strings.Contains(response.Header.Get("Content-Type"), "json") { |
| 148 | if err := json.Unmarshal(bodybytes, m); err != nil { |
| 149 | return nil, "", err |
| 150 | } |
| 151 | } else { |
| 152 | // legacy path |
| 153 | text := strings.Trim(string(bodybytes), "\r\n") |
| 154 | if len(text) == 0 { |
| 155 | return nil, encodings, nil |
| 156 | } |
| 157 | m.Hosts = strings.Split(text, "\r\n") |
| 158 | } |
| 159 | return m, encodings, nil |
| 160 | } |
| 161 | |
| 162 | // Build a HTTP request from various bits and pieces |
| 163 | func (cli *client) buildRequest(base, endpoint, method, encoding string, query *url.Values, bodyFile ReaderGetter) (*http.Request, error) { |
| 164 | request, err := http.NewRequest(method, base, nil) |
| 165 | if err != nil { |
| 166 | return nil, err |
| 167 | } |
| 168 | request.URL, err = request.URL.Parse(endpoint) |
| 169 | if err != nil { |
| 170 | return nil, err |
| 171 | } |
| 172 | if query != nil { |
| 173 | request.URL.RawQuery = query.Encode() |
| 174 | } |
| 175 | request.Header.Set("User-Agent", config.UserAgent) |
| 176 | if encoding != "" { |
| 177 | request.Header.Set("Accept-Encoding", encoding) |
| 178 | } |
| 179 | if cli.tokenSource != nil { |
| 180 | tok, err := cli.tokenSource.Token() |
| 181 | if err != nil { |
| 182 | return nil, err |
| 183 | } |
| 184 | tok.SetAuthHeader(request) |
| 185 | } |
| 186 | if bodyFile != nil { |
| 187 | stream, err := bodyFile.GetReader() |
| 188 | if err != nil { |
| 189 | return nil, err |
| 190 | } |
| 191 | request.Body = io.NopCloser(stream) |
| 192 | if err := compresshttp.CompressRequest(request, encoding); err != nil { |
| 193 | return nil, err |
| 194 | } |
| 195 | } |
| 196 | if endpoint == "directory" { |
| 197 | request.Header.Set("Accept", "application/json, */*") |
| 198 | } |
| 199 | return request, nil |
| 200 | } |
| 201 | |
| 202 | // Build TLS config based on client configuration |
| 203 | func makeTLSConfig(cfg *config.RemoteConfig) (*tls.Config, error) { |
| 204 | tconf := new(tls.Config) |
| 205 | if err := x509tools.LoadCertPool(cfg.CaCert, tconf); err != nil { |
| 206 | return nil, err |
| 207 | } |
| 208 | x509tools.SetKeyLogFile(tconf) |
| 209 | if cfg.CertFile == "" && cfg.KeyFile == "" { |
| 210 | return tconf, nil |
| 211 | } |
| 212 | var err error |
| 213 | var certBytes, keyBytes []byte |
| 214 | if strings.Contains(cfg.CertFile, "-----BEGIN") { |
| 215 | certBytes = []byte(cfg.CertFile) |
| 216 | } else { |
| 217 | certBytes, err = os.ReadFile(cfg.CertFile) |
| 218 | if err != nil { |
| 219 | return nil, fmt.Errorf("remote.certfile: %w", err) |
| 220 | } |
| 221 | } |
| 222 | if strings.Contains(cfg.KeyFile, "-----BEGIN") { |
| 223 | keyBytes = []byte(cfg.KeyFile) |
| 224 | } else { |
| 225 | keyBytes, err = os.ReadFile(cfg.KeyFile) |
| 226 | if err != nil { |
| 227 | return nil, fmt.Errorf("remote.keyfile: %w", err) |
| 228 | } |
| 229 | } |
| 230 | tlscert, err := tls.X509KeyPair(certBytes, keyBytes) |
| 231 | if err != nil { |
| 232 | return nil, err |
| 233 | } |
| 234 | // When the server is running behind nginx, nginx must be configured to send |
| 235 | // at least one CA-cert to the client to pick from. However, it's not |
| 236 | // feasible to list every cert the server would accept as most of them are |
| 237 | // self-signed, so only a dummy cert is sent. Go is clever though, and if we |
| 238 | // set tconf.Certificates here it will try to match it again what the server |
| 239 | // claims to want, and if none match then no cert is sent at all. Work |
| 240 | // around this by using GetClientCertificate so that the matching behavior |
| 241 | // is bypassed and it always sends the configured client cert. |
| 242 | tconf.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { |
| 243 | return &tlscert, nil |
| 244 | } |
| 245 | return tconf, nil |
| 246 | } |
| 247 | |
| 248 | // Transact one request, trying multiple servers if necessary. Internal use only. |
| 249 | func (cli *client) doRequest(bases []string, endpoint, method, encodings string, query *url.Values, bodyFile ReaderGetter) (response *http.Response, err error) { |
| 250 | minAttempts := shared.CurrentConfig.Remote.Retries |
| 251 | if len(bases) < minAttempts { |
| 252 | var repeated []string |
| 253 | for len(repeated) < minAttempts { |
| 254 | repeated = append(repeated, bases...) |
| 255 | } |
| 256 | bases = repeated |
| 257 | } |
| 258 | |
| 259 | loop: |
| 260 | for i, base := range bases { |
| 261 | var request *http.Request |
| 262 | request, err = cli.buildRequest(base, endpoint, method, encodings, query, bodyFile) |
| 263 | if err != nil { |
| 264 | return nil, err |
| 265 | } |
| 266 | response, err = cli.cli.Do(request) |
| 267 | if request.Body != nil { |
| 268 | request.Body.Close() |
| 269 | } |
| 270 | if err == nil { |
| 271 | if response.StatusCode < 300 { |
| 272 | if i != 0 { |
| 273 | fmt.Printf("successfully contacted %s\n", request.URL) |
| 274 | } |
| 275 | break loop |
| 276 | } |
| 277 | // HTTP error, probably a 503 |
| 278 | err = httperror.FromResponse(response) |
| 279 | } |
| 280 | if response != nil && response.StatusCode == http.StatusNotAcceptable && encodings != "" { |
| 281 | // try again without compression |
| 282 | encodings = "" |
| 283 | goto loop |
| 284 | } else if httperror.Temporary(err) && i+1 < len(bases) { |
| 285 | fmt.Printf("%s\nunable to connect to %s; trying next server\n", err, request.URL) |
| 286 | } else { |
| 287 | return nil, err |
| 288 | } |
| 289 | } |
| 290 | if response != nil { |
| 291 | if err := compresshttp.DecompressResponse(response); err != nil { |
| 292 | return nil, err |
| 293 | } |
| 294 | } |
| 295 | return |
| 296 | } |
| 297 | |
| 298 | func setDigestQueryParam(query url.Values) error { |
| 299 | if shared.ArgDigest == "" { |
| 300 | return nil |
| 301 | } |
| 302 | if _, err := shared.GetDigest(); err != nil { |
| 303 | return err |
| 304 | } |
| 305 | query.Add("digest", shared.ArgDigest) |
| 306 | return nil |
| 307 | } |