blib/lib/File/SOPS/Format/JSON.pm

filter: Statementstmt 96.1% 100 / 104 Branchbran 75.0% 42 / 56 Conditioncond 68.7% 11 / 16 MC/DCmcdc 55.5% 5 / 9 Subroutinesub 91.3% 21 / 23 Podpod 100% 7 / 7 totaltotal 86.5% 186 / 215 CC 37 SCAR 18.4
CC
37
Cov
87%
_wide_number
12.1
_restore_wide_numbers
11.8
detect
6.0
CRAP 6.3
« blib/lib/File/SOPS/Backend/Age.pm ↑ Summary blib/lib/File/SOPS/Format/ENV.pm »
1 package File::SOPS::Format::JSON;
2 # ABSTRACT: JSON format handler for SOPS
3 90 our $VERSION = '0.005';
4 90 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 90 ▶use B ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 90 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 90 ▶use Cpanel::JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 90 ▶use Cpanel::JSON::XS::Type qw(JSON_TYPE_INT);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 90 ▶use Math::BigFloat ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 90 ▶use Scalar::Util qw(blessed dualvar);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 90 ▶use File::SOPS::Encrypted;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 # For parse_in_document_order only -- see the note there. This module owns no
13 # order-preserving reader of its own, deliberately.
14 90 ▶use File::SOPS::Format::YAML;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 90 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 # Carp reports the caller of the frame croak stands in, and every frame between
18 # a caller and this module is this distribution's own: File::SOPS::encrypt calls
19 # emit(), emit() calls File::SOPS::Encrypted->canonical_float_tree, and the walk
20 # calls the guards below BACK. So a refusal named a line in Encrypted.pm -- the
21 # walk's own recursion -- where the house rule asks for the line the caller
22 # wrote encrypt() or emit() on (k71). Naming both packages here makes Carp
23 # walk out of them: it skips a frame when either side trusts the other, so this
24 # one list also fixes the guard that croaks from inside the walk.
25 #
26 # It is the frames, not the messages, that this changes. Every message still
27 # names the leaf's key path (k68), which is what a caller acts on.
28 90 our @CARP_NOT = qw( File::SOPS File::SOPS::Encrypted );
29  
30 # The only JSON encoder AND decoder in this distribution's document path, and
31 # the only definition of their options. utf8 makes it emit encoded bytes
32 # whatever Perl's UTF-8 flag says (and expect encoded bytes on the way in),
33 # canonical makes it emit keys sorted -- which the MAC's encrypt side depends
34 # on, since that walk hashes in sorted order. emit() and parse() below are the
35 # only entry points to it.
36 #
37 # The backend is NAMED here rather than left to JSON::MaybeXS, which binds once
38 # per process to whichever backend is already in %INC -- so the calling program
39 # decided our wire bytes, and CryptX (loaded by File::SOPS::Encrypted) pulls in
40 # JSON::XS. That is not a formatting preference:
41 #
42 # * JSON::XS's decoder is not correctly rounded. It reads 0.3 back as the
43 # double whose shortest form is 0.30000000000000004, so File::SOPS in a
44 # process that had loaded JSON::XS REFUSED a valid sops document
45 # ("MAC verification failed") over an unencrypted 0.3.
46 # * JSON::XS writes an NV -0.0 as `-0`, which parses back as the INTEGER zero
47 # and digests as "0" while the MAC covers "-0". Such a document fails its
48 # own MAC here and in sops (exit 51). sops writes `-0` itself and cannot
49 # read that file back either -- matching its bytes would import its bug.
50 # * JSON::PP loses the sign entirely (`0`), same failure.
51 #
52 # Cpanel writes `1.0` and `-0.0` where sops writes `1` and `-0`; the first is
53 # cosmetic (both digest as "1", sops -d accepts ours), the second is the point.
54 # See docs/adr/0005. Do not "modernise" this back to JSON::MaybeXS.
55 #
56 # TWO objects, ONE definition of the options, because allow_bignum is not
57 # symmetric and must not be enabled on the decoder. On the way out it makes
58 # Cpanel render a Math::BigFloat as a bare JSON number, which is the only way
59 # measured to get a 17-digit double into JSON unquoted (docs/adr/0006). On the
60 # way IN it would hand back Math::BigFloat and Math::BigInt OBJECTS for
61 # ordinary literals -- measured, `0.30000000000000004` decodes to a
62 # Math::BigFloat and `100000000000000000000` to a Math::BigInt -- and
63 # detect_type calls a blessed leaf `str`, so every float in every document we
64 # read would change type and digest.
65 #
66 # It has no effect on the way out for anything that is not one of those objects:
67 # a sample of integers, NVs, strings, booleans, undef, arrays and -0.0 encodes
68 # byte-identically with and without it.
69 180 ▶sub _configured_json { return Cpanel::JSON::XS->new->utf8->pretty->canonical }
Subroutine _configured_json: called CC=1 SCAR=0.0
70  
71 90 my $json = _configured_json(); # parse(): NEVER allow_bignum
72 90 my $encoder = _configured_json()->allow_bignum; # emit()
73  
74  
75 123 ▶sub parse {
Subroutine parse: called CC=4 SCAR=13.9
Pod documented
76 123 my ($class, $content) = @_;
77 123 ▶ croak "content required" unless defined $content;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 0 123 123
78  
79 # The second argument is an OUTPUT parameter: Cpanel fills $types with a
80 # parallel tree of type constants and hands back exactly the data it would
81 # have handed back without it (measured -- structurally identical, and the
82 # duplicate-key refusal below is unchanged). See _restore_wide_numbers.
83 123 my $data = $json->decode($content, my $types);
84 122 ▶ croak "JSON did not parse to a hash" unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 122 122
85  
86 122 my $metadata;
87 122 ▶ if (exists $data->{sops}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"sops"}) 82 40 122
88 82 require File::SOPS::Metadata;
89 82 $metadata = File::SOPS::Metadata->from_hash(delete $data->{sops});
90 }
91  
92 # AFTER the sops section is split off, so the metadata is never rewritten:
93 # its version and lastmodified are strings the reference wrote and this
94 # walk has no business touching. $types still carries a `sops` branch, and
95 # the walk never reaches it because it descends $data.
96 115 _restore_wide_numbers($data, $types);
97  
98 115 return ($data, $metadata);
99 }
100  
101  
102 # Give back the leaf Go reads for the same digits: past int64, a float.
103 #
104 # Everything below -- k63, the ORACLE, the GATE -- is the UPPER window's
105 # branch, where that leaf is also the one YAML::XS gives. The LOWER window is
106 # the other branch: YAML::XS gives a Perl integer there and this parser
107 # deliberately does not follow it, it reads no map, and it gates on SVf_IOK.
108 # k101, docs/adr/0021, and the two-class table above _wide_number.
109 #
110 # Cpanel::JSON::XS returns a bare JSON integer literal it cannot hold in an IV
111 # or a UV as a plain PV -- a STRING -- so `100000000000000000000` reached the
112 # tree indistinguishable from `"100000000000000000000"` (measured: bit-identical
113 # SVs, FLAGS 0x4403, POK alone). detect_type therefore called it `str`, and
114 # rotate wrote a document sops had written with a NUMBER there back with a
115 # string. Silent schema drift on the reference's own file, k63.
116 #
117 # There is no big integer in the SOPS data model: past int64 a JSON number is a
118 # float64 to Go, and sops writes such a leaf as type:float in an encrypted slot
119 # and loses the digits itself in an unencrypted one (`sops -e` on
120 # 99999999999999999999 writes 100000000000000000000). YAML::XS already hands
121 # back the right shape for the same literal -- the double, carrying its source
122 # spelling, i.e. a dualvar -- which is a leaf class this distribution handles
123 # end to end. So the fix is only that THIS parser gives what the OTHER one
124 # gives; nothing in Format::YAML moves, and nothing in emit() moves either,
125 # because ADR 0011's repair path already writes such a leaf as a bare number.
126 # See docs/adr/0020.
127 #
128 # The ORACLE is the decoder's own type map, read from the same $json object the
129 # document goes through (ADR 0005: the backend is named, so its options are
130 # ours) -- never allow_bignum, which would hand back Math::BigFloat objects for
131 # every ordinary float and retype every document, and costs two orders of
132 # magnitude more besides (docs/adr/0020 has the figures). A plain-PV leaf is a
133 # plain PV for exactly two reasons, a JSON string or a bare integer too wide for
134 # an IV/UV, and the map separates them without fail: re-measured here across
135 # every IV/UV boundary and a set of pathological literals (400-digit integers,
136 # 400-digit fractions, 1e309, thirty ones), every plain-PV leaf is either
137 # JSON_TYPE_INT or JSON_TYPE_STRING and there is no third case. k63's
138 # parking note dismissed this mechanism over encode($data, $type) rewriting the
139 # value as UINT64_MAX; that is the ENCODE side, and the map is read here and
140 # handed to no encoder.
141 #
142 # The GATE is the plain tree, not the map. A leaf is touched only where the
143 # plain decode left a defined, unreferenced scalar carrying the public SVf_POK
144 # and NEITHER SVf_IOK NOR SVf_NOK; everywhere else the map is not even read.
145 # That is what keeps the float path out of this: a bare float literal decodes
146 # NOK and fails the first test. It is also why no Math::BigInt ever enters the
147 # tree, so _reject_referenced_leaf below keeps refusing one, unchanged.
148 136 ▶sub _restore_wide_numbers {
Subroutine _restore_wide_numbers: called CC=11 SCAR=24.7
149 136 my ($node, $type) = @_;
150  
151 136 ▶ if (ref $node eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $node eq 'HASH') { } 133 3 136
elsif (ref $node eq 'ARRAY') { } 3 0 3
152 133 ▶ my $map = ref $type eq 'HASH' ? $type : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $type eq 'HASH' ? : 133 0 133
153 133 for my $key (keys %$node) {
154 309 ▶ my $wide = _wide_number($node->{$key}, $map ? $map->{$key} : undef);
Branch: 1 branch
BranchTrueFalseTotal
$map ? : 309 0 309
155 309 ▶ $node->{$key} = $wide if defined $wide;
Branch: 1 branch
BranchTrueFalseTotal
if defined $wide 42 267 309
156 }
157 }
158 elsif (ref $node eq 'ARRAY') {
159 3 ▶ my $map = ref $type eq 'ARRAY' ? $type : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $type eq 'ARRAY' ? : 3 0 3
160 3 for my $index (0 .. $#$node) {
161 7 ▶ my $wide = _wide_number($node->[$index],
Branch: 1 branch
BranchTrueFalseTotal
$map ? : 7 0 7
162 $map ? $map->[$index] : undef);
163 7 ▶ $node->[$index] = $wide if defined $wide;
Branch: 1 branch
BranchTrueFalseTotal
if defined $wide 1 6 7
164 }
165 }
166  
167 136 return;
168 }
169  
170 # The dualvar for a leaf the decoder could not hold, or undef for a leaf that
171 # is to be left EXACTLY as the decoder returned it -- containers included, which
172 # are walked in place instead of being handed back.
173 #
174 # undef rather than the leaf itself so that an untouched slot is never assigned
175 # to at all. Storing a leaf back over itself preserves every flag that carries
176 # meaning -- measured, IOK/NOK/POK and their private twins identical across
177 # floats, integers, strings, -0.0, booleans, null and a UTF-8 string -- but it
178 # does set the pad housekeeping bits on an SV this walk had no business
179 # touching, and a parse path that leaves fingerprints on leaves it did not fix
180 # is one a later flag-level regression test cannot read.
181 #
182 # TWO leaf classes end up as that dualvar, one magnitude apart, and the public
183 # flags of the decoder's own SV are what tell them apart:
184 #
185 # IOK a bare literal Perl DID hold and Go cannot, [2**63 .. 2**64-1] --
186 # a UV here, a float64 there. k101, docs/adr/0021.
187 # POK alone a bare literal Perl could NOT hold, past 2**64-1, which the
188 # decoder hands back as a plain string. k63, docs/adr/0020.
189 #
190 # The flags are read ONCE for both, which is why the second class costs nothing:
191 # ADR 0021 measured the fold slightly FASTER than the single read this walk
192 # already made through the plain-PV test, which used to be a sub of its own.
193 # The question that test asks is unchanged and so is the reason it asks it of
194 # the PUBLIC SVf_POK -- as Encrypted::_has_public_pv does, because merely
195 # stringifying a number sets the PRIVATE pPOK and reading that would call an
196 # integer a string because someone had logged it. It is a question about the
197 # DECODER's output, not about the SOPS type; the type ladder stays in
198 # File::SOPS::Encrypted::detect_type and is not repeated here.
199 #
200 # THE ORDER OF THE TWO GATES IN THE IOK BRANCH IS CORRECTNESS, NOT COST.
201 # The flag comes first and the numeric comparison second, never the other way
202 # round: a numeric comparison against a scalar sets the PUBLIC SVf_IOK on it in
203 # place, so run ahead of the flag test over {"port":"5432","zip":"007",
204 # "ver":"1.50"} it retypes three of four string leaves -- measured, '5432' and
205 # '007' become ints and '1.50' a float, and the document either changes schema
206 # or croaks on ADR 0012's guard, from a walk that never reached the window.
207 # That is k32's mechanism and ADR 0002's rule. Two things keep it away
208 # from here and BOTH are deliberate: the SVf_IOK test that gates the branch,
209 # and the copying done by this sub's own `my ($node, $type) = @_` and again by
210 # Encrypted::integer_fits_int64. Neither is the redundant half -- the order is
211 # also what keeps the comparison off a leaf where it would warn, measured: one
212 # "isn't numeric" warning per string leaf.
213 316 ▶sub _wide_number {
Subroutine _wide_number: called CC=12 SCAR=25.0
214 316 my ($node, $type) = @_;
215  
216 316 ▶ if (ref $node eq 'HASH' || ref $node eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node eq "HASH" or ref $node eq "ARRAY") 21 295 316
Condition100%3/3
ref $node eq "HASH" or ref $node eq "ARRAY"
l!l&&r!l&&!r
183295
MC/DC100%2/2
ref $node eq "HASH" or ref $node eq "ARRAY"
ref $node eq "HASH" ref $node eq "ARRAY"
Truth table100%3/3
A or B
A= ref $node eq "HASH"B= ref $node eq "ARRAY"
ABresult
1X1
011
000
217 21 _restore_wide_numbers($node, $type);
218 21 return;
219 }
220  
221 295 ▶ return if !defined $node || ref $node;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $node or ref $node 23 272 295
Condition100%3/3
not defined $node or ref $node
l!l&&r!l&&!r
221272
MC/DC100%2/2
not defined $node or ref $node
not defined $node ref $node
Truth table100%3/3
not(A) or B
A= not defined $nodeB= ref $node
ABresult
1X1
011
000
222  
223 272 my $flags = B::svref_2object(\$node)->FLAGS;
224  
225 272 ▶ if ($flags & B::SVf_IOK()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flags & 256) 23 249 272
226 # The boundary is asked of File::SOPS::Encrypted and is NOT spelled a
227 # second time here: two copies of int64 drift together, which leaves
228 # the wire self-consistent and only the reference disagreeing. Only
229 # the upper end can fail -- an IV cannot reach below int64min, so the
230 # negative half of this window does not exist and -9223372036854775809
231 # is already the plain-PV branch's leaf.
232 23 ▶ return if File::SOPS::Encrypted->integer_fits_int64($node);
Branch: 1 branch
BranchTrueFalseTotal
if "File::SOPS::Encrypted"->integer_fits_int64($node) 7 16 23
233  
234 # NOT `$digits + 0`, which is what the branch below can use: these
235 # digits still fit a UV, so numifying them gives back an INTEGER and
236 # detect_type would go on calling the leaf an int -- the fix would be
237 # a silent no-op. pack/unpack forces the double Go reads there, and
238 # value_to_bytes then re-derives sops's own digits from it
239 # (9223372036854775808 -> 9223372036854776000, measured identical to
240 # what `sops -e` writes for the same input, in both slots).
241 16 my $digits = "$node";
242  
243 16 return dualvar(unpack('d', pack('d', $digits)), $digits);
244 }
245  
246 249 ▶ return unless $flags & B::SVf_POK();
Branch: 1 branch
BranchTrueFalseTotal
unless $flags & 1024 36 213 249
247 213 ▶ return if $flags & B::SVf_NOK();
Branch: 1 branch
BranchTrueFalseTotal
if $flags & 512 0 213 213
248 213 ▶ return unless defined $type && !ref $type && $type == JSON_TYPE_INT;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type and not ref $type and $type == 2 186 27 213
Condition50%3/6
defined $type and not ref $type and $type == 2
!ll&&!rl&&r
018627
defined $type and not ref $type
!ll&&!rl&&r
00213
MC/DC33%1/3
defined $type and not ref $type and $type == 2
defined $type not ref $type $type == 2
Truth table50%2/4
A and not(B) and C
A= defined $typeB= not ref $typeC= $type == 2
ABCresult
0XX0
10X0
1100
1111
249  
250 # The numification runs on a COPY of the PV. Perl marks a scalar numeric IN
251 # PLACE the first time it is read as a number, so numifying the leaf itself
252 # would set a flag on an SV the decoder still holds -- the trap ADR 0002
253 # and k72/k73 are about, one frame earlier.
254 27 my $digits = "$node";
255 27 my $number = $digits + 0;
256  
257 27 return dualvar($number, $digits);
258 }
259  
260 ###############################################################################
261 # The order-preserving reparse behind MAC verification (docs/adr/0001, 0036)
262 #
263 # ONE reader covers both formats, and it is the YAML one. That is ADR 0001's
264 # decision, not an omission here: JSON is a subset of YAML 1.2, YAML::PP reads
265 # what sops and Cpanel::JSON::XS write, and only ORDER AND SHAPE are read back
266 # -- a scalar the two decoders resolve differently never reaches the digest,
267 # because the values come from parse().
268 #
269 # Cpanel::JSON::XS has no order-preserving decode mode, so the alternative is a
270 # second hand-written scanner over the raw text. ADR 0001 rejected exactly that
271 # for exactly this job: the text-scraping order recovery it replaced is what
272 # silently dropped values from the digest.
273 #
274 # The one measured divergence is a key spelled with a surrogate PAIR escape
275 # (`"😀"`): Cpanel::JSON::XS combines it into U+1F600, YAML::PP keeps
276 # two lone surrogates. Neither emitter writes that -- both put non-ASCII on the
277 # wire as UTF-8 -- and where it is hand-written the key sets disagree and the
278 # walk says so at the path. It is a false refusal, never a false pass.
279 70 ▶sub parse_in_document_order {
Subroutine parse_in_document_order: called CC=1 SCAR=0.0
Pod documented
280 70 my ($class, $content) = @_;
281 70 return File::SOPS::Format::YAML->parse_in_document_order($content);
282 }
283  
284  
285 115 ▶sub serialize {
Subroutine serialize: called CC=4 SCAR=14.3
Pod documented
286 115 my ($class, %args) = @_;
287 115 ▶ my $data = $args{data} // croak "data required";
Condition50%1/2
$args{"data"} // croak("data required")
l!l
1150
MC/DC0%0/1
$args{"data"} // croak("data required")
$args{"data"}
Truth table50%1/2
A
A= $args{"data"}
Aresult
11
00
288 115 ▶ my $metadata = $args{metadata} // croak "metadata required";
Condition50%1/2
$args{"metadata"} // croak("metadata required")
l!l
1150
MC/DC0%0/1
$args{"metadata"} // croak("metadata required")
$args{"metadata"}
Truth table50%1/2
A
A= $args{"metadata"}
Aresult
11
00
289  
290 # The metadata goes into `sops`, so a value already there would be
291 # overwritten -- and since the digest was computed over the tree BEFORE
292 # serialization, the document that came out failed its own MAC. Refuse
293 # instead, as sops does (exit 203). See File::SOPS::encrypt.
294 croak "data contains a top-level 'sops' entry, which is where the SOPS "
295 . "metadata section goes"
296 115 ▶ if exists $data->{sops};
Branch: 1 branch
BranchTrueFalseTotal
if exists $data->{"sops"} 0 115 115
297  
298 115 my %output = %$data;
299 115 $output{sops} = $metadata->to_hash;
300  
301 115 return $class->emit(\%output);
302 }
303  
304  
305 # The one place this distribution turns a Perl tree into JSON. serialize() is
306 # this plus the metadata section, and File::SOPS::_serialize_plaintext (what
307 # decrypt_file writes and what edit hands the editor) is this on its own.
308 #
309 # It stays ONE sub because the options above have to be identical in both, and
310 # until k35 they were kept identical by hand: decrypt_file built its own
311 # encoder with the same options copied across -- and, being a second encoder,
312 # it could also have bound a different backend. canonical in particular is not
313 # a formatting preference -- the
314 # MAC's encrypt side hashes in sorted key order, and that is only the document's
315 # own order because this emitter sorts.
316 #
317 # Consequence, deliberately accepted: this sub is on the wire path. Changing
318 # what it emits changes the encrypted document too, so it is not a plaintext
319 # formatting knob.
320 149 ▶sub emit {
Subroutine emit: called CC=2 SCAR=7.1
Pod documented
321 149 my ($class, $data) = @_;
322 149 ▶ croak "data required" unless defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 149 149
323  
324 149 return $encoder->encode(File::SOPS::Encrypted->canonical_float_tree(
325 $data,
326 roundtrips => \&_float_roundtrips,
327 carrier => \&_float_carrier,
328 reject => \&_reject_referenced_leaf,
329 ));
330 }
331  
332 # Every referenced leaf the JSON emitter cannot write as the text the digest
333 # covers. Closes the asymmetry Format::YAML closed in k65 / ADR 0008:
334 # detect_type calls every reference but a JSON::PP::Boolean `str`, so the
335 # digest covers the leaf's STRINGIFICATION, while Cpanel::JSON::XS -- with
336 # allow_bignum widened for _float_carrier -- writes a Math::BigFloat /
337 # Math::BigInt as a bare number, and writes an UNBLESSED scalar ref as a bare
338 # true/false (the documented JSON::XS convention for \1 / \0). Measured
339 # against sops 3.13.3, unencrypted leaf x_unencrypted:
340 #
341 # Math::BigFloat->new("1.5") bare number 1.5 self-MAC FAIL, exit 51
342 # Math::BigInt->new("42") bare number 42 self-MAC FAIL, exit 51
343 # bless {a=>1}, 'Foo' Cpanel refuses self-MAC FAIL, exit 51
344 # \1 (unblessed) bare true self-MAC FAIL, exit 51
345 # \0 (unblessed) bare false self-MAC FAIL, exit 51
346 #
347 # All five -- the two we caught, the two Cpanel catches on its own, and the
348 # two nobody caught -- are the same defect: document and digest state
349 # different things, and the file is unreadable, written silently.
350 #
351 # The exception is the EXACT class, not ->isa: detect_type accepts a
352 # JSON::PP::Boolean subclass as bool, but neither Cpanel nor the carrier
353 # pipeline knows how to write it as bare true/false, and the guard's job is
354 # what the emitter can write. ref($node) eq 'JSON::PP::Boolean' matches the
355 # one class $YAML::XS::Boolean = 'JSON::PP' produces, JSON->true / JSON->false
356 # produce, and every JSON::MaybeXS backend produces -- the only reference
357 # whose document form and digest agree.
358 #
359 # Unblessed refs are in scope deliberately: \1 and \0 are the k66 case
360 # and the callback already has them in hand. They are not blessed, so the
361 # earlier "Math::BigFloat / Math::BigInt by name" rule could not see them.
362 #
363 # Not in assert_representable: that runs on the verify side too, and over
364 # leaves that are about to become ENC[...] strings. A referenced leaf in an
365 # ENCRYPTED slot works in both formats today (type:str, plaintext = the same
366 # stringification) and must keep working. See docs/adr/0008 and k66.
367 #
368 # $where is the leaf's key path from canonical_float_tree, in the shape the MAC
369 # walk's messages already use. It goes in FRONT of the message: the class alone
370 # told a caller what was wrong and left finding it a manual search (k68).
371 15 ▶sub _reject_referenced_leaf {
Subroutine _reject_referenced_leaf: called CC=3 SCAR=11.0
372 15 my ($node, $where) = @_;
373  
374 15 ▶ return if ref($node) eq 'JSON::PP::Boolean';
Branch: 1 branch
BranchTrueFalseTotal
if ref $node eq "JSON::PP::Boolean" 13 2 15
375  
376 2 ▶ my $what = Scalar::Util::blessed($node)
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($node) ? : 1 1 2
377 ? "a leaf blessed into " . ref($node)
378 : "an unblessed " . ref($node) . " reference";
379  
380 2 croak "$where: cannot write $what to a SOPS document: Cpanel::JSON::XS "
381 . "writes it differently from the stringification the digest covers -- a "
382 . "Math::BigFloat or Math::BigInt as a bare number, an unblessed "
383 . "scalar reference as bare true/false, any other object is refused "
384 . "by Cpanel itself. The document and its own MAC would state "
385 . "different things, and neither sops nor this module could read the "
386 . "file. Pass a plain Perl scalar, or the string you want stored. A "
387 . "boolean has to be an exact JSON::PP::Boolean (JSON->true / "
388 . "JSON->false); a subclass of it is written as a tag as well";
389 }
390  
391 # Does this emitter's own rendering of the float come back as the same double?
392 #
393 # Measured through the two objects the document itself goes through, so the
394 # question asked is exactly "if I write this and read it back, do I get the
395 # same number". Cpanel renders an NV through %.15g, so 0.1+0.2 comes back as
396 # 0.3 -- a different double from the one value_to_bytes digested.
397 #
398 # Unlike YAML::XS, Cpanel keeps no PV, so a float PARSED from a JSON document
399 # is a bare NV and fails this test too. That is why rotate on a legitimate
400 # sops-written JSON file used to rewrite 0.30000000000000004 as 0.3.
401 #
402 # Equality via value_to_bytes on both sides, not ==, so it means what the digest
403 # means; == cannot tell -0.0 from 0.0, and -0.0 is a case ADR 0005 paid for.
404 #
405 # The reparsed leaf has to come back a FLOAT, and that is asked FIRST, because
406 # the byte comparison below cannot see the case where it does not.
407 # Cpanel::JSON::XS writes a scalar carrying a public PV as a JSON STRING when
408 # that PV differs from its own rendering of the number, so a float leaf that is
409 # a Scalar::Util::dualvar -- numerically the double, as text the canonical
410 # decimal -- is emitted quoted. The byte test then passes: the reparsed value
411 # is the string "0.30000000000000004", whose value_to_bytes is itself, which is
412 # the text the digest covers. Equal, so the walk left the leaf alone and the
413 # document silently held a string where the caller passed a number. Measured
414 # against sops 3.13.3, leaf ratio_unencrypted:
415 #
416 # dualvar(0.1+0.2, "0.30000000000000004")
417 # -> "ratio_unencrypted" : "0.30000000000000004"
418 # -> sops -d exit 0, read back AS A STRING
419 #
420 # Answering NO sends the leaf to _float_carrier, which writes that same
421 # canonical decimal as a BARE NUMBER -- the document YAML has always produced
422 # for the same leaf, and, for the k78 case, byte-identical to the one a
423 # bare NV of the same value produces (both go through the carrier). 89ed194
424 # croaked here instead; that refused every float that arrived through a YAML
425 # parse as well, because YAML::XS keeps the source text of every scalar it
426 # parses. See docs/adr/0011, which replaces that refusal, and k85 for the
427 # question it leaves open (a string half that CONTRADICTS the number, such as
428 # dualvar(1.5, 'banana'), is written as 1.5 here and in YAML alike).
429 #
430 # The nearest route in is ordinary caller code, not a contrivance:
431 # `my $v = File::SOPS->extract(...)` returns exactly that dualvar for a float
432 # leaf since ADR 0010, and feeding it back into encrypt() under an unencrypted
433 # key lands here.
434 #
435 # JSON ONLY, deliberately. The same question asked of Format::YAML would send
436 # `0.0` and `2.0` to a carrier they do not need: YAML::XS writes an integral
437 # float as `0` / `2`, which reparses as an INT, and both are handled correctly
438 # today -- `0.0` compares equal on bytes and is left alone, `-0.0` goes to the
439 # carrier that writes `-0.0` (ADR 0005/0006). Cpanel writes every NV with a
440 # `.0` or an exponent, so a non-float reparse there means a quoted string and
441 # nothing else.
442 #
443 # It cannot fire on a float that was merely printed: measured, Perl does not
444 # set the PUBLIC SVf_POK when it stringifies an NV, and Cpanel reads the public
445 # flag, so `my $s = "$float"` leaves the emission bare. A real dualvar, or a
446 # scalar a YAML parser kept the source text of, is what reaches this.
447 55 ▶sub _float_roundtrips {
Subroutine _float_roundtrips: called CC=4 SCAR=13.9
448 55 my ($value, $text) = @_;
449  
450 55 my $back = eval { $json->decode($encoder->encode({ v => $value }))->{v} };
451 55 ▶ return 0 unless defined $back;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $back 0 55 55
452  
453 55 ▶ return 0 unless File::SOPS::Encrypted->detect_type($back)
Branch: 1 branch
BranchTrueFalseTotal
unless "File::SOPS::Encrypted"->detect_type($back) eq "File::SOPS::Encrypted"->detect_type($value) 7 48 55
454 eq File::SOPS::Encrypted->detect_type($value);
455  
456 48 ▶ return File::SOPS::Encrypted->value_to_bytes($back) eq $text ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
'File::SOPS::Encrypted'->value_to_bytes($back) eq $text ? : 45 3 48
457 }
458  
459 # Math::BigFloat is the only carrier measured to survive into JSON as a bare
460 # number: a dualvar, a plain string and a TO_JSON return are all quoted by every
461 # backend, and Cpanel::JSON::XS::Type's JSON_TYPE_FLOAT still renders 0.3.
462 #
463 # The explicit `undef, undef` are the accuracy and precision arguments, and they
464 # are load-bearing. Math::BigFloat->new otherwise applies CLASS-GLOBAL accuracy
465 # and precision, so a caller who had set Math::BigFloat->accuracy(5) anywhere in
466 # their program silently turned our text into 0.30000 -- the calling program
467 # deciding our wire bytes again, which is the whole subject of ADR 0005. A
468 # subclass would be immune to that, but allow_bignum matches the class name
469 # exactly and refuses one.
470 #
471 # The ONE canonical float text it cannot carry is a NEGATIVE ZERO: Math::BigFloat
472 # has no signed zero, so new('-0') stringifies as `0` and the assertion below
473 # fired -- on a sign, with a message about a precision setting that was never in
474 # play (k88). Measured: of 2018 canonical texts from value_to_bytes, `-0` is
475 # the only one it does not reproduce.
476 #
477 # So a negative zero is carried by the DOUBLE ITSELF, stripped of the string half
478 # that sent it here. Cpanel writes a bare NV -0.0 as `-0.0` (ADR 0005 names that
479 # as the reason this handler binds Cpanel and not JSON::XS), and that text parses
480 # back to the same double -- which is what ADR 0006 asks of an emitted decimal,
481 # not that it be spelled canonically. Measured against sops 3.13.3, an
482 # unencrypted JSON leaf whose digest is `-0`:
483 #
484 # -0.0 sops -d exit 0, reads back -0 <- this, and what a bare NV writes
485 # -0 sops -d exit 51 (MAC mismatch) <- Go reads a JSON -0 as an INTEGER
486 #
487 # The same split the YAML carrier measured in k62, in the other format: `-0`
488 # is the canonical text and the one spelling neither implementation reads back.
489 #
490 # The copy goes through pack/unpack, and NO arithmetic route works. Measured on
491 # a leaf out of a YAML parse, three rounds each:
492 #
493 # 0 + $v -0 once, then 0 $v * 1 -0 once, then 0
494 # $v * 1.0 0 every round $v - 0.0 0 every round
495 # unpack d pack d -0 every round
496 #
497 # Two mechanisms, and the second is the dangerous one. IEEE-754 makes
498 # -0.0 + 0.0 a POSITIVE zero, so adding zero drops the sign outright. And
499 # Perl's arithmetic ops call SvIV_please on their operands, which sets the
500 # PRIVATE IOK on the CALLER'S scalar in place -- so the next multiplication of
501 # the same leaf takes the integer path and returns a plain 0. That is k72
502 # and k73 again, one frame further in: the first document written would have
503 # been right and every later one wrong, in the same process, from the same
504 # tree. pack 'd' reads the NV and nothing else.
505 #
506 # The strip is not cosmetic: with the PV still on it, Cpanel quotes the leaf and
507 # the document holds a string where the caller passed a number.
508 21 ▶sub _float_carrier {
Subroutine _float_carrier: called CC=3 SCAR=11.0
509 21 my ($value, $text) = @_;
510  
511 21 ▶ my $carrier = $text eq '-0' ? unpack('d', pack('d', $value))
Branch: 1 branch
BranchTrueFalseTotal
$text eq '-0' ? : 0 21 21
512 : Math::BigFloat->new($text, undef, undef);
513  
514 # Both bypasses above are measured, but the failure they prevent is silent
515 # and produces a document that fails its own MAC, so it is asserted rather
516 # than trusted -- through value_to_bytes, so the assertion means what the
517 # digest means. No value in the message: it is the plaintext.
518 21 ▶ croak "the JSON float carrier did not reproduce the text the MAC digest "
Branch: 1 branch
BranchTrueFalseTotal
unless "File::SOPS::Encrypted"->value_to_bytes($carrier) eq $text 12 9 21
519 . "covers, so nothing was written. Everything but a negative zero is "
520 . "carried by a Math::BigFloat, where the cause is a global "
521 . "Math::BigFloat->accuracy or ->precision setting that survived the "
522 . "explicit undef, undef; a negative zero is carried by the double "
523 . "itself, where it is a build whose arithmetic drops the sign of a "
524 . "signed zero"
525 unless File::SOPS::Encrypted->value_to_bytes($carrier) eq $text;
526  
527 9 return $carrier;
528 }
529  
530  
531 133 ▶sub format_name { 'json' }
Subroutine format_name: called CC=1 SCAR=0.0
Pod documented
532  
533  
534 0 ▶sub file_extensions { qw(json) }
Subroutine file_extensions: not called CC=1 SCAR=6.9
Pod documented
535  
536  
537 0 ▶sub detect {
Subroutine detect: not called CC=2 SCAR=17.9
Pod documented
538 0 my ($class, $filename) = @_;
539 0 ▶ return 1 if $filename =~ /\.json$/i;
Branch: 1 branch
BranchTrueFalseTotal
if $filename =~ /\.json$/i 0 0 0
540 0 return 0;
541 }
542  
543  
544  
545 90 1;
546  
547 __END__
« blib/lib/File/SOPS/Backend/Age.pm ↑ Summary blib/lib/File/SOPS/Format/ENV.pm »