summaryrefslogtreecommitdiff
path: root/spec/lib/gitlab/kubernetes/kube_client_spec.rb
blob: 521f13dc9ccda4a9768175dd3ae1d19119b39990 (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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::Kubernetes::KubeClient do
  include StubRequests
  include KubernetesHelpers

  let(:api_url) { 'https://kubernetes.example.com/prefix' }
  let(:kubeclient_options) { { auth_options: { bearer_token: 'xyz' } } }

  let(:client) { described_class.new(api_url, **kubeclient_options) }

  before do
    stub_kubeclient_discover(api_url)
  end

  def method_call(client, method_name)
    case method_name
    when /\A(get_|delete_)/
      client.public_send(method_name)
    when /\A(create_|update_|patch_)/
      client.public_send(method_name, {})
    else
      raise "Unknown method name #{method_name}"
    end
  end

  shared_examples 'a Kubeclient' do
    it 'is a Kubeclient::Client' do
      is_expected.to be_an_instance_of Kubeclient::Client
    end

    it 'has the kubeclient options' do
      expect(subject.auth_options).to eq({ bearer_token: 'xyz' })
    end
  end

  shared_examples 'redirection not allowed' do |method_name|
    context 'api_url is redirected' do
      before do
        redirect_url = 'https://not-under-our-control.example.com/api/v1/pods'

        stub_request(:get, %r{\A#{api_url}/})
          .to_return(status: 302, headers: { location: redirect_url })

        stub_request(:get, redirect_url)
          .to_return(status: 200, body: '{}')
      end

      it 'does not follow redirects' do
        expect { method_call(client, method_name) }.to raise_error(Kubeclient::HttpError)
      end
    end
  end

  shared_examples 'dns rebinding not allowed' do |method_name|
    it 'does not allow DNS rebinding' do
      stub_dns(api_url, ip_address: '8.8.8.8')
      client

      stub_dns(api_url, ip_address: '192.168.2.120')
      expect { method_call(client, method_name) }.to raise_error(ArgumentError, /is blocked/)
    end
  end

  describe '.graceful_request' do
    context 'successful' do
      before do
        allow(client).to receive(:foo).and_return(true)
      end

      it 'returns connected status and foo response' do
        result = described_class.graceful_request(1) { client.foo }

        expect(result).to eq({ status: :connected, response: true })
      end
    end

    context 'errored' do
      using RSpec::Parameterized::TableSyntax

      where(:error, :connection_status, :error_status) do
        SocketError                                      | :unreachable            | :connection_error
        OpenSSL::X509::CertificateError                  | :authentication_failure | :authentication_error
        StandardError                                    | :unknown_failure        | :unknown_error
        Kubeclient::HttpError.new(408, "timed out", nil) | :unreachable            | :http_error
        Kubeclient::HttpError.new(408, "timeout", nil)   | :unreachable            | :http_error
        Kubeclient::HttpError.new(408, "", nil)          | :authentication_failure | :http_error
      end

      with_them do
        before do
          allow(client).to receive(:foo).and_raise(error)
        end

        it 'returns error status' do
          result = described_class.graceful_request(1) { client.foo }

          expect(result).to eq({ status: connection_status, connection_error: error_status })
        end
      end
    end
  end

  describe '#initialize' do
    shared_examples 'local address' do
      it 'blocks local addresses' do
        expect { client }.to raise_error(Gitlab::UrlBlocker::BlockedUrlError)
      end

      context 'when local requests are allowed' do
        before do
          stub_application_setting(allow_local_requests_from_web_hooks_and_services: true)
        end

        it 'allows local addresses' do
          expect { client }.not_to raise_error
        end
      end
    end

    context 'localhost address' do
      let(:api_url) { 'http://localhost:22' }

      it_behaves_like 'local address'
    end

    context 'private network address' do
      let(:api_url) { 'http://192.168.1.2:3003' }

      it_behaves_like 'local address'
    end

    it 'falls back to default options, but allows overriding' do
      client = described_class.new(api_url)
      defaults = Gitlab::Kubernetes::KubeClient::DEFAULT_KUBECLIENT_OPTIONS
      expect(client.kubeclient_options[:timeouts]).to eq(defaults[:timeouts])

      client = Gitlab::Kubernetes::KubeClient.new(api_url, timeouts: { read: 7 })
      expect(client.kubeclient_options[:timeouts][:read]).to eq(7)
      expect(client.kubeclient_options[:timeouts][:open]).to eq(defaults[:timeouts][:open])
    end
  end

  describe '#core_client' do
    subject { client.core_client }

    it_behaves_like 'a Kubeclient'

    it 'has the core API endpoint' do
      expect(subject.api_endpoint.to_s).to match(%r{\/api\Z})
    end

    it 'has the api_version' do
      expect(subject.instance_variable_get(:@api_version)).to eq('v1')
    end
  end

  describe '#rbac_client' do
    subject { client.rbac_client }

    it_behaves_like 'a Kubeclient'

    it 'has the RBAC API group endpoint' do
      expect(subject.api_endpoint.to_s).to match(%r{\/apis\/rbac.authorization.k8s.io\Z})
    end

    it 'has the api_version' do
      expect(subject.instance_variable_get(:@api_version)).to eq('v1')
    end
  end

  describe '#extensions_client' do
    subject { client.extensions_client }

    it_behaves_like 'a Kubeclient'

    it 'has the extensions API group endpoint' do
      expect(subject.api_endpoint.to_s).to match(%r{\/apis\/extensions\Z})
    end

    it 'has the api_version' do
      expect(subject.instance_variable_get(:@api_version)).to eq('v1beta1')
    end
  end

  describe '#istio_client' do
    subject { client.istio_client }

    it_behaves_like 'a Kubeclient'

    it 'has the Istio API group endpoint' do
      expect(subject.api_endpoint.to_s).to match(%r{\/apis\/networking.istio.io\Z})
    end

    it 'has the api_version' do
      expect(subject.instance_variable_get(:@api_version)).to eq('v1alpha3')
    end
  end

  describe '#knative_client' do
    subject { client.knative_client }

    it_behaves_like 'a Kubeclient'

    it 'has the extensions API group endpoint' do
      expect(subject.api_endpoint.to_s).to match(%r{\/apis\/serving.knative.dev\Z})
    end

    it 'has the api_version' do
      expect(subject.instance_variable_get(:@api_version)).to eq('v1alpha1')
    end
  end

  describe '#networking_client' do
    subject { client.networking_client }

    it_behaves_like 'a Kubeclient'

    it 'has the networking API group endpoint' do
      expect(subject.api_endpoint.to_s).to match(%r{\/apis\/networking.k8s.io\Z})
    end

    it 'has the api_version' do
      expect(subject.instance_variable_get(:@api_version)).to eq('v1')
    end
  end

  describe '#cilium_networking_client' do
    subject { client.cilium_networking_client }

    it_behaves_like 'a Kubeclient'

    it 'has the cilium API group endpoint' do
      expect(subject.api_endpoint.to_s).to match(%r{\/apis\/cilium.io\Z})
    end

    it 'has the api_version' do
      expect(subject.instance_variable_get(:@api_version)).to eq('v2')
    end
  end

  describe '#metrics_client' do
    subject { client.metrics_client }

    it_behaves_like 'a Kubeclient'

    it 'has the metrics API group endpoint' do
      expect(subject.api_endpoint.to_s).to match(%r{\/apis\/metrics.k8s.io\Z})
    end

    it 'has the api_version' do
      expect(subject.instance_variable_get(:@api_version)).to eq('v1beta1')
    end
  end

  describe 'core API' do
    let(:core_client) { client.core_client }

    [
      :get_nodes,
      :get_pods,
      :get_secrets,
      :get_config_map,
      :get_pod,
      :get_namespace,
      :get_secret,
      :get_service,
      :get_service_account,
      :delete_namespace,
      :delete_pod,
      :delete_service_account,
      :create_config_map,
      :create_namespace,
      :create_pod,
      :create_secret,
      :create_service_account,
      :update_config_map,
      :update_secret,
      :update_service_account
    ].each do |method|
      describe "##{method}" do
        include_examples 'redirection not allowed', method
        include_examples 'dns rebinding not allowed', method

        it 'delegates to the core client' do
          expect(client).to delegate_method(method).to(:core_client)
        end

        it 'responds to the method' do
          expect(client).to respond_to method
        end
      end
    end
  end

  describe 'rbac API group' do
    let(:rbac_client) { client.rbac_client }

    [
      :create_role,
      :get_role,
      :update_role,
      :delete_role_binding,
      :update_role_binding,
      :update_cluster_role_binding
    ].each do |method|
      describe "##{method}" do
        include_examples 'redirection not allowed', method
        include_examples 'dns rebinding not allowed', method

        it 'delegates to the rbac client' do
          expect(client).to delegate_method(method).to(:rbac_client)
        end

        it 'responds to the method' do
          expect(client).to respond_to method
        end
      end
    end
  end

  describe '#get_deployments' do
    let(:extensions_client) { client.extensions_client }
    let(:apps_client) { client.apps_client }

    include_examples 'redirection not allowed', 'get_deployments'
    include_examples 'dns rebinding not allowed', 'get_deployments'

    it 'delegates to the extensions client' do
      expect(extensions_client).to receive(:get_deployments)

      client.get_deployments
    end

    context 'extensions does not have deployments for Kubernetes 1.16+ clusters' do
      before do
        WebMock
          .stub_request(:get, api_url + '/apis/extensions/v1beta1')
          .to_return(kube_response(kube_1_16_extensions_v1beta1_discovery_body))
      end

      it 'delegates to the apps client' do
        expect(apps_client).to receive(:get_deployments)

        client.get_deployments
      end
    end
  end

  describe '#get_ingresses' do
    let(:extensions_client) { client.extensions_client }
    let(:networking_client) { client.networking_client }

    include_examples 'redirection not allowed', 'get_ingresses'
    include_examples 'dns rebinding not allowed', 'get_ingresses'

    it 'delegates to the extensions client' do
      expect(extensions_client).to receive(:get_ingresses)

      client.get_ingresses
    end

    context 'extensions does not have deployments for Kubernetes 1.22+ clusters' do
      before do
        WebMock
          .stub_request(:get, api_url + '/apis/extensions/v1beta1')
          .to_return(kube_response(kube_1_22_extensions_v1beta1_discovery_body))
      end

      it 'delegates to the apps client' do
        expect(networking_client).to receive(:get_ingresses)

        client.get_ingresses
      end
    end
  end

  describe '#patch_ingress' do
    let(:extensions_client) { client.extensions_client }
    let(:networking_client) { client.networking_client }

    include_examples 'redirection not allowed', 'patch_ingress'
    include_examples 'dns rebinding not allowed', 'patch_ingress'

    it 'delegates to the extensions client' do
      expect(extensions_client).to receive(:patch_ingress)

      client.patch_ingress
    end

    context 'extensions does not have ingress for Kubernetes 1.22+ clusters' do
      before do
        WebMock
          .stub_request(:get, api_url + '/apis/extensions/v1beta1')
          .to_return(kube_response(kube_1_22_extensions_v1beta1_discovery_body))
      end

      it 'delegates to the apps client' do
        expect(networking_client).to receive(:patch_ingress)

        client.patch_ingress
      end
    end
  end

  describe 'istio API group' do
    let(:istio_client) { client.istio_client }

    [
      :create_gateway,
      :get_gateway,
      :update_gateway
    ].each do |method|
      describe "##{method}" do
        include_examples 'redirection not allowed', method
        include_examples 'dns rebinding not allowed', method

        it 'delegates to the istio client' do
          expect(client).to delegate_method(method).to(:istio_client)
        end

        it 'responds to the method' do
          expect(client).to respond_to method
        end
      end
    end
  end

  describe 'networking API group' do
    let(:networking_client) { client.networking_client }

    [
      :create_network_policy,
      :get_network_policies,
      :get_network_policy,
      :update_network_policy,
      :delete_network_policy
    ].each do |method|
      describe "##{method}" do
        include_examples 'redirection not allowed', method
        include_examples 'dns rebinding not allowed', method

        it 'delegates to the networking client' do
          expect(client).to delegate_method(method).to(:networking_client)
        end

        it 'responds to the method' do
          expect(client).to respond_to method
        end
      end
    end
  end

  describe 'cilium API group' do
    let(:cilium_networking_client) { client.cilium_networking_client }

    [
      :create_cilium_network_policy,
      :get_cilium_network_policies,
      :get_cilium_network_policy,
      :update_cilium_network_policy,
      :delete_cilium_network_policy
    ].each do |method|
      describe "##{method}" do
        include_examples 'redirection not allowed', method
        include_examples 'dns rebinding not allowed', method

        it 'delegates to the cilium client' do
          expect(client).to delegate_method(method).to(:cilium_networking_client)
        end

        it 'responds to the method' do
          expect(client).to respond_to method
        end
      end
    end
  end

  describe 'non-entity methods' do
    it 'does not proxy for non-entity methods' do
      expect(client).not_to respond_to :proxy_url
    end

    it 'throws an error' do
      expect { client.proxy_url }.to raise_error(NoMethodError)
    end
  end

  describe '#get_pod_log' do
    let(:core_client) { client.core_client }

    it 'is delegated to the core client' do
      expect(client).to delegate_method(:get_pod_log).to(:core_client)
    end
  end

  describe '#watch_pod_log' do
    let(:core_client) { client.core_client }

    it 'is delegated to the core client' do
      expect(client).to delegate_method(:watch_pod_log).to(:core_client)
    end
  end

  shared_examples 'create_or_update method using put' do
    let(:update_method) { "update_#{resource_type}" }

    it 'calls the update method' do
      expect(client).to receive(update_method).with(resource)

      subject
    end
  end

  shared_examples 'create_or_update method' do
    let(:get_method) { "get_#{resource_type}" }
    let(:update_method) { "update_#{resource_type}" }
    let(:create_method) { "create_#{resource_type}" }

    context 'resource exists' do
      before do
        expect(client).to receive(get_method).and_return(resource)
      end

      it 'calls the update method' do
        expect(client).to receive(update_method).with(resource)

        subject
      end
    end

    context 'resource does not exist' do
      before do
        expect(client).to receive(get_method).and_raise(Kubeclient::ResourceNotFoundError.new(404, 'Not found', nil))
      end

      it 'calls the create method' do
        expect(client).to receive(create_method).with(resource)

        subject
      end
    end
  end

  describe '#create_or_update_cluster_role_binding' do
    let(:resource_type) { 'cluster_role_binding' }

    let(:resource) do
      ::Kubeclient::Resource.new(metadata: { name: 'name', namespace: 'namespace' })
    end

    subject { client.create_or_update_cluster_role_binding(resource) }

    it_behaves_like 'create_or_update method using put'
  end

  describe '#create_or_update_role_binding' do
    let(:resource_type) { 'role_binding' }

    let(:resource) do
      ::Kubeclient::Resource.new(metadata: { name: 'name', namespace: 'namespace' })
    end

    subject { client.create_or_update_role_binding(resource) }

    it_behaves_like 'create_or_update method using put'
  end

  describe '#create_or_update_service_account' do
    let(:resource_type) { 'service_account' }

    let(:resource) do
      ::Kubeclient::Resource.new(metadata: { name: 'name', namespace: 'namespace' })
    end

    subject { client.create_or_update_service_account(resource) }

    it_behaves_like 'create_or_update method'
  end

  describe '#create_or_update_secret' do
    let(:resource_type) { 'secret' }

    let(:resource) do
      ::Kubeclient::Resource.new(metadata: { name: 'name', namespace: 'namespace' })
    end

    subject { client.create_or_update_secret(resource) }

    it_behaves_like 'create_or_update method'
  end

  describe 'methods that do not exist on any client' do
    it 'throws an error' do
      expect { client.non_existent_method }.to raise_error(NoMethodError)
    end

    it 'returns false for respond_to' do
      expect(client.respond_to?(:non_existent_method)).to be_falsey
    end
  end
end