File: server.go

package info (click to toggle)
gitlab-agent 16.1.3-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 6,324 kB
  • sloc: makefile: 175; sh: 52; ruby: 3
file content (194 lines) | stat: -rw-r--r-- 6,166 bytes parent folder | download
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
package agent

import (
	"context"
	"crypto/tls"
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"strings"
	"time"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/kubernetes_api/rpc"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/modagent"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/modshared"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/grpctool"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/httpz"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/prototool"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/tlstool"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/transport"
)

type server struct {
	rpc.UnimplementedKubernetesApiServer
	restConfig *rest.Config
	baseUrl    *url.URL
	userAgent  string
	via        string
}

func newServer(restConfig *rest.Config, baseUrl *url.URL, userAgent string) *server {
	return &server{
		restConfig: restConfig,
		baseUrl:    baseUrl,
		userAgent:  userAgent,
		via:        "gRPC/1.0 " + userAgent,
	}
}

func (s *server) MakeRequest(server rpc.KubernetesApi_MakeRequestServer) error {
	rpcApi := modagent.RpcApiFromContext(server.Context())
	log := rpcApi.Log()
	grpc2http := grpctool.InboundGrpcToOutboundHttp{
		Log: log,
		HandleProcessingError: func(msg string, err error) {
			rpcApi.HandleProcessingError(log, modshared.NoAgentId, msg, err)
		},
		HandleIoError: func(msg string, err error) error {
			return rpcApi.HandleIoError(log, msg, err)
		},
		HttpDo: s.httpDo,
	}
	return grpc2http.Pipe(server)
}

func (s *server) httpDo(ctx context.Context, h *grpctool.HttpRequest_Header, body io.Reader) (grpctool.DoResponse, error) {
	// 1. Construct request
	req, err := s.newRequest(ctx, h.Request, body)
	if err != nil {
		return grpctool.DoResponse{}, err
	}
	// 2. Construct rest config
	var headerExtra rpc.HeaderExtra
	if h.Extra != nil { // Optional field.
		err = h.Extra.UnmarshalTo(&headerExtra)
		if err != nil {
			return grpctool.DoResponse{}, err
		}
	}
	restConfig, err := restImpersonationConfig(headerExtra.ImpConfig, s.restConfig, req)
	if err != nil {
		return grpctool.DoResponse{}, err
	}
	// 3. Construct round tripper
	var (
		rt        http.RoundTripper
		upgradeRT *httpz.UpgradeRoundTripper
	)
	transportCfg, err := restConfig.TransportConfig()
	if err != nil {
		return grpctool.DoResponse{}, err
	}
	isUpgrade := h.Request.IsUpgrade()
	if isUpgrade {
		var tlsConfig *tls.Config
		tlsConfig, err = transport.TLSConfigFor(transportCfg)
		if err != nil {
			return grpctool.DoResponse{}, err
		}
		if tlsConfig == nil { // transport.TLSConfigFor() can return nil
			tlsConfig = tlstool.DefaultClientTLSConfig()
		}
		tlsConfig.NextProtos = []string{httpz.TLSNextProtoH1} // HTTP Upgrade doesn't work over HTTP/2, so enforce HTTP/1.1
		dialer := &net.Dialer{
			Timeout: 30 * time.Second,
		}
		upgradeRT = &httpz.UpgradeRoundTripper{
			Dialer: dialer,
			TlsDialer: &tls.Dialer{
				NetDialer: dialer,
				Config:    tlsConfig,
			},
		}
		rt, err = transport.HTTPWrappersForConfig(transportCfg, upgradeRT)
	} else {
		rt, err = transport.New(transportCfg) // returns pooled transports that reuse TCP connections
	}
	if err != nil {
		return grpctool.DoResponse{}, err
	}
	// 4. Make a request
	resp, err := rt.RoundTrip(req) // nolint: bodyclose
	if err != nil {
		ctxErr := ctx.Err()
		if ctxErr != nil {
			err = ctxErr // assume request errored out because of context
		}
		return grpctool.DoResponse{}, err
	}
	resp.Header[httpz.ViaHeader] = append(resp.Header[httpz.ViaHeader], fmt.Sprintf("%d.%d %s", resp.ProtoMajor, resp.ProtoMinor, s.userAgent))
	if isUpgrade {
		return grpctool.DoResponse{
			Resp:        resp,
			UpgradeConn: upgradeRT.Conn,
			ConnReader:  upgradeRT.ConnReader,
		}, nil
	} else {
		return grpctool.DoResponse{
			Resp: resp,
		}, nil
	}
}

func (s *server) newRequest(ctx context.Context, requestInfo *prototool.HttpRequest, body io.Reader) (*http.Request, error) {
	u := *s.baseUrl
	u.Path = requestInfo.UrlPath
	u.RawQuery = requestInfo.UrlQuery().Encode()

	req, err := http.NewRequestWithContext(ctx, requestInfo.Method, u.String(), body)
	if err != nil {
		return nil, err
	}
	req.Header = requestInfo.HttpHeader()
	req.Header[httpz.ViaHeader] = append(req.Header[httpz.ViaHeader], s.via)
	return req, nil
}

func restImpersonationConfig(impConfig *rpc.ImpersonationConfig, restConfig *rest.Config, r *http.Request) (*rest.Config, error) {
	restImp := !isEmptyImpersonationConfig(restConfig.Impersonate)
	cfgImp := !impConfig.IsEmpty()
	reqImp := hasImpersonationHeaders(r)
	switch {
	case !restImp && !cfgImp && !reqImp:
		// No impersonation
	case restImp && !cfgImp && !reqImp:
		// Impersonation is configured in the rest config
	case !restImp && cfgImp && !reqImp:
		// Impersonation is configured in the agent config
		restConfig = rest.CopyConfig(restConfig) // copy to avoid mutating a potentially shared config object
		restConfig.Impersonate.UserName = impConfig.Username
		restConfig.Impersonate.UID = impConfig.Uid
		restConfig.Impersonate.Groups = impConfig.Groups
		restConfig.Impersonate.Extra = impConfig.GetExtraAsMap()
	case !restImp && !cfgImp && reqImp:
		// Impersonation is configured in the HTTP request
	default:
		// Nested impersonation support https://gitlab.com/gitlab-org/gitlab/-/issues/338664
		return nil, errors.New("nested impersonation is not supported - agent is already configured to impersonate an identity")
	}
	return restConfig, nil
}

func isEmptyImpersonationConfig(cfg rest.ImpersonationConfig) bool {
	return cfg.UserName == "" && len(cfg.Groups) == 0 && len(cfg.Extra) == 0
}

func hasImpersonationHeaders(r *http.Request) bool {
	for k := range r.Header {
		if isImpersonationHeader(k) {
			return true
		}
	}
	return false
}

func isImpersonationHeader(header string) bool {
	return header == transport.ImpersonateUserHeader ||
		header == transport.ImpersonateUIDHeader ||
		header == transport.ImpersonateGroupHeader ||
		strings.HasPrefix(header, transport.ImpersonateUserExtraHeaderPrefix)
}