summaryrefslogtreecommitdiffstats
path: root/services/httpservice/httpservice.go
blob: 5ed42a12dc8a5acadcc9031c30dff1dc375046eb (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
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

package httpservice

import (
	"net"
	"net/http"
	"strings"

	"github.com/mattermost/mattermost-server/services/configservice"
)

// Wraps the functionality for creating a new http.Client to encapsulate that and allow it to be mocked when testing
type HTTPService interface {
	MakeClient(trustURLs bool) *http.Client
	Close()
}

type HTTPServiceImpl struct {
	configService configservice.ConfigService
}

func MakeHTTPService(configService configservice.ConfigService) HTTPService {
	return &HTTPServiceImpl{configService}
}

func (h *HTTPServiceImpl) MakeClient(trustURLs bool) *http.Client {
	insecure := h.configService.Config().ServiceSettings.EnableInsecureOutgoingConnections != nil && *h.configService.Config().ServiceSettings.EnableInsecureOutgoingConnections

	if trustURLs {
		return NewHTTPClient(insecure, nil, nil)
	}

	allowHost := func(host string) bool {
		if h.configService.Config().ServiceSettings.AllowedUntrustedInternalConnections == nil {
			return false
		}
		for _, allowed := range strings.Fields(*h.configService.Config().ServiceSettings.AllowedUntrustedInternalConnections) {
			if host == allowed {
				return true
			}
		}
		return false
	}

	allowIP := func(ip net.IP) bool {
		if !IsReservedIP(ip) {
			return true
		}
		if h.configService.Config().ServiceSettings.AllowedUntrustedInternalConnections == nil {
			return false
		}
		for _, allowed := range strings.Fields(*h.configService.Config().ServiceSettings.AllowedUntrustedInternalConnections) {
			if _, ipRange, err := net.ParseCIDR(allowed); err == nil && ipRange.Contains(ip) {
				return true
			}
		}
		return false
	}

	return NewHTTPClient(insecure, allowHost, allowIP)
}

func (h *HTTPServiceImpl) Close() {
	// Does nothing, but allows this to be overridden when mocking the service
}