lib/Kubernetes/REST/Kubeconfig.pm

filter: Statementstmt 98.0% 201 / 205 Branchbran 89.8% 88 / 98 Conditioncond 65.1% 43 / 66 MC/DCmcdc 40.0% 16 / 40 Subroutinesub 100% 33 / 33 Podpod 100% 6 / 6 totaltotal 86.3% 387 / 448 CC 87 SCAR 20.2
CC
87
Cov
90%
api
17.2
_merge_configs
13.2
_resolve_file_references
11.2
CRAP 7.5
« lib/Kubernetes/REST/LWPIO.pm ↑ Summary blib/lib/Kubernetes/REST/HTTPTinyIO.pm »
1 package Kubernetes::REST::Kubeconfig;
2 # ABSTRACT: Parse kubeconfig files and create Kubernetes::REST instances
3 11 our $VERSION = '1.108';
4 11 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 11 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 11 ▶use Config ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 11 ▶use YAML::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 11 ▶use Path::Tiny qw(path);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 11 ▶use MIME::Base64 qw(decode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 11 ▶use Kubernetes::REST;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 11 ▶use Kubernetes::REST::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 11 ▶use Kubernetes::REST::AuthToken;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 11 ▶use Kubernetes::REST::AuthTokenFile;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 11 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16  
17 has kubeconfig_path => (
18 is => 'ro',
19 10 ▶ default => sub { $_[0]->_default_kubeconfig_path },
Subroutine __ANON__: called CC=1 SCAR=0.0
20 11 );
21  
22  
23 10 ▶sub _default_kubeconfig_path {
Subroutine _default_kubeconfig_path: called CC=5 SCAR=16.1
24 10 my $self = shift;
25 10 ▶ return $ENV{KUBECONFIG} if defined $ENV{KUBECONFIG} and length $ENV{KUBECONFIG};
Branch: 1 branch
BranchTrueFalseTotal
if defined $ENV{"KUBECONFIG"} and length $ENV{"KUBECONFIG"} 3 7 10
Condition100%3/3
defined $ENV{"KUBECONFIG"} and length $ENV{"KUBECONFIG"}
!ll&&!rl&&r
613
MC/DC100%2/2
defined $ENV{"KUBECONFIG"} and length $ENV{"KUBECONFIG"}
defined $ENV{"KUBECONFIG"} length $ENV{"KUBECONFIG"}
Truth table100%3/3
A and B
A= defined $ENV{"KUBECONFIG"}B= length $ENV{"KUBECONFIG"}
ABresult
0X0
100
111
26 7 ▶ return undef unless defined $ENV{HOME} and length $ENV{HOME};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ENV{"HOME"} and length $ENV{"HOME"} 3 4 7
Condition66%2/3
defined $ENV{"HOME"} and length $ENV{"HOME"}
!ll&&!rl&&r
304
MC/DC50%1/2
defined $ENV{"HOME"} and length $ENV{"HOME"}
defined $ENV{"HOME"} length $ENV{"HOME"}
Truth table66%2/3
A and B
A= defined $ENV{"HOME"}B= length $ENV{"HOME"}
ABresult
0X0
100
111
27 4 return "$ENV{HOME}/.kube/config";
28 }
29  
30 11 ▶my $PATH_SEP = $Config::Config{path_sep} || ':';
Condition50%1/2
$Config::Config{'path_sep'} || ':'
l!l
110
MC/DC0%0/1
$Config::Config{'path_sep'} || ':'
$Config::Config{'path_sep'}
Truth table50%1/2
A
A= $Config::Config{'path_sep'}
Aresult
11
00
31  
32 has kubeconfig_paths => (
33 is => 'lazy',
34 init_arg => undef,
35 65 ▶ builder => sub {
Subroutine _build_kubeconfig_paths: called CC=4 SCAR=14.5
36 65 my $self = shift;
37 65 my $path = $self->kubeconfig_path;
38 65 ▶ return [] unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 65 65
39 65 ▶ my @entries = ref $path eq 'ARRAY' ? @$path : split /\Q$PATH_SEP\E/, $path, -1;
Branch: 1 branch
BranchTrueFalseTotal
ref $path eq 'ARRAY' ? : 1 64 65
40 65 ▶ return [ grep { defined and length } @entries ];
Condition50%3/6
defined $_ && length $_
!ll&&!rl&&r
0066
defined $_ && length $_
!ll&&!rl&&r
0357
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
MC/DC50%1/2
defined $_ && length $_
defined $_ length $_
Truth table33%1/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
Truth table66%2/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
41 },
42 11 );
43  
44  
45 11 has context_name => (
46 is => 'ro',
47 predicate => 1,
48 );
49  
50  
51 has refresh_token_files => (
52 is => 'ro',
53 108 ▶ default => sub { 1 },
Subroutine __ANON__: called CC=1 SCAR=0.0
54 11 );
55  
56  
57 has _config => (
58 is => 'lazy',
59 60 ▶ builder => sub {
Subroutine _build__config: called CC=5 SCAR=16.1
Subroutine __ANON__: called CC=5 SCAR=16.1
60 60 my $self = shift;
61 60 my @configs;
62 60 for my $path (@{ $self->kubeconfig_paths }) {
63 # A file the list names but that is not there is not an error, the
64 # same way it is not one for kubectl.
65 63 ▶ next unless -f $path;
Branch: 2 branches
BranchTrueFalseTotal
unless -f $path 1 62 63
unless -f $path 9 90 99
66 62 my $config = YAML::XS::LoadFile($path);
67 62 ▶ next unless ref $config eq 'HASH';
Branch: 2 branches
BranchTrueFalseTotal
unless ref $config eq "HASH" 0 62 62
unless ref $config eq "HASH" 4 86 90
68 # While the file is being read is the only place where its own
69 # directory is still known: the merge below keeps whole entries but
70 # not where they came from, and with several files merged that
71 # directory differs per entry.
72 62 push @configs, $self->_resolve_file_references($config, $path);
73 }
74 60 ▶ return undef unless @configs;
Branch: 2 branches
BranchTrueFalseTotal
unless @configs 0 60 60
unless @configs 4 40 44
75 60 return $self->_merge_configs(@configs);
76 },
77 11 );
78  
79 # The file references a kubeconfig entry can hold, per section: the key of the
80 # entry body, and the fields in it that name a file. The *-data twins hold
81 # base64 content rather than a path and are none of this code's business, and
82 # neither is an exec plugin's command, which is looked up in PATH.
83 11 my %FILE_REFERENCES = (
84 clusters => { body => 'cluster', fields => ['certificate-authority'] },
85 users => { body => 'user', fields => [qw(client-certificate client-key tokenFile)] },
86 );
87  
88 114 ▶sub _resolve_file_references {
Subroutine _resolve_file_references: called CC=11 SCAR=24.2
89 114 my ($self, $config, $file) = @_;
90  
91 # Absolute, so the result survives a later chdir - the file itself may well
92 # have been named relatively.
93 114 my $dir = path($file)->absolute->parent;
94  
95 114 for my $section (sort keys %FILE_REFERENCES) {
96 228 my $spec = $FILE_REFERENCES{$section};
97 228 ▶ for my $entry (@{ $config->{$section} // [] }) {
Condition100%2/2
$config->{$section} // []
l!l
21216
MC/DC100%1/1
$config->{$section} // []
$config->{$section}
Truth table100%2/2
A
A= $config->{$section}
Aresult
11
00
98 667 ▶ next unless ref $entry eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" 0 667 667
99 667 my $body = $entry->{ $spec->{body} };
100 667 ▶ next unless ref $body eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 0 667 667
101 667 for my $field (@{ $spec->{fields} }) {
102 1601 my $value = $body->{$field};
103 1601 ▶ next unless defined $value and !ref $value and length $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and not ref $value and length $value 1239 362 1601
Condition66%4/6
defined $value and not ref $value and length $value
!ll&&!rl&&r
12390362
defined $value and not ref $value
!ll&&!rl&&r
12390362
MC/DC33%1/3
defined $value and not ref $value and length $value
defined $value not ref $value length $value
Truth table50%2/4
A and not(B) and C
A= defined $valueB= not ref $valueC= length $value
ABCresult
0XX0
10X0
1100
1111
104 362 ▶ next if path($value)->is_absolute;
Branch: 1 branch
BranchTrueFalseTotal
if path($value)->is_absolute 92 270 362
105 270 $body->{$field} = $dir->child($value)->stringify;
106 }
107 }
108 }
109  
110 114 return $config;
111 }
112  
113 # The sections keyed by name, which are unioned; everything else is a plain
114 # top-level key taken from the first file that has it.
115 11 my @NAMED_SECTIONS = qw(clusters contexts users);
116 11 my %IS_NAMED_SECTION = map { $_ => 1 } @NAMED_SECTIONS;
117  
118 100 ▶sub _merge_configs {
Subroutine _merge_configs: called CC=13 SCAR=25.8
119 100 my ($self, @configs) = @_;
120  
121 100 my (%merged, %seen);
122 100 for my $config (@configs) {
123 114 for my $section (@NAMED_SECTIONS) {
124 342 ▶ for my $entry (@{ $config->{$section} // [] }) {
Condition100%2/2
$config->{$section} // []
l!l
31923
MC/DC100%1/1
$config->{$section} // []
$config->{$section}
Truth table100%2/2
A
A= $config->{$section}
Aresult
11
00
125 1108 ▶ next unless ref $entry eq 'HASH' and defined $entry->{name};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" and defined $entry->{"name"} 0 1108 1108
Condition33%1/3
ref $entry eq "HASH" and defined $entry->{"name"}
!ll&&!rl&&r
001108
MC/DC0%0/2
ref $entry eq "HASH" and defined $entry->{"name"}
ref $entry eq "HASH" defined $entry->{"name"}
Truth table33%1/3
A and B
A= ref $entry eq "HASH"B= defined $entry->{"name"}
ABresult
0X0
100
111
126 1108 ▶ next if $seen{$section}{ $entry->{name} }++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$section}{$entry->{"name"}}++ 31 1077 1108
127 1077 push @{ $merged{$section} }, $entry;
128 }
129 }
130 114 for my $key (grep { !$IS_NAMED_SECTION{$_} } keys %$config) {
131 345 ▶ next if exists $merged{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $merged{$key} 40 305 345
132 305 my $value = $config->{$key};
133 305 ▶ next unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 305 305
134 305 ▶ next if !ref $value and !length $value;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value or length $value 12 293 305
Condition100%3/3
ref $value or length $value
l!l&&r!l&&!r
728612
MC/DC100%2/2
ref $value or length $value
ref $value length $value
Truth table100%3/3
A or B
A= ref $valueB= length $value
ABresult
1X1
011
000
135 293 $merged{$key} = $value;
136 }
137 }
138  
139 100 return \%merged;
140 }
141  
142 22 ▶sub _kubeconfig_paths_string {
Subroutine _kubeconfig_paths_string: called CC=2 SCAR=6.9
143 22 my $self = shift;
144 22 my $paths = $self->kubeconfig_paths;
145 22 ▶ return join($PATH_SEP, @$paths) if @$paths;
Branch: 1 branch
BranchTrueFalseTotal
if @$paths 16 6 22
146 6 return 'neither KUBECONFIG nor HOME is set';
147 }
148  
149 9 ▶sub _not_found_error {
Subroutine _not_found_error: called CC=1 SCAR=0.0
150 9 my $self = shift;
151 9 return 'Kubeconfig not found: ' . $self->_kubeconfig_paths_string;
152 }
153  
154 # The two ways a lookup fails before a single name is compared: the kubeconfig
155 # defines no such section at all, or there is no name to look for. Both used to
156 # reach _find_by_name, which compared against undef and croaked "not found: "
157 # with nothing behind the colon - an unusable kubeconfig, described in a way
158 # nobody can act on.
159 225 ▶sub _assert_lookup {
Subroutine _assert_lookup: called CC=5 SCAR=16.2
160 225 my ($self, $config, $section, $name, $missing_name_error) = @_;
161 225 my $entries = $config->{$section};
162 225 ▶ croak "kubeconfig defines no $section: " . $self->_kubeconfig_paths_string
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entries eq "ARRAY" and @$entries 7 218 225
Condition66%2/3
ref $entries eq "ARRAY" and @$entries
!ll&&!rl&&r
70218
MC/DC50%1/2
ref $entries eq "ARRAY" and @$entries
ref $entries eq "ARRAY" @$entries
Truth table66%2/3
A and B
A= ref $entries eq "ARRAY"B= @$entries
ABresult
0X0
100
111
163 unless ref $entries eq 'ARRAY' and @$entries;
164 218 ▶ croak "$missing_name_error: " . $self->_kubeconfig_paths_string
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 6 212 218
Condition66%2/3
defined $name and length $name
!ll&&!rl&&r
60212
MC/DC50%1/2
defined $name and length $name
defined $name length $name
Truth table66%2/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
165 unless defined $name and length $name;
166 212 return;
167 }
168  
169 51 ▶sub current_context_name {
Subroutine current_context_name: called CC=3 SCAR=11.0
Pod documented
170 51 my $self = shift;
171  
172  
173 51 ▶ return $self->context_name if $self->has_context_name;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_context_name 5 46 51
174 46 ▶ my $config = $self->_config
Branch: 1 branch
BranchTrueFalseTotal
my $config = $self->_config or croak($self->_not_found_error) 45 1 46
175 or croak $self->_not_found_error;
176 45 return $config->{'current-context'};
177 }
178  
179 10 ▶sub contexts {
Subroutine contexts: called CC=3 SCAR=11.0
Pod documented
180 10 my $self = shift;
181  
182  
183 10 ▶ my $config = $self->_config
Branch: 1 branch
BranchTrueFalseTotal
my $config = $self->_config or croak($self->_not_found_error) 6 4 10
184 or croak $self->_not_found_error;
185 6 ▶ return [ map { $_->{name} } @{$config->{contexts} // []} ];
Condition100%2/2
$config->{"contexts"} // []
l!l
51
MC/DC100%1/1
$config->{"contexts"} // []
$config->{"contexts"}
Truth table100%2/2
A
A= $config->{"contexts"}
Aresult
11
00
186 }
187  
188 212 ▶sub _find_by_name {
Subroutine _find_by_name: called CC=4 SCAR=13.9
189 212 my ($self, $list, $name) = @_;
190 212 ▶ for my $item (@{$list // []}) {
Condition50%1/2
$list // []
l!l
2120
MC/DC0%0/1
$list // []
$list
Truth table50%1/2
A
A= $list
Aresult
11
00
191 509 ▶ return $item if $item->{name} eq $name;
Branch: 1 branch
BranchTrueFalseTotal
if $item->{"name"} eq $name 206 303 509
192 }
193 6 return undef;
194 }
195  
196 73 ▶sub context {
Subroutine context: called CC=4 SCAR=13.9
Pod documented
197 73 my ($self, $name) = @_;
198  
199  
200 73 ▶ my $config = $self->_config
Branch: 1 branch
BranchTrueFalseTotal
my $config = $self->_config or croak($self->_not_found_error) 72 1 73
201 or croak $self->_not_found_error;
202 72 ▶ $name //= $self->current_context_name;
Condition100%3/3
$name //= $self->current_context_name
l!l&&r!l&&!r
6417
MC/DC100%2/2
$name //= $self->current_context_name
$name $self->current_context_name
Truth table100%3/3
A //= B
A= $nameB= $self->current_context_name
ABresult
1X1
011
000
203 72 $self->_assert_lookup($config, 'contexts', $name,
204 'kubeconfig has no current-context set');
205 64 ▶ my $ctx = $self->_find_by_name($config->{contexts}, $name)
Branch: 1 branch
BranchTrueFalseTotal
my $ctx = $self->_find_by_name($config->{"contexts"}, $name) or croak("Context not found: $name") 62 2 64
206 or croak "Context not found: $name";
207 62 return $ctx->{context};
208 }
209  
210 82 ▶sub cluster {
Subroutine cluster: called CC=3 SCAR=11.0
Pod documented
211 82 my ($self, $name) = @_;
212  
213  
214 82 ▶ my $config = $self->_config
Branch: 1 branch
BranchTrueFalseTotal
my $config = $self->_config or croak($self->_not_found_error) 81 1 82
215 or croak $self->_not_found_error;
216 81 $self->_assert_lookup($config, 'clusters', $name, 'no cluster name given');
217 78 ▶ my $cluster = $self->_find_by_name($config->{clusters}, $name)
Branch: 1 branch
BranchTrueFalseTotal
my $cluster = $self->_find_by_name($config->{"clusters"}, $name) or croak("Cluster not found: $name") 76 2 78
218 or croak "Cluster not found: $name";
219 76 return $cluster->{cluster};
220 }
221  
222 73 ▶sub user {
Subroutine user: called CC=3 SCAR=11.0
Pod documented
223 73 my ($self, $name) = @_;
224  
225  
226 73 ▶ my $config = $self->_config
Branch: 1 branch
BranchTrueFalseTotal
my $config = $self->_config or croak($self->_not_found_error) 72 1 73
227 or croak $self->_not_found_error;
228 72 $self->_assert_lookup($config, 'users', $name, 'no user name given');
229 70 ▶ my $user = $self->_find_by_name($config->{users}, $name)
Branch: 1 branch
BranchTrueFalseTotal
my $user = $self->_find_by_name($config->{"users"}, $name) or croak("User not found: $name") 68 2 70
230 or croak "User not found: $name";
231 68 return $user->{user};
232 }
233  
234 171 ▶sub _resolve_cert {
Subroutine _resolve_cert: called CC=3 SCAR=11.0
235 171 my ($self, $hash, $key) = @_;
236  
237 171 my $data_key = "${key}-data";
238 171 ▶ if (my $data = $hash->{$data_key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $data = $hash->{$data_key}) 7 164 171
239 7 return (pem => decode_base64($data));
240 }
241  
242 164 ▶ if (my $file = $hash->{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $file = $hash->{$key}) 20 144 164
243 20 return (file => $file);
244 }
245  
246 144 return ();
247 }
248  
249 61 ▶sub api {
Subroutine api: called CC=17 SCAR=28.4
Pod documented
250 61 my ($self, $context_name) = @_;
251  
252  
253 # If no kubeconfig, try in-cluster
254 61 ▶ unless ($self->_config) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_config) 1 60 61
255 1 ▶ return $self->_in_cluster_api
Condition33%1/3
$self->_in_cluster_api // croak($self->_not_found_error . ' and not running in-cluster')
l!l&&r!l&&!r
010
MC/DC0%0/2
$self->_in_cluster_api // croak($self->_not_found_error . ' and not running in-cluster')
$self->_in_cluster_api croak($self->_not_found_error . ' and not running in-cluster')
Truth table33%1/3
A // B
A= $self->_in_cluster_apiB= croak($self->_not_found_error . ' and not running in-cluster')
ABresult
1X1
011
000
256 // croak $self->_not_found_error . " and not running in-cluster";
257 }
258  
259 60 ▶ $context_name //= $self->current_context_name;
Condition100%3/3
$context_name //= $self->current_context_name
l!l&&r!l&&!r
31272
MC/DC100%2/2
$context_name //= $self->current_context_name
$context_name $self->current_context_name
Truth table100%3/3
A //= B
A= $context_nameB= $self->current_context_name
ABresult
1X1
011
000
260 60 my $ctx = $self->context($context_name);
261 58 my $cluster = $self->cluster($ctx->{cluster});
262 57 my $user = $self->user($ctx->{user});
263  
264 # Build server config
265 my %server = (
266 endpoint => $cluster->{server},
267 57 );
268  
269 57 ▶ if (my %ca = $self->_resolve_cert($cluster, 'certificate-authority')) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(%ca) = $self->_resolve_cert($cluster, "certificate-authority")) 11 46 57
270 11 ▶ $server{ $ca{pem} ? 'ssl_ca_pem' : 'ssl_ca_file' } = $ca{pem} // $ca{file};
Branch: 1 branch
BranchTrueFalseTotal
$ca{'pem'} ? : 5 6 11
Condition66%2/3
$ca{"pem"} // $ca{"file"}
l!l&&r!l&&!r
560
MC/DC0%0/2
$ca{"pem"} // $ca{"file"}
$ca{"pem"} $ca{"file"}
Truth table66%2/3
A // B
A= $ca{"pem"}B= $ca{"file"}
ABresult
1X1
011
000
271 }
272  
273 57 ▶ if ($cluster->{'insecure-skip-tls-verify'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cluster->{'insecure-skip-tls-verify'}) { } 46 11 57
274 46 $server{ssl_verify_server} = 0;
275 } else {
276 11 $server{ssl_verify_server} = 1;
277 }
278  
279 57 ▶ if (my %cert = $self->_resolve_cert($user, 'client-certificate')) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(%cert) = $self->_resolve_cert($user, "client-certificate")) 8 49 57
280 8 ▶ $server{ $cert{pem} ? 'ssl_cert_pem' : 'ssl_cert_file' } = $cert{pem} // $cert{file};
Branch: 1 branch
BranchTrueFalseTotal
$cert{'pem'} ? : 1 7 8
Condition66%2/3
$cert{"pem"} // $cert{"file"}
l!l&&r!l&&!r
170
MC/DC0%0/2
$cert{"pem"} // $cert{"file"}
$cert{"pem"} $cert{"file"}
Truth table66%2/3
A // B
A= $cert{"pem"}B= $cert{"file"}
ABresult
1X1
011
000
281 }
282  
283 57 ▶ if (my %key = $self->_resolve_cert($user, 'client-key')) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(%key) = $self->_resolve_cert($user, "client-key")) 8 49 57
284 8 ▶ $server{ $key{pem} ? 'ssl_key_pem' : 'ssl_key_file' } = $key{pem} // $key{file};
Branch: 1 branch
BranchTrueFalseTotal
$key{'pem'} ? : 1 7 8
Condition66%2/3
$key{"pem"} // $key{"file"}
l!l&&r!l&&!r
170
MC/DC0%0/2
$key{"pem"} // $key{"file"}
$key{"pem"} $key{"file"}
Truth table66%2/3
A // B
A= $key{"pem"}B= $key{"file"}
ABresult
1X1
011
000
285 }
286  
287 # Build credentials
288 57 my $credentials;
289 57 ▶ if (my $token = $user->{token}) {
Branch: 3 branches
BranchTrueFalseTotal
if (my $token = $user->{'token'}) { } 23 34 57
elsif (my $token_file = $user->{'tokenFile'}) { } 23 11 34
elsif (my $exec = $user->{'exec'}) { } 1 10 11
290 23 $credentials = Kubernetes::REST::AuthToken->new(token => $token);
291 } elsif (my $token_file = $user->{tokenFile}) {
292 23 $credentials = $self->_token_file_credential(
293 $token_file, "tokenFile of user '$ctx->{user}'"
294 );
295 } elsif (my $exec = $user->{exec}) {
296 1 $credentials = $self->_exec_credential($exec);
297 } else {
298 # No token auth, might be using client certs only
299 10 $credentials = Kubernetes::REST::AuthToken->new(token => '');
300 }
301  
302 51 return Kubernetes::REST->new(
303 server => Kubernetes::REST::Server->new(%server),
304 credentials => $credentials,
305 );
306 }
307  
308 # Credentials for a file holding a bearer token: a user's tokenFile, or the
309 # service account token mounted into a pod. Both are written by something else
310 # - the kubelet, a login helper - and both are rotated under a running process,
311 # so both get credentials that notice.
312 25 ▶sub _token_file_credential {
Subroutine _token_file_credential: called CC=2 SCAR=6.9
313 25 my ($self, $file, $what) = @_;
314  
315 25 ▶ return Kubernetes::REST::AuthTokenFile->new(
Branch: 1 branch
BranchTrueFalseTotal
$self->refresh_token_files ? : 23 2 25
316 file => $file,
317 description => $what,
318 refresh => $self->refresh_token_files ? 1 : 0,
319 );
320 }
321  
322 1 ▶sub _exec_credential {
Subroutine _exec_credential: called CC=6 SCAR=18.7
323 1 my ($self, $exec) = @_;
324  
325 1 my $cmd = $exec->{command};
326 1 ▶ my @args = @{$exec->{args} // []};
Condition50%1/2
$exec->{"args"} // []
l!l
01
MC/DC0%0/1
$exec->{"args"} // []
$exec->{"args"}
Truth table50%1/2
A
A= $exec->{"args"}
Aresult
11
00
327  
328 # Set up environment
329 1 local %ENV = %ENV;
330 1 ▶ for my $env (@{$exec->{env} // []}) {
Condition50%1/2
$exec->{"env"} // []
l!l
01
MC/DC0%0/1
$exec->{"env"} // []
$exec->{"env"}
Truth table50%1/2
A
A= $exec->{"env"}
Aresult
11
00
331 0 $ENV{$env->{name}} = $env->{value};
332 }
333  
334 1 my $output = `$cmd @args`;
335 1 ▶ croak "exec credential command failed: $cmd" if $?;
Branch: 1 branch
BranchTrueFalseTotal
if $? 0 1 1
336  
337 1 my $cred = YAML::XS::Load($output);
338 my $token = $cred->{status}{token}
339 1 ▶ or croak "exec credential did not return token";
Branch: 1 branch
BranchTrueFalseTotal
my $token = $cred->{"status"}{"token"} or croak("exec credential did not return token") 1 0 1
340  
341 1 return Kubernetes::REST::AuthToken->new(token => $token);
342 }
343  
344 11 my $SA_TOKEN = '/var/run/secrets/kubernetes.io/serviceaccount/token';
345 11 my $SA_CA = '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt';
346  
347 1 ▶sub _in_cluster_api {
Subroutine _in_cluster_api: called CC=4 SCAR=23.2
348 1 my ($self) = @_;
349 1 ▶ return undef unless -f $SA_TOKEN;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $SA_TOKEN 1 0 1
350  
351 0 ▶ my $host = $ENV{KUBERNETES_SERVICE_HOST} // 'kubernetes.default.svc';
Condition0%0/2
$ENV{"KUBERNETES_SERVICE_HOST"} // "kubernetes.default.svc"
l!l
00
MC/DC0%0/1
$ENV{"KUBERNETES_SERVICE_HOST"} // "kubernetes.default.svc"
$ENV{"KUBERNETES_SERVICE_HOST"}
Truth table0%0/2
A
A= $ENV{"KUBERNETES_SERVICE_HOST"}
Aresult
11
00
352 0 ▶ my $port = $ENV{KUBERNETES_SERVICE_PORT} // '443';
Condition0%0/2
$ENV{"KUBERNETES_SERVICE_PORT"} // 443
l!l
00
MC/DC0%0/1
$ENV{"KUBERNETES_SERVICE_PORT"} // 443
$ENV{"KUBERNETES_SERVICE_PORT"}
Truth table0%0/2
A
A= $ENV{"KUBERNETES_SERVICE_PORT"}
Aresult
11
00
353  
354 0 return Kubernetes::REST->new(
355 server => Kubernetes::REST::Server->new(
356 endpoint => "https://$host:$port",
357 ssl_ca_file => $SA_CA,
358 ssl_verify_server => 1,
359 ),
360 credentials => $self->_token_file_credential(
361 $SA_TOKEN, 'service account token'
362 ),
363 );
364 }
365  
366 11 1;
367  
368 __END__
369  
370 =pod
371  
372 =encoding UTF-8
373  
374 =head1 NAME
375  
376 Kubernetes::REST::Kubeconfig - Parse kubeconfig files and create Kubernetes::REST instances
377  
378 =head1 VERSION
379  
380 version 1.108
381  
382 =head1 SYNOPSIS
383  
384 use Kubernetes::REST::Kubeconfig;
385  
386 # Use default kubeconfig and current context
387 my $kc = Kubernetes::REST::Kubeconfig->new;
388 my $api = $kc->api;
389  
390 # Specify kubeconfig and context
391 my $kc = Kubernetes::REST::Kubeconfig->new(
392 kubeconfig_path => '/path/to/kubeconfig',
393 context_name => 'my-cluster',
394 );
395  
396 # Several kubeconfigs, merged the way kubectl merges $KUBECONFIG
397 my $kc = Kubernetes::REST::Kubeconfig->new(
398 kubeconfig_path => '/etc/kube/base:/home/me/.kube/extra',
399 );
400 my $kc = Kubernetes::REST::Kubeconfig->new(
401 kubeconfig_path => [ '/etc/kube/base', '/home/me/.kube/extra' ],
402 );
403  
404 # List available contexts
405 my $contexts = $kc->contexts;
406  
407 # Get API for specific context
408 my $api = $kc->api('production');
409  
410 # Inside a Kubernetes pod: no kubeconfig needed, auto-detects service account
411 my $api = Kubernetes::REST::Kubeconfig->new->api;
412  
413 =head1 DESCRIPTION
414  
415 Parses Kubernetes kubeconfig files (typically C<~/.kube/config>) and creates configured L<Kubernetes::REST> instances.
416  
417 Several kubeconfig files can be given at once - as the C<:>-separated list
418 C<kubectl> expects in C<KUBECONFIG>, or as an arrayref - and are merged into
419 one configuration the way C<kubectl> merges them. See L</MERGING>.
420  
421 When no kubeconfig file is found, automatically falls back to in-cluster
422 authentication using the pod's service account token.
423  
424 Supports:
425  
426 =over 4
427  
428 =item * Multiple clusters and contexts
429  
430 =item * Merging several kubeconfig files, C<kubectl>-style
431  
432 =item * Token authentication, inline or from a C<tokenFile>
433  
434 =item * Client certificate authentication
435  
436 =item * Inline certificate data (base64 encoded)
437  
438 =item * External certificate files
439  
440 =item * Exec-based credential plugins
441  
442 =item * In-cluster service account auto-detection
443  
444 =back
445  
446 =head2 kubeconfig_path
447  
448 Path to the kubeconfig file: a single path, a C<$Config{path_sep}>-separated
449 list of paths (C<:> on Unix, C<;> on Win32), or an arrayref of paths. A list is
450 merged as described in L</MERGING>; a single path behaves exactly as it always
451 has.
452  
453 Defaults to the C<KUBECONFIG> environment variable if it is set and not empty,
454 otherwise to C<~/.kube/config>. With neither C<KUBECONFIG> nor C<HOME> set
455 there is no path to guess, and the default is C<undef>: L</api> then goes
456 straight to in-cluster authentication, and every method that needs a file
457 croaks naming the two missing variables instead of reaching for C</.kube/config>.
458  
459 The split list, without empty entries, is L</kubeconfig_paths>.
460  
461 =head2 kubeconfig_paths
462  
463 Arrayref of the individual kubeconfig paths L</kubeconfig_path> names, in the
464 order they are merged, with empty entries removed. Derived from
465 C<kubeconfig_path> and not settable on its own. Empty when neither
466 C<KUBECONFIG> nor C<HOME> is set.
467  
468 The paths are not checked for existence here - see L</MERGING> for what happens
469 to entries that are not there.
470  
471 =head2 context_name
472  
473 Optional. The context name to use. If not specified, uses the current-context from the kubeconfig.
474  
475 =head2 refresh_token_files
476  
477 Whether a token that comes from a file - a user's C<tokenFile>, or the service
478 account token of the in-cluster fallback - is re-read when the file changes.
479 True by default; see L</TOKEN FILES AND ROTATION>.
480  
481 Set it to false and such a token is read once, when L</api> builds the client,
482 and never again, which is what this module did before it could refresh.
483  
484 my $kc = Kubernetes::REST::Kubeconfig->new(refresh_token_files => 0);
485  
486 It reaches every client this object builds. A caller who wants it per client
487 can build a second C<Kubernetes::REST::Kubeconfig> - they are cheap, and the
488 kubeconfig is only read when a client is actually built.
489  
490 =head2 current_context_name
491  
492 my $name = $kc->current_context_name;
493  
494 Returns the current context name (either from C<context_name> attribute or from the kubeconfig's C<current-context>). With several kubeconfig files merged, C<current-context> is the one from the first file that sets it.
495  
496 =head2 contexts
497  
498 my $contexts = $kc->contexts;
499  
500 Returns an arrayref of all available context names from the kubeconfig, or from every merged kubeconfig.
501  
502 =head2 context
503  
504 my $ctx = $kc->context;
505 my $ctx = $kc->context('production');
506  
507 Look up a context entry by name and return its C<context> hashref (with C<cluster>, C<user>, and optional C<namespace> keys). Defaults to C<current_context_name> when C<$name> is omitted. Croaks if the context is not found, and, before it gets that far, with a message naming the kubeconfig if the kubeconfig defines no contexts at all or has no C<current-context> to fall back to.
508  
509 =head2 cluster
510  
511 my $cluster = $kc->cluster('prod-cluster');
512  
513 Look up a cluster entry by name and return its C<cluster> hashref (with keys such as C<server>, C<certificate-authority>/C<certificate-authority-data>, and C<insecure-skip-tls-verify>). Croaks if the cluster is not found, and, before it gets that far, with a message naming the kubeconfig if the kubeconfig defines no clusters at all or no name was given.
514  
515 =head2 user
516  
517 my $user = $kc->user('token-user');
518  
519 Look up a user entry by name and return its C<user> hashref (with keys such as C<token>, C<client-certificate>/C<client-certificate-data>, C<client-key>/C<client-key-data>, or C<exec>). Croaks if the user is not found, and, before it gets that far, with a message naming the kubeconfig if the kubeconfig defines no users at all or no name was given.
520  
521 =head2 api
522  
523 my $api = $kc->api;
524 my $api = $kc->api('production');
525  
526 Create a L<Kubernetes::REST> instance (with a L<Kubernetes::REST::Server> built from the cluster entry and credentials built from the user entry) configured from the kubeconfig. If C<$context_name> is provided, uses that context; otherwise uses the current context.
527  
528 Certificate and key material can come from either an inline base64 C<*-data> field or a plain file-path field in the kubeconfig. Inline data is decoded and passed to L<Kubernetes::REST::Server> as an in-memory PEM string (C<ssl_ca_pem>/C<ssl_cert_pem>/C<ssl_key_pem>) rather than written to a temporary file, so the returned L<Kubernetes::REST> instance keeps working after this C<Kubernetes::REST::Kubeconfig> object is garbage-collected. A file path is passed on as C<ssl_ca_file>/C<ssl_cert_file>/C<ssl_key_file>, absolute: a relative one is resolved against the directory of the kubeconfig that defined the entry, see L</MERGING>.
529  
530 User authentication is resolved in this order: a plain C<token> field; a C<tokenFile>, whose content is the bearer token; an C<exec> block (kubectl's exec-credential-plugin mechanism, used for e.g. cloud IAM auth), which runs the configured C<command> (with C<args> and any C<env> entries applied to the child process) and reads C<status.token> from its output (parsed as YAML, which also accepts the JSON that real exec plugins emit); otherwise an empty token, for setups that authenticate via client certificate alone.
531  
532 That order is C<kubectl>'s. An inline C<token> wins over a C<tokenFile> - client-go's C<getUserIdentificationPartialConfig> reads the file only when there is no inline token - and either of them wins over an C<exec> block, which C<kubectl> skips whenever a request already carries an C<Authorization> header. An C<exec> plugin is therefore not run at all when the user also has a token or a token file.
533  
534 A C<tokenFile> that cannot be read, or that holds nothing but whitespace, is a fatal error naming the user and the file. It is deliberately not a fall-through to the next mechanism: a kubeconfig saying where its token lives is a statement about how this user authenticates, and quietly carrying on would produce a 401 from the cluster with nothing pointing at the file. Leading and trailing whitespace is stripped - such files almost always end in a newline, and a newline in an C<Authorization> header does not reach the server as intended.
535  
536 A C<tokenFile> is handed to L<Kubernetes::REST> as a L<Kubernetes::REST::AuthTokenFile>, which reads the file again when it changes, so a rotated token is picked up without rebuilding the client. The in-cluster service account token works the same way. See L</TOKEN FILES AND ROTATION>, and L</refresh_token_files> to turn it off.
537  
538 Falls back to in-cluster service account authentication when no kubeconfig
539 file is found - none of the merged paths exists, or there is no path at all
540 because neither C<KUBECONFIG> nor C<HOME> is set - and the pod has a mounted
541 token at
542 C</var/run/secrets/kubernetes.io/serviceaccount/token>. In that case the API
543 server address comes from the C<KUBERNETES_SERVICE_HOST>/C<KUBERNETES_SERVICE_PORT>
544 environment variables (defaulting to C<kubernetes.default.svc:443>), and the
545 cluster CA is read from C</var/run/secrets/kubernetes.io/serviceaccount/ca.crt>.
546  
547 =head1 MERGING
548  
549 C<KUBECONFIG> is a C<PATH>-style list of kubeconfig files, not a single path -
550 C<:>-separated everywhere except on Win32, where it is C<;>-separated, the same
551 separator Perl reports in C<$Config{path_sep}>. C<kubectl> merges every file in
552 that list into one configuration, and so does this module:
553  
554 =over 4
555  
556 =item * Clusters, contexts and users are unioned by name. The B<first> file
557 that defines a given name wins; later definitions of that same name are
558 discarded, they do not overwrite fields.
559  
560 =item * C<current-context> comes from the first file in the list that sets one,
561 as does every other top-level key (C<apiVersion>, C<kind>, C<preferences>).
562  
563 =item * Entries that name a file that does not exist are skipped silently,
564 which is what C<kubectl> does - a list assembled by a shell profile or by
565 C<direnv> routinely mentions files that are not there. So are empty entries, so
566 C</a::/b> and a trailing C<:> are harmless.
567  
568 =item * Relative entries in the list itself are resolved against the current
569 working directory.
570  
571 =back
572  
573 If no file in the list exists, the configuration is empty and L</api> falls
574 back to in-cluster authentication exactly as it does for a single missing file.
575  
576 =head2 Relative paths inside a kubeconfig
577  
578 The file references an entry holds - C<certificate-authority> on a cluster,
579 C<client-certificate>, C<client-key> and C<tokenFile> on a user - are resolved
580 against the directory of the kubeconfig file that defines that entry, the way
581 C<kubectl> resolves them, and not against the current working directory.
582  
583 With several files merged that directory is a property of the entry, not of the
584 configuration: a cluster that won from F</a/config> resolves its CA against
585 F</a> even when the current context came from F</b/config>. Resolution
586 therefore happens as each file is read, before anything is merged, so what
587 L</cluster>, L</user> and L</api> hand back are absolute paths that keep
588 pointing at the same file after a C<chdir>.
589  
590 An absolute reference is passed through untouched, and so is the inline base64
591 of the C<*-data> fields, which names no file. A leading C<~> is not expanded -
592 it is an ordinary directory name, exactly as it is for C<kubectl>, and resolves
593 like any other relative path. An C<exec> plugin's C<command> is not a file
594 reference in this sense either: it is looked up in C<PATH> and is left alone.
595  
596 =head1 TOKEN FILES AND ROTATION
597  
598 Kubernetes rotates the files a token can come from. The kubelet replaces a
599 projected service account token well before it expires, and a client that read
600 the file once at startup would go on sending a token that has stopped being
601 valid while a good one sits in the file next to it.
602  
603 A token that comes from a file - a user's C<tokenFile>, or the service account
604 token of the in-cluster fallback - is therefore not handed over as a fixed
605 string. L</api> builds a L<Kubernetes::REST::AuthTokenFile>, which reads the
606 file again whenever it has changed. There is no timer and no interval to
607 configure: the trigger is the file itself, and a client picks up a new token on
608 the first request after the rotation.
609  
610 What "changed" means, and what it costs, is
611 L<Kubernetes::REST::AuthTokenFile/token>: one C<stat> per request, comparing
612 device, inode, size and modification time, so the C<..data> symlink swap the
613 kubelet performs is seen as the different file it is. A read that fails after a
614 successful one - the file gone for a moment mid-rotation - keeps the last good
615 token rather than breaking the client. Only the first read, when the client is
616 built, is fatal.
617  
618 Set L</refresh_token_files> to false to switch this off. The token is then read
619 exactly once, when C<api()> builds the client, and never again: no C<stat> per
620 request, and the client stops working when that token expires, until something
621 builds it anew.
622  
623 An inline C<token> in the kubeconfig is unaffected either way - there is no
624 file to watch, and it is used exactly as it is written.
625  
626 =head1 SEE ALSO
627  
628 =over
629  
630 =item * L<Kubernetes::REST> - Main API client
631  
632 =item * L<Kubernetes::REST::Server> - Server configuration
633  
634 =item * L<Kubernetes::REST::AuthToken> - Authentication credentials
635  
636 =back
637  
638 =head1 SUPPORT
639  
640 =head2 Issues
641  
642 Please report bugs and feature requests on GitHub at
643 L<https://github.com/pplu/kubernetes-rest/issues>.
644  
645 =head2 IRC
646  
647 Join C<#kubernetes> on C<irc.perl.org> or message Getty directly.
648  
649 =head1 CONTRIBUTING
650  
651 Contributions are welcome! Please fork the repository and submit a pull request.
652  
653 =head1 AUTHORS
654  
655 =over 4
656  
657 =item *
658  
659 Torsten Raudssus <getty@cpan.org>
660  
661 =item *
662  
663 Jose Luis Martinez Torres <jlmartin@cpan.org>
664  
665 =back
666  
667 =head1 COPYRIGHT AND LICENSE
668  
669 This software is Copyright (c) 2019-2026 by Jose Luis Martinez Torres <jlmartin@cpan.org>.
670  
671 This is free software, licensed under:
672  
673 The Apache License, Version 2.0, January 2004
674  
675 =cut
« lib/Kubernetes/REST/LWPIO.pm ↑ Summary blib/lib/Kubernetes/REST/HTTPTinyIO.pm »