blib/lib/File/SOPS/Encrypted.pm

filter: Statementstmt 99.2% 272 / 274 Branchbran 94.2% 179 / 190 Conditioncond 77.0% 104 / 135 MC/DCmcdc 66.6% 46 / 69 Subroutinesub 97.8% 46 / 47 Podpod 100% 14 / 14 totaltotal 90.6% 661 / 729 CC 134 SCAR 21.4
CC
134
Cov
93%
_canonical_floats
19.0
_deserialize_value
17.1
value_to_bytes
15.0
CRAP 8.5
« blib/lib/File/SOPS/Metadata/Flat.pm ↑ Summary blib/lib/File/SOPS/Backend/Age.pm »
1 package File::SOPS::Encrypted;
2 # ABSTRACT: Parse and generate SOPS encrypted values
3 97 our $VERSION = '0.005';
4 97 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 97 ▶use B ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 97 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 97 ▶use Scalar::Util qw(blessed dualvar);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 97 ▶use MIME::Base64 qw(encode_base64 decode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 97 ▶use Crypt::AuthEnc::GCM qw(gcm_encrypt_authenticate gcm_decrypt_verify);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 97 ▶use Crypt::PRNG ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 97 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 # The type ladder's own value: detect_type produces the type from it and
13 # _deserialize_value produces it from the type (docs/adr/0041). It loads
14 # nothing from this distribution, so the dependency runs one way only.
15 97 ▶use File::SOPS::Comment;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 97 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18  
19 97 has algorithm => (is => 'ro', default => 'AES256_GCM');
20  
21  
22 97 has data => (is => 'ro', required => 1);
23  
24  
25 97 has iv => (is => 'ro', required => 1);
26  
27  
28 97 has tag => (is => 'ro', required => 1);
29  
30  
31 97 has type => (is => 'ro', default => 'str');
32  
33  
34 97 my $ENC_REGEX = qr/^ENC\[([^,]+),data:([^,]+),iv:([^,]+),tag:([^,]+),type:([^\]]+)\]$/;
35  
36 8637 ▶sub parse {
Subroutine parse: called CC=3 SCAR=11.0
Pod documented
37 8637 my ($class, $string) = @_;
38  
39 8637 ▶ return unless defined $string && $string =~ $ENC_REGEX;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $string and $string =~ /$ENC_REGEX/ 1 8636 8637
Condition66%2/3
defined $string and $string =~ /$ENC_REGEX/
!ll&&!rl&&r
018636
MC/DC50%1/2
defined $string and $string =~ /$ENC_REGEX/
defined $string $string =~ /$ENC_REGEX/
Truth table66%2/3
A and B
A= defined $stringB= $string =~ /$ENC_REGEX/
ABresult
0X0
100
111
40  
41 8636 my ($algo, $data, $iv, $tag, $type) = ($1, $2, $3, $4, $5);
42  
43 8636 return $class->new(
44 algorithm => $algo,
45 data => _decode_base64_strict($data, 'data'),
46 iv => _decode_base64_strict($iv, 'iv'),
47 tag => _decode_base64_strict($tag, 'tag'),
48 type => $type,
49 );
50 }
51  
52 # MIME::Base64::decode_base64 IGNORES anything outside the alphabet and stops
53 # at a short group, so a corrupted field decoded to a shorter string and turned
54 # into "Authentication failed - data may be corrupted" three calls later, or --
55 # for the iv and the tag -- into a wrong length passed straight to the cipher.
56 # Go decodes with base64.StdEncoding, which fails on the spot and says so, and
57 # the field it fails on is the useful half of the message.
58 25903 ▶sub _decode_base64_strict {
Subroutine _decode_base64_strict: called CC=3 SCAR=11.0
59 25903 my ($encoded, $field) = @_;
60  
61 25903 ▶ croak "Invalid base64 in the '$field' field of an ENC value: "
Branch: 1 branch
BranchTrueFalseTotal
unless $encoded =~ m[\A[A-Za-z0-9+/]*={0,2}\z] 3 25900 25903
62 . "characters outside the standard alphabet"
63 unless $encoded =~ m{\A[A-Za-z0-9+/]*={0,2}\z};
64 25900 ▶ croak "Invalid base64 in the '$field' field of an ENC value: "
Branch: 1 branch
BranchTrueFalseTotal
if length($encoded) % 4 1 25899 25900
65 . "length is not a multiple of 4"
66 if length($encoded) % 4;
67  
68 25899 return decode_base64($encoded);
69 }
70  
71  
72 8224 ▶sub is_encrypted {
Subroutine is_encrypted: called CC=2 SCAR=6.9
Pod documented
73 8224 my ($class, $string) = @_;
74 8224 ▶ return defined $string && $string =~ $ENC_REGEX;
Condition100%3/3
defined $string && $string =~ /$ENC_REGEX/
!ll&&!rl&&r
5518168
MC/DC100%2/2
defined $string && $string =~ /$ENC_REGEX/
defined $string $string =~ /$ENC_REGEX/
Truth table100%3/3
A && B
A= defined $stringB= $string =~ /$ENC_REGEX/
ABresult
0X0
100
111
75 }
76  
77  
78 # The type LABEL, without decoding anything. The third sharer of $ENC_REGEX,
79 # alongside is_encrypted and parse -- one anchored pattern, so a caller asking
80 # "what kind of leaf is this" can never disagree with a caller asking "is this a
81 # leaf at all".
82 #
83 # Deliberately not `parse($s)->type`: parse decodes all three base64 fields and
84 # croaks on a damaged one, and the caller this exists for -- the comment guard
85 # in File::SOPS::Format::YAML -- has to recognise a comment leaf whose
86 # ciphertext is broken. Measured against sops 3.13.3: a comment whose ciphertext
87 # was swapped for another value's is NOT fatal to sops (`sops -d` exit 0, with a
88 # warning), so identifying it by the label alone is what matches the reference.
89 8834 ▶sub encrypted_type {
Subroutine encrypted_type: called CC=3 SCAR=11.0
Pod documented
90 8834 my ($class, $string) = @_;
91  
92 8834 ▶ return unless defined $string && $string =~ $ENC_REGEX;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $string and $string =~ /$ENC_REGEX/ 690 8144 8834
Condition100%3/3
defined $string and $string =~ /$ENC_REGEX/
!ll&&!rl&&r
126788144
MC/DC100%2/2
defined $string and $string =~ /$ENC_REGEX/
defined $string $string =~ /$ENC_REGEX/
Truth table100%3/3
A and B
A= defined $stringB= $string =~ /$ENC_REGEX/
ABresult
0X0
100
111
93 8144 return $5;
94 }
95  
96  
97 # Is this PERL VALUE a comment rather than a value? The plaintext side of the
98 # question detect_type answers with the label -- same predicate, one place, so
99 # a walk that has to skip comments and the ladder that types them can never
100 # disagree.
101 #
102 # Deliberately NOT true for an ENC[...,type:comment] string. That is what the
103 # FILE says a leaf is, which is a different question with a different answer:
104 # on the encrypt side such a string is a caller's plain string and is written
105 # as a type:str value. Reading them as one predicate is how the digest and the
106 # document end up covering different leaves. encrypted_type is the wire half,
107 # and File::SOPS::_is_comment_leaf is where the two meet, each under the
108 # condition that makes it the right one.
109 124281 ▶sub is_comment {
Subroutine is_comment: called CC=3 SCAR=11.0
Pod documented
110 124281 my ($class, $value) = @_;
111 124281 ▶ return blessed($value) && $value->isa('File::SOPS::Comment') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($value) && $value->isa('File::SOPS::Comment') ? : 52 124229 124281
Condition100%3/3
builtin::blessed($value) and $value->isa("File::SOPS::Comment")
!ll&&!rl&&r
12408614352
MC/DC100%2/2
builtin::blessed($value) and $value->isa("File::SOPS::Comment")
builtin::blessed($value) $value->isa("File::SOPS::Comment")
Truth table100%3/3
A and B
A= builtin::blessed($value)B= $value->isa("File::SOPS::Comment")
ABresult
0X0
100
111
112 }
113  
114  
115 5391 ▶sub to_string {
Subroutine to_string: called CC=1 SCAR=0.0
Pod documented
116 5391 my ($self) = @_;
117  
118 5391 my $data = _encode_base64_oneline($self->data);
119 5391 my $iv = _encode_base64_oneline($self->iv);
120 5391 my $tag = _encode_base64_oneline($self->tag);
121  
122 5391 return sprintf('ENC[%s,data:%s,iv:%s,tag:%s,type:%s]',
123 $self->algorithm, $data, $iv, $tag, $self->type);
124 }
125  
126  
127 5449 ▶sub encrypt_value {
Subroutine encrypt_value: called CC=5 SCAR=16.1
Pod documented
128 5449 my ($class, %args) = @_;
129 5449 my $value = $args{value};
130 5449 ▶ my $key = $args{key} // croak "key required";
Condition50%1/2
$args{"key"} // croak("key required")
l!l
54490
MC/DC0%0/1
$args{"key"} // croak("key required")
$args{"key"}
Truth table50%1/2
A
A= $args{"key"}
Aresult
11
00
131 5449 my $aad = _aad_bytes($args{aad});
132 5449 ▶ my $type = $args{type} // $class->detect_type($value);
Condition66%2/3
$args{"type"} // $class->detect_type($value)
l!l&&r!l&&!r
76246870
MC/DC0%0/2
$args{"type"} // $class->detect_type($value)
$args{"type"} $class->detect_type($value)
Truth table66%2/3
A // B
A= $args{"type"}B= $class->detect_type($value)
ABresult
1X1
011
000
133  
134 5449 ▶ $value //= '';
Condition100%2/2
$value //= ""
l!l
54481
MC/DC100%1/1
$value //= ""
$value
Truth table100%2/2
A
A= $value
Aresult
11
00
135  
136 # THE SLOT, from the one place that cannot be wrong about it: this method
137 # exists to put a value in an encrypted slot, so every value it is handed
138 # is in one. That is what lets assert_representable stop asking about a
139 # non-finite float here -- an encrypted slot's wire form for one is
140 # type:float plus the plaintext Go's strconv.FormatFloat writes, which is
141 # what sops itself puts in BOTH formats, so the scalar's string half plays
142 # no part and there is nothing left to refuse. See docs/adr/0040.
143 5449 $class->assert_representable($value, encrypted => 1);
144  
145 5448 my $plaintext = $class->value_to_bytes($value, $type);
146  
147 # AES-GCM ciphertext is exactly as long as its plaintext, so an empty
148 # value produces an empty `data:` field -- and neither implementation's
149 # parser accepts that. Ours requires one character ([^,]+); sops stops with
150 # "Input string ENC[...] does not match sops' data format" (exit 25). sops
151 # never produces the shape either: it leaves an empty value unencrypted,
152 # which is what File::SOPS::encrypt does before it ever gets here.
153 5448 ▶ croak "Cannot encrypt an empty value: the SOPS wire format has no "
Branch: 1 branch
BranchTrueFalseTotal
unless length $plaintext 2 5446 5448
154 . "representation for empty ciphertext. Leave the value unencrypted "
155 . "instead, which is what sops does with an empty scalar."
156 unless length $plaintext;
157  
158 5446 my $iv = _random_bytes(32); # SOPS uses 32-byte nonce
159  
160 5443 my ($ciphertext, $tag) = gcm_encrypt_authenticate('AES', $key, $iv, $aad, $plaintext);
161  
162 5443 return $class->new(
163 algorithm => 'AES256_GCM',
164 data => $ciphertext,
165 iv => $iv,
166 tag => $tag,
167 type => $type,
168 );
169 }
170  
171  
172 8696 ▶sub decrypt_bytes {
Subroutine decrypt_bytes: called CC=4 SCAR=14.0
Pod documented
173 8696 my ($self, %args) = @_;
174 8696 ▶ my $key = $args{key} // croak "key required";
Condition50%1/2
$args{"key"} // croak("key required")
l!l
86960
MC/DC0%0/1
$args{"key"} // croak("key required")
$args{"key"}
Truth table50%1/2
A
A= $args{"key"}
Aresult
11
00
175 8696 my $aad = _aad_bytes($args{aad});
176  
177 8696 ▶ croak "Unsupported algorithm: " . $self->algorithm
Branch: 1 branch
BranchTrueFalseTotal
unless $self->algorithm eq "AES256_GCM" 0 8696 8696
178 unless $self->algorithm eq 'AES256_GCM';
179  
180 8696 my $plaintext = gcm_decrypt_verify('AES', $key, $self->iv, $aad, $self->data, $self->tag);
181 8696 ▶ croak "Authentication failed - data may be corrupted" unless defined $plaintext;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $plaintext 11 8685 8696
182  
183 # The stringify is load-bearing, and `return $plaintext` is a silent
184 # data-corruption bug -- do not "simplify" it away.
185 #
186 # CryptX (measured on 0.087) hands back the plaintext in an SV whose PV
187 # buffer is NOT NUL-terminated at SvCUR. Perl's own string-to-number
188 # conversion depends on that terminator: sv_2nv only
189 # consults SvCUR through grok_number, and for anything grok_number cannot
190 # settle as an integer inside a UV -- every float, and every integer wider
191 # than 64 bits -- it falls through to Atof(SvPVX), a C string read with no
192 # length. So a numeric read of the raw scalar runs off the end of the
193 # plaintext into whatever the allocator left there, and when that byte is
194 # one of the ten digit characters it joins the number: the
195 # 100000000000000000000 Go writes for 1e20 came back as 1e21, on maybe one
196 # leaf in a hundred, with the ciphertext and the MAC both intact.
197 # Assignment through a stringify goes via sv_setpvn, which allocates a
198 # buffer Perl terminates itself.
199 #
200 # It belongs here rather than at the two conversions in _deserialize_value
201 # because this is the boundary the foreign scalar crosses: the type
202 # conversion, the MAC digest and any caller doing arithmetic on what this
203 # method returns are all downstream of it, and a fix at the conversions
204 # would have to be repeated at each new one. See t/18-decrypt-determinism.t.
205 #
206 # This is the ONLY such normalisation, deliberately: the ciphertext, the tag
207 # and the IV come out of CryptX just as unterminated, and are left alone
208 # because nothing ever reads them as anything but length-delimited bytes.
209 # docs/adr/0004 has the measurements and says why "normalise every CryptX
210 # boundary" is not the rule -- and why "normalise every foreign scalar"
211 # would break ADR 0002 outright.
212 8685 return "$plaintext";
213 }
214  
215  
216 4112 ▶sub decrypt_value {
Subroutine decrypt_value: called CC=1 SCAR=0.0
Pod documented
217 4112 my ($self, %args) = @_;
218 4112 return _deserialize_value($self->decrypt_bytes(%args), $self->type);
219 }
220  
221  
222 # Perl's own boolean SV -- the value !!1, $x > 3, 'a' eq 'a' and
223 # builtin::true produce -- asked through the same predicate BOTH emitters ask.
224 #
225 # YAML::XS and Cpanel::JSON::XS write exactly such an SV as a bare true/false,
226 # and they use SvIsBOOL to decide it. That is not a flag pattern this module
227 # could reimplement: measured on YAML::XS 0.910.0 and Cpanel::JSON::XS 4.43,
228 # dualvar(1, '1') carries the same IV, the same PV and the same PUBLIC flags as
229 # !!1, and both emitters write it as `1`. The two differ only in whether the PV
230 # buffer is perl's own static PL_Yes, which B does not expose. A lookalike test
231 # here would therefore type a dualvar `bool` and digest `True` while the
232 # document said `1` -- this defect again, introduced by its own fix.
233 #
234 # builtin::is_bool is the only way to reach SvIsBOOL from Perl. It arrived with
235 # the SV mark in 5.36; on an older perl there is no such SV for either emitter
236 # to recognise, so `sub { 0 }` is the whole answer there and not a degraded
237 # one. Loaded through a string eval because `use builtin` and
238 # `no warnings 'experimental::builtin'` are each a compile-time error on a perl
239 # that has neither, and this distribution declares 5.010.
240 #
241 # This is NOT a return to the pattern match ADR 0002 removed: nothing looks at
242 # the value's text. It reads a mark Perl itself put on the scalar, exactly as
243 # _sv_kind reads IOK. See docs/adr/0016.
244 97 my $IS_BOOL_SV = do {
245 97 ▶ my $probe = eval q{
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
246 no warnings 'experimental::builtin';
247 use builtin qw(is_bool);
248 sub { is_bool($_[0]) }
249 };
250  
251 # VERIFIED, not assumed: it has to say yes to both sentinels and no to the
252 # integer and the string that share their flags and their PV. A predicate
253 # that answers anything else is not the one the emitters use, and typing a
254 # leaf by it would write a document that fails its own MAC.
255 97 ▶ $probe = undef unless $probe
Branch: 1 branch
BranchTrueFalseTotal
unless 0 97 97
Condition33%6/18
and not &$probe(1)
!ll&&!rl&&r
0097
and not &$probe("")
!ll&&!rl&&r
0097
and not &$probe(0)
!ll&&!rl&&r
0097
and not &$probe(1)
!ll&&!rl&&r
0097
and
!ll&&!rl&&r
0097
$probe and
!ll&&!rl&&r
0097
256 && $probe->(!!1) && $probe->(!!0)
257 && !$probe->(1) && !$probe->(0)
258 && !$probe->('') && !$probe->('1');
259  
260 # Below 5.36 there is no boolean SV, so "no" is the whole answer and the
261 # emitters agree. At or above it there is one, both emitters write it as a
262 # bare true/false, and having no way to recognise it means every boolean
263 # this process encrypts is a document nothing can read -- which is a thing
264 # to say at load time, not to discover from a MAC mismatch.
265 97 ▶ croak "File::SOPS::Encrypted: perl $] has a boolean SV (SvIsBOOL) but "
Branch: 1 branch
BranchTrueFalseTotal
if not $probe and $] >= "5.036" 0 97 97
Condition33%1/3
not $probe and $] >= "5.036"
!ll&&!rl&&r
9700
MC/DC0%0/2
not $probe and $] >= "5.036"
not $probe $] >= "5.036"
Truth table33%1/3
not(A) and B
A= not $probeB= $] >= "5.036"
ABresult
0X0
100
111
266 . "builtin::is_bool is not usable here, so a Perl boolean cannot be "
267 . "told from the integer 1. Every such value would be written as "
268 . "type:int while both emitters write it as a bare true/false, and the "
269 . "document would fail its own MAC. See docs/adr/0016."
270 if !$probe && $] >= 5.036;
271  
272 0 ▶ $probe || sub { 0 };
Subroutine __ANON__: not called CC=1 SCAR=2.0
Condition33%1/3
$probe || sub { 0; }
l!l&&r!l&&!r
9700
MC/DC0%0/2
$probe || sub { 0; }
$probe sub { 0; }
Truth table33%1/3
A || B
A= $probeB= sub { 0; }
ABresult
1X1
011
000
273 };
274  
275 29726 ▶sub detect_type {
Subroutine detect_type: called CC=8 SCAR=20.8
Pod documented
276 29726 my ($class, $value) = @_;
277 29726 ▶ return 'str' unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1 29725 29726
278 # JSON::PP::Boolean is the class every JSON::MaybeXS backend blesses into
279 # (Cpanel::JSON::XS and JSON::XS included), and the class YAML::XS blesses
280 # into under $YAML::XS::Boolean = 'JSON::PP', so this test is
281 # backend-agnostic. blessed() guard: ->isa dies on an unblessed ref, and a
282 # plain SCALAR/CODE ref can reach here from encrypt_value or the
283 # _encrypt_tree leaf branch.
284 # A comment is not a value and has no scalar of its own, so it gets a class
285 # -- the same move type:bool makes with JSON::PP::Boolean. Before that
286 # check because the two are independent: what matters is that neither can
287 # be reached by the ref -> 'str' line below. See docs/adr/0041.
288 29725 ▶ return 'comment' if blessed($value) && $value->isa('File::SOPS::Comment');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($value) and $value->isa("File::SOPS::Comment") 31 29694 29725
Condition100%3/3
builtin::blessed($value) and $value->isa("File::SOPS::Comment")
!ll&&!rl&&r
2944924531
MC/DC100%2/2
builtin::blessed($value) and $value->isa("File::SOPS::Comment")
builtin::blessed($value) $value->isa("File::SOPS::Comment")
Truth table100%3/3
A and B
A= builtin::blessed($value)B= $value->isa("File::SOPS::Comment")
ABresult
0X0
100
111
289 29694 ▶ return 'bool' if blessed($value) && $value->isa('JSON::PP::Boolean');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($value) and $value->isa("JSON::PP::Boolean") 223 29471 29694
Condition100%3/3
builtin::blessed($value) and $value->isa("JSON::PP::Boolean")
!ll&&!rl&&r
2944922223
MC/DC100%2/2
builtin::blessed($value) and $value->isa("JSON::PP::Boolean")
builtin::blessed($value) $value->isa("JSON::PP::Boolean")
Truth table100%3/3
A and B
A= builtin::blessed($value)B= $value->isa("JSON::PP::Boolean")
ABresult
0X0
100
111
290 29471 ▶ return 'str' if ref $value;
Branch: 1 branch
BranchTrueFalseTotal
if ref $value 22 29449 29471
291 # Before the flag ladder: a boolean sentinel publishes IOK, so _sv_kind
292 # would call it an int and value_to_bytes would digest 1 / 0 against a
293 # document both emitters write as true / false. k90.
294 29449 ▶ return 'bool' if $IS_BOOL_SV->($value);
Branch: 1 branch
BranchTrueFalseTotal
if &$IS_BOOL_SV($value) 368 29081 29449
295 29081 return _sv_kind($value);
296 }
297  
298  
299 # Go's int is int64 on every platform SOPS ships for, and its range is what
300 # strconv.Atoi accepts on the way back in. Written as MAX-1 plus one so the
301 # literal itself never has to survive as a negative UV.
302 97 my $INT64_MAX = 9223372036854775807;
303 97 my $INT64_MIN = -9223372036854775807 - 1;
304  
305 # Range test on the DECIMAL TEXT, not on a numified copy. -9223372036854775809
306 # rounds to exactly -2**63 as a double, so `0 + $s >= $INT64_MIN` says yes to a
307 # value Go says no to. $s has already been matched against /\A[+-]?[0-9]+\z/.
308 2087 ▶sub _decimal_fits_int64 {
Subroutine _decimal_fits_int64: called CC=5 SCAR=16.1
309 2087 my ($s) = @_;
310 2087 my ($sign, $digits) = $s =~ /\A([+-]?)0*([0-9]+)\z/;
311 2087 ▶ my $limit = $sign eq '-' ? '9223372036854775808' : '9223372036854775807';
Branch: 1 branch
BranchTrueFalseTotal
$sign eq '-' ? : 6 2081 2087
312 2087 ▶ return 0 if length($digits) > length($limit);
Branch: 1 branch
BranchTrueFalseTotal
if length $digits > length $limit 12 2075 2087
313 2075 ▶ return 0 if length($digits) == length($limit) && $digits gt $limit;
Branch: 1 branch
BranchTrueFalseTotal
if length $digits == length $limit and $digits gt $limit 7 2068 2075
Condition100%3/3
length $digits == length $limit and $digits gt $limit
!ll&&!rl&&r
206357
MC/DC100%2/2
length $digits == length $limit and $digits gt $limit
length $digits == length $limit $digits gt $limit
Truth table100%3/3
A and B
A= length $digits == length $limitB= $digits gt $limit
ABresult
0X0
100
111
314 2068 return 1;
315 }
316  
317 # The same boundary asked of a scalar Perl already holds as a NUMBER, for a
318 # format handler that has read the SV's flags itself and needs the limit
319 # without spelling it a second time (k101, ADR 0021). One definition of
320 # int64 in this distribution, here, is the point of the method.
321 #
322 # The unpacking COPIES, and that is load-bearing rather than house style: a
323 # comparison against $_[1] would numify the CALLER's scalar in place, and
324 # measured, that sets the PUBLIC SVf_IOK -- `'5432' > $INT64_MAX` leaves
325 # detect_type calling '5432' an int. That is k32's mechanism and ADR
326 # 0002's rule; the copy is what keeps this predicate from retyping the
327 # document it is asked about. Do not "optimise" it away.
328 #
329 # The argument has to be an INTEGER, which is the caller's cheap first gate
330 # and never this method's business (asking would be a second type ladder).
331 # Neither other kind is answered correctly, and both for the same rounding:
332 # an NV of exactly 2**63 says yes, because the comparison promotes the IV
333 # limit to a double and 2**63-1 becomes 2**63; and a decimal STRING is the
334 # trap _decimal_fits_int64 exists for, from the other side. Text goes there.
335 57 ▶sub integer_fits_int64 {
Subroutine integer_fits_int64: called CC=3 SCAR=11.1
Pod documented
336 57 my ($class, $value) = @_;
337 57 ▶ return $value >= $INT64_MIN && $value <= $INT64_MAX ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$value >= $INT64_MIN && $value <= $INT64_MAX ? : 35 22 57
Condition66%2/3
$value >= $INT64_MIN and $value <= $INT64_MAX
!ll&&!rl&&r
02235
MC/DC50%1/2
$value >= $INT64_MIN and $value <= $INT64_MAX
$value >= $INT64_MIN $value <= $INT64_MAX
Truth table66%2/3
A and B
A= $value >= $INT64_MINB= $value <= $INT64_MAX
ABresult
0X0
100
111
338 }
339  
340  
341 # Canonical texts no emitter has a wire form for that it derives from the
342 # NUMBER alone: Go's strconv.FormatFloat produces them, and Perl's encoders
343 # produce something else (`null`, `Inf`) for the same double. Everything below
344 # that treats a non-finite float differently keys on this one regex, and it
345 # matches the output of value_to_bytes, never a rendering derived beside it.
346 #
347 # -0 used to be on this list and is not any more: k62 measured a YAML
348 # spelling that works, and the format that needed one supplies it in its own
349 # carrier. See docs/adr/0006.
350 97 my $NO_AGREED_FORM = qr/\A(?:NaN|[+-]Inf)\z/;
351  
352 # The text value_to_bytes covers for a non-finite float, and undef for every
353 # other float. THE one statement of the rule: _float_bytes calls this and
354 # returns its answer, so what the digest covers and what the guards below ask
355 # about cannot become two comparisons against 9**9**9 that drift apart.
356 #
357 # It answers in three comparisons rather than through _float_bytes's whole
358 # shortest-round-trip loop, and that is measured rather than assumed: with the
359 # loop in the way, encrypt_value on a float leaf cost 130ms -> 272ms per 5000
360 # calls, a tax on every encrypted float for a guard about three values.
361 #
362 # The scalar is read numerically, which is what the digest does to it anyway.
363 # Nothing here reads or writes its string half.
364 97 my $POSITIVE_INFINITY = 9**9**9;
365  
366 13237 ▶sub _non_finite_bytes {
Subroutine _non_finite_bytes: called CC=5 SCAR=16.1
367 13237 my ($n) = @_;
368  
369 13237 ▶ return 'NaN' if $n != $n; # only NaN is unequal to itself
Branch: 1 branch
BranchTrueFalseTotal
if $n != $n 147 13090 13237
370 13090 ▶ return $n > 0 ? '+Inf' : '-Inf'
Branch: 2 branches
BranchTrueFalseTotal
if $n == $POSITIVE_INFINITY or $n == -$POSITIVE_INFINITY 583 12507 13090
$n > 0 ? : 429 154 583
Condition100%3/3
$n == $POSITIVE_INFINITY or $n == -$POSITIVE_INFINITY
l!l&&r!l&&!r
42915412507
MC/DC100%2/2
$n == $POSITIVE_INFINITY or $n == -$POSITIVE_INFINITY
$n == $POSITIVE_INFINITY $n == -$POSITIVE_INFINITY
Truth table100%3/3
A or B
A= $n == $POSITIVE_INFINITYB= $n == -$POSITIVE_INFINITY
ABresult
1X1
011
000
371 if $n == $POSITIVE_INFINITY || $n == -$POSITIVE_INFINITY;
372 12507 return undef;
373 }
374  
375 # The bytes go-yaml derives from a plain scalar it resolves to a non-finite
376 # float, for the twelve tokens that are the only spellings it does that for --
377 # and undef for everything else, `.INf`, `+.nan` and `.infinity` included.
378 #
379 # A SECOND STATEMENT of twelve rows of Go's resolveMap, whose single home is
380 # %GO_CONSTANT in Format::YAML, and deliberately so: this is a GATE and not a
381 # verdict. It decides only whether a leaf is worth deferring to the emitter's
382 # own foreign-resolution guard, which answers from `_go_scalar_bytes` -- the one
383 # model of resolve.go -- and has the last word on every document that carries a
384 # MAC. Both drift directions therefore fail CLOSED: a row here that
385 # %GO_CONSTANT lacks is refused by that guard on bytes, and a row %GO_CONSTANT
386 # gains that is missing here is refused by this gate. Neither can put a file on
387 # disk. See docs/adr/0031.
388 243 ▶sub _go_non_finite_token_bytes {
Subroutine _go_non_finite_token_bytes: called CC=4 SCAR=13.9
389 243 my ($token) = @_;
390 243 ▶ return '+Inf' if $token =~ /\A\+?\.(?:inf|Inf|INF)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $token =~ /\A\+?\.(?:inf|Inf|INF)\z/ 99 144 243
391 144 ▶ return '-Inf' if $token =~ /\A-\.(?:inf|Inf|INF)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $token =~ /\A-\.(?:inf|Inf|INF)\z/ 50 94 144
392 94 ▶ return 'NaN' if $token =~ /\A\.(?:nan|NaN|NAN)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $token =~ /\A\.(?:nan|NaN|NAN)\z/ 37 57 94
393 57 return undef;
394 }
395  
396 # Does this scalar carry, as its OWN public string half, a token a foreign
397 # reader resolves back to exactly the double it holds?
398 #
399 # Both halves have to agree. dualvar(+Inf, '-.inf') is a contradiction -- the
400 # document would say one infinity and the digest cover the other -- and it is
401 # refused, the same answer docs/adr/0012 gives an integer whose halves disagree,
402 # and measured the same way (sops -d exit 51 for every mismatched pairing).
403 #
404 # The PUBLIC SVf_POK, for the reason _has_public_pv gives: merely printing a
405 # float sets the private flag, and a gate that read that one would take a
406 # caller's logging for a promise about the wire. Nothing here numifies the
407 # string half or stringifies the number (docs/adr/0002, k32).
408 244 ▶sub _carries_go_non_finite_token {
Subroutine _carries_go_non_finite_token: called CC=4 SCAR=13.9
409 244 my ($value, $text) = @_;
410 244 ▶ return 0 unless _has_public_pv($value);
Branch: 1 branch
BranchTrueFalseTotal
unless _has_public_pv($value) 1 243 244
411 243 my $bytes = _go_non_finite_token_bytes("$value");
412 243 ▶ return defined $bytes && $bytes eq $text ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $bytes && $bytes eq $text ? : 148 95 243
Condition100%3/3
defined $bytes and $bytes eq $text
!ll&&!rl&&r
5738148
MC/DC100%2/2
defined $bytes and $bytes eq $text
defined $bytes $bytes eq $text
Truth table100%3/3
A and B
A= defined $bytesB= $bytes eq $text
ABresult
0X0
100
111
413 }
414  
415 10318 ▶sub assert_representable {
Subroutine assert_representable: called CC=15 SCAR=27.1
Pod documented
416 10318 my ($class, $value, %args) = @_;
417 10318 ▶ return 1 unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 7 10311 10318
418  
419 # k67: an unblessed reference in an encrypted slot would be
420 # stringified as 'SCALAR(0x...)' / 'ARRAY(0x...)' / 'HASH(0x...)' /
421 # 'CODE(0x...)' -- a heap address that differs per process run -- and
422 # value_to_bytes would feed that same address into the MAC digest. The
423 # document verifies (the doc and the digest agree on the address), but the
424 # stored value is unrecognisable and impossible to reproduce on a later
425 # read. Refused here, the same shape as the int64 check below. A blessed
426 # object passes: ADR 0008 measured that an encrypted Math::BigFloat, an
427 # object overloading "" and a qr// all round-trip correctly -- they have a
428 # stringification the caller chose.
429 10311 ▶ if (ref $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value) 110 10201 10311
430 110 ▶ return 1 if blessed($value);
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($value) 108 2 110
431 2 croak "cannot encrypt an unblessed " . ref($value)
432 . " reference; the SOPS digest covers the reference's heap "
433 . "address (e.g. SCALAR(0x...)), which differs per run, and "
434 . "storing that as an encrypted value is almost never what the "
435 . "caller means. Pass a string (the value the ref was holding, "
436 . "or its stringification), or a blessed object whose "
437 . "stringification is the value you mean.";
438 }
439  
440 # k59: a non-finite float (NaN, +Inf, -Inf) has no agreed form on the
441 # wire OF ITS OWN. value_to_bytes writes +Inf / -Inf / NaN -- the same text
442 # Go's strconv.FormatFloat produces -- but the emitters write something
443 # else for the same double: Cpanel::JSON::XS writes `null`, and YAML::XS
444 # writes a bare `Inf` / `-Inf` / `NaN`, which go-yaml resolves as a STRING.
445 # Measured against sops 3.13.3, unencrypted YAML leaf: `Inf` is `sops -d`
446 # exit 51, and `-Inf` / `NaN` are exit 0 with the leaf silently retyped
447 # from a float to a string -- which is worse, not better. Refused here, the
448 # same shape as the ref and int64 checks.
449 #
450 # NARROWED for k113 / docs/adr/0031: that premise is about a scalar
451 # whose only form is its number. One that also carries a plain YAML token
452 # go-yaml resolves back to exactly that double -- the shape docs/adr/0026's
453 # parse produces for a document sops wrote -- does have a wire form, and
454 # refusing it left this library reading a document it could not write back
455 # (rotate croaked on a file `sops -d` reads at exit 0). Measured, all twelve
456 # tokens, unencrypted YAML slot: `sops -e` -> File::SOPS->rotate ->
457 # `sops -d` exit 0, the wire byte-identical.
458 #
459 # This is a GATE, not the verdict. Whether the document being written can
460 # really carry the token is a question about one emitter and one foreign
461 # reader, and it is answered where the format is known: by docs/adr/0013's
462 # foreign-resolution guard in Format::YAML, which compares the token that
463 # emitter actually writes against Go's own resolution -- the single copy of
464 # that model. canonical_float_tree hands the leaf over, and refuses it in a
465 # MAC-covered document whose handler installs no such guard.
466 #
467 # Reading is unaffected -- a type:float plaintext of +Inf or NaN is accepted
468 # by _deserialize_value today (k59's request, and Go writes it) and
469 # stays accepted: assert_representable is encrypt-side only.
470 #
471 # NARROWED AGAIN for k122 / docs/adr/0040, and this time by SLOT. All
472 # of the above is about a leaf the DOCUMENT carries as a token, which is
473 # the unencrypted slot and nothing else. An encrypted slot carries
474 # type:float and the plaintext value_to_bytes writes, in both formats, and
475 # measured against sops 3.13.3 that is exactly what `sops -e` puts there --
476 # `--output-type json` included, exit 0. So the emitters' inability to
477 # spell the number says nothing about that slot, and the leaf is written.
478 # The caller supplies the slot; the two that do are encrypt_value, which is
479 # the encrypted slot by construction, and File::SOPS::_compute_mac's leaf
480 # sweep, which asks the encryption rules.
481 #
482 # What stays refused in an encrypted slot is a scalar that STATES a string
483 # half contradicting its number -- dualvar(+Inf, 'banana'), and the JSON
484 # literal of 400 zeros whose text is its digits (docs/adr/0020). The wire
485 # is derived from the number, so that text would be dropped without a
486 # trace, and choosing between a scalar's two halves is the guess
487 # docs/adr/0012 refuses to make.
488 #
489 # NARROWED AGAIN for k141 / docs/adr/0060, and this time by PUBLIC PV.
490 # All of the above is about a leaf WITH a public PV -- the case where the
491 # scalar already states a string half. A leaf WITHOUT one (a bare NV, like
492 # `9**9**9`) has only the number to say what it is, and docs/adr/0037's
493 # _non_finite_token_leaf manufactures the carrying dualvar for it in YAML:
494 # the carrier consults go-yaml's own twelve tokens and the YAML emitter
495 # writes the token the digest covers. JSON has no such carrier, and the
496 # refusal there is the emit walk's croak -- where the question of "can this
497 # format spell this number" actually belongs, not in assert_representable,
498 # which sees both formats the same.
499 #
500 # What stays refused in an unencrypted slot is the same shape that stayed
501 # refused in an encrypted slot: a public PV that contradicts its number.
502 # A caller who constructs dualvar(+Inf, 'banana') by hand -- no parse and
503 # no decryption produces one -- is told which half they meant.
504 10201 ▶ if (_sv_kind($value) eq 'float') {
Branch: 1 branch
BranchTrueFalseTotal
if (_sv_kind($value) eq "float") 6389 3812 10201
505 6389 my $form = _non_finite_bytes($value);
506  
507 croak "value is a non-finite float ($form) that also states a string "
508 . "half of its own, and an encrypted slot carries only one of "
509 . "them: the wire holds type:float and the plaintext $form, "
510 . "derived from the NUMBER, so the text beside it would be "
511 . "dropped without a trace. Which half you meant is yours to say "
512 . "and this library does not guess -- the same answer an integer "
513 . "whose two halves disagree gets. Pass the number on its own to "
514 . "store it as a float, which is what sops writes for the same "
515 . "value; or pass the text as a string (type:str), which is "
516 . "written verbatim and round-trips exactly through both."
517 6389 ▶ if $args{encrypted} && defined $form && _has_public_pv($value)
Branch: 1 branch
BranchTrueFalseTotal
if $args{"encrypted"} and defined $form and _has_public_pv($value) and not _carries_go_non_finite_token($value, $form) 19 6370 6389
Condition100%9/9
$args{"encrypted"} and defined $form and _has_public_pv($value) and not _carries_go_non_finite_token($value, $form)
!ll&&!rl&&r
63462419
$args{"encrypted"} and defined $form and _has_public_pv($value)
!ll&&!rl&&r
63044243
$args{"encrypted"} and defined $form
!ll&&!rl&&r
246605885
MC/DC100%4/4
$args{"encrypted"} and defined $form and _has_public_pv($value) and not _carries_go_non_finite_token($value, $form)
$args{"encrypted"} defined $form _has_public_pv($value) not _carries_go_non_finite_token($value, $form)
Truth table100%5/5
A and B and C and not(D)
A= $args{"encrypted"}B= defined $formC= _has_public_pv($value)D= not _carries_go_non_finite_token($value, $form)
ABCDresult
0XXX0
10XX0
110X0
11100
11111
518 && !_carries_go_non_finite_token($value, $form);
519  
520 croak "value is a non-finite float ($form) that also states a string "
521 . "half of its own, and an unencrypted slot can carry only one "
522 . "of them: the wire holds the token the emitter writes -- the "
523 . "public PV when it is one of go-yaml's twelve non-finite "
524 . "tokens, and a token the YAML carrier manufactures for a bare "
525 . "number. Yours is neither, so the text beside it would be "
526 . "dropped without a trace. Which half you meant is yours to say "
527 . "-- pass the number on its own to let the carrier write, or "
528 . "pass the text as a string (type:str), which is written verbatim "
529 . "and round-trips exactly through both."
530 6370 ▶ if !$args{encrypted} && defined $form && _has_public_pv($value)
Branch: 1 branch
BranchTrueFalseTotal
if not $args{"encrypted"} and defined $form and _has_public_pv($value) and not _carries_go_non_finite_token($value, $form) 75 6295 6370
Condition100%9/9
not $args{"encrypted"} and defined $form and _has_public_pv($value) and not _carries_go_non_finite_token($value, $form)
!ll&&!rl&&r
619410175
not $args{"encrypted"} and defined $form and _has_public_pv($value)
!ll&&!rl&&r
616529176
not $args{"encrypted"} and defined $form
!ll&&!rl&&r
612441205
MC/DC100%4/4
not $args{"encrypted"} and defined $form and _has_public_pv($value) and not _carries_go_non_finite_token($value, $form)
not $args{"encrypted"} defined $form _has_public_pv($value) not _carries_go_non_finite_token($value, $form)
Truth table100%5/5
not(A) and B and C and not(D)
A= not $args{"encrypted"}B= defined $formC= _has_public_pv($value)D= not _carries_go_non_finite_token($value, $form)
ABCDresult
0XXX0
10XX0
110X0
11100
11111
531 && !_carries_go_non_finite_token($value, $form);
532 }
533  
534 10107 ▶ return 1 unless _sv_kind($value) eq 'int';
Branch: 1 branch
BranchTrueFalseTotal
unless _sv_kind($value) eq "int" 8421 1686 10107
535  
536 # The same decimal value_to_bytes would write, tested by the same rule the
537 # decrypt side uses -- so what we refuse to write is exactly what we refuse
538 # to read.
539 1686 ▶ return 1 if _decimal_fits_int64('' . (0 + $value));
Branch: 1 branch
BranchTrueFalseTotal
if _decimal_fits_int64('' . (0 + $value)) 1670 16 1686
540  
541 # Only the POSITIVE window [2**63 .. 2**64-1] can reach this croak, and
542 # that is structural rather than lucky: SVf_IOK means the SV carries an IV
543 # or a UV, an IV bottoms out at exactly int64min and a UV cannot be
544 # negative, so no integer SV exists below the range. Measured for karr
545 # k104 -- 14 negative decimals bracketing int64min, uint64max and beyond,
546 # through 13 construction routes each (Perl literals, arithmetic,
547 # sprintf/int clamps, dualvar, a numerically-read PV, and the JSON and
548 # YAML parsers): 182 rows, 36 of them `int`, zero below int64min, zero
549 # croaks. Below the range a value arrives NOK or POK and takes the float
550 # rung instead (ADR 0020). This confirms the premise ADR 0021's decision
551 # rests on; the message below therefore never has to speak about a
552 # negative value.
553 #
554 # The two answers it offers were both measured against sops 3.13.3, 12
555 # literals across the window x 2 formats x 2 slots. The STRING answer:
556 # 48 of 48 `sops -d` exit 0, digits verbatim in every cell. The FLOAT
557 # answer: 41 of 48 exit 0 with sops's own normalisation, 7 refused HERE by
558 # ADR 0013's guard (all of them unencrypted YAML, where ADR 0011's repair
559 # has to write the canonical decimal bare and Go's resolver reads it as a
560 # uint64) -- and zero cells that put a file on disk sops rejects. That
561 # 7-of-48 is why the float is offered as an answer and not as a promise;
562 # note the split is NOT "canonical decimal past uint64max", which is only
563 # one of the two ways through.
564 #
565 # `unpack('d', pack('d', $value))` is named in the message because the
566 # obvious spellings do not work: measured, `$value + 0.0` and
567 # `$value * 1.0` on a UV come back IOK+IVisUV and land on this croak
568 # again, Perl having kept the integer.
569 16 croak
570 "value is an integer outside the range the SOPS int type can hold "
571 . "($INT64_MIN .. $INT64_MAX, Go's int64). Perl's integers are wider "
572 . "than Go's, and there is no SOPS wire form that preserves this one: "
573 . "written as type:int, sops refuses the file with "
574 . "\"strconv.Atoi: value out of range\"; written as type:float it would "
575 . "silently lose digits. Two answers, and which one you want is yours "
576 . "to say: pass it as a string to store the digits exactly -- type:str, "
577 . "written verbatim, in both formats and both slots -- or as a float, "
578 . "which is unpack('d', pack('d', \$value)) and not \$value + 0.0, to "
579 . "get what sops itself writes for these digits: type:float and the "
580 . "double's canonical decimal, at the cost of the digits the double "
581 . "cannot hold. That second answer is the one a bare JSON number in "
582 . "this range already takes, because Go's own decoder reads it as a "
583 . "float64. It is not unconditional: in an unencrypted YAML slot the "
584 . "float may be refused again, by the guard that keeps this library's "
585 . "digest and Go's YAML resolver agreeing.";
586 }
587  
588  
589 11721 ▶sub value_to_bytes {
Subroutine value_to_bytes: called CC=15 SCAR=27.1
Pod documented
590 11721 my ($class, $value, $type) = @_;
591 11721 ▶ return '' unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 14 11707 11721
592 11707 ▶ $type //= $class->detect_type($value);
Condition66%2/3
$type //= $class->detect_type($value)
l!l&&r!l&&!r
546962380
MC/DC0%0/2
$type //= $class->detect_type($value)
$type $class->detect_type($value)
Truth table66%2/3
A //= B
A= $typeB= $class->detect_type($value)
ABresult
1X1
011
000
593  
594 # A comment's wire plaintext is its text, verbatim and UTF-8 encoded --
595 # the same treatment a string gets, and for the same reason (docs/adr/0003:
596 # the flag is not consulted, here either). Measured against sops 3.13.3:
597 # the plaintext is everything after the `#`, leading space included, so
598 # nothing is trimmed on the way out. See docs/adr/0041.
599 11707 ▶ if (blessed($value) && $value->isa('File::SOPS::Comment')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($value) and $value->isa("File::SOPS::Comment")) 30 11677 11707
Condition100%3/3
builtin::blessed($value) and $value->isa("File::SOPS::Comment")
!ll&&!rl&&r
1148619130
MC/DC100%2/2
builtin::blessed($value) and $value->isa("File::SOPS::Comment")
builtin::blessed($value) $value->isa("File::SOPS::Comment")
Truth table100%3/3
A and B
A= builtin::blessed($value)B= $value->isa("File::SOPS::Comment")
ABresult
0X0
100
111
600 30 return _utf8_bytes($value->text);
601 }
602 # SOPS uses Titlecase for bools: "True" / "False"
603 11677 ▶ if (blessed($value) && $value->isa('JSON::PP::Boolean')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($value) and $value->isa("JSON::PP::Boolean")) 169 11508 11677
Condition100%3/3
builtin::blessed($value) and $value->isa("JSON::PP::Boolean")
!ll&&!rl&&r
1148622169
MC/DC100%2/2
builtin::blessed($value) and $value->isa("JSON::PP::Boolean")
builtin::blessed($value) $value->isa("JSON::PP::Boolean")
Truth table100%3/3
A and B
A= builtin::blessed($value)B= $value->isa("JSON::PP::Boolean")
ABresult
0X0
100
111
604 169 ▶ return $value ? 'True' : 'False';
Branch: 1 branch
BranchTrueFalseTotal
$value ? : 93 76 169
605 }
606 11508 ▶ if ($type eq 'bool') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "bool") 235 11273 11508
607 # Explicit rule, symmetric with _deserialize_value, for a caller who
608 # forced type => 'bool' on a plain scalar. The old test ended in
609 # "|| $value", a bare Perl truthiness fallback, so the non-empty
610 # string 'false' came out as 'True'.
611 235 ▶ return (lc("$value") eq 'true' || "$value" eq '1') ? 'True' : 'False';
Branch: 1 branch
BranchTrueFalseTotal
lc "$value" eq 'true' || "$value" eq '1' ? : 134 101 235
Condition100%3/3
lc "$value" eq "true" or "$value" eq 1
l!l&&r!l&&!r
5129101
MC/DC100%2/2
lc "$value" eq "true" or "$value" eq 1
lc "$value" eq "true" "$value" eq 1
Truth table100%3/3
A or B
A= lc "$value" eq "true"B= "$value" eq 1
ABresult
1X1
011
000
612 }
613  
614 # SOPS's binary type is not text, so there is nothing to encode. Mirrors
615 # _deserialize_value, which does not decode it either. This is also the
616 # only way a caller can say "these really are bytes" -- see the encoding
617 # note on _utf8_bytes.
618 11273 ▶ return "$value" if $type eq 'bytes';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "bytes" 4 11269 11273
619  
620 # Everything else is decided by what the scalar IS, not by the label:
621 # a number is written in the canonical form Go would re-derive from it,
622 # a string is written verbatim.
623 11269 ▶ my $kind = ref($value) ? 'str' : _sv_kind($value);
Branch: 1 branch
BranchTrueFalseTotal
ref $value ? : 22 11247 11269
624 11269 ▶ my $str
Branch: 2 branches
BranchTrueFalseTotal
$kind eq 'int' ? : 1766 9503 11269
$kind eq 'float' ? : 6848 2655 9503
625 = $kind eq 'int' ? '' . (0 + $value)
626 : $kind eq 'float' ? _float_bytes($value)
627 : "$value";
628  
629 11269 return _utf8_bytes($str);
630 }
631  
632  
633 900 ▶sub canonical_float_tree {
Subroutine canonical_float_tree: called CC=3 SCAR=11.2
Pod documented
634 900 my ($class, $tree, %args) = @_;
635 900 ▶ my $roundtrips = $args{roundtrips} // croak "roundtrips callback required";
Condition50%1/2
$args{"roundtrips"} // croak("roundtrips callback required")
l!l
9000
MC/DC0%0/1
$args{"roundtrips"} // croak("roundtrips callback required")
$args{"roundtrips"}
Truth table50%1/2
A
A= $args{"roundtrips"}
Aresult
11
00
636 900 ▶ my $carrier = $args{carrier} // croak "carrier callback required";
Condition50%1/2
$args{"carrier"} // croak("carrier callback required")
l!l
9000
MC/DC0%0/1
$args{"carrier"} // croak("carrier callback required")
$args{"carrier"}
Truth table50%1/2
A
A= $args{"carrier"}
Aresult
11
00
637 900 my $reject = $args{reject};
638 900 my $scalars = $args{reject_scalar};
639  
640 900 return _canonical_floats($tree, $roundtrips, $carrier, $reject, $scalars,
641 _document_carries_mac($tree), []);
642 }
643  
644 # Does the document about to be written carry a MAC a foreign reader will
645 # recompute from these bytes?
646 #
647 # Read off the tree, because that is the only place it is available here: a
648 # handler's serialize() puts the metadata under `sops` before it calls its
649 # emitter, and the plaintext emitters (decrypt_file, edit) hand over the tree
650 # without one. The YAML handler additionally says so by installing a
651 # reject_scalar (docs/adr/0013), but the JSON handler's emit is the IDENTICAL
652 # call on both paths, so for that one this is the only signal there is.
653 #
654 # The same fact docs/adr/0026's parse-side walk keys on, read from the same
655 # place. It cannot answer wrongly in the direction that matters: serialize
656 # always adds the key and refuses a tree that already has one, and a
657 # multi-document stream is refused one layer up, so the root is always the
658 # single document's hash. A caller who invokes a handler's emit() directly on a
659 # plaintext tree that happens to carry a top-level `sops` key gets a leaf
660 # refused that would have been written -- fail-closed, and the only reachable
661 # false answer. See docs/adr/0031.
662 900 ▶sub _document_carries_mac {
Subroutine _document_carries_mac: called CC=3 SCAR=11.1
663 900 my ($tree) = @_;
664 900 ▶ return ref $tree eq 'HASH' && exists $tree->{sops} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
ref $tree eq 'HASH' && exists $tree->{'sops'} ? : 629 271 900
Condition66%2/3
ref $tree eq "HASH" and exists $tree->{"sops"}
!ll&&!rl&&r
0271629
MC/DC50%1/2
ref $tree eq "HASH" and exists $tree->{"sops"}
ref $tree eq "HASH" exists $tree->{"sops"}
Truth table66%2/3
A and B
A= ref $tree eq "HASH"B= exists $tree->{"sops"}
ABresult
0X0
100
111
665 }
666  
667 # WHERE a rejected leaf sits, in the shape File::SOPS::_at_path already uses for
668 # the MAC walk's messages -- keys colon-joined, '(document root)' for the empty
669 # path. One copy of the convention, here, rather than one per reject callback:
670 # a caller who has to learn two notations for the same document is the reason
671 # k68 exists at all.
672 #
673 # Array INDICES are carried, where the MAC's own _sorted_leaves drops them --
674 # that omission is the AAD rule (SOPS gives every element of an array its
675 # parent's path), and this string is a diagnostic, never an AAD. `items:3:key`
676 # is the same shape _extract_path reports a navigation failure at.
677 7603 ▶sub _leaf_location {
Subroutine _leaf_location: called CC=3 SCAR=13.1
678 7603 my ($path) = @_;
679 7603 ▶ return ($path && @$path) ? join(':', @$path) : '(document root)';
Branch: 1 branch
BranchTrueFalseTotal
$path && @$path ? : 7603 0 7603
Condition33%1/3
$path and @$path
!ll&&!rl&&r
007603
MC/DC0%0/2
$path and @$path
$path @$path
Truth table33%1/3
A and B
A= $pathB= @$path
ABresult
0X0
100
111
680 }
681  
682 # The leaf as it will be WRITTEN, handed to the handler's foreign-resolution
683 # check on its way out. Every plain-scalar return path in _canonical_floats goes
684 # through here, so the check sees the carrier's replacement rather than the
685 # scalar the carrier replaced -- for a negative zero those two are `-0.0` and
686 # `-0`, and only the first is what a reader gets to resolve.
687 8490 ▶sub _written_leaf {
Subroutine _written_leaf: called CC=2 SCAR=6.9
688 8490 my ($leaf, $text, $reject_scalar, $path) = @_;
689 8490 ▶ $reject_scalar->($leaf, _leaf_location($path), $path, $text) if $reject_scalar;
Branch: 1 branch
BranchTrueFalseTotal
if $reject_scalar 7455 1035 8490
690 8443 return $leaf;
691 }
692  
693 # The one spelling per non-finite value that `sops -e` itself writes, keyed by
694 # the bytes value_to_bytes covers for it. The INVERSE of
695 # _go_non_finite_token_bytes, narrowed to three of its twelve rows: sops
696 # normalises `.Inf`, `+.INF` and the rest away, so these are the only ones a
697 # document sops wrote can hold, and the only ones worth manufacturing.
698 #
699 # Not a third statement of Go's resolveMap. Every token this table produces is
700 # handed straight back to _go_non_finite_token_bytes by the check below, so a
701 # row here that gate does not accept REFUSES the document rather than writing
702 # it -- the same fail-closed pairing docs/adr/0031 set up between that gate and
703 # %GO_CONSTANT, one layer in.
704 97 my %GO_NON_FINITE_TOKEN = ('+Inf' => '.inf', '-Inf' => '-.inf', 'NaN' => '.nan');
705  
706 # A non-finite float whose only form is its NUMBER, in the shape the emitter
707 # writing this document can put on the wire -- or a croak, where it has none.
708 #
709 # k134: an encrypted type:float decrypts to a bare Perl infinity, and
710 # YAML::XS writes one as `Inf` / `-Inf` / `NaN`, which go-yaml resolves as a
711 # STRING. So the plaintext decrypt_file and edit produce says a string where
712 # the document held a number, the editor hands that string back, and the leaf
713 # is re-encrypted as type:str -- silently, `sops -d` exit 0. Measured against
714 # sops 3.13.3, encrypted slot, three spellings: `sops -d` writes `.inf`,
715 # `-.inf` and `.nan`, and `sops edit` keeps the leaf a type:float. In JSON the
716 # same leaf reached the file as `null`, and edit replaced the whole ENC[...]
717 # with a bare unencrypted null -- where `sops -d --output-type json` and
718 # `sops edit` both refuse the document, exit 4.
719 #
720 # ASKED OF THE EMITTER, through the carrier -- the one hook whose job is
721 # already "the replacement, format-specific", and the only format signal that
722 # exists on this path. docs/adr/0031 read the same distinction off
723 # reject_scalar, which a plaintext emit installs in neither format, deliberately
724 # (docs/adr/0013). Measured, neither carrier needed changing: the YAML one
725 # returns dualvar($double, '.inf'), which YAML::XS writes as the bare token, and
726 # the JSON one croaks, because Math::BigFloat cannot reproduce a token it was
727 # never given.
728 #
729 # VERIFIED, not trusted, and with docs/adr/0031's own gate: the answer has to be
730 # an unreferenced scalar whose public string half is a token go-yaml resolves to
731 # these bytes AND whose number still renders as them. Both halves, so a carrier
732 # that returns something else -- or dies -- refuses the document instead of
733 # putting a wrong one on disk.
734 #
735 # NO VALUE IN THE MESSAGE. assert_representable's neighbouring refusal names the
736 # form (`+Inf`), because there the scalar came from the caller. This one is
737 # reached for a leaf that came out of an ENCRYPTED slot, and which of the three
738 # it is, is the plaintext.
739 40 ▶sub _non_finite_token_leaf {
Subroutine _non_finite_token_leaf: called CC=5 SCAR=16.1
740 40 my ($node, $text, $carrier, $path) = @_;
741  
742 40 my $leaf = eval { $carrier->($node, $GO_NON_FINITE_TOKEN{$text}) };
743  
744 40 ▶ return $leaf
Branch: 1 branch
BranchTrueFalseTotal
if defined $leaf and not ref $leaf and _carries_go_non_finite_token($leaf, $text) and __PACKAGE__->value_to_bytes($leaf) eq $text 23 17 40
Condition88%8/9
defined $leaf and not ref $leaf and _carries_go_non_finite_token($leaf, $text) and __PACKAGE__->value_to_bytes($leaf) eq $text
!ll&&!rl&&r
17023
defined $leaf and not ref $leaf and _carries_go_non_finite_token($leaf, $text)
!ll&&!rl&&r
15223
defined $leaf and not ref $leaf
!ll&&!rl&&r
14125
MC/DC75%3/4
defined $leaf and not ref $leaf and _carries_go_non_finite_token($leaf, $text) and __PACKAGE__->value_to_bytes($leaf) eq $text
defined $leaf not ref $leaf _carries_go_non_finite_token($leaf, $text) __PACKAGE__->value_to_bytes($leaf) eq $text
Truth table80%4/5
A and not(B) and C and D
A= defined $leafB= not ref $leafC= _carries_go_non_finite_token($leaf, $text)D= __PACKAGE__->value_to_bytes($leaf) eq $text
ABCDresult
0XXX0
10XX0
110X0
11100
11111
745 if defined $leaf && !ref $leaf
746 && _carries_go_non_finite_token($leaf, $text)
747 && __PACKAGE__->value_to_bytes($leaf) eq $text;
748  
749 17 croak _leaf_location($path) . ": cannot write a non-finite float to this "
750 . "SOPS document: the only form both implementations read back as the "
751 . "same number is a YAML plain scalar Go's yaml.v3 resolves to it "
752 . "(`.inf`, `-.inf`, `.nan`), and the emitter writing this document "
753 . "has none -- JSON has no spelling for one at all, so the leaf would "
754 . "reach the file as `null` or as a quoted string and stop being a "
755 . "number on the next read. sops refuses the same document rather "
756 . "than writing one (measured, `sops -d --output-type json` and "
757 . "`sops edit` are both exit 4). The value is still readable with "
758 . "decrypt or extract; to write it out, write the document as YAML, "
759 . "or store it as a string (type:str), which is written verbatim and "
760 . "round-trips exactly through both implementations";
761 }
762  
763 85161 ▶sub _canonical_floats {
Subroutine _canonical_floats: called CC=19 SCAR=29.4
764 97 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
765 85161 my ($node, $roundtrips, $carrier, $reject, $reject_scalar, $mac_covered,
766 $path) = @_;
767  
768 85161 ▶ if (ref $node eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node eq "HASH") 72780 12381 85161
769 return { map {
770 72780 push @$path, $_;
771 83570 my $result = _canonical_floats($node->{$_}, $roundtrips,
772 $carrier, $reject,
773 $reject_scalar, $mac_covered,
774 $path);
775 83436 pop @$path;
776 83436 $_ => $result;
777 } keys %$node };
778 }
779 12381 ▶ if (ref $node eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node eq "ARRAY") 3680 8701 12381
780 return [ map {
781 3680 push @$path, $_;
782 691 my $result = _canonical_floats($node->[$_], $roundtrips,
783 $carrier, $reject,
784 $reject_scalar, $mac_covered,
785 $path);
786 686 pop @$path;
787 686 $result;
788 } 0 .. $#$node ];
789 }
790  
791 # Blessed leaves (JSON::PP::Boolean) and anything else with a reference are
792 # not floats and must reach the emitter untouched -- unless the caller's
793 # emitter says it cannot write this one faithfully.
794 8701 ▶ if (ref $node) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node) 84 8617 8701
795 84 ▶ $reject->($node, _leaf_location($path)) if $reject;
Branch: 1 branch
BranchTrueFalseTotal
if $reject 84 0 84
796 75 return $node;
797 }
798 8617 ▶ return $node unless defined $node;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node 12 8605 8617
799  
800 # A boolean sentinel, before the kind ladder. It publishes IOK, so
801 # _sv_kind calls it an int and the guard below would ask the emitter about
802 # every boolean in every document -- an emit and a reparse per leaf, to
803 # arrive at "yes, it writes it faithfully". detect_type calls it a bool
804 # (k90), both emitters write a bare true/false, and that token is what
805 # the digest's True/False resolves from: nothing here to repair or refuse.
806 # No text is derived on the way past, for the same reason the string branch
807 # below derives none -- the handler's check has its own gate and its own
808 # call to the one conversion.
809 8605 ▶ return _written_leaf($node, undef, $reject_scalar, $path)
Branch: 1 branch
BranchTrueFalseTotal
if __PACKAGE__->detect_type($node) eq "bool" 34 8571 8605
810 if __PACKAGE__->detect_type($node) eq 'bool';
811  
812 8571 my $kind = _sv_kind($node);
813  
814 # k84: an INTEGER leaf that carries its own string form. detect_type
815 # calls it an int, so value_to_bytes derives the digest from the NUMBER,
816 # while both emitters write the STRING half -- YAML::XS bare,
817 # Cpanel::JSON::XS quoted whenever that half differs from its own rendering
818 # of the number. Measured against sops 3.13.3, leaf x_unencrypted:
819 #
820 # dualvar(5, 'five') digest 5 yaml: five json: "five" exit 51
821 # dualvar(0, 'zero') digest 0 yaml: zero json: "zero" exit 51
822 # YAML-parsed 007 digest 7 yaml: 007 (0) json: "007" exit 51 (json)
823 # YAML-parsed +7 / -0 digest 7/0 yaml: ok (0) json: quoted exit 51 (json)
824 #
825 # The float branch below cannot see any of it: it only runs for a leaf
826 # whose SV kind is float, and an int leaf reaches neither callback.
827 #
828 # ASKED OF THE EMITTER, not modelled. YAML::XS keeps the source text of
829 # every scalar it parses, so `007`, `+7`, `-0` and `1e3` all arrive here
830 # with a public PV that differs from the canonical decimal -- and YAML
831 # writes them back exactly as they came, where Go reads the same number the
832 # digest covers (measured, exit 0). Only the emitter can say which of those
833 # it survives, which is what $roundtrips already measures for floats.
834 #
835 # REFUSED rather than repaired, unlike the float leaf one line below (see
836 # docs/adr/0011 and 0012). Both halves of such a scalar are a candidate for
837 # what the caller meant, the two repairs write different documents, and
838 # nothing measurable separates a spelling (`007` for 7) from a
839 # contradiction (`five` for 5): dualvar(0, 'zero') numifies to the very
840 # number it would be compared against, and pattern-matching a value's text
841 # is what ADR 0002 removed. Nothing that worked stops working -- every
842 # input that croaks here produced a document that failed its own MAC.
843 #
844 # Two gates before the emitter is asked, and both are facts about the leaf
845 # rather than models of the emitter. It has to carry a PUBLIC PV at all --
846 # an int without one is rendered by both emitters from the number itself,
847 # which is what the digest covers -- and that PV has to DIFFER from the
848 # digest's text, which is the disagreement this guard is about. Every int
849 # in a YAML-parsed tree carries a PV (YAML::XS keeps the source text), so
850 # without the second gate every one of them would pay an emit-and-reparse:
851 # measured, 1000 such leaves cost 11ms -> 38ms in YAML and 2ms -> 10ms in
852 # JSON. With it, an ordinary `port: 5432` costs one string comparison.
853 8571 ▶ if ($kind eq 'int' && _has_public_pv($node)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "int" and _has_public_pv($node)) 60 8511 8571
Condition100%3/3
$kind eq "int" and _has_public_pv($node)
!ll&&!rl&&r
84624960
MC/DC100%2/2
$kind eq "int" and _has_public_pv($node)
$kind eq "int" _has_public_pv($node)
Truth table100%3/3
A and B
A= $kind eq "int"B= _has_public_pv($node)
ABresult
0X0
100
111
854 # THE one conversion again -- the text the digest covers, from the same
855 # method on the same scalar. The halves agreeing is the ordinary case
856 # and ends here, without asking the emitter anything.
857 60 my $text = __PACKAGE__->value_to_bytes($node);
858 60 ▶ return _written_leaf($node, $text, $reject_scalar, $path) if "$node" eq $text;
Branch: 1 branch
BranchTrueFalseTotal
if "$node" eq $text 14 46 60
859  
860 46 ▶ croak _leaf_location($path) . ": cannot write an integer leaf that "
Branch: 1 branch
BranchTrueFalseTotal
unless &$roundtrips($node, $text) 2 44 46
861 . "carries its own, different string form to a SOPS document: the "
862 . "MAC digest covers the NUMBER, while the emitter writes the "
863 . "string half -- YAML::XS bare, Cpanel::JSON::XS quoted -- so the "
864 . "document and its own MAC would state different things and "
865 . "neither sops nor this module could read the file back "
866 . "(measured, sops -d exit 51 in both formats). Perl produces such "
867 . "a scalar as a Scalar::Util::dualvar, or as a value a YAML "
868 . "parser kept the source spelling of. Which half is meant cannot "
869 . "be read off the scalar, so it is not guessed: pass 0 + \$value "
870 . "to store the number, or \"\$value\" to store the text"
871 unless $roundtrips->($node, $text);
872 44 return _written_leaf($node, $text, $reject_scalar, $path);
873 }
874  
875 # A string leaf, or an integer without a string form of its own: neither is
876 # rewritten here, and both still have to survive the reader on the other side
877 # of the file. No text is derived for them on the way past -- value_to_bytes
878 # encodes, and a handler with a cheap gate of its own should not pay a
879 # conversion for every leaf it waves through.
880 8511 ▶ return _written_leaf($node, undef, $reject_scalar, $path) unless $kind eq 'float';
Branch: 1 branch
BranchTrueFalseTotal
unless $kind eq "float" 8307 204 8511
881  
882 # THE one conversion. This is the same method, on the same scalar, that the
883 # MAC digest goes through -- not a second rendering that happens to agree
884 # today. Do not inline a copy of it here.
885 204 my $text = __PACKAGE__->value_to_bytes($node);
886  
887 # NaN and the infinities. The leaf is never REWRITTEN here -- neither the
888 # round-trip test nor the carrier can help it, and k113 measured what
889 # happens if they are asked: YAML::XS writes the token and libyaml reads it
890 # back as a STRING, so $roundtrips answers no for a leaf that is perfectly
891 # writable, and the carrier then replaces the document's own `.inf` with a
892 # bare `+Inf` -- `sops -d` exit 0 and the leaf silently retyped to a string,
893 # in both formats. A local reparse cannot answer a question about a foreign
894 # resolver (docs/adr/0013). What changes is only who gets to CHECK it.
895 #
896 # A leaf whose string half is a token go-yaml resolves back to this same
897 # double goes to the handler's foreign-resolution guard, which is the single
898 # copy of Go's resolution model (docs/adr/0013 and 0017) and compares the
899 # token the emitter really writes. A MAC-covered document whose handler
900 # installs no such guard has nothing that can vouch for the leaf, and it is
901 # refused rather than written: that is JSON, where a non-finite float has no
902 # spelling at all (measured, unencrypted slot, all twelve tokens, `sops -d`
903 # exit 51).
904 #
905 # A leaf with NO string half of its own -- the shape a decrypted type:float
906 # arrives in -- has stated no spelling, so one is asked of the emitter and
907 # it enters that same verdict carrying it. This used to `return $node`, and
908 # the plaintext then said `Inf` where the document held a number
909 # (k134, docs/adr/0037). It is the ONLY leaf this manufactures a token
910 # for: one that publishes a string half has stated one, and it is left
911 # alone whatever it says, so `dualvar(+Inf, 'banana')` is not overwritten on
912 # the strength of the number beside it (docs/adr/0012's answer to the same
913 # question for an integer, and docs/adr/0031's `banana` row).
914 #
915 # Nothing a caller can construct becomes writable to a MAC-covered document
916 # that was not writable before: assert_representable runs first, from
917 # _compute_mac's leaf sweep, and its gate is untouched. A bare NV cannot
918 # reach this walk on the encrypt path at all.
919 204 ▶ if ($text =~ $NO_AGREED_FORM) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /$NO_AGREED_FORM/) 129 75 204
920 # k140: refuse the contradiction the MAC-covered paths already
921 # refuse -- a non-finite float whose public PV disagrees with its
922 # number. The MAC-covered paths caught it through assert_representable
923 # in _compute_mac's leaf sweep, and the mac_covered croak below
924 # refuses the JSON case where the handler has no spelling for a
925 # non-finite value at all. Only the plaintext emit path silently
926 # wrote the string half verbatim, the leaf retyped to str on a later
927 # parse, and a decrypt_file -> encrypt_file round trip changed the
928 # type without warning.
929 #
930 # The predicate is the same one assert_representable uses
931 # (encrypted => 0 already gates on !_carries_go_non_finite_token, see
932 # the k59 message above for the wire-form reasoning). Consulting
933 # it here keeps the rule in one place -- the gate does not drift if
934 # the wire format changes -- and reaches every caller of the walk:
935 # decrypt_file, edit, _serialize_plaintext, and a direct emit() call
936 # on a tree the caller constructed.
937 #
938 # Bare NV leaves are not in scope: _non_finite_token_leaf below
939 # manufactures a token PV for them in YAML and croaks in JSON, which
940 # is the existing k113 / k134 behaviour. Without that
941 # filter here, assert_representable would refuse the bare-NV case
942 # that k134 / ADR 0037 made writable.
943 129 ▶ if (_has_public_pv($node)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_has_public_pv($node)) 89 40 129
944 89 ▶ eval { __PACKAGE__->assert_representable($node, encrypted => 0); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { __PACKAGE__->assert_representable($node, "encrypted", 0); 1 } } or croak(_leaf_location($path) . ': ' . $@ =~ s/\s+at\s+\S+\s+line\s+\d+\.?\s*\z//r) 59 30 89
945 or croak _leaf_location($path) . ": "
946 . ($@ =~ s/\s+at\s+\S+\s+line\s+\d+\.?\s*\z//r);
947 }
948  
949 99 ▶ $node = _non_finite_token_leaf($node, $text, $carrier, $path)
Branch: 1 branch
BranchTrueFalseTotal
unless _has_public_pv($node) 40 59 99
950 unless _has_public_pv($node);
951 82 ▶ return _written_leaf($node, $text, $reject_scalar, $path)
Branch: 1 branch
BranchTrueFalseTotal
if $reject_scalar 16 66 82
952 if $reject_scalar;
953 66 ▶ return $node unless $mac_covered;
Branch: 1 branch
BranchTrueFalseTotal
unless $mac_covered 51 15 66
954  
955 15 croak _leaf_location($path) . ": cannot write a non-finite float to "
956 . "this SOPS document: the only wire form for one that both "
957 . "implementations read back as the same number is a YAML plain "
958 . "scalar Go's yaml.v3 resolves to it (`.inf`, `-.inf`, `.nan` and "
959 . "their case variants), and the handler writing this document has "
960 . "no such form -- JSON has none, so the document would state a "
961 . "quoted string where its own MAC covers the number, and neither "
962 . "sops nor this module could read the file back (measured, sops "
963 . "-d exit 51). Store the value as a string (type:str), which is "
964 . "written verbatim and round-trips exactly through both "
965 . "implementations, or write the document as YAML";
966 }
967  
968 # The emitter's own output already comes back as this number: leave the
969 # scalar alone, so the document keeps the bytes it has always had.
970 75 ▶ return _written_leaf($node, $text, $reject_scalar, $path) if $roundtrips->($node, $text);
Branch: 1 branch
BranchTrueFalseTotal
if &$roundtrips($node, $text) 58 17 75
971  
972 # The CARRIER is what gets written, and $text is what the digest covers --
973 # for a negative zero those are `-0.0` and `-0`, and the check needs both.
974 17 return _written_leaf($carrier->($node, $text), $text, $reject_scalar, $path);
975 }
976  
977  
978 23 ▶sub canonical_float_dualvar {
Subroutine canonical_float_dualvar: called CC=5 SCAR=16.1
Pod documented
979 23 my ($class, $value) = @_;
980  
981 23 ▶ return $value unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 23 23
982 23 ▶ return $value if ref $value;
Branch: 1 branch
BranchTrueFalseTotal
if ref $value 2 21 23
983 21 ▶ return $value unless _sv_kind($value) eq 'float';
Branch: 1 branch
BranchTrueFalseTotal
unless _sv_kind($value) eq "float" 18 3 21
984  
985 # THE one conversion, again. The string half is the text the wire carries
986 # and the digest covers, taken from the same method on the same scalar --
987 # never a second rendering that agrees with it today.
988 3 my $text = $class->value_to_bytes($value, 'float');
989 3 ▶ return $value if $text =~ $NO_AGREED_FORM;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /$NO_AGREED_FORM/ 1 2 3
990  
991 2 return dualvar($value, $text);
992 }
993  
994  
995 # Which of Perl's three scalar shapes this is, read off the SV rather than off
996 # its text. The PUBLIC IOK/NOK flags deliberately, not the private pIOK/pNOK
997 # that JSON::PP's number heuristic uses: the private ones are set by merely
998 # READING a string numerically, which would make a caller's `$h{port} > 1024`
999 # rewrite the document's type fields. The public ones are set less often, but
1000 # not never -- see the contamination note in detect_type's POD.
1001 #
1002 # Nothing on the encrypt path numifies a leaf before this runs. The one thing
1003 # that touches it is _encrypt_tree's `$node eq ''`, which is a string
1004 # comparison: it can set pPOK on a number, never IOK or NOK on a string.
1005 #
1006 # \$_[0] aliases the caller's scalar instead of copying it. Copying preserves
1007 # the flags too, but the alias makes that independent of how Perl chooses to
1008 # implement assignment.
1009 #
1010 # The one place the public IOK is not taken at face value: Perl caches an IV on
1011 # an NV whenever `(NV)(IV)nv == nv`, and for a NEGATIVE ZERO that test passes
1012 # while the sign does not survive the cast -- the IV 0 is a different value from
1013 # the NV -0.0, and the wire has a spelling for each. So a scalar publishing both
1014 # halves is asked which half is the value, not which flag came first. This is
1015 # still the SV deciding (ADR 0002): the NV is read only where it is already
1016 # public, never derived from the text and never numified into existence.
1017 #
1018 # YAML::XS is where such a scalar comes from in practice -- it caches the IV for
1019 # an integral float in EXPONENT notation, so `-0.0e0` arrives IOK+NOK where
1020 # `-0.0` arrives NOK alone. k89, docs/adr/0015.
1021 97 my $NEGATIVE_ZERO_BITS = pack('d', -0.0);
1022  
1023 69228 ▶sub _sv_kind {
Subroutine _sv_kind: called CC=5 SCAR=16.2
1024 69228 my $sv = B::svref_2object(\$_[0]);
1025 69228 my $flags = $sv->FLAGS;
1026 69228 ▶ if ($flags & B::SVf_IOK()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flags & 256) 7200 62028 69228
1027 7200 ▶ return 'float'
Branch: 1 branch
BranchTrueFalseTotal
if $flags & 512 and pack("d", $sv->NV) eq $NEGATIVE_ZERO_BITS 0 7200 7200
Condition66%2/3
$flags & 512 and pack("d", $sv->NV) eq $NEGATIVE_ZERO_BITS
!ll&&!rl&&r
67674330
MC/DC0%0/2
$flags & 512 and pack("d", $sv->NV) eq $NEGATIVE_ZERO_BITS
$flags & 512 pack("d", $sv->NV) eq $NEGATIVE_ZERO_BITS
Truth table66%2/3
A and B
A= $flags & 512B= pack("d", $sv->NV) eq $NEGATIVE_ZERO_BITS
ABresult
0X0
100
111
1028 if ($flags & B::SVf_NOK())
1029 && pack('d', $sv->NV) eq $NEGATIVE_ZERO_BITS;
1030 7200 return 'int';
1031 }
1032 62028 ▶ return 'float' if $flags & B::SVf_NOK();
Branch: 1 branch
BranchTrueFalseTotal
if $flags & 512 27075 34953 62028
1033 34953 return 'str';
1034 }
1035  
1036 # Does this scalar carry a string form of its OWN, on top of its number? The
1037 # public SVf_POK again, for the same reason _sv_kind reads the public IOK/NOK:
1038 # merely stringifying a number sets the private pPOK (measured: `my $s = "$i"`,
1039 # `$i eq ''` and `length($i)` all leave SVf_POK clear), and a guard that read
1040 # the private flag would fire on a caller who logged the value.
1041 871 ▶sub _has_public_pv {
Subroutine _has_public_pv: called CC=2 SCAR=6.9
1042 871 my $flags = B::svref_2object(\$_[0])->FLAGS;
1043 871 ▶ return $flags & B::SVf_POK() ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$flags & 1024 ? : 670 201 871
1044 }
1045  
1046 # strconv.FormatFloat(v, 'f', -1, 64).
1047 #
1048 # 'f' means positional notation, never an exponent. -1 means the shortest
1049 # digit string that parses back to the same float64. Perl's own
1050 # stringification is neither: it is roughly %.15g, so it exponentiates 1e20
1051 # and truncates 0.1+0.2 to 0.3, and both of those disagree with what the Go
1052 # side re-derives when it recomputes the MAC.
1053 #
1054 # The shortest-form test is `0 + "$g"` and NOT the obvious `$g + 0`, which
1055 # numifies $g IN PLACE: the digits then left the loop carrying the double as
1056 # well, so value_to_bytes returned a scalar detect_type called a float -- and
1057 # for a negative zero an INT, since the text `-0` numifies to an IV. Text in,
1058 # a number back out, from the one method whose whole job is to say what the
1059 # wire carries. k72 and k73 are the same mechanism on the input side;
1060 # this is k80 on the output side. Stringifying first numifies a COPY and
1061 # leaves the digits a string, which is what they are.
1062 6848 ▶sub _float_bytes {
Subroutine _float_bytes: called CC=4 SCAR=13.9
1063 6848 my ($n) = @_;
1064  
1065 # NaN and the infinities, from the one sub that decides what they are --
1066 # the same answer assert_representable and the emit walk ask for.
1067 6848 my $non_finite = _non_finite_bytes($n);
1068 6848 ▶ return $non_finite if defined $non_finite;
Branch: 1 branch
BranchTrueFalseTotal
if defined $non_finite 440 6408 6848
1069  
1070 6408 my $g;
1071 6408 for my $precision (1 .. 17) { # 17 always round-trips a double
1072 12172 $g = sprintf('%.*g', $precision, $n);
1073 12172 ▶ last if 0 + "$g" == $n;
Branch: 1 branch
BranchTrueFalseTotal
if 0 + "$g" == $n 6408 5764 12172
1074 }
1075  
1076 6408 return _expand_exponent($g);
1077 }
1078  
1079 # "1.5e-07" -> "0.00000015", "1e+20" -> "100000000000000000000".
1080 6408 ▶sub _expand_exponent {
Subroutine _expand_exponent: called CC=5 SCAR=16.2
1081 6408 my ($s) = @_;
1082 6408 ▶ return $s unless $s =~ /\A([+-]?)(\d+)(?:\.(\d+))?[eE]([+-]?\d+)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $s =~ /\A([+-]?)(\d+)(?:\.(\d+))?[eE]([+-]?\d+)\z/ 302 6106 6408
1083  
1084 6106 ▶ my ($sign, $int, $frac, $exp) = ($1, $2, $3 // '', $4 + 0);
Condition100%2/2
$3 // ""
l!l
29143192
MC/DC100%1/1
$3 // ""
$3
Truth table100%2/2
A
A= $3
Aresult
11
00
1085 6106 my $digits = $int . $frac;
1086 6106 my $point = length($int) + $exp; # where the decimal point lands in $digits
1087  
1088 6106 ▶ return $sign . '0.' . ('0' x -$point) . $digits if $point <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $point <= 0 968 5138 6106
1089 5138 ▶ return $sign . $digits . ('0' x ($point - length $digits))
Branch: 1 branch
BranchTrueFalseTotal
if $point >= length $digits 5138 0 5138
1090 if $point >= length $digits;
1091 0 return $sign . substr($digits, 0, $point) . '.' . substr($digits, $point);
1092 }
1093  
1094 # The plaintext's crossing from characters into bytes. CryptX takes bytes, so a
1095 # character string arriving at the cipher is either downgraded to Latin-1
1096 # (U+0080..U+00FF) or dies outright with "Wide character in subroutine entry"
1097 # (above U+00FF).
1098 #
1099 # UNCONDITIONAL, by the same argument as _aad_bytes below: for a string whose
1100 # characters are all under U+0100 Perl's UTF-8 flag is storage, not meaning,
1101 # and neither emitter consults it -- YAML::XS::Dump and Format::JSON's encoder
1102 # (utf8) write "caf\x{e9}" as caf\xc3\xa9 whichever way Perl is holding it.
1103 # Under the old flag-guarded rule an unflagged "caf\x{e9}" reached the wire as
1104 # caf\xe9, which is not UTF-8 at all, with two measured consequences: an
1105 # UNENCRYPTED value went into the document as UTF-8 and into the digest as
1106 # Latin-1, so the file failed its own MAC and sops reported "MAC mismatch";
1107 # and an encrypted one was self-consistent but came back out of `sops -d` as
1108 # `!!binary Y2Fm6Q==` rather than as café. See ADR 0003.
1109 #
1110 # The cost is a caller who passes UTF-8 BYTES rather than characters: their
1111 # plaintext is now double-encoded, because Perl cannot tell that scalar apart
1112 # from an unflagged Latin-1 string and the ambiguity has to be resolved the
1113 # same way everywhere. Note the emitters were already double-encoding such a
1114 # caller's unencrypted values, so this was never a whole guarantee. A caller
1115 # who really means bytes says so with type => 'bytes', which skips this
1116 # entirely (see value_to_bytes).
1117 11299 ▶sub _utf8_bytes {
Subroutine _utf8_bytes: called CC=2 SCAR=7.0
1118 11299 my ($str) = @_;
1119 11299 ▶ return $str unless defined $str;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str 0 11299 11299
1120 11299 utf8::encode($str); # no-op for ASCII, correct for the rest
1121 11299 return $str;
1122 }
1123  
1124 # The AAD's crossing, which has always been unconditional and is where the rule
1125 # above came from.
1126 #
1127 # The AAD is derived from the document's key path, and the key it names is
1128 # written to the file by YAML::XS::Dump / Format::JSON's encoder (utf8). Both of
1129 # those encode a key to UTF-8 whether or not it carries Perl's UTF-8 flag,
1130 # because for a string whose characters are all below U+0100 that flag is an
1131 # internal storage detail and not a statement about the string's meaning. So
1132 # "caf\x{e9}" is written to the file as the five bytes caf\xc3\xa9 no matter how
1133 # Perl happens to be holding it, and the AAD has to say the same thing.
1134 #
1135 # Under a flag-guarded rule it did not: an unflagged "caf\x{e9}" authenticated
1136 # against caf\xe9: while the emitter wrote caf\xc3\xa9, so the very next read of
1137 # our own file re-derived the UTF-8 form and the document failed its own MAC.
1138 # Matching the emitter is what makes the AAD single-valued for a given
1139 # document, and it is also what Go does, where a map key is UTF-8 by
1140 # construction. The value conversion above now says the same thing about the
1141 # same scalar; a document cannot hold two answers to that question.
1142 14145 ▶sub _aad_bytes {
Subroutine _aad_bytes: called CC=2 SCAR=6.9
1143 14145 my ($aad) = @_;
1144 14145 ▶ return '' unless defined $aad;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $aad 16 14129 14145
1145 14129 utf8::encode($aad); # unconditional: no-op for ASCII, correct for the rest
1146 14129 return $aad;
1147 }
1148  
1149 4110 ▶sub _deserialize_value {
Subroutine _deserialize_value: called CC=17 SCAR=28.4
1150 4110 my ($data, $type) = @_;
1151  
1152 # SOPS's binary type. Not text, so there is nothing to decode -- see the
1153 # boundary note in the decrypt_value POD.
1154 4110 ▶ return $data if $type eq 'bytes';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "bytes" 2 4108 4110
1155  
1156 # Go reads this back with strconv.Atoi, so int64 is the whole range, and
1157 # anything outside it stops sops with "value out of range". int() would
1158 # instead route it through a double and hand back a DIFFERENT number
1159 # without saying so -- the silent half of the same defect. Refuse, and
1160 # leave decrypt_bytes as the way to recover the digits.
1161 4108 ▶ if ($type eq 'int') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "int") 401 3707 4108
1162 401 ▶ croak "type:int plaintext is not an integer"
Branch: 1 branch
BranchTrueFalseTotal
unless $data =~ /\A[+-]?[0-9]+\z/ 0 401 401
1163 unless $data =~ /\A[+-]?[0-9]+\z/;
1164 401 ▶ croak "type:int plaintext is outside the int64 range "
Branch: 1 branch
BranchTrueFalseTotal
unless _decimal_fits_int64($data) 3 398 401
1165 . "($INT64_MIN .. $INT64_MAX); sops refuses such a value too "
1166 . "(\"strconv.Atoi: value out of range\"). "
1167 . "Use decrypt_bytes to recover the plaintext."
1168 unless _decimal_fits_int64($data);
1169 398 return 0 + $data;
1170 }
1171 # Go reads this back with strconv.ParseFloat, which fails on anything that
1172 # is not a number. Perl's numeric conversion turns it into 0 and says
1173 # nothing.
1174 3707 ▶ if ($type eq 'float') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "float") 3028 679 3707
1175 3028 ▶ croak "type:float plaintext is not a number"
Branch: 1 branch
BranchTrueFalseTotal
unless $data =~ /\A[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+) (?:[eE][+-]?[0-9]+)?\z/x or $data =~ /\A[+-]?(?:Inf(?:inity)?|NaN)\z/i 0 3028 3028
Condition66%2/3
$data =~ /\A[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+) (?:[eE][+-]?[0-9]+)?\z/x or $data =~ /\A[+-]?(?:Inf(?:inity)?|NaN)\z/i
l!l&&r!l&&!r
3017110
MC/DC0%0/2
$data =~ /\A[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+) (?:[eE][+-]?[0-9]+)?\z/x or $data =~ /\A[+-]?(?:Inf(?:inity)?|NaN)\z/i
$data =~ /\A[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+) (?:[eE][+-]?[0-9]+)?\z/x $data =~ /\A[+-]?(?:Inf(?:inity)?|NaN)\z/i
Truth table66%2/3
A or B
A= $data =~ /\A[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+) (?:[eE][+-]?[0-9]+)?\z/xB= $data =~ /\A[+-]?(?:Inf(?:inity)?|NaN)\z/i
ABresult
1X1
011
000
1176 unless $data =~ /\A[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)
1177 (?:[eE][+-]?[0-9]+)?\z/x
1178 || $data =~ /\A[+-]?(?:Inf(?:inity)?|NaN)\z/i;
1179  
1180 # NOT `$data + 0.0`. That addition hands back a scalar carrying the
1181 # PUBLIC SVf_IOK flag whenever the result is integral -- grok_number
1182 # settles a text like `2` as an integer and pp_add calls SvIV_please --
1183 # so detect_type called the value an int and the next write relabelled
1184 # a leaf the document itself had marked type:float. Measured on a
1185 # document sops wrote: three of five type:float leaves came back
1186 # type:int after our rotate, exit 0 both times, silently (k73).
1187 #
1188 # pack 'd' lays the scalar's numeric value out as a native double and
1189 # unpack builds a fresh SV from those bytes with sv_setnv, so the
1190 # result is NOK and nothing else. It is also float64 whatever this
1191 # Perl's NV is, which is the width Go's strconv.ParseFloat works in.
1192 # No arithmetic form does this: `0.0 + $data` and `$data * 1.0` set IOK
1193 # too, and a dualvar INHERITS it from its numeric argument. See ADR
1194 # 0009.
1195 3028 my $number = unpack('d', pack('d', $data));
1196  
1197 # strconv.ParseFloat("-0", 64) is NEGATIVE zero in Go. The conversion
1198 # above still is not: grok_number settles the text -0 as an INTEGER
1199 # zero, which has no sign to keep, so pack sees a plain 0 and measured
1200 # hands back a POSITIVE zero -- exactly as `+ 0.0` did before it, which
1201 # additionally lost the sign a second time to IEEE round-to-nearest
1202 # (-0.0 + 0.0 is +0.0). So the sign has to come back from the
1203 # plaintext, which is the only place it survived.
1204 #
1205 # The MAC does not catch this -- the digest covers decrypt_bytes, the
1206 # plaintext "-0", not what this returns -- so every document involved
1207 # verified while our own rotate turned a sops-written `negzero: -0`
1208 # into `negzero: 0`, exit 0, both formats (k72).
1209 #
1210 # Reading a value's TEXT is what ADR 0002 forbids; this is not that.
1211 # The type is not being guessed here, it came from the type: label on
1212 # the wire, and $data is authenticated plaintext this module just
1213 # decrypted, not a caller's scalar. The condition is "negative sign,
1214 # and the conversion produced a zero", so a negative underflow such as
1215 # -1e-400 lands on -0 too, which is what Go parses it to.
1216 3028 ▶ if ($data =~ /\A-/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data =~ /\A-/) 483 2545 3028
1217 # The zero test runs on a THROWAWAY copy, and that is load-bearing.
1218 # Perl's == calls SvIV_please on an NV whose value is integral and
1219 # sets the PUBLIC IOK flag in place, so comparing $number itself
1220 # retypes it: measured, a type:float plaintext of 0.0 came back as
1221 # a value detect_type calls int, and the next write relabelled the
1222 # leaf type:int. ADR 0002, from the other side.
1223 483 my $is_zero = $number;
1224 483 ▶ return -0.0 if $is_zero == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $is_zero == 0 1 482 483
1225 }
1226  
1227 3027 return $number;
1228 }
1229  
1230 679 ▶ if ($type eq 'bool') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "bool") 74 605 679
1231 # SOPS uses "True"/"False" (titlecase)
1232 # Return JSON::PP::Boolean to preserve bool type through YAML/JSON serialization
1233 74 ▶ return (lc($data) eq 'true' || $data eq '1') ? JSON->true : JSON->false;
Branch: 1 branch
BranchTrueFalseTotal
lc $data eq 'true' || $data eq '1' ? : 38 36 74
Condition66%2/3
lc $data eq "true" or $data eq 1
l!l&&r!l&&!r
38036
MC/DC50%1/2
lc $data eq "true" or $data eq 1
lc $data eq "true" $data eq 1
Truth table66%2/3
A or B
A= lc $data eq "true"B= $data eq 1
ABresult
1X1
011
000
1234 }
1235  
1236 # str, time and comment are all text on the wire, and all come back as the
1237 # text they are.
1238 #
1239 # time -- Go stores a time.Time as RFC3339, which is what the
1240 # plaintext holds. Measured against sops 3.13.3: a bare
1241 # `2026-08-09T12:00:00Z` and a bare `2026-08-09` both become
1242 # type:time, the latter as `2026-08-09T00:00:00Z`. Perl has no
1243 # native date, and handing back a DateTime would make this
1244 # module a data-model library, so the RFC3339 string is the
1245 # value. It is also what the YAML and JSON parsers give the
1246 # caller for the same scalar when it is NOT encrypted, so the
1247 # document reads consistently either way.
1248 # comment -- a YAML comment. sops attaches a comment to the node that
1249 # FOLLOWS it, so where that node is a MAPPING entry the comment
1250 # stays a `#ENC[...]` line, which YAML::XS drops before this
1251 # module sees it. Where it is a SEQUENCE entry there is no
1252 # comment line to write and sops emits the comment as a real
1253 # sequence element, `- ENC[...,type:comment]` -- so File::SOPS
1254 # very much does meet one through a document, and read it as an
1255 # ordinary value until k108. It comes back as a
1256 # File::SOPS::Comment and NOT as the text, which is the whole
1257 # of how a comment is kept apart from a value: an object
1258 # nothing here compares equal to a string, the same move
1259 # type:bool makes with JSON::PP::Boolean. k76,
1260 # docs/adr/0041, which supersedes docs/adr/0024's refusal.
1261 #
1262 # utf8::decode leaves the scalar alone and returns false if the plaintext
1263 # is not valid UTF-8, which is the graceful direction -- such a value comes
1264 # back as the bytes it was.
1265 605 ▶ if ($type eq 'str' || $type eq 'time' || $type eq 'comment') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "str" or $type eq "time" or $type eq "comment") 604 1 605
Condition100%6/6
$type eq "str" or $type eq "time" or $type eq "comment"
l!l&&r!l&&!r
583211
$type eq "str" or $type eq "time"
l!l&&r!l&&!r
582122
MC/DC100%3/3
$type eq "str" or $type eq "time" or $type eq "comment"
$type eq "str" $type eq "time" $type eq "comment"
Truth table100%4/4
A or B or C
A= $type eq "str"B= $type eq "time"C= $type eq "comment"
ABCresult
1XX1
01X1
0011
0000
1266 604 utf8::decode($data);
1267 604 ▶ return $type eq 'comment'
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'comment' ? : 21 583 604
1268 ? File::SOPS::Comment->new(text => $data)
1269 : $data;
1270 }
1271  
1272 # Everything else used to fall through to the branch above and return the
1273 # raw string, so a document this library could not actually interpret
1274 # looked like it had been read. Go stops here, and so do we.
1275 1 croak "Unknown datatype: $type";
1276 }
1277  
1278 16173 ▶sub _encode_base64_oneline {
Subroutine _encode_base64_oneline: called CC=1 SCAR=0.0
1279 16173 my ($data) = @_;
1280 16173 my $encoded = encode_base64($data, '');
1281 16173 return $encoded;
1282 }
1283  
1284 # The only source of random bytes in this distribution. Both things that must
1285 # never repeat come from here: the per-value GCM nonce above, and the data key
1286 # in File::SOPS::encrypt, which calls this directly. It lived in both files
1287 # once, byte-identical; nothing made them stay that way.
1288 #
1289 # The length check is not defensive noise, and it is the reason this is a sub
1290 # at all rather than a bare call. A short return is invisible to everything
1291 # downstream of it -- measured here against CryptX 0.087 and sops 3.13.3:
1292 #
1293 # * A data key truncated to 16 or 24 bytes is a valid AES-128 or AES-192
1294 # key. Encryption succeeds, our own decrypt succeeds, and `sops -d`
1295 # accepts the document and exits 0. The key is silently weaker than the
1296 # one every part of the system believes it is using, and no error exists
1297 # anywhere to say so.
1298 # * An IV truncated to anything from 1 to 31 bytes is accepted by GCM
1299 # identically at both ends, because the nonce length is not fixed by the
1300 # construction. A 1-byte nonce also round-trips through `sops -d` with
1301 # exit 0 -- from an 8-bit space, so it repeats under the same data key
1302 # within a couple of hundred values, which is the one thing GCM does not
1303 # survive.
1304 #
1305 # Only two short lengths fail on their own: a data key that is not 16, 24 or
1306 # 32 bytes, and an IV of exactly 0 bytes. Both fail inside CryptX as "FATAL:
1307 # ccm_memory failed: Invalid key size" attributed to the gcm call, naming
1308 # neither the CSPRNG nor which of the two values was short. Nothing else in
1309 # either implementation looks at these lengths, so this is the only place that
1310 # can look at them.
1311 #
1312 # Crypt::PRNG is not optional and there is no fallback: it ships in CryptX,
1313 # the same distribution as the Crypt::AuthEnc::GCM this module already loads at
1314 # compile time, so an install missing it cannot compile this file. The
1315 # /dev/urandom branch that used to stand here was unreachable, and if it had
1316 # ever been reached it would have downgraded a seeded CSPRNG to an unchecked
1317 # read without telling anyone.
1318 6148 ▶sub _random_bytes {
Subroutine _random_bytes: called CC=4 SCAR=13.9
1319 6148 my ($length) = @_;
1320  
1321 6148 my $bytes = Crypt::PRNG::random_bytes($length);
1322  
1323 # Lengths only. The bytes themselves are the data key or the nonce, and an
1324 # error message is something a user pastes into a bug report.
1325 6148 ▶ croak "Refusing to use the result: Crypt::PRNG::random_bytes($length) "
Branch: 2 branches
BranchTrueFalseTotal
unless defined $bytes and length $bytes == $length 14 6134 6148
defined $bytes ? : 13 1 14
Condition100%3/3
defined $bytes and length $bytes == $length
!ll&&!rl&&r
1136134
MC/DC100%2/2
defined $bytes and length $bytes == $length
defined $bytes length $bytes == $length
Truth table100%3/3
A and B
A= defined $bytesB= length $bytes == $length
ABresult
0X0
100
111
1326 . "returned "
1327 . (defined $bytes ? length($bytes) . " bytes" : "undef")
1328 . ". A wrong length here becomes a data key or a GCM nonce of that "
1329 . "length, which neither this implementation nor sops rejects."
1330 unless defined $bytes && length($bytes) == $length;
1331  
1332 6134 return $bytes;
1333 }
1334  
1335  
1336 97 1;
1337  
1338 __END__
« blib/lib/File/SOPS/Metadata/Flat.pm ↑ Summary blib/lib/File/SOPS/Backend/Age.pm »