File: config.rb

package info (click to toggle)
ruby-kubeclient 4.13.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,112 kB
  • sloc: ruby: 4,225; makefile: 6
file content (204 lines) | stat: -rw-r--r-- 6,700 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
195
196
197
198
199
200
201
202
203
204
# frozen_string_literal: true

require 'yaml'
require 'base64'
require 'pathname'

module Kubeclient
  # Kubernetes client configuration class
  class Config
    # Kubernetes client configuration context class
    class Context
      attr_reader :api_endpoint, :api_version, :ssl_options, :auth_options, :namespace

      def initialize(api_endpoint, api_version, ssl_options, auth_options, namespace)
        @api_endpoint = api_endpoint
        @api_version = api_version
        @ssl_options = ssl_options
        @auth_options = auth_options
        @namespace = namespace
      end
    end

    # data (Hash) - Parsed kubeconfig data.
    # kcfg_path (string) - Base directory for resolving relative references to external files.
    #   If set to nil, all external lookups & commands are disabled (even for absolute paths).
    # See also the more convenient Config.read
    def initialize(data, kcfg_path)
      @kcfg = data
      @kcfg_path = kcfg_path
      raise 'Unknown kubeconfig version' if @kcfg['apiVersion'] != 'v1'
    end

    # Builds Config instance by parsing given file, with lookups relative to file's directory.
    def self.read(filename)
      parsed =
        if RUBY_VERSION >= '2.6'
          YAML.safe_load(File.read(filename), permitted_classes: [Date, Time])
        else
          YAML.safe_load(File.read(filename), [Date, Time])
        end
      Config.new(parsed, File.dirname(filename))
    end

    def contexts
      @kcfg['contexts'].map { |x| x['name'] }
    end

    def context(context_name = nil)
      cluster, user, namespace = fetch_context(context_name || @kcfg['current-context'])

      if user.key?('exec')
        exec_opts = expand_command_option(user['exec'], 'command')
        user['exec_result'] = ExecCredentials.run(exec_opts)
      end

      client_cert_data = fetch_user_cert_data(user)
      client_key_data  = fetch_user_key_data(user)
      auth_options     = fetch_user_auth_options(user)

      ssl_options = {}

      ssl_options[:verify_ssl] = if cluster['insecure-skip-tls-verify'] == true
                                   OpenSSL::SSL::VERIFY_NONE
                                 else
                                   OpenSSL::SSL::VERIFY_PEER
                                 end

      if cluster_ca_data?(cluster)
        cert_store = OpenSSL::X509::Store.new
        populate_cert_store_from_cluster_ca_data(cluster, cert_store)
        ssl_options[:cert_store] = cert_store
      end

      unless client_cert_data.nil?
        ssl_options[:client_cert] = OpenSSL::X509::Certificate.new(client_cert_data)
      end

      unless client_key_data.nil?
        ssl_options[:client_key] = OpenSSL::PKey.read(client_key_data)
      end

      Context.new(cluster['server'], @kcfg['apiVersion'], ssl_options, auth_options, namespace)
    end

    private

    def allow_external_lookups?
      @kcfg_path != nil
    end

    def ext_file_path(path)
      unless allow_external_lookups?
        raise "Kubeclient::Config: external lookups disabled, can't load '#{path}'"
      end
      Pathname(path).absolute? ? path : File.join(@kcfg_path, path)
    end

    def ext_command_path(path)
      unless allow_external_lookups?
        raise "Kubeclient::Config: external lookups disabled, can't execute '#{path}'"
      end
      # Like go client https://github.com/kubernetes/kubernetes/pull/59495#discussion_r171138995,
      # distinguish 3 cases:
      # - absolute (e.g. /path/to/foo)
      # - $PATH-based (e.g. curl)
      # - relative to config file's dir (e.g. ./foo)
      if Pathname(path).absolute?
        path
      elsif File.basename(path) == path
        path
      else
        File.join(@kcfg_path, path)
      end
    end

    def fetch_context(context_name)
      context = @kcfg['contexts'].detect do |x|
        break x['context'] if x['name'] == context_name
      end

      raise KeyError, "Unknown context #{context_name}" unless context

      cluster = @kcfg['clusters'].detect do |x|
        break x['cluster'] if x['name'] == context['cluster']
      end

      raise KeyError, "Unknown cluster #{context['cluster']}" unless cluster

      user = @kcfg['users'].detect do |x|
        break x['user'] if x['name'] == context['user']
      end || {}

      namespace = context['namespace']

      [cluster, user, namespace]
    end

    def cluster_ca_data?(cluster)
      cluster.key?('certificate-authority') || cluster.key?('certificate-authority-data')
    end

    def populate_cert_store_from_cluster_ca_data(cluster, cert_store)
      if cluster.key?('certificate-authority')
        cert_store.add_file(ext_file_path(cluster['certificate-authority']))
      elsif cluster.key?('certificate-authority-data')
        ca_cert_data = Base64.decode64(cluster['certificate-authority-data'])
        cert_store.add_cert(OpenSSL::X509::Certificate.new(ca_cert_data))
      end
    end

    def fetch_user_cert_data(user)
      if user.key?('client-certificate')
        File.read(ext_file_path(user['client-certificate']))
      elsif user.key?('client-certificate-data')
        Base64.decode64(user['client-certificate-data'])
      elsif user.key?('exec_result') && user['exec_result'].key?('clientCertificateData')
        user['exec_result']['clientCertificateData']
      end
    end

    def fetch_user_key_data(user)
      if user.key?('client-key')
        File.read(ext_file_path(user['client-key']))
      elsif user.key?('client-key-data')
        Base64.decode64(user['client-key-data'])
      elsif user.key?('exec_result') && user['exec_result'].key?('clientKeyData')
        user['exec_result']['clientKeyData']
      end
    end

    def fetch_user_auth_options(user)
      options = {}
      if user.key?('token')
        options[:bearer_token] = user['token']
      elsif user.key?('exec_result') && user['exec_result'].key?('token')
        options[:bearer_token] = user['exec_result']['token']
      elsif user.key?('auth-provider')
        options[:bearer_token] = fetch_token_from_provider(user['auth-provider'])
      else
        %w[username password].each do |attr|
          options[attr.to_sym] = user[attr] if user.key?(attr)
        end
      end
      options
    end

    def fetch_token_from_provider(auth_provider)
      case auth_provider['name']
      when 'gcp'
        config = expand_command_option(auth_provider['config'], 'cmd-path')
        Kubeclient::GCPAuthProvider.token(config)
      when 'oidc'
        Kubeclient::OIDCAuthProvider.token(auth_provider['config'])
      end
    end

    def expand_command_option(config, key)
      config = config.dup
      config[key] = ext_command_path(config[key]) if config[key]

      config
    end
  end
end