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

filter: Statementstmt 98.5% 1040 / 1055 Branchbran 84.4% 407 / 482 Conditioncond 75.1% 139 / 185 MC/DCmcdc 51.4% 53 / 103 Subroutinesub 99.1% 219 / 221 Podpod 100% 7 / 7 totaltotal 90.8% 1865 / 2053 CC 331 SCAR 15.9
CC
331
Cov
92%
__ANON__
23.1
_pair_plain_infinities
19.5
_go_timestamp
19.2
CRAP 4.9
« blib/lib/File/SOPS/Format/ENV.pm ↑ Summary blib/lib/File/SOPS/Comment.pm »
1 package File::SOPS::Format::YAML;
2 # ABSTRACT: YAML format handler for SOPS
3 91 our $VERSION = '0.005';
4 222 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 140 ▶use B ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 115 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 102 ▶use Scalar::Util qw(blessed dualvar refaddr);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 102 ▶use YAML::PP;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 95 ▶use YAML::PP::Parser;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 93 ▶use YAML::PP::Common qw( PRESERVE_ORDER YAML_PLAIN_SCALAR_STYLE );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 93 ▶use YAML::XS qw(Load Dump);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 93 ▶use File::SOPS::Encrypted;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 93 ▶use File::SOPS::Metadata;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 93 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 # Carp reports the caller of the frame croak stands in, and every frame between
17 # a caller and this module is this distribution's own: File::SOPS::encrypt calls
18 # emit(), emit() calls File::SOPS::Encrypted->canonical_float_tree, and the walk
19 # calls the guards below BACK. So a refusal named a line in Encrypted.pm -- the
20 # walk's own recursion -- where the house rule asks for the line the caller
21 # wrote encrypt() or emit() on (k71). Naming both packages here makes Carp
22 # walk out of them: it skips a frame when either side trusts the other, so this
23 # one list also fixes the guard that croaks from inside the walk.
24 #
25 # It is the frames, not the messages, that this changes. Every message still
26 # names the leaf's key path (k68), which is what a caller acts on.
27 91 our @CARP_NOT = qw( File::SOPS File::SOPS::Encrypted );
28  
29 # 'JSON::PP' here is one of YAML::XS's own two mode names (the other is
30 # 'boolean'), not a module this distribution loads or talks to. It makes
31 # Load/Dump round-trip YAML true/false as JSON::PP::Boolean objects -- the same
32 # class JSON::MaybeXS blesses into on every backend. Do not "modernise" this
33 # string to 'JSON::MaybeXS'; YAML::XS would reject it.
34 #
35 # LOCALISED around our own calls, never assigned at load time. $YAML::XS::Boolean
36 # is a process-global that changes what YAML::XS::Load and ::Dump do for
37 # EVERYONE in the program, and setting it as a side effect of `use File::SOPS`
38 # silently rewrote the semantics of unrelated code that merely happened to share
39 # the interpreter.
40 91 our $BOOLEAN_MODE = 'JSON::PP';
41  
42  
43 952 ▶sub parse {
Subroutine parse: called CC=8 SCAR=20.8
Pod documented
44 952 my ($class, $content) = @_;
45 952 ▶ croak "content required" unless defined $content;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 0 950 950
46  
47 952 local $YAML::XS::Boolean = $BOOLEAN_MODE;
48  
49 # LIST context is load-bearing, and it is the whole of the trap this ADR
50 # names. YAML::XS::Load in SCALAR context returns only the LAST document of
51 # a multi-document stream, so `a: 1\n---\nb: 2` parsed to just {b=>2} -- and
52 # encrypt_file then wrote that back as the whole file. In LIST context @docs
53 # holds every document, in order.
54 #
55 # sops supports multi-document YAML as ONE tree with N branches carrying ONE
56 # metadata section (written into every document) and ONE MAC spanning all
57 # documents in order (docs/adr/0033, k31). This method now returns the
58 # DOCUMENT LIST rather than refusing above one document -- see
59 # _parse_multidoc. The single-document path below is untouched, so a
60 # one-document file is byte-identical to before.
61 #
62 # parse_in_document_order moved to a document list in the SAME commit, and
63 # it had to: that reparse supplies the MAC walk's key ORDER while the tree
64 # here supplies the VALUES, so if one became a list and the other did not
65 # the walk would pair one document's order with another's values -- a wrong
66 # MAC with no error. Both are lists now.
67 #
68 # The retries below exist for TWO tokens and run only after YAML::XS has
69 # already refused the document. See _without_merge_tags and
70 # _without_bool_tags; _refuse_unreadable_tag names the tag for the ones
71 # that carry a type this module cannot reproduce, and reports libyaml's own
72 # message, unchanged, for everything that is not a tag at all.
73 952 ▶ my @docs = eval { Load($content) };
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
74 952 ▶ if (my $load_error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $load_error = $@) 38 912 950
75 40 my $retry = _without_redundant_tags($content);
76 40 ▶ _refuse_unreadable_tag($content, $load_error) unless defined $retry;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $retry 17 21 38
77 23 @docs = eval { Load($retry) };
78 23 ▶ _refuse_unreadable_tag($content, $load_error) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 3 18 21
79 }
80  
81 932 ▶ return _parse_multidoc($content, \@docs) if @docs > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @docs > 1 7 923 930
82  
83 925 my $data = $docs[0];
84 925 ▶ croak "YAML did not parse to a hash" unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 3 920 923
85  
86 922 my $metadata;
87 922 ▶ if (exists $data->{sops}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"sops"}) 663 257 920
88 # The RAW section, read before from_hash and not from $metadata:
89 # from_hash stores the timestamp Go RE-FORMATS (docs/adr/0044), and the
90 # question here is about the text the document holds. Warns, never
91 # refuses -- see _warn_plain_lastmodified for why, and for what it can
92 # never fire on.
93 665 my $section = delete $data->{sops};
94 665 _warn_plain_lastmodified($section, $content);
95  
96 665 $metadata = File::SOPS::Metadata->from_hash($section);
97 }
98  
99 # AFTER the split, so the sops section is never rewritten -- and after the
100 # HashRef check, so there is a tree to walk. See _restring_non_finite_leaf.
101 911 _restring_non_finite_leaves($data, {});
102  
103 # Same position shape: AFTER _restring_non_finite_leaves, because that walk
104 # produces its own dualvar and reads SVf_NOK; this one reads SVf_IOK and
105 # produces another dualvar. So they cannot collide, but the dualvars they
106 # each leave must be the only ones anyone sees -- hence the order.
107 911 _go_repair_int_leaves($data, {});
108  
109 # AFTER _restring_non_finite_leaves, and that order is load-bearing: the
110 # walk above turns a leaf whose PUBLIC NOK and POK are both set and whose
111 # NV is non-finite back into its string half, which is exactly the shape of
112 # the dualvar the walk below produces. Second, it would undo this one leaf
113 # for leaf.
114 #
115 # It runs for EVERY document, plaintext included. It used to be gated on
116 # `if $metadata`, and k123 and docs/adr/0034 are why that gate is
117 # gone: sops has one parse, and this had two.
118 911 _restore_plain_infinities($data, $content);
119  
120 # The document list is [$data] for a single document, so a caller wanting a
121 # uniform shape (the api lane, k31 step 4) can read the third value
122 # without special-casing the count. The two-value unpacking every current
123 # caller uses ignores it, so the single-document path is byte-identical.
124 911 return ($data, $metadata, [$data]);
125 }
126  
127 ###############################################################################
128 # A multi-document stream, parsed into a DOCUMENT LIST (docs/adr/0033, k31)
129 #
130 # Reached only when YAML::XS::Load returned more than one document. The wire
131 # machinery below this -- the MAC over all documents (File::SOPS::_compute_mac,
132 # _verify_mac) and the order-preserving reparse (parse_in_document_order) -- is
133 # built to consume this list, but the public API return shape, the one-instance
134 # metadata attach/detach and the emitter's separators are NOT in place yet
135 # (k31 steps 4-5). Until they are, File::SOPS refuses a multi-document
136 # read or write at its own boundary rather than processing only the first
137 # document, which is the k14 data-loss defect this whole ticket exists to
138 # fix. So this returns a correct, non-corrupting list; it does not yet round
139 # trip.
140 #
141 # The single-document walks are run once PER DOCUMENT here, each with a fresh
142 # visited set -- which is what docs/adr/0033 Decision 4 requires for the
143 # overflow-literal (docs/adr/0023) and comment-leaf (docs/adr/0024) repairs.
144 9 ▶sub _parse_multidoc {
Subroutine _parse_multidoc: called CC=8 SCAR=20.8
145 9 my ($content, $docs) = @_;
146  
147 9 my @documents;
148 9 for my $doc (@$docs) {
149 # An empty document is a real document that reads back as {} (measured;
150 # `a: 1\n---\n---\nb: 2\n` is three documents to YAML::XS and to sops).
151 17 ▶ $doc = {} unless defined $doc;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $doc 2 13 15
152  
153 # Every document must be a mapping. sops has a distinct multi-document
154 # code path with two distinct messages -- its fingerprint -- for the two
155 # non-mapping shapes; both are refused, as the single-document HashRef
156 # check refuses them.
157 17 ▶ croak "YAML documents that are sequences are not supported"
Branch: 1 branch
BranchTrueFalseTotal
if ref $doc eq "ARRAY" 0 15 15
158 if ref $doc eq 'ARRAY';
159 17 ▶ croak "YAML documents that are values are not supported"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $doc eq "HASH" 0 15 15
160 unless ref $doc eq 'HASH';
161  
162 17 push @documents, $doc;
163 }
164  
165 # Metadata comes from the FIRST document only (measured: a stream carrying
166 # it only in a later document is `sops metadata not found` at sops). Later
167 # documents' sops sections are stripped from the value trees so the walks
168 # see clean document contents; the read-side policy (reject metadata that is
169 # only in a later document) and the write-side one-instance attach are the
170 # api lane's, k31 step 4.
171 9 my $metadata;
172 9 my $first = $documents[0];
173 9 ▶ if (exists $first->{sops}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $first->{"sops"}) 2 5 7
174 4 my $section = delete $first->{sops};
175 4 _warn_plain_lastmodified($section, $content);
176 4 $metadata = File::SOPS::Metadata->from_hash($section);
177 }
178 9 delete $_->{sops} for @documents[1 .. $#documents];
179  
180 # Fresh visited set per document (docs/adr/0023, 0024 via 0033 Decision 4).
181 9 for my $doc (@documents) {
182 17 _restring_non_finite_leaves($doc, {});
183 17 _go_repair_int_leaves($doc, {});
184 }
185  
186 # The plain-infinity repair (docs/adr/0026) reparses the raw text and pairs
187 # it against the value trees. On a stream that pairing has to be
188 # document-by-document -- list context yields N reparsed documents, and the
189 # single-tree pairing has no counterpart (docs/adr/0033 Decision 4).
190 9 _restore_plain_infinities_multi(\@documents, $content);
191  
192 9 return ($documents[0], $metadata, \@documents);
193 }
194  
195 ###############################################################################
196 # The !!merge tag sops writes on a merge key (k116, docs/adr/0028)
197 #
198 # sops does not expand a YAML merge key. It reads the document into a
199 # yaml.Node tree, where go-yaml performs no merge resolution, so `<<` survives
200 # as an ordinary key -- and go-yaml's emitter then writes the tag its resolver
201 # assigned back out EXPLICITLY:
202 #
203 # derived:
204 # !!merge <<:
205 # x: ENC[AES256_GCM,...,type:int]
206 # "y": ENC[AES256_GCM,...,type:int]
207 #
208 # YAML::XS accepts exactly three tags on a scalar -- !!str, !!int, !!float --
209 # and dies on every other one, so this document could not be opened here at
210 # all: `bad tag found for scalar: 'tag:yaml.org,2002:merge'`, a parse error
211 # rather than a MAC error, on a file `sops -d` reads at exit 0. It is not only
212 # a document sops authored: measured, `sops rotate -i` on a document THIS
213 # library wrote with a `<<` key adds the tag, so one sops write-back was enough
214 # to make our own output unreadable to us.
215 #
216 # For everything below the parse the tag carries nothing. Measured against
217 # sops 3.13.3, `<<` is a completely ordinary key on both sides of the wire:
218 # it is a path component in the AAD (`derived:<<:x:` decrypts and authenticates
219 # the leaf under a merge key), and it is in the digest with its subtree, in the
220 # document's own order, exactly like any other key. So dropping the tag before
221 # YAML::XS sees it changes no path, no digest and no emitted byte -- the tree
222 # is the tree sops has.
223 #
224 # WHY TEXT AND NOT A SECOND PARSER. YAML::PP reads the tag and gives the same
225 # literal `<<` key, but it is not this module's parser and cannot become one
226 # for one class of document: types come from the parser (ADR 0002) and the two
227 # resolvers disagree, so a document would be typed by which tag it happened to
228 # carry. YAML::XS has no hook -- no tag handler, and $YAML::XS::LoadBlessed
229 # does not reach the yaml.org tags (measured, both settings die). What is left
230 # is removing a tag that is redundant by construction: a plain `<<` key
231 # resolves to this very tag, which is why go-yaml can add it back when reading
232 # our untagged output (measured, `sops -d` prints `!!merge <<:` for a document
233 # we wrote as `<<:`).
234 #
235 # WHY THIS TEXT SURGERY AND NOT THE ONE ADR 0019 REJECTED. There the surgery
236 # would have had to find an arbitrary key path at arbitrary nesting in a
237 # FINISHED document about to go on the wire, and a mis-hit would have written a
238 # corrupt file. Here the target is one fixed token in one lexical position, on
239 # the READ path, on a document YAML::XS has already refused -- and the
240 # substitution is reconciled against ground truth before its result is parsed:
241 # YAML::PP's PARSER (events only, no tree, no resolver) says how many
242 # merge-tagged scalars the document really has, and unless the substitution
243 # removed exactly that many, nothing is retried and libyaml's original error
244 # stands. That closes the mis-hit: a tag the pattern missed is still in the
245 # text and YAML::XS refuses again, so a successful retry with matching counts
246 # proves every removal landed on a real tag. The case that gets no repair is a
247 # tag the pattern cannot see -- flow style, or a %TAG-directive spelling --
248 # which sops does not write and which fails exactly as it does today.
249 91 my $MERGE_TAG = 'tag:yaml.org,2002:merge';
250  
251 # Tag position, block style: the start of the node, i.e. after the line's
252 # indentation and after any block-sequence indicators (`- !!merge <<:`).
253 91 my $MERGE_TAG_IN_TAG_POSITION = qr/^([ \t]*(?:-[ \t]+)*)!!merge[ \t]+(?=<<[ \t]*:)/m;
254  
255 40 ▶sub _without_merge_tags {
Subroutine _without_merge_tags: called CC=5 SCAR=16.2
256 40 my ($content) = @_;
257  
258 # Cheapest gate first, and the only one that runs for a document that
259 # failed to parse for any other reason.
260 40 ▶ return unless $content =~ /!!merge/;
Branch: 1 branch
BranchTrueFalseTotal
unless $content =~ /!!merge/ 27 11 38
261  
262 13 my $wanted = _merge_tagged_scalars($content);
263 13 ▶ return unless $wanted;
Branch: 1 branch
BranchTrueFalseTotal
unless $wanted 0 11 11
264  
265 13 my $stripped = $content;
266 # s///g returns the empty string, not 0, when it matches nothing -- which
267 # is exactly the flow-style case below, and `'' == 1` is a warning.
268 13 ▶ my $removed = ($stripped =~ s/$MERGE_TAG_IN_TAG_POSITION/$1/g) || 0;
Condition50%1/2
$stripped =~ s/$MERGE_TAG_IN_TAG_POSITION/$1/g || 0
l!l
110
MC/DC0%0/1
$stripped =~ s/$MERGE_TAG_IN_TAG_POSITION/$1/g || 0
$stripped =~ s/$MERGE_TAG_IN_TAG_POSITION/$1/g
Truth table50%1/2
A
A= $stripped =~ s/$MERGE_TAG_IN_TAG_POSITION/$1/g
Aresult
11
00
269  
270 11 ▶ return unless $removed == $wanted;
Branch: 1 branch
BranchTrueFalseTotal
unless $removed == $wanted 1 10 11
271 10 return $stripped;
272 }
273  
274 # Ground truth, from the parser and not from the tree: YAML::PP's loader would
275 # resolve values and blur the question, its parser only reports what the
276 # document says. Fails safe -- a document YAML::PP refuses counts as nothing to
277 # repair, which leaves today's error in place rather than guessing.
278 13 ▶sub _merge_tagged_scalars {
Subroutine _merge_tagged_scalars: called CC=3 SCAR=11.0
279 11 my ($content) = @_;
280  
281 # YAML::XS::Load takes bytes and hands back characters; YAML::PP wants the
282 # characters. Same decode as File::SOPS::_parse_in_document_order, and for
283 # the same reason.
284 11 my $text = $content;
285 11 ▶ utf8::decode($text) unless utf8::is_utf8($text);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($text) 11 0 11
286  
287 11 my $count = 0;
288 11 my $ok = eval {
289 246 ▶ YAML::PP::Parser->new(receiver => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
290 244 my (undef, $name, $event) = @_;
291 244 ▶ return unless $name eq 'scalar_event';
Branch: 1 branch
BranchTrueFalseTotal
unless $name eq "scalar_event" 133 111 244
292 111 ▶ $count++ if ($event->{tag} // '') eq $MERGE_TAG;
Branch: 1 branch
BranchTrueFalseTotal
if ($event->{"tag"} // "") eq $MERGE_TAG 12 99 111
Condition100%2/2
$event->{"tag"} // ""
l!l
1497
MC/DC100%1/1
$event->{"tag"} // ""
$event->{"tag"}
Truth table100%2/2
A
A= $event->{"tag"}
Aresult
11
00
293 11 })->parse_string($text);
294 11 1;
295 };
296  
297 11 ▶ return unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 11 11
298 11 return $count;
299 }
300  
301 ###############################################################################
302 # The OTHER yaml.org tags on a scalar (k118, docs/adr/0030)
303 #
304 # YAML::XS accepts exactly three tags on a scalar -- !!str, !!int and !!float
305 # -- and dies on every other one with `bad tag found for scalar`, which reads
306 # like a bug in a foreign library rather than a statement about the document.
307 # sops accepts them all, resolves them, and writes the resolved value with the
308 # tag gone. So a hand-written plaintext that `sops -e` encrypts at exit 0 could
309 # not be opened here at all. Measured, sops 3.13.3, one leaf encrypted and the
310 # same leaf under a `_unencrypted` key, with the stored MAC decrypted out of
311 # each document and reproduced here leaf by leaf:
312 #
313 # plaintext leaf type ciphertext plaintext = MAC bytes unencrypted slot
314 # !!bool true bool True true
315 # !!bool True bool True true
316 # !!binary aGVsbG8= str hello hello
317 # !!timestamp 2026-08-21 time 2026-08-21T00:00:00Z 2026-08-21T00:00:00Z
318 # !!null ~ - (not encrypted, nothing hashed) null
319 # !!str 5 str 5 "5"
320 # !!int 0755 int 493 493
321 # !!float 1 float 1 1
322 #
323 # Only ONE of them carries nothing. `!!bool true` produces a document that is
324 # byte-identical to the one a bare `true` produces -- same type:bool, same
325 # plaintext `True`, and the two MAC digests measured out identical -- because a
326 # plain `true` resolves to this very tag on both sides. That is the same shape
327 # as the !!merge repair above, so it gets the same treatment: the tag is
328 # removed from the text and the parse is retried, reconciled against YAML::PP's
329 # parser so a mis-hit cannot reach libyaml.
330 #
331 # EVERY OTHER TAG HERE CARRIES A TYPE, and the type comes from the scalar in
332 # this distribution (ADR 0002), so removing the tag is not a no-op:
333 #
334 # !!binary sops base64-DECODES it. `aGVsbG8=` becomes the value `hello`.
335 # Dropping the tag would encrypt the base64 text -- a different
336 # value and a different digest, not a tag removal. Decoding it
337 # here would be a value transformation on the wire path, which
338 # is not this module's to make.
339 # !!timestamp sops resolves it to a time.Time and re-renders it in RFC3339
340 # under type:time. Dropping the tag leaves the SOURCE spelling as
341 # a string, so `2026-08-21` would digest as `2026-08-21` here and
342 # as `2026-08-21T00:00:00Z` there.
343 # !!bool on a spelling libyaml does not resolve (True, False, TRUE, FALSE,
344 # or a quoted `true`): sops types the leaf bool, dropping the tag
345 # types it str here. The digest bytes still agree -- `True` both
346 # sides -- so such a file would verify; the TYPE would not.
347 # !!null on a spelling libyaml does not resolve (Null, NULL): sops makes it a
348 # null, which is hashed as nothing at all; dropping the tag makes
349 # it the string `Null`.
350 # !!value !!set !!omap !!seq !!map on a scalar: sops leaves the text verbatim
351 # under type:str, but only because the tag suppressed its own
352 # resolver -- `!!value 1` is the string `1` there and would be
353 # the integer 1 here.
354 #
355 # So those are REFUSED, by name, saying what sops resolves the tag to. That is
356 # all this changes for them: they died before and they die now, with a message
357 # about the document instead of one about libyaml. !!str, !!int, !!float and
358 # !!merge are not spoken for here -- the first three YAML::XS reads, and the
359 # fourth is the repair above -- so a document that fails on one of them keeps
360 # libyaml's own message, unchanged.
361  
362 91 my $BOOL_TAG = 'tag:yaml.org,2002:bool';
363  
364 # Same lexical position as the merge tag, plus the node itself: the tag is only
365 # removed from a PLAIN `true`/`false` ending the node, which is the only
366 # spelling measured to be equivalent. Every other spelling fails the count
367 # reconciliation below and lands in the refusal instead.
368 91 my $BOOL_TAG_ON_A_PLAIN_BOOLEAN = qr/
369 ( ^[ \t]* (?: -[ \t]+ )* | :[ \t]+ | -[ \t]+ )
370 !!bool [ \t]+
371 (?= (?: true | false ) [ \t]* (?: \# | $ ) )
372 /mx;
373  
374 40 ▶sub _without_redundant_tags {
Subroutine _without_redundant_tags: called CC=3 SCAR=11.0
375 38 my ($content) = @_;
376  
377 # Composed, not chained: a document may carry both, and each repair is
378 # reconciled against its own count. Either one landing is enough to retry.
379 38 my $repaired = _without_merge_tags($content);
380 38 ▶ my $with_bools = _without_bool_tags(defined $repaired ? $repaired : $content);
Branch: 1 branch
BranchTrueFalseTotal
defined $repaired ? : 10 28 38
381 38 ▶ return defined $with_bools ? $with_bools : $repaired;
Branch: 1 branch
BranchTrueFalseTotal
defined $with_bools ? : 12 26 38
382 }
383  
384 40 ▶sub _without_bool_tags {
Subroutine _without_bool_tags: called CC=5 SCAR=16.1
385 38 my ($content) = @_;
386  
387 38 ▶ return unless $content =~ /!!bool/;
Branch: 1 branch
BranchTrueFalseTotal
unless $content =~ /!!bool/ 23 15 38
388  
389 15 my $wanted = _plain_boolean_tagged_scalars($content);
390 15 ▶ return unless $wanted;
Branch: 1 branch
BranchTrueFalseTotal
unless $wanted 2 13 15
391  
392 13 my $stripped = $content;
393 # s///g returns the empty string, not 0, when it matches nothing.
394 13 ▶ my $removed = ($stripped =~ s/$BOOL_TAG_ON_A_PLAIN_BOOLEAN/$1/g) || 0;
Condition50%1/2
$stripped =~ s/$BOOL_TAG_ON_A_PLAIN_BOOLEAN/$1/g || 0
l!l
130
MC/DC0%0/1
$stripped =~ s/$BOOL_TAG_ON_A_PLAIN_BOOLEAN/$1/g || 0
$stripped =~ s/$BOOL_TAG_ON_A_PLAIN_BOOLEAN/$1/g
Truth table50%1/2
A
A= $stripped =~ s/$BOOL_TAG_ON_A_PLAIN_BOOLEAN/$1/g
Aresult
11
00
395  
396 13 ▶ return unless $removed == $wanted;
Branch: 1 branch
BranchTrueFalseTotal
unless $removed == $wanted 1 12 13
397 12 return $stripped;
398 }
399  
400 # The count is deliberately NOT "how many !!bool tags are in the document" but
401 # "how many of them sit on a plain true/false" -- the ones the substitution is
402 # allowed to touch. A document mixing `!!bool true` with `!!bool True` therefore
403 # has its equivalent tag removed, fails the parse again on the other one, and
404 # gets the refusal that names it. Fails safe like its merge twin: a document
405 # YAML::PP refuses counts as nothing to repair.
406 17 ▶sub _plain_boolean_tagged_scalars {
Subroutine _plain_boolean_tagged_scalars: called CC=3 SCAR=11.0
407 15 my ($content) = @_;
408  
409 15 my $text = $content;
410 15 ▶ utf8::decode($text) unless utf8::is_utf8($text);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($text) 15 0 15
411  
412 15 my $count = 0;
413 15 my $ok = eval {
414 146 ▶ YAML::PP::Parser->new(receiver => sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
415 144 my (undef, $name, $event) = @_;
416 144 ▶ return unless $name eq 'scalar_event';
Branch: 1 branch
BranchTrueFalseTotal
unless $name eq "scalar_event" 98 46 144
417 46 ▶ return unless ($event->{tag} // '') eq $BOOL_TAG;
Branch: 1 branch
BranchTrueFalseTotal
unless ($event->{"tag"} // "") eq $BOOL_TAG 28 18 46
Condition100%2/2
$event->{"tag"} // ""
l!l
1927
MC/DC100%1/1
$event->{"tag"} // ""
$event->{"tag"}
Truth table100%2/2
A
A= $event->{"tag"}
Aresult
11
00
418 18 ▶ return unless ($event->{style} // 0) == YAML_PLAIN_SCALAR_STYLE;
Branch: 1 branch
BranchTrueFalseTotal
unless ($event->{"style"} // 0) == 1 1 17 18
Condition50%1/2
$event->{"style"} // 0
l!l
180
MC/DC0%0/1
$event->{"style"} // 0
$event->{"style"}
Truth table50%1/2
A
A= $event->{"style"}
Aresult
11
00
419 17 ▶ $count++ if $event->{value} eq 'true' || $event->{value} eq 'false';
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"value"} eq "true" or $event->{"value"} eq "false" 15 2 17
Condition100%3/3
$event->{"value"} eq "true" or $event->{"value"} eq "false"
l!l&&r!l&&!r
1052
MC/DC100%2/2
$event->{"value"} eq "true" or $event->{"value"} eq "false"
$event->{"value"} eq "true" $event->{"value"} eq "false"
Truth table100%3/3
A or B
A= $event->{"value"} eq "true"B= $event->{"value"} eq "false"
ABresult
1X1
011
000
420 15 })->parse_string($text);
421 15 1;
422 };
423  
424 15 ▶ return unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 15 15
425 15 return $count;
426 }
427  
428 # Which scalar tags this module has measured and can therefore speak about, and
429 # for each one whether THIS scalar is readable here. A tag outside the table is
430 # left to libyaml.
431 my %TAG_IS_READABLE = (
432 7 ▶ binary => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
433 1 ▶ timestamp => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
434 1 ▶ value => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
435 1 ▶ set => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
436 0 ▶ omap => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=6.9
437 0 ▶ seq => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=6.9
438 0 ▶ map => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=6.9
439 6 ▶ bool => sub {
Subroutine __ANON__: called CC=4 SCAR=14.2
440 6 my ($event) = @_;
441 6 ▶ return 0 unless ($event->{style} // 0) == YAML_PLAIN_SCALAR_STYLE;
Branch: 1 branch
BranchTrueFalseTotal
unless ($event->{"style"} // 0) == 1 1 5 6
Condition50%1/2
$event->{"style"} // 0
l!l
60
MC/DC0%0/1
$event->{"style"} // 0
$event->{"style"}
Truth table50%1/2
A
A= $event->{"style"}
Aresult
11
00
442 5 ▶ return $event->{value} eq 'true' || $event->{value} eq 'false';
Condition66%2/3
$event->{'value'} eq 'true' || $event->{'value'} eq 'false'
l!l&&r!l&&!r
302
MC/DC50%1/2
$event->{'value'} eq 'true' || $event->{'value'} eq 'false'
$event->{'value'} eq 'true' $event->{'value'} eq 'false'
Truth table66%2/3
A || B
A= $event->{'value'} eq 'true'B= $event->{'value'} eq 'false'
ABresult
1X1
011
000
443 },
444 1 ▶ null => sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
445 1 my ($event) = @_;
446 1 ▶ return $event->{value} =~ /\A(?: | ~ | null )\z/x ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$event->{'value'} =~ /\A(?: | ~ | null )\z/x ? : 0 1 1
447 },
448 91 );
449  
450 91 my %TAG_REFUSAL = (
451 binary => 'sops resolves !!binary by base64-DECODING the scalar and '
452 . 'encrypting the decoded bytes -- measured against sops 3.13.3, '
453 . '`!!binary aGVsbG8=` becomes the value `hello` under type:str, and '
454 . 'those decoded bytes are what its MAC covers. Removing the tag here '
455 . 'would encrypt the base64 text instead: a different value, a '
456 . 'different digest, and a document that disagrees with the one sops '
457 . 'writes from the same plaintext. Decode the value yourself and write '
458 . 'it as a plain scalar, or quote the base64 text to keep it a string '
459 . 'on both sides',
460 timestamp => 'sops resolves !!timestamp to a Go time.Time and re-renders '
461 . 'it in RFC3339 under type:time -- measured against sops 3.13.3, '
462 . '`2026-08-21` becomes `2026-08-21T00:00:00Z` and '
463 . '`2001-12-14t21:59:43.10-05:00` becomes `2001-12-14T21:59:43.1-05:00` '
464 . '-- and that rendering is what its MAC covers. This module has no '
465 . 'date type and would keep the source spelling as a string, so the two '
466 . 'would digest different bytes. Remove the tag and quote the scalar to '
467 . 'make it a string on both sides, or write the RFC3339 form sops would '
468 . 'have written',
469 bool => 'File::SOPS supports !!bool on a plain `true` or `false`, where the '
470 . 'tag carries nothing and is dropped before parsing -- measured '
471 . 'against sops 3.13.3, `!!bool true` and a bare `true` produce the '
472 . 'identical document, type:bool with the plaintext True, down to the '
473 . 'MAC. This scalar is spelled some other way. sops also resolves '
474 . 'True, False, TRUE and FALSE under the tag; libyaml leaves those a '
475 . 'string, so File::SOPS would write type:str where sops writes '
476 . 'type:bool. Spell the value `true` or `false`',
477 null => 'File::SOPS reads !!null on `~`, `null` or an empty scalar. sops '
478 . 'also resolves Null and NULL, and a null is hashed as nothing at all, '
479 . 'so removing the tag would turn a value the MAC does not cover into a '
480 . 'string it does. Spell the value `null`',
481 );
482  
483 91 my $TAG_REFUSAL_GENERIC =
484 'YAML::XS accepts only !!str, !!int and !!float on a scalar. sops '
485 . 'resolves this tag and writes the resolved value without it -- measured '
486 . 'against sops 3.13.3, a scalar under !!value, !!set, !!omap, !!seq or '
487 . '!!map keeps its text under type:str, which is NOT what removing the tag '
488 . 'would give here (`!!value 1` is the string `1` there and the integer 1 '
489 . 'here). Remove the tag and write the value sops would have written';
490  
491 # Runs only on a document YAML::XS has already refused. It answers from the
492 # document rather than from libyaml's message, which names whichever tag it
493 # reached first and not necessarily the one that is still there after a repair.
494 # No value is ever quoted back: an error message is no place for plaintext
495 # (the same rule every guard in this distribution follows).
496 20 ▶sub _refuse_unreadable_tag {
Subroutine _refuse_unreadable_tag: called CC=3 SCAR=11.0
497 20 my ($content, $load_error) = @_;
498  
499 20 my ($where, $tag) = _first_unreadable_tag($content);
500 20 ▶ die $load_error unless defined $tag;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tag 6 14 20
501  
502 croak sprintf(
503 '%s: this document tags a scalar !!%s, which File::SOPS cannot read. %s.',
504 14 ▶ $where, $tag, ($TAG_REFUSAL{$tag} // $TAG_REFUSAL_GENERIC)
Condition66%2/3
$TAG_REFUSAL{$tag} // $TAG_REFUSAL_GENERIC
l!l&&r!l&&!r
1220
MC/DC0%0/2
$TAG_REFUSAL{$tag} // $TAG_REFUSAL_GENERIC
$TAG_REFUSAL{$tag} $TAG_REFUSAL_GENERIC
Truth table66%2/3
A // B
A= $TAG_REFUSAL{$tag}B= $TAG_REFUSAL_GENERIC
ABresult
1X1
011
000
505 );
506 }
507  
508 # The key path is tracked the way the rest of this distribution paths a leaf:
509 # mapping keys join with a colon and a sequence contributes NO component, which
510 # is the AAD rule (see File::SOPS::_encrypt_tree). Fails safe -- a document
511 # YAML::PP cannot parse either yields no tag and leaves libyaml's message.
512 20 ▶sub _first_unreadable_tag {
Subroutine _first_unreadable_tag: called CC=4 SCAR=13.9
513 20 my ($content) = @_;
514  
515 20 my $text = $content;
516 20 ▶ utf8::decode($text) unless utf8::is_utf8($text);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($text) 20 0 20
517  
518 20 my (@stack, $found);
519 48 ▶ my $close_value = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
520 48 ▶ return unless @stack && $stack[-1]{kind} eq 'map';
Branch: 1 branch
BranchTrueFalseTotal
unless @stack and $stack[-1]{"kind"} eq "map" 21 27 48
Condition100%3/3
@stack and $stack[-1]{"kind"} eq "map"
!ll&&!rl&&r
17427
MC/DC100%2/2
@stack and $stack[-1]{"kind"} eq "map"
@stack $stack[-1]{"kind"} eq "map"
Truth table100%3/3
A and B
A= @stackB= $stack[-1]{"kind"} eq "map"
ABresult
0X0
100
111
521 27 $stack[-1]{expect} = 'key';
522 20 };
523 55 ▶ my $inspect = sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
524 55 my ($event) = @_;
525 55 ▶ return if $found;
Branch: 1 branch
BranchTrueFalseTotal
if $found 0 55 55
526 55 ▶ my $tag = $event->{tag} // '';
Condition100%2/2
$event->{"tag"} // ""
l!l
2035
MC/DC100%1/1
$event->{"tag"} // ""
$event->{"tag"}
Truth table100%2/2
A
A= $event->{"tag"}
Aresult
11
00
527 55 ▶ return unless $tag =~ m{\Atag:yaml\.org,2002:(\w+)\z};
Branch: 1 branch
BranchTrueFalseTotal
unless $tag =~ /\Atag:yaml\.org,2002:(\w+)\z/ 35 20 55
528 20 my $short = $1;
529 20 ▶ my $readable = $TAG_IS_READABLE{$short} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $readable = $TAG_IS_READABLE{$short} or return 17 3 20
530 17 ▶ return if $readable->($event);
Branch: 1 branch
BranchTrueFalseTotal
if &$readable($event) 3 14 17
531 14 my @path = map { $_->{key} } grep { defined $_->{key} } @stack;
532 14 ▶ $found = [ (@path ? join(':', @path) : '(document root)'), $short ];
Branch: 1 branch
BranchTrueFalseTotal
@path ? : 13 1 14
533 20 };
534  
535 20 my $ok = eval {
536 181 ▶ YAML::PP::Parser->new(receiver => sub {
Subroutine __ANON__: called CC=14 SCAR=26.5
537 181 my (undef, $name, $event) = @_;
538 181 ▶ if ($name eq 'mapping_start_event') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "mapping_start_event") 26 155 181
539 26 ▶ $close_value->() if @stack && $stack[-1]{kind} eq 'seq';
Branch: 1 branch
BranchTrueFalseTotal
if @stack and $stack[-1]{"kind"} eq "seq" 0 26 26
Condition66%2/3
@stack and $stack[-1]{"kind"} eq "seq"
!ll&&!rl&&r
1970
MC/DC0%0/2
@stack and $stack[-1]{"kind"} eq "seq"
@stack $stack[-1]{"kind"} eq "seq"
Truth table66%2/3
A and B
A= @stackB= $stack[-1]{"kind"} eq "seq"
ABresult
0X0
100
111
540 26 push @stack, { kind => 'map', expect => 'key' };
541 26 return;
542 }
543 155 ▶ if ($name eq 'sequence_start_event') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "sequence_start_event") 3 152 155
544 3 push @stack, { kind => 'seq' };
545 3 return;
546 }
547 152 ▶ if ($name eq 'mapping_end_event' || $name eq 'sequence_end_event') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "mapping_end_event" or $name eq "sequence_end_event") 23 129 152
Condition100%3/3
$name eq "mapping_end_event" or $name eq "sequence_end_event"
l!l&&r!l&&!r
221129
MC/DC100%2/2
$name eq "mapping_end_event" or $name eq "sequence_end_event"
$name eq "mapping_end_event" $name eq "sequence_end_event"
Truth table100%3/3
A or B
A= $name eq "mapping_end_event"B= $name eq "sequence_end_event"
ABresult
1X1
011
000
548 23 pop @stack;
549 23 $close_value->();
550 23 return;
551 }
552 129 ▶ return unless $name eq 'scalar_event' || $name eq 'alias_event';
Branch: 1 branch
BranchTrueFalseTotal
unless $name eq "scalar_event" or $name eq "alias_event" 74 55 129
Condition66%2/3
$name eq "scalar_event" or $name eq "alias_event"
l!l&&r!l&&!r
55074
MC/DC50%1/2
$name eq "scalar_event" or $name eq "alias_event"
$name eq "scalar_event" $name eq "alias_event"
Truth table66%2/3
A or B
A= $name eq "scalar_event"B= $name eq "alias_event"
ABresult
1X1
011
000
553 55 ▶ if (@stack && $stack[-1]{kind} eq 'map' && $stack[-1]{expect} eq 'key') {
Branch: 1 branch
BranchTrueFalseTotal
if (@stack and $stack[-1]{"kind"} eq "map" and $stack[-1]{"expect"} eq "key") 30 25 55
Condition100%6/6
@stack and $stack[-1]{"kind"} eq "map" and $stack[-1]{"expect"} eq "key"
!ll&&!rl&&r
52030
@stack and $stack[-1]{"kind"} eq "map"
!ll&&!rl&&r
1450
MC/DC100%3/3
@stack and $stack[-1]{"kind"} eq "map" and $stack[-1]{"expect"} eq "key"
@stack $stack[-1]{"kind"} eq "map" $stack[-1]{"expect"} eq "key"
Truth table100%4/4
A and B and C
A= @stackB= $stack[-1]{"kind"} eq "map"C= $stack[-1]{"expect"} eq "key"
ABCresult
0XX0
10X0
1100
1111
554 30 ▶ $inspect->($event) if $name eq 'scalar_event';
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "scalar_event" 30 0 30
555 30 $stack[-1]{key} = $event->{value};
556 30 $stack[-1]{expect} = 'value';
557 30 return;
558 }
559 25 ▶ $inspect->($event) if $name eq 'scalar_event';
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "scalar_event" 25 0 25
560 25 $close_value->();
561 20 })->parse_string($text);
562 17 1;
563 };
564  
565 20 ▶ return unless $ok && $found;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok and $found 6 14 20
Condition100%3/3
$ok and $found
!ll&&!rl&&r
3314
MC/DC100%2/2
$ok and $found
$ok $found
Truth table100%3/3
A and B
A= $okB= $found
ABresult
0X0
100
111
566 14 return @$found;
567 }
568  
569 ###############################################################################
570 # A comment sops wrote as a list element (k108, k76, docs/adr/0041)
571 #
572 # sops attaches a YAML comment to the node that FOLLOWS it. Above a mapping key
573 # that is a `#ENC[...,type:comment]` line, which YAML::XS discards before this
574 # module sees it -- and sops does not hash it either, so both sides agree and
575 # the document reads correctly. Above a SEQUENCE entry there is no comment line
576 # to write, so sops emits the comment as a real element:
577 #
578 # list:
579 # - ENC[AES256_GCM,...,type:comment]
580 # - ENC[AES256_GCM,...,type:str]
581 #
582 # and every parser keeps it. THIS MODULE NO LONGER GUARDS AGAINST THAT. Under
583 # docs/adr/0024 parse croaked on any type:comment leaf, because reading one as a
584 # value put a string in the caller's list that the file does not contain
585 # (k108). Under docs/adr/0041 the leaf is PRESERVED instead: File::SOPS
586 # decrypts it into a File::SOPS::Comment, keeps it at its index, leaves it out
587 # of the digest -- measured, that is exactly the digest sops computes -- and
588 # writes it back as a type:comment element. There is nothing left for a parse
589 # guard to catch, and the two refusals that remain are on the WRITE side, where
590 # the shape is one no SOPS store writes (File::SOPS::_encrypt_tree, and
591 # _reject_unwritable_leaf below for a comment this emitter is asked to write as
592 # plain text). The read-side twin of the first lives in File::SOPS::_decrypt_tree
593 # rather than here, because the same document is read through the JSON handler
594 # too -- which never had this guard, and carried k108's defect unnoticed
595 # the whole time (measured against sops 3.13.3: `sops -e --output-type json`
596 # writes type:comment leaves into JSON).
597 #
598 # Mapping-position comments are unchanged and remain the open half of k76:
599 # YAML::XS drops them on the way in and no emitter here can write one.
600  
601 ###############################################################################
602 # A literal libyaml numifies past the end of a double (k102, docs/adr/0023)
603 #
604 # `1e400`, a 401-digit integer, `Inf`, `NaN`: libyaml resolves each of them to a
605 # number, and the number it lands on is +Inf, -Inf or NaN. go-yaml resolves none
606 # of them -- strconv.ParseFloat answers ErrRange and yaml.v3 keeps a STRING --
607 # so sops writes `type:str` and digests the token's own bytes. Ours said `float`
608 # and digested `+Inf`, which is a document sops wrote that we cannot read and a
609 # value we cannot write.
610 #
611 # The repair is at PARSE time and nowhere else, because what is wrong is our
612 # parse result and not any guard downstream. _go_scalar_bytes already models the
613 # Go side correctly for all 29 spellings measured; detect_type already reads the
614 # SV and nothing else (ADR 0002); the non-finite guard from k59 is right
615 # about every value it was written for and is untouched here. What this does is
616 # hand the rest of the distribution the leaf go-yaml sees.
617 #
618 # The predicate is the SV, not the text (ADR 0002): a leaf whose PUBLIC SVf_NOK
619 # and SVf_POK are both set and whose NV is NaN or +-Inf. It cannot collide with
620 # the tokens Go DOES resolve to a non-finite float -- `.inf .Inf .INF +.inf
621 # +.Inf +.INF -.inf -.Inf -.INF .nan .NaN .NAN`, the twelve in %GO_CONSTANT --
622 # because YAML::XS hands every one of those back POK-ONLY. Measured against
623 # sops 3.13.3: those twelve are `type:float` to sops and fire nothing here; the
624 # 29 spellings that do fire are `type:str` to sops, every one. The two sets are
625 # disjoint, and that disjointness is what keeps this from retyping a leaf Go
626 # reads as a float.
627 #
628 # JSON is deliberately NOT walked. sops refuses such a JSON document at
629 # unmarshal time (`strconv.ParseFloat: value out of range`, exit 2), so the
630 # croak Format::JSON's leaf earns there is the reference behaviour -- see
631 # ADR 0020, which predicted this lever and expected it to answer for both
632 # parsers at once. Measured, it must not.
633 91 my $POSITIVE_INFINITY = 9**9**9;
634  
635 36936 ▶sub _restring_non_finite_leaves {
Subroutine _restring_non_finite_leaves: called CC=8 SCAR=20.8
636 93 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
637 36936 my ($node, $seen) = @_;
638  
639 # A recursive YAML anchor (`root: &a\n b: *a`) really does come back from
640 # YAML::XS as a cycle, so this walk carries its own visited set. That keeps
641 # THIS walk terminating; the encrypt and decrypt walks do not and hang on
642 # such a document today, which is k110 and not widened into here.
643 36936 ▶ return if $seen->{refaddr($node)}++;
Branch: 1 branch
BranchTrueFalseTotal
if $$seen{builtin::refaddr($node)}++ 201 36735 36936
644  
645 36735 ▶ if (ref $node eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $node eq 'HASH') { } 36604 131 36735
elsif (ref $node eq 'ARRAY') { } 93 38 131
646 36604 for my $key (keys %$node) {
647 ref $node->{$key}
648 ? _restring_non_finite_leaves($node->{$key}, $seen)
649 40572 ▶ : _restring_non_finite_leaf($node->{$key});
Branch: 1 branch
BranchTrueFalseTotal
ref $node->{$key} ? : 35977 4595 40572
650 }
651 }
652 elsif (ref $node eq 'ARRAY') {
653 93 for my $entry (@$node) {
654 197 ▶ ref $entry
Branch: 1 branch
BranchTrueFalseTotal
ref $entry ? : 35 162 197
655 ? _restring_non_finite_leaves($entry, $seen)
656 : _restring_non_finite_leaf($entry);
657 }
658 }
659  
660 36735 return;
661 }
662  
663 # $_[0] is the caller's element by alias, deliberately: the flags are read off
664 # the SV the tree holds rather than off a copy, and the replacement is written
665 # back into the same slot. Nothing here numifies anything -- B reads the NV and
666 # the PV out of the SV's own slots, so this cannot retype a scalar the way a
667 # numeric comparison on it would (k32).
668 4757 ▶sub _restring_non_finite_leaf {
Subroutine _restring_non_finite_leaf: called CC=8 SCAR=20.8
669 4757 ▶ return unless defined $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 6 4751 4757
670  
671 4751 my $sv = B::svref_2object(\$_[0]);
672 4751 my $flags = $sv->FLAGS;
673 4751 ▶ return unless ($flags & B::SVf_NOK()) && ($flags & B::SVf_POK());
Branch: 1 branch
BranchTrueFalseTotal
unless $flags & 512 and $flags & 1024 4691 60 4751
Condition66%2/3
$flags & 512 and $flags & 1024
!ll&&!rl&&r
4691060
MC/DC50%1/2
$flags & 512 and $flags & 1024
$flags & 512 $flags & 1024
Truth table66%2/3
A and B
A= $flags & 512B= $flags & 1024
ABresult
0X0
100
111
674  
675 60 my $nv = $sv->NV;
676 60 ▶ return unless $nv != $nv
Branch: 1 branch
BranchTrueFalseTotal
unless $nv != $nv or $nv == $POSITIVE_INFINITY or $nv == -$POSITIVE_INFINITY 18 42 60
Condition100%6/6
$nv != $nv or $nv == $POSITIVE_INFINITY or $nv == -$POSITIVE_INFINITY
l!l&&r!l&&!r
37518
$nv != $nv or $nv == $POSITIVE_INFINITY
l!l&&r!l&&!r
82923
MC/DC100%3/3
$nv != $nv or $nv == $POSITIVE_INFINITY or $nv == -$POSITIVE_INFINITY
$nv != $nv $nv == $POSITIVE_INFINITY $nv == -$POSITIVE_INFINITY
Truth table100%4/4
A or B or C
A= $nv != $nvB= $nv == $POSITIVE_INFINITYC= $nv == -$POSITIVE_INFINITY
ABCresult
1XX1
01X1
0011
0000
677 || $nv == $POSITIVE_INFINITY
678 || $nv == -$POSITIVE_INFINITY;
679  
680 # The string half is what go-yaml kept, so it is what replaces the number.
681 # An empty one is not a token Go reads as anything but a null, and there is
682 # nothing to hand back, so the leaf is left exactly as it came.
683 42 my $pv = $sv->PV;
684 42 ▶ return unless length $pv;
Branch: 1 branch
BranchTrueFalseTotal
unless length $pv 0 42 42
685  
686 42 $_[0] = $pv;
687 42 return;
688 }
689  
690 ###############################################################################
691 # A bare leading-zero integer libyaml and Go disagree about (k127, docs/adr/0054)
692 #
693 # `v: 0755` is parsed by YAML::XS as a Perl dualvar: POK with PV="0755", IOK
694 # with IV=755. go-yaml's resolver reads `0755` through strconv.ParseInt(_, 0, 64),
695 # which interprets a leading zero as octal and reads it as 493. sops digests the
696 # bytes Go produced -- so a document f-sops wrote (data:"755") and a document
697 # sops wrote (data:"493") were both verified by their own readers, and neither
698 # could read the other; on a wire that crosses implementations the encrypted-slot
699 # value was silently different.
700 #
701 # The fix is the same shape _restring_non_finite_leaves uses -- a tree walk that
702 # reads the SV's own flags and rewrites the integer leaves whose PV is a bare
703 # leading-zero token, leaving a non-disagreeing leaf alone. The whole scalar is
704 # replaced with the integer Go reads, dropping the source spelling: a
705 # dualvar(493, "0755") is exactly the shape Encrypted::assert_representable
706 # refuses (a value that carries its own, different string form), so carrying
707 # the PV across would just trade today's silent value divergence for today's
708 # loud dualvar refusal. The repaired leaf is a plain integer Go's number, the
709 # digest covers Go's number, the emitter writes Go's number, and the whole
710 # chain is one value the MAC covers and sops reads -- which is the entire
711 # shape the encrypted slot has been missing, and the unencrypted slot gets as
712 # a side effect because the slot is the slot the parse handed back.
713 #
714 # PREDICATE, measured, on eight spellings of the same family:
715 #
716 # "0755" POK+IOK+PV="0755"+IV=755 => becomes 493, plain int (the ticket)
717 # "010" POK+IOK+PV="010"+IV=8 => already agrees, no-op
718 # "017" POK+IOK+PV="017"+IV=15 => already agrees, no-op
719 # "007" POK+IOK+PV="007"+IV=7 => already agrees (7 is 7 in both bases)
720 # "0o10" POK-only (PV="0o10") => predicate skips, no repair (string PV)
721 # "0x1f" POK-only (PV="0x1f") => predicate skips, no repair
722 # "1_000" POK-only (PV="1_000") => predicate skips, no repair (string PV)
723 # "0755e0" POK+IOK+NOK+PV="0755e0" => predicate skips (not bare integer syntax)
724 #
725 # So the predicate is exactly: scalar with SVf_IOK, PV present, PV matches
726 # /\A[+-]?0\d+\z/, _go_scalar_bytes(PV) returns a decimal that does not equal
727 # IV. Anything else is left alone. The mirror order to the call below is
728 # exactly the order from _restring_non_finite_leaves -- AFTER the non-finite
729 # repair, which can produce its own dualvar and which reads NOK+POK, never IOK,
730 # so the two predicates do not collide.
731  
732 36936 ▶sub _go_repair_int_leaves {
Subroutine _go_repair_int_leaves: called CC=8 SCAR=20.8
733 93 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
734 36936 my ($node, $seen) = @_;
735  
736 36936 ▶ return if $seen->{refaddr($node)}++;
Branch: 1 branch
BranchTrueFalseTotal
if $$seen{builtin::refaddr($node)}++ 201 36735 36936
737  
738 36735 ▶ if (ref $node eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $node eq 'HASH') { } 36604 131 36735
elsif (ref $node eq 'ARRAY') { } 93 38 131
739 36604 for my $key (keys %$node) {
740 ref $node->{$key}
741 ? _go_repair_int_leaves($node->{$key}, $seen)
742 40572 ▶ : _go_repair_int_leaf($node->{$key});
Branch: 1 branch
BranchTrueFalseTotal
ref $node->{$key} ? : 35977 4595 40572
743 }
744 }
745 elsif (ref $node eq 'ARRAY') {
746 93 for my $entry (@$node) {
747 197 ▶ ref $entry
Branch: 1 branch
BranchTrueFalseTotal
ref $entry ? : 35 162 197
748 ? _go_repair_int_leaves($entry, $seen)
749 : _go_repair_int_leaf($entry);
750 }
751 }
752  
753 36735 return;
754 }
755  
756 # $_[0] is the caller's slot by alias, deliberately, and the rewrite is
757 # written back into the same place. The PV is dropped, not kept as a dualvar:
758 # a dualvar(493, "0755") is exactly the shape Encrypted::assert_representable
759 # refuses (a "value that carries its own, different string form" -- YAML::XS
760 # writes the string half, the digest covers the int, and the two disagree).
761 # So the repaired scalar is a plain integer Go's number, with no public PV,
762 # and the assert_representable check at Encrypted.pm line 1596 skips it
763 # entirely: _has_public_pv is false and the int branch is bypassed. The same
764 # is what sops itself does on the parse side -- it loses the source spelling
765 # of `0755` because Go's resolver reads it as the integer 493, and that is
766 # the trailing edge of k127.
767 4757 ▶sub _go_repair_int_leaf {
Subroutine _go_repair_int_leaf: called CC=9 SCAR=22.4
768 4757 ▶ return unless defined $_[0] and !ref $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and not ref $_[0] 6 4751 4757
Condition66%2/3
defined $_[0] and not ref $_[0]
!ll&&!rl&&r
604751
MC/DC50%1/2
defined $_[0] and not ref $_[0]
defined $_[0] not ref $_[0]
Truth table66%2/3
A and not(B)
A= defined $_[0]B= not ref $_[0]
ABresult
0X0
100
111
769  
770 4751 my $sv = B::svref_2object(\$_[0]);
771 4751 ▶ return unless $sv->FLAGS & B::SVf_IOK;
Branch: 1 branch
BranchTrueFalseTotal
unless $sv->FLAGS & 256 4666 85 4751
772  
773 85 my $pv = $sv->PV;
774 85 ▶ return unless length $pv;
Branch: 1 branch
BranchTrueFalseTotal
unless length $pv 0 85 85
775 85 ▶ return unless $pv =~ /\A[+-]?0\d+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $pv =~ /\A[+-]?0\d+\z/ 70 15 85
776  
777 15 my $go_bytes = _go_scalar_bytes($pv);
778 15 ▶ return unless defined $go_bytes && $go_bytes =~ /\A-?\d+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $go_bytes and $go_bytes =~ /\A-?\d+\z/ 0 15 15
Condition33%1/3
defined $go_bytes and $go_bytes =~ /\A-?\d+\z/
!ll&&!rl&&r
0015
MC/DC0%0/2
defined $go_bytes and $go_bytes =~ /\A-?\d+\z/
defined $go_bytes $go_bytes =~ /\A-?\d+\z/
Truth table33%1/3
A and B
A= defined $go_bytesB= $go_bytes =~ /\A-?\d+\z/
ABresult
0X0
100
111
779 15 ▶ return if $go_bytes + 0 == $sv->IV; # already agrees; no-op
Branch: 1 branch
BranchTrueFalseTotal
if $go_bytes + 0 == $sv->IV 9 6 15
780  
781 6 $_[0] = $go_bytes + 0;
782 6 return;
783 }
784  
785 ###############################################################################
786 # A YAML infinity the DOCUMENT wrote plain (k105, docs/adr/0026)
787 #
788 # The mirror image of the walk above, and it needs a different authority.
789 # libyaml leaves `.inf` a STRING; gopkg.in/yaml.v3 resolves it to the float
790 # +Inf, and sops digests `+Inf`. So a document sops writes and `sops -d`
791 # verifies failed its MAC here, naming nothing.
792 #
793 # What makes this repair unlike every other one in this distribution is that
794 # the missing fact is NOT in the SV. Measured against sops 3.13.3, one
795 # unencrypted slot per row:
796 #
797 # v_unencrypted: .inf Go: float +Inf, digested `+Inf` <- we digested `.inf`
798 # v_unencrypted: ".inf" Go: string, digested `.inf` <- we agree, today
799 #
800 # and YAML::XS hands back the SAME POK-only scalar for both. Both spellings
801 # also occur in ONE document as easily as in two -- measured, sops writes this
802 # and reads it back at exit 0:
803 #
804 # list_unencrypted:
805 # - .inf <- digested `+Inf`
806 # - ".inf" <- digested `.inf`
807 #
808 # So a repair keyed on the leaf's TEXT fixes the first row and silently breaks
809 # the second, which works today. The question is not what the value is; it is
810 # whether the document wrote the scalar PLAIN, and that is a fact about the
811 # bytes.
812 #
813 # YAML::PP -- already this distribution's second parser (ADR 0001) -- answers
814 # it. Its Core schema resolves a scalar to a non-finite number IFF the scalar
815 # was written plain and its token is one of the twelve in %GO_CONSTANT.
816 # Measured: 12 of 12 plain tokens yes; 0 of 24 quoted; 0 of 12 near misses
817 # (`.INf` `.iNF` `.Nan` `.NAn` `+.nan` `-.nan` `-.NAN` `.infinity` `.Infinity`
818 # `Inf` `inf` `NaN`), every one of which is a type:str to sops and reads
819 # correctly here today. On the WIRE -- which is what this path sees -- sops has
820 # already normalised `!!float .inf` and `&a .inf` to a bare `.inf` and
821 # `!!str .inf` and `'.inf'` to a quoted `".inf"`, so only those two spellings
822 # arrive, and the oracle separates them in all four cases.
823 #
824 # This is NOT the "ask YAML::PP instead of modelling Go" that ADR 0013 and
825 # ADR 0023 rejected. There the question was what a value IS, and YAML::PP
826 # answers it the way libyaml does -- `0755` is 755 to both and 493 to Go, so it
827 # agrees with the side that is already wrong. Here it is asked whether a scalar
828 # was written plain, which is syntax rather than resolution; the VALUE still
829 # comes from %GO_CONSTANT, and the token has to be in %GO_CONSTANT before
830 # YAML::PP is consulted at all.
831 #
832 # FOR EVERY DOCUMENT, PLAINTEXT INCLUDED (k123, docs/adr/0034). This was
833 # gated on a `sops:` section until 0.003, on the argument that a plaintext has
834 # no MAC for a foreign reader to disagree with and that ADR 0013's guard gives
835 # a better error on the encrypt path anyway -- "a worse message for no gain,
836 # since neither path can write the document".
837 #
838 # ADR 0031 removed the premise: an unencrypted YAML slot holding one of these
839 # tokens IS written now, byte-identical to what sops writes. So the gate was
840 # refusing three documents this library can produce, and the two parses
841 # disagreed about identical bytes -- measured, `decrypt_file` wrote
842 # `v_unencrypted: .inf` and `encrypt_file` refused to read its own output back.
843 # sops resolves a plain scalar the same way on every parse; so does this now.
844 #
845 # WHAT IS WRITTEN BACK is a dualvar, not a bare infinity, and that is measured
846 # rather than tidy: YAML::XS writes a bare non-finite NV as `Inf` / `-Inf` /
847 # `NaN`, tokens go-yaml resolves as STRINGS, and writes dualvar(+Inf, '.inf')
848 # as `.inf`, the token sops itself writes. So decrypt_file reproduces sops's
849 # own plaintext byte for byte instead of degrading the value on the first
850 # round trip. Same shape as ADR 0011's carrier: a float leaf whose string half
851 # is the text the document contains.
852 #
853 # Since k113 (docs/adr/0031) such a document is written back as well: the
854 # non-finite guard lets a leaf carrying one of these tokens through to
855 # ADR 0013's foreign-resolution guard, which measures the token the emitter
856 # really writes. An ENCRYPTED slot is still refused there (k122).
857 91 my $PLAIN_STYLE_LOADER = YAML::PP->new(schema => [qw( Core )]);
858  
859 909 ▶sub _restore_plain_infinities {
Subroutine _restore_plain_infinities: called CC=6 SCAR=18.0
860 909 my ($data, $content) = @_;
861  
862 # The cheapest gate first, and a sound one: a PLAIN scalar is literal text,
863 # so a token this walk could repair is in the raw bytes or it is nowhere.
864 # The only way the string `.inf` reaches a leaf without those four bytes
865 # being in the document is an escape in a QUOTED scalar, which this walk
866 # does not repair anyway -- so the pre-filter can only be conservative in
867 # the direction that changes nothing. A document that never mentions one
868 # pays a single scan and no tree walk at all.
869 909 ▶ return unless _go_non_finite_in_text($content);
Branch: 1 branch
BranchTrueFalseTotal
unless _go_non_finite_in_text($content) 691 218 909
870  
871 # Then the tree, because `config.info` and `.infrastructure` carry those
872 # bytes too: one flag per leaf and, for a leaf starting `.`, `+` or `-`,
873 # one hash lookup. YAML::PP parses nothing unless a candidate is really
874 # there.
875 218 ▶ return unless _has_plain_infinity_candidate($data, {});
Branch: 1 branch
BranchTrueFalseTotal
unless _has_plain_infinity_candidate($data, scalar {}) 18 200 218
876  
877 # FAIL SAFE, deliberately: YAML::PP is a second parser and refuses things
878 # YAML::XS accepts. Measured, the one that really occurs is a recursive
879 # anchor -- `Found cyclic ref for alias 'a'` where YAML::XS hands back a
880 # real Perl cycle -- and such a document is refused downstream anyway
881 # (k110). Nothing is repaired then, which is exactly today's behaviour
882 # and today's MAC error, never a partially repaired tree whose digest would
883 # be wrong in a new way.
884 200 my $theirs = eval { $PLAIN_STYLE_LOADER->load_string($content) };
885 200 ▶ return unless ref $theirs eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $theirs eq "HASH" 0 200 200
886 200 delete $theirs->{sops};
887  
888 # Collected first and applied only if the two trees turned out structurally
889 # identical, for the same reason.
890 200 my @fix;
891 200 ▶ return unless _pair_plain_infinities($data, $theirs, \@fix, {});
Branch: 1 branch
BranchTrueFalseTotal
unless _pair_plain_infinities($data, $theirs, \@fix, scalar {}) 0 200 200
892  
893 200 for my $entry (@fix) {
894 152 my ($slot, $token) = @$entry;
895 152 $$slot = dualvar(_go_non_finite_double($token), $token);
896 }
897  
898 200 return;
899 }
900  
901 # The multi-document counterpart of _restore_plain_infinities (docs/adr/0033
902 # Decision 4, ADR 0026). The single-document version reparses $content in scalar
903 # context, which yields the FIRST document only -- on a stream that would pair
904 # the first reparsed document against every value tree. Here the reparse is in
905 # LIST context, N documents, and each is paired against its own value tree by
906 # index. Everything else is the single-document version's mechanism unchanged:
907 # the same pre-filters, the same structural pairing that abandons the whole
908 # repair on any disagreement, the same fail-safe on a document YAML::PP refuses.
909 7 ▶sub _restore_plain_infinities_multi {
Subroutine _restore_plain_infinities_multi: called CC=13 SCAR=26.7
910 7 my ($documents, $content) = @_;
911  
912 7 ▶ return unless _go_non_finite_in_text($content);
Branch: 1 branch
BranchTrueFalseTotal
unless _go_non_finite_in_text($content) 6 1 7
913  
914 1 my $any = 0;
915 1 for my $doc (@$documents) {
916 2 ▶ $any = 1, last if _has_plain_infinity_candidate($doc, {});
Branch: 1 branch
BranchTrueFalseTotal
if _has_plain_infinity_candidate($doc, scalar {}) 1 1 2
917 }
918 1 ▶ return unless $any;
Branch: 1 branch
BranchTrueFalseTotal
unless $any 0 1 1
919  
920 # FAIL SAFE, as in the single-document path: a document YAML::PP refuses
921 # yields nothing, and nothing is repaired -- today's behaviour and today's
922 # MAC error, never a partially repaired tree.
923 1 my @theirs = eval { $PLAIN_STYLE_LOADER->load_string($content) };
924 1 ▶ return unless @theirs == @$documents;
Branch: 1 branch
BranchTrueFalseTotal
unless @theirs == @$documents 0 1 1
925 1 for my $t (@theirs) {
926 # An empty document reparses to undef; treat it as {} the way the value
927 # side does, so the structural pairing lines up.
928 2 ▶ $t = {} unless defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 0 2 2
929 2 ▶ return unless ref $t eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $t eq "HASH" 0 2 2
930 }
931 # The value trees had `sops` stripped from every document; strip it from
932 # every reparsed document too, or the key-set comparison in
933 # _pair_plain_infinities would disagree on the metadata-bearing ones.
934 1 delete $_->{sops} for @theirs;
935  
936 1 my @fix;
937 1 for my $i (0 .. $#$documents) {
938 2 ▶ return unless _pair_plain_infinities($documents->[$i], $theirs[$i],
Branch: 1 branch
BranchTrueFalseTotal
unless _pair_plain_infinities($documents->[$i], $theirs[$i], \@fix, scalar {}) 0 2 2
939 \@fix, {});
940 }
941  
942 1 for my $entry (@fix) {
943 0 my ($slot, $token) = @$entry;
944 0 $$slot = dualvar(_go_non_finite_double($token), $token);
945 }
946  
947 1 return;
948 }
949  
950 453 ▶sub _has_plain_infinity_candidate {
Subroutine _has_plain_infinity_candidate: called CC=10 SCAR=23.4
951 453 my ($node, $seen) = @_;
952  
953 453 ▶ if (ref $node eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node eq "HASH") 220 233 453
954 220 ▶ return 0 if $seen->{refaddr($node)}++;
Branch: 1 branch
BranchTrueFalseTotal
if $$seen{builtin::refaddr($node)}++ 0 220 220
955 _has_plain_infinity_candidate($node->{$_}, $seen) and return 1
956 220 ▶ for keys %$node;
Branch: 1 branch
BranchTrueFalseTotal
_has_plain_infinity_candidate($node->{$_}, $seen) and return 1 201 28 229
957 19 return 0;
958 }
959 233 ▶ if (ref $node eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node eq "ARRAY") 3 230 233
960 3 ▶ return 0 if $seen->{refaddr($node)}++;
Branch: 1 branch
BranchTrueFalseTotal
if $$seen{builtin::refaddr($node)}++ 0 3 3
961 3 ▶ _has_plain_infinity_candidate($_, $seen) and return 1 for @$node;
Branch: 1 branch
BranchTrueFalseTotal
_has_plain_infinity_candidate($_, $seen) and return 1 3 1 4
962 0 return 0;
963 }
964 230 ▶ return 0 if ref $node;
Branch: 1 branch
BranchTrueFalseTotal
if ref $node 0 230 230
965 230 return defined _plain_infinity_token($node);
966 }
967  
968 # The two trees walked side by side, the way _document_leaves already pairs the
969 # ordered reparse against the real one (ADR 0001). Any disagreement about shape
970 # -- a container against a leaf, a different key set, a different length --
971 # abandons the whole repair rather than guessing which side is right.
972 431 ▶sub _pair_plain_infinities {
Subroutine _pair_plain_infinities: called CC=17 SCAR=29.7
973 431 my ($ours, $theirs, $fix, $seen) = @_;
974  
975 431 ▶ if (ref $ours eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $ours eq "HASH") 204 227 431
976 204 ▶ return 0 unless ref $theirs eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $theirs eq "HASH" 0 204 204
977 204 ▶ return 1 if $seen->{refaddr($ours)}++;
Branch: 1 branch
BranchTrueFalseTotal
if $$seen{builtin::refaddr($ours)}++ 0 204 204
978 204 ▶ return 0 unless keys %$ours == keys %$theirs;
Branch: 1 branch
BranchTrueFalseTotal
unless keys %$ours == keys %$theirs 0 204 204
979 204 for my $key (keys %$ours) {
980 220 ▶ return 0 unless exists $theirs->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $theirs->{$key} 0 220 220
981 return 0
982 220 ▶ unless _pair_plain_infinities($ours->{$key}, $theirs->{$key},
Branch: 1 branch
BranchTrueFalseTotal
unless _pair_plain_infinities($ours->{$key}, $theirs->{$key}, $fix, $seen) 0 220 220
983 $fix, $seen);
984 220 my $token = _plain_infinity_leaf($ours->{$key}, $theirs->{$key});
985 220 ▶ push @$fix, [ \$ours->{$key}, $token ] if defined $token;
Branch: 1 branch
BranchTrueFalseTotal
if defined $token 149 71 220
986 }
987 204 return 1;
988 }
989  
990 227 ▶ if (ref $ours eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $ours eq "ARRAY") 3 224 227
991 3 ▶ return 0 unless ref $theirs eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $theirs eq "ARRAY" 0 3 3
992 3 ▶ return 1 if $seen->{refaddr($ours)}++;
Branch: 1 branch
BranchTrueFalseTotal
if $$seen{builtin::refaddr($ours)}++ 0 3 3
993 3 ▶ return 0 unless @$ours == @$theirs;
Branch: 1 branch
BranchTrueFalseTotal
unless @$ours == @$theirs 0 3 3
994 3 for my $i (0 .. $#$ours) {
995 9 ▶ return 0
Branch: 1 branch
BranchTrueFalseTotal
unless _pair_plain_infinities($ours->[$i], $theirs->[$i], $fix, $seen) 0 9 9
996 unless _pair_plain_infinities($ours->[$i], $theirs->[$i],
997 $fix, $seen);
998 9 my $token = _plain_infinity_leaf($ours->[$i], $theirs->[$i]);
999 9 ▶ push @$fix, [ \$ours->[$i], $token ] if defined $token;
Branch: 1 branch
BranchTrueFalseTotal
if defined $token 3 6 9
1000 }
1001 3 return 1;
1002 }
1003  
1004 # A leaf on our side has to be a leaf on theirs, or the trees do not
1005 # describe the same document and nothing here can be trusted.
1006 224 ▶ return ref($theirs) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
ref $theirs ? : 0 224 224
1007 }
1008  
1009 # $_[0] is OUR leaf and $_[1] is YAML::PP's, both by alias: the flags come off
1010 # the SVs the trees hold rather than off copies, and B reads the NV and the PV
1011 # out of the SV's own slots. Nothing numifies anything, so this cannot retype a
1012 # scalar the way a numeric comparison on it would (k32).
1013 229 ▶sub _plain_infinity_leaf {
Subroutine _plain_infinity_leaf: called CC=12 SCAR=25.5
1014 229 ▶ return undef unless defined $_[0] && !ref $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and not ref $_[0] 5 224 229
Condition66%2/3
defined $_[0] and not ref $_[0]
!ll&&!rl&&r
05224
MC/DC50%1/2
defined $_[0] and not ref $_[0]
defined $_[0] not ref $_[0]
Truth table66%2/3
A and not(B)
A= defined $_[0]B= not ref $_[0]
ABresult
0X0
100
111
1015 224 ▶ return undef unless defined $_[1] && !ref $_[1];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[1] and not ref $_[1] 0 224 224
Condition33%1/3
defined $_[1] and not ref $_[1]
!ll&&!rl&&r
00224
MC/DC0%0/2
defined $_[1] and not ref $_[1]
defined $_[1] not ref $_[1]
Truth table33%1/3
A and not(B)
A= defined $_[1]B= not ref $_[1]
ABresult
0X0
100
111
1016  
1017 # Ours has to be a plain string -- what YAML::XS returns for all twelve
1018 # tokens. A leaf that already carries a number is not one of them.
1019 224 my $ours = B::svref_2object(\$_[0]);
1020 224 my $flags = $ours->FLAGS;
1021 224 ▶ return undef unless $flags & B::SVf_POK();
Branch: 1 branch
BranchTrueFalseTotal
unless $flags & 1024 0 224 224
1022 224 ▶ return undef if $flags & (B::SVf_NOK() | B::SVf_IOK());
Branch: 1 branch
BranchTrueFalseTotal
if $flags & 768 5 219 224
1023  
1024 219 my $token = $ours->PV;
1025 219 ▶ return undef unless defined _go_non_finite_double($token);
Branch: 1 branch
BranchTrueFalseTotal
unless defined _go_non_finite_double($token) 15 204 219
1026  
1027 # And theirs has to be the non-finite number, which is how YAML::PP says
1028 # `this scalar was written plain`.
1029 204 my $theirs = B::svref_2object(\$_[1]);
1030 204 ▶ return undef unless $theirs->FLAGS & B::SVf_NOK();
Branch: 1 branch
BranchTrueFalseTotal
unless $theirs->FLAGS & 512 52 152 204
1031 152 my $nv = $theirs->NV;
1032 152 ▶ return undef unless $nv != $nv
Branch: 1 branch
BranchTrueFalseTotal
unless $nv != $nv or $nv == $POSITIVE_INFINITY or $nv == -$POSITIVE_INFINITY 0 152 152
Condition83%5/6
$nv != $nv or $nv == $POSITIVE_INFINITY or $nv == -$POSITIVE_INFINITY
l!l&&r!l&&!r
115370
$nv != $nv or $nv == $POSITIVE_INFINITY
l!l&&r!l&&!r
367937
MC/DC0%0/3
$nv != $nv or $nv == $POSITIVE_INFINITY or $nv == -$POSITIVE_INFINITY
$nv != $nv $nv == $POSITIVE_INFINITY $nv == -$POSITIVE_INFINITY
Truth table75%3/4
A or B or C
A= $nv != $nvB= $nv == $POSITIVE_INFINITYC= $nv == -$POSITIVE_INFINITY
ABCresult
1XX1
01X1
0011
0000
1033 || $nv == $POSITIVE_INFINITY
1034 || $nv == -$POSITIVE_INFINITY;
1035  
1036 152 return $token;
1037 }
1038  
1039 # The gate's own predicate, without a second tree to pair against.
1040 230 ▶sub _plain_infinity_token {
Subroutine _plain_infinity_token: called CC=6 SCAR=18.0
1041 230 ▶ return undef unless defined $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 0 230 230
1042  
1043 230 my $flags = B::svref_2object(\$_[0])->FLAGS;
1044 230 ▶ return undef unless $flags & B::SVf_POK();
Branch: 1 branch
BranchTrueFalseTotal
unless $flags & 1024 0 230 230
1045 230 ▶ return undef if $flags & (B::SVf_NOK() | B::SVf_IOK());
Branch: 1 branch
BranchTrueFalseTotal
if $flags & 768 3 227 230
1046  
1047 227 my $token = B::svref_2object(\$_[0])->PV;
1048 227 ▶ return undef unless $token =~ /\A[-+.]/;
Branch: 1 branch
BranchTrueFalseTotal
unless $token =~ /\A[-+.]/ 14 213 227
1049 213 ▶ return defined _go_non_finite_double($token) ? $token : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined _go_non_finite_double($token) ? : 201 12 213
1050 }
1051  
1052 ###############################################################################
1053 # A `lastmodified` the DOCUMENT wrote plain (k159, docs/adr/0050)
1054 #
1055 # The mirror of _quote_sops_timestamp below, on the read side. That one exists
1056 # because YAML::XS emits an RFC3339 timestamp bare and go-yaml resolves a bare
1057 # RFC3339 scalar to a time.Time, where sops's decoder wants a string:
1058 #
1059 # decoding failed due to the following error(s):
1060 # 'lastmodified' expected type 'string', got unconvertible type 'time.Time'
1061 #
1062 # So this library has never WRITTEN such a document. It has always READ one,
1063 # and k144 / docs/adr/0044 could not close that from Metadata.pm: a bare
1064 # and a quoted scalar arrive at from_hash as the same Perl string. The missing
1065 # fact is not in the SV, it is in the bytes -- the same shape as
1066 # _restore_plain_infinities above, and the reason both live in this file.
1067 #
1068 # THE MECHANISM IS NOT ADR 0026's, though. There YAML::PP is asked as a
1069 # RESOLVER: its Core schema answers `+Inf` for a plain `.inf` and the string
1070 # `.inf` for a quoted one, so the resolution IS the plain/quoted answer. That
1071 # does not carry here, measured: YAML 1.2's Core schema has no timestamp type,
1072 # so YAML::PP hands back the same Perl string for `lastmodified: 2026-08-21T...`
1073 # and `lastmodified: "2026-08-21T..."`. What carries is the QUESTION, and
1074 # YAML::PP's parser answers it directly -- the scalar event's style, the same
1075 # oracle _plain_boolean_tagged_scalars already uses for the !!bool retry.
1076 #
1077 # WHAT IS REFUSED IS NOTHING. This warns, and that is the measured choice
1078 # rather than the timid one. Every write path here re-stamps and quotes the
1079 # timestamp, so `rotate` on such a document produces one `sops -d` reads at
1080 # exit 0 -- measured. A refusal would take the one tool that can still repair
1081 # the file and make the file unopenable by every tool, which in a secrets
1082 # library is a worse outcome than the divergence it closes.
1083 #
1084 # THE GUARD NEVER FIRES ON A DOCUMENT SOPS READS, which is k145's
1085 # condition and the reason that ticket was closed unimplemented. Measured
1086 # against sops 3.13.3, one document per spelling, each carrying a `mac` built
1087 # under the AAD ADR 0044 derives:
1088 #
1089 # * all 15 RFC3339 spellings sops accepts QUOTED (exit 0) are refused BARE
1090 # (exit 1, `unconvertible type 'time.Time'`) -- there is no accepted bare
1091 # one to warn about wrongly;
1092 # * `!!str 2026-08-21T09:05:08Z` -- bare, but TAGGED -- is exit 0 at sops,
1093 # because an explicit tag stops go-yaml's implicit resolver before
1094 # parseTimestamp runs. Hence the tag check below; without it this guard
1095 # would fire on a document sops reads, which is the whole thing k145
1096 # was protecting.
1097 #
1098 # The two places where _go_timestamp and go-yaml's own parseTimestamp were
1099 # measured to disagree both land in the safe direction: `...09:05:08,123Z` (a
1100 # comma fraction) is a timestamp to go-yaml and not to this model, so the
1101 # guard stays quiet on a document sops refuses; `...09:05:08+25:00` is a
1102 # timestamp to this model and a string to go-yaml, so the guard fires on a
1103 # document sops refuses anyway -- for the other of its two reasons.
1104 665 ▶sub _warn_plain_lastmodified {
Subroutine _warn_plain_lastmodified: called CC=6 SCAR=17.9
1105 665 my ($section, $content) = @_;
1106  
1107 # The cheapest gate first: no metadata, or a `lastmodified` that is not a
1108 # scalar, and there is nothing a plain/quoted question could be about.
1109 # ADR 0043 refuses a reference here further down the read path.
1110 665 ▶ return unless ref $section eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $section eq "HASH" 10 655 665
1111 655 my $text = $section->{lastmodified};
1112 655 ▶ return unless defined $text && !ref $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text and not ref $text 116 539 655
Condition66%2/3
defined $text and not ref $text
!ll&&!rl&&r
1160539
MC/DC50%1/2
defined $text and not ref $text
defined $text not ref $text
Truth table66%2/3
A and not(B)
A= defined $textB= not ref $text
ABresult
0X0
100
111
1113  
1114 # Then the model, which is a regex and no parse: go-yaml only resolves a
1115 # scalar to a timestamp when parseTimestamp takes it, and _go_timestamp is
1116 # this module's measured reimplementation of that (see _go_scalar_bytes,
1117 # where the emit-side guard asks the same question of the same tokens).
1118 539 ▶ return unless defined _go_timestamp($text);
Branch: 1 branch
BranchTrueFalseTotal
unless defined _go_timestamp($text) 4 535 539
1119  
1120 # Only then the second parser, and only for the style of one scalar.
1121 535 ▶ return unless _plain_lastmodified($content);
Branch: 1 branch
BranchTrueFalseTotal
unless _plain_lastmodified($content) 517 18 535
1122  
1123 18 carp "sops:lastmodified: this timestamp is written as a PLAIN scalar. "
1124 . "gopkg.in/yaml.v3 resolves a bare RFC3339 scalar to a Go time.Time "
1125 . "where sops's decoder wants a string, so sops refuses this whole "
1126 . "document before decrypting anything -- measured against sops "
1127 . "3.13.3: `'lastmodified' expected type 'string', got unconvertible "
1128 . "type 'time.Time'`. Nothing here is affected: the values and the MAC "
1129 . "are read normally, and every file this library writes quotes the "
1130 . "timestamp, so re-encrypting the document (rotate, edit, "
1131 . "encrypt_in_place, or decrypt_file plus encrypt_file) repairs it. "
1132 . "Quoting the line by hand does the same";
1133  
1134 18 return;
1135 }
1136  
1137 # Was the `sops` section's `lastmodified` value written as a plain scalar?
1138 # 1 yes, 0 no, undef for "this parser could not say" -- an unreadable document,
1139 # or no such key in that position at all.
1140 #
1141 # Ground truth from the PARSER, not from a regex over the text and not from a
1142 # tree: a plain scalar may sit on the line below its key, inside a flow
1143 # mapping, or behind an explicit `? key`, and all three are the ordinary YAML
1144 # a hand edit produces. Measured over 17 spellings, the event stream places
1145 # every one of them; the value's own bytes are never looked at.
1146 #
1147 # A TAGGED scalar answers 0 whatever its style. go-yaml runs parseTimestamp
1148 # only for an untagged node, so `!!str 2026-08-21T09:05:08Z` is a string there
1149 # and sops reads the document at exit 0 -- measured. The one tag that would
1150 # resolve to a timestamp, `!!timestamp`, never reaches here: YAML::XS refuses
1151 # it at parse and %TAG_REFUSAL names it (docs/adr/0032).
1152 #
1153 # An ALIAS answers 0 as well. `lastmodified: *t` carries the anchor's resolved
1154 # type in go-yaml, so it CAN be a time.Time there, but the event carries no
1155 # style of its own and nothing here would be measuring the right scalar. A
1156 # quiet miss on a document sops refuses is this guard's safe direction.
1157 #
1158 # Fails safe like its merge and !!bool twins: a document YAML::PP will not read
1159 # answers undef, which leaves today's behaviour exactly in place.
1160 552 ▶sub _plain_lastmodified {
Subroutine _plain_lastmodified: called CC=3 SCAR=11.0
1161 552 my ($content) = @_;
1162  
1163 # YAML::XS::Load takes bytes and hands back characters; YAML::PP wants the
1164 # characters. Same decode as parse_in_document_order, for the same reason.
1165 552 my $text = $content;
1166 552 ▶ utf8::decode($text) unless utf8::is_utf8($text);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($text) 552 0 552
1167  
1168 # One frame per open collection, innermost last. @key holds the key each
1169 # mapping frame is currently on, so the target is recognised by position:
1170 # the value of `lastmodified` in the mapping that is the value of `sops`
1171 # in the root mapping -- never a user's own `lastmodified` somewhere else.
1172 552 my (@kind, @expect_key, @key);
1173 552 my ($plain, $done);
1174  
1175 552 my $ok = eval {
1176 144905 ▶ YAML::PP::Parser->new(receiver => sub {
Subroutine __ANON__: called CC=23 SCAR=31.4
1177 144905 my (undef, $name, $event) = @_;
1178 144905 ▶ return if $done;
Branch: 1 branch
BranchTrueFalseTotal
if $done 596 144309 144905
1179  
1180 144309 ▶ if ($name eq 'mapping_start_event' || $name eq 'sequence_start_event') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "mapping_start_event" or $name eq "sequence_start_event") 41657 102652 144309
Condition100%3/3
$name eq "mapping_start_event" or $name eq "sequence_start_event"
l!l&&r!l&&!r
384233234102652
MC/DC100%2/2
$name eq "mapping_start_event" or $name eq "sequence_start_event"
$name eq "mapping_start_event" $name eq "sequence_start_event"
Truth table100%3/3
A or B
A= $name eq "mapping_start_event"B= $name eq "sequence_start_event"
ABresult
1X1
011
000
1181 41657 _consume_node_slot(\@kind, \@expect_key, \@key, undef);
1182 41657 ▶ push @kind, $name eq 'mapping_start_event' ? 'map' : 'seq';
Branch: 1 branch
BranchTrueFalseTotal
$name eq 'mapping_start_event' ? : 38423 3234 41657
1183 41657 push @expect_key, 1;
1184 41657 push @key, undef;
1185 41657 return;
1186 }
1187 102652 ▶ if ($name eq 'mapping_end_event' || $name eq 'sequence_end_event') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "mapping_end_event" or $name eq "sequence_end_event") 41655 60997 102652
Condition100%3/3
$name eq "mapping_end_event" or $name eq "sequence_end_event"
l!l&&r!l&&!r
38422323360997
MC/DC100%2/2
$name eq "mapping_end_event" or $name eq "sequence_end_event"
$name eq "mapping_end_event" $name eq "sequence_end_event"
Truth table100%3/3
A or B
A= $name eq "mapping_end_event"B= $name eq "sequence_end_event"
ABresult
1X1
011
000
1188 41655 pop @kind; pop @expect_key; pop @key;
1189 41655 return;
1190 }
1191 # The one-document rule is parse()'s, held here independently: a
1192 # second document's `sops` section is not the one that was read.
1193 60997 ▶ if ($name eq 'document_end_event') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "document_end_event") 551 60446 60997
1194 551 $done = 1;
1195 551 return;
1196 }
1197 60446 ▶ return unless $name eq 'scalar_event' || $name eq 'alias_event';
Branch: 1 branch
BranchTrueFalseTotal
unless $name eq "scalar_event" or $name eq "alias_event" 1104 59342 60446
Condition100%3/3
$name eq "scalar_event" or $name eq "alias_event"
l!l&&r!l&&!r
591791631104
MC/DC100%2/2
$name eq "scalar_event" or $name eq "alias_event"
$name eq "scalar_event" $name eq "alias_event"
Truth table100%3/3
A or B
A= $name eq "scalar_event"B= $name eq "alias_event"
ABresult
1X1
011
000
1198  
1199 my $slot = _consume_node_slot(\@kind, \@expect_key, \@key,
1200 59342 ▶ $name eq 'scalar_event' ? $event->{value} : undef);
Branch: 1 branch
BranchTrueFalseTotal
$name eq 'scalar_event' ? : 59179 163 59342
1201 59342 ▶ return unless ($slot // '') eq 'value';
Branch: 1 branch
BranchTrueFalseTotal
unless ($slot // "") eq "value" 49432 9910 59342
Condition100%2/2
$slot // ""
l!l
59199143
MC/DC100%1/1
$slot // ""
$slot
Truth table100%2/2
A
A= $slot
Aresult
11
00
1202 9910 ▶ return unless @kind == 2
Branch: 1 branch
BranchTrueFalseTotal
unless @kind == 2 and $kind[0] eq "map" and ($key[0] // "") eq "sops" and ($key[1] // "") eq "lastmodified" 9362 548 9910
Condition76%10/13
@kind == 2 and $kind[0] eq "map" and ($key[0] // "") eq "sops" and ($key[1] // "") eq "lastmodified"
!ll&&!rl&&r
77431619548
@kind == 2 and $kind[0] eq "map" and ($key[0] // "") eq "sops"
!ll&&!rl&&r
73703732167
@kind == 2 and $kind[0] eq "map"
!ll&&!rl&&r
737002540
$key[0] // ""
l!l
25400
$key[1] // ""
l!l
21670
MC/DC25%1/4
@kind == 2 and $kind[0] eq "map" and ($key[0] // "") eq "sops" and ($key[1] // "") eq "lastmodified"
@kind == 2 $kind[0] eq "map" $key[0] $key[1]
Truth table40%2/5
A and B and C and D
A= @kind == 2B= $kind[0] eq "map"C= $key[0]D= $key[1]
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1203 && $kind[0] eq 'map'
1204 && ($key[0] // '') eq 'sops'
1205 && ($key[1] // '') eq 'lastmodified';
1206  
1207 $plain = $name eq 'scalar_event'
1208 && !defined $event->{tag}
1209 548 ▶ && ($event->{style} // 0) == YAML_PLAIN_SCALAR_STYLE ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$name eq 'scalar_event' && !defined($event->{'tag'}) && ($event->{'style'} // 0) == 1 ? : 25 523 548
Condition87%7/8
$name eq "scalar_event" and not defined $event->{"tag"} and ($event->{"style"} // 0) == 1
!ll&&!rl&&r
451925
$name eq "scalar_event" and not defined $event->{"tag"}
!ll&&!rl&&r
13544
$event->{"style"} // 0
l!l
5440
MC/DC66%2/3
$name eq "scalar_event" and not defined $event->{"tag"} and ($event->{"style"} // 0) == 1
$name eq "scalar_event" not defined $event->{"tag"} $event->{"style"}
Truth table75%3/4
A and not(B) and C
A= $name eq "scalar_event"B= not defined $event->{"tag"}C= $event->{"style"}
ABCresult
0XX0
10X0
1100
1111
1210 552 })->parse_string($text);
1211 551 1;
1212 };
1213  
1214 552 ▶ return unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 1 551 552
1215 551 return $plain;
1216 }
1217  
1218 # One node has started. Tell the enclosing mapping whether it is that
1219 # mapping's key or its value, and advance it; a sequence element is neither.
1220 # Returns 'key', 'value' or undef for "not inside a mapping".
1221 100999 ▶sub _consume_node_slot {
Subroutine _consume_node_slot: called CC=4 SCAR=13.9
1222 100999 my ($kind, $expect_key, $key, $scalar) = @_;
1223  
1224 100999 ▶ return undef unless @$kind && $kind->[-1] eq 'map';
Branch: 1 branch
BranchTrueFalseTotal
unless @$kind and $kind->[-1] eq "map" 2421 98578 100999
Condition100%3/3
@$kind and $kind->[-1] eq "map"
!ll&&!rl&&r
552186998578
MC/DC100%2/2
@$kind and $kind->[-1] eq "map"
@$kind $kind->[-1] eq "map"
Truth table100%3/3
A and B
A= @$kindB= $kind->[-1] eq "map"
ABresult
0X0
100
111
1225  
1226 98578 ▶ if ($expect_key->[-1]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expect_key->[-1]) 49289 49289 98578
1227 # A complex key -- `? [a, b] : v` -- has no name this walk can use, and
1228 # undef is not a key any sops document writes, so it matches nothing.
1229 49289 $key->[-1] = $scalar;
1230 49289 $expect_key->[-1] = 0;
1231 49289 return 'key';
1232 }
1233  
1234 49289 $expect_key->[-1] = 1;
1235 49289 return 'value';
1236 }
1237  
1238  
1239 ###############################################################################
1240 # The order-preserving reparse behind MAC verification (docs/adr/0001, 0036)
1241 #
1242 # The MAC is order dependent and the order is the DOCUMENT's, which a Perl hash
1243 # cannot carry. File::SOPS recovers it by reparsing the raw text with key order
1244 # preserved and walking that skeleton against the real tree. This is the half
1245 # of the mechanism that has to know the format, so it lives here rather than in
1246 # File::SOPS -- see parse_in_document_order's POD for the contract a handler
1247 # has to meet.
1248 #
1249 # YAML::PP supplies ORDER AND NOTHING ELSE. Values still come from parse()'s
1250 # tree, so a scalar this loader resolves differently from YAML::XS cannot reach
1251 # the digest -- which is why the boolean mode below is set for consistency and
1252 # not because anything reads what it produces.
1253 91 my $ORDERED_LOADER = YAML::PP->new(
1254 boolean => 'JSON::PP',
1255 preserve => PRESERVE_ORDER,
1256 );
1257  
1258 465 ▶sub parse_in_document_order {
Subroutine parse_in_document_order: called CC=8 SCAR=20.9
Pod documented
1259 465 my ($class, $content) = @_;
1260 465 ▶ return unless defined $content;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 0 465 465
1261  
1262 # YAML::XS::Load hands back decoded characters, so the reparse has to
1263 # decode too or a non-ASCII key would not match its twin in the tree.
1264 465 my $text = $content;
1265 465 ▶ utf8::decode($text) unless utf8::is_utf8($text);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($text) 465 0 465
1266  
1267 # LIST context, matching parse(): the two loaders disagree ONLY in scalar
1268 # context on a multi-document stream (YAML::PP->load_string returns the
1269 # FIRST document, YAML::XS::Load the LAST), and the MAC walk takes its order
1270 # from here and its values from parse()'s tree. Both read the stream in list
1271 # context now, so document i's order is paired with document i's values
1272 # (docs/adr/0033, k31). A stream that cannot be read this way still
1273 # declines to nothing, which falls back to sorted order -- can make
1274 # verification fail, never wrongly succeed.
1275 465 my @docs = eval { $ORDERED_LOADER->load_string($text) };
1276 465 ▶ return unless @docs;
Branch: 1 branch
BranchTrueFalseTotal
unless @docs 1 464 465
1277  
1278 # The metadata MAC lives in the `sops` mapping and must not hash itself.
1279 # WHERE it sits is format knowledge, so the handler drops it structurally
1280 # (the same way parse() does) rather than by pattern-matching "mac:" in the
1281 # raw text -- which used to swallow any user key ending in "mac". On a
1282 # stream sops writes an identical block into every document, so it is
1283 # dropped from every document here.
1284 464 for my $doc (@docs) {
1285 # An empty document reparses to undef; {} keeps it a real, empty
1286 # document so its shape lines up with the value tree's.
1287 469 ▶ $doc = {} unless defined $doc;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $doc 0 469 469
1288 469 ▶ return unless ref $doc eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $doc eq "HASH" 1 468 469
1289 468 delete $doc->{sops};
1290 }
1291  
1292 # A single document stays a bare HashRef, byte-identical to before, so every
1293 # existing caller and test is unaffected. A stream is returned as an
1294 # ArrayRef of ordered documents -- an unambiguous reference in any context,
1295 # which File::SOPS::_parse_in_document_order pairs against the value trees.
1296 463 ▶ return @docs == 1 ? $docs[0] : \@docs;
Branch: 1 branch
BranchTrueFalseTotal
@docs == 1 ? : 458 5 463
1297 }
1298  
1299  
1300 513 ▶sub serialize {
Subroutine serialize: called CC=9 SCAR=22.1
Pod documented
1301 513 my ($class, %args) = @_;
1302 513 ▶ my $data = $args{data} // croak "data required";
Condition50%1/2
$args{"data"} // croak("data required")
l!l
5130
MC/DC0%0/1
$args{"data"} // croak("data required")
$args{"data"}
Truth table50%1/2
A
A= $args{"data"}
Aresult
11
00
1303 513 ▶ my $metadata = $args{metadata} // croak "metadata required";
Condition50%1/2
$args{"metadata"} // croak("metadata required")
l!l
5130
MC/DC0%0/1
$args{"metadata"} // croak("metadata required")
$args{"metadata"}
Truth table50%1/2
A
A= $args{"metadata"}
Aresult
11
00
1304  
1305 # A stream is an ArrayRef of encrypted document trees; a single document is a
1306 # bare HashRef and stays byte-identical -- a one-element list attaches the
1307 # same one metadata block and emits through the same Dump call (docs/adr/0033
1308 # Decision 1, k31). The SAME metadata is written into EVERY document,
1309 # byte-identical (same age blob, lastmodified and mac), which is the exact
1310 # inverse of the read-side detach in parse/_parse_multidoc (point 1). An
1311 # empty document is a real document and STILL gets its own metadata block
1312 # (point 6): here it is `{}` and comes out carrying only the `sops:` section.
1313 513 ▶ my @docs = ref $data eq 'ARRAY' ? @$data : ($data);
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'ARRAY' ? : 1 512 513
1314 513 ▶ croak "data required" unless @docs;
Branch: 1 branch
BranchTrueFalseTotal
unless @docs 0 513 513
1315  
1316 # to_hash once, so every document gets a byte-identical block rather than N
1317 # freshly built ones that only happen to match.
1318 513 my $section = $metadata->to_hash;
1319  
1320 513 my @output;
1321 513 for my $doc (@docs) {
1322 # The metadata goes into `sops`, so a value already there would be
1323 # overwritten -- and since the digest was computed over the tree BEFORE
1324 # serialization, the document that came out failed its own MAC. Refuse
1325 # instead, as sops does (exit 203). See File::SOPS::encrypt. Checked per
1326 # document, so a `sops` key in any document of a stream is refused.
1327 croak "data contains a top-level 'sops' entry, which is where the SOPS "
1328 . "metadata section goes"
1329 514 ▶ if exists $doc->{sops};
Branch: 1 branch
BranchTrueFalseTotal
if exists $doc->{"sops"} 1 513 514
1330  
1331 513 push @output, { %$doc, sops => $section };
1332 }
1333  
1334 # The timestamp fixup applies to the metadata section only, so it sits here
1335 # rather than in emit -- a plaintext document has no `sops:` block to fix. On
1336 # a stream it rewrites the bare RFC3339 lastmodified inside EVERY `sops:`
1337 # block: it already resets its state at each column-0 line, so a `---`
1338 # separator and each later document's `sops:` are handled the same as the
1339 # first.
1340 #
1341 # mac_covered turns on the foreign-resolution guard (k86, ADR 0013):
1342 # this document carries a MAC, and sops recomputes that MAC from the values
1343 # ITS parser resolves out of these bytes.
1344 #
1345 # For mac_only_encrypted the digest covers encrypted values only, so an
1346 # unencrypted leaf cannot make such a document disagree with its own MAC and
1347 # refusing it would refuse a document that works today -- measured, sops -d
1348 # exit 0. It still reads 493 out of a `0755` this module reads as 755, so
1349 # the same check runs there and WARNS instead (k87, ADR 0018).
1350 512 ▶ return _quote_sops_timestamp($class->emit(
Branch: 2 branches
BranchTrueFalseTotal
@output == 1 ? : 511 1 512
$metadata->mac_only_encrypted ? : 40 472 512
1351 @output == 1 ? $output[0] : \@output,
1352 $metadata->mac_only_encrypted ? (warn_foreign_resolution => 1)
1353 : (mac_covered => 1)));
1354 }
1355  
1356 # YAML::XS emits plain (unquoted) scalars for anything its resolver does not
1357 # recognise as a YAML core-schema type. $YAML::XS::QuoteNumericStrings (on by
1358 # default) already covers numbers, booleans and nulls -- '3.8', '123', 'true'
1359 # and 'null' all come out quoted -- but the resolver has no notion of
1360 # timestamps, so an RFC3339 lastmodified is emitted bare.
1361 #
1362 # Go's yaml.v3 DOES resolve a bare RFC3339 scalar, to time.Time, and sops then
1363 # refuses the whole file before it decrypts anything:
1364 #
1365 # decoding failed due to the following error(s):
1366 # 'lastmodified' expected type 'string', got unconvertible type 'time.Time'
1367 #
1368 # sops itself writes lastmodified: "2026-08-08T21:28:58Z" -- quoted. YAML::XS
1369 # exposes no per-scalar style control (no tag, no forced-quote hook), so the
1370 # only way to get a quoted scalar out of this emitter is to quote it after the
1371 # dump. Kept deliberately narrow: it rewrites one key, only inside the
1372 # top-level `sops:` block, so a user's own `lastmodified:` in the data section
1373 # is never touched. JSON needs none of this -- JSON has no timestamp type and
1374 # its strings are always quoted.
1375 486 ▶sub _quote_sops_timestamp {
Subroutine _quote_sops_timestamp: called CC=6 SCAR=17.9
1376 486 my ($yaml) = @_;
1377  
1378 486 my @lines = split /\n/, $yaml, -1;
1379 486 my $in_sops = 0;
1380  
1381 486 for my $line (@lines) {
1382 85703 ▶ if ($line =~ /\A sops : \s* \z/x) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\A sops : \s* \z/x) 486 85217 85703
1383 486 $in_sops = 1;
1384 486 next;
1385 }
1386 # any other column-0 line ends the sops block (Dump sorts keys, so a
1387 # data key sorting after "sops" can follow it)
1388 85217 ▶ $in_sops = 0 if $in_sops && $line =~ /\A\S/;
Branch: 1 branch
BranchTrueFalseTotal
if $in_sops and $line =~ /\A\S/ 124 85093 85217
Condition100%3/3
$in_sops and $line =~ /\A\S/
!ll&&!rl&&r
754719622124
MC/DC100%2/2
$in_sops and $line =~ /\A\S/
$in_sops $line =~ /\A\S/
Truth table100%3/3
A and B
A= $in_sopsB= $line =~ /\A\S/
ABresult
0X0
100
111
1389 85217 ▶ next unless $in_sops;
Branch: 1 branch
BranchTrueFalseTotal
unless $in_sops 75595 9622 85217
1390  
1391 # already-quoted values are left alone
1392 9622 $line =~ s{
1393 \A (\s+ lastmodified: [ \t]+) (?!['"]) (\S.*?) [ \t]* \z
1394 }{$1"$2"}x;
1395 }
1396  
1397 486 return join "\n", @lines;
1398 }
1399  
1400  
1401 # The one place this distribution turns a Perl tree into YAML. serialize() is
1402 # this plus the metadata section, and File::SOPS::_serialize_plaintext (what
1403 # decrypt_file writes and what edit hands the editor) is this on its own.
1404 #
1405 # It stays ONE sub because the emitter options are not local taste: the MAC's
1406 # encrypt side walks the tree in sorted order and is correct only because this
1407 # emitter writes keys sorted, and the boolean mode decides whether a
1408 # JSON::PP::Boolean reaches the file as `true` or as
1409 # `!!perl/scalar:JSON::PP::Boolean 1`. A second copy of those options is a
1410 # second answer to a question that has one -- which is what k35 found: the
1411 # plaintext emitter used to work only because this module set
1412 # $YAML::XS::Boolean process-wide at load time.
1413 #
1414 # Consequence, deliberately accepted: this sub is on the wire path. Changing
1415 # what it emits changes the encrypted document too, so it is not a plaintext
1416 # formatting knob.
1417 # The safely-quotable non-finite spellings (docs/adr/0070), scoped to EXACTLY
1418 # the seven ADR 0038/0039 measured. A str leaf whose value is one of these came
1419 # unambiguously from a QUOTED source or a caller's own Perl string, because
1420 # _restore_plain_infinities (docs/adr/0026, 0034) already resolved a bare one to
1421 # a float at parse -- so writing it double-quoted states the type it already
1422 # has, and sops writes and reads the same bytes (measured, sops -d exit 0). The
1423 # other five non-finite tokens in %GO_CONSTANT (`+.Inf +.INF -.Inf -.INF .NAN`)
1424 # are deliberately NOT here: the corpus did not measure them, and "no wider than
1425 # the nine rows" keeps them refused as they are today.
1426 my %QUOTABLE_NON_FINITE =
1427 91 map { $_ => 1 } ( '.inf', '.Inf', '.INF', '+.inf', '-.inf', '.nan', '.NaN' );
1428  
1429 734 ▶sub emit {
Subroutine emit: called CC=9 SCAR=22.0
Pod documented
1430 734 my ($class, $data, %args) = @_;
1431 734 ▶ croak "data required" unless defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 734 734
1432  
1433 # A multi-document stream is an ArrayRef of document trees (docs/adr/0033,
1434 # k31). A bare HashRef is one document and stays byte-identical.
1435 734 ▶ my @docs = ref $data eq 'ARRAY' ? @$data : ($data);
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'ARRAY' ? : 3 731 734
1436 734 ▶ croak "data required" unless @docs;
Branch: 1 branch
BranchTrueFalseTotal
unless @docs 0 734 734
1437  
1438 # Only a document that a reader re-derives values from has anything to
1439 # disagree with. serialize sets one of these; the plaintext emitters
1440 # (decrypt_file, edit) set neither, and must not -- refusing there would
1441 # refuse to WRITE OUT a document this module reads correctly, and warning
1442 # would warn about a file with no MAC and no second reader. The two differ in
1443 # the verdict only: croak where the MAC covers the leaf, carp where
1444 # mac_only_encrypted means it does not. See docs/adr/0013 and docs/adr/0018.
1445 my $reject_scalar =
1446 $args{mac_covered} ? \&_reject_foreign_resolution
1447 734 ▶ : $args{warn_foreign_resolution} ? \&_warn_foreign_resolution
Branch: 2 branches
BranchTrueFalseTotal
$args{'mac_covered'} ? : 568 166 734
$args{'warn_foreign_resolution'} ? : 40 126 166
1448 : undef;
1449  
1450 # Force-quoting runs on EVERY path except mac_only_encrypted (warn):
1451 #
1452 # * MAC-covered (docs/adr/0070): a divergent leaf makes the file fail its
1453 # own MAC (the non-finite class) or silently retypes a caller's string
1454 # (the True/False class), and quoting the safe subset is what lets such a
1455 # document be written at all.
1456 # * Plaintext -- decrypt_file, edit (k186): sops writes `".inf"` and
1457 # `"True"` double-quoted, and without this the plaintext emitter wrote
1458 # them bare, so a decrypt_file -> re-encrypt round trip flipped the leaf
1459 # from string to float/bool (a bare `.inf` resolves to +Inf at the next
1460 # parse, docs/adr/0026). Quoting the same safe subset makes the plaintext
1461 # emitter a faithful inverse of what sops wrote.
1462 #
1463 # The mac_only_encrypted (warn) path is the one exception, kept as ADR 0070
1464 # left it: there the document already works and the leaf is not MAC-covered,
1465 # so its bytes are unchanged. Neither the MAC-covered digest (computed over
1466 # the original tree before emit) nor the plaintext output (never hashed) has
1467 # a digest quoting could move, so this is safe on every path it runs.
1468 734 my $force_quote = !$args{warn_foreign_resolution};
1469  
1470 734 ▶ return _emit_docs($class, \@docs, $reject_scalar) unless $force_quote;
Branch: 1 branch
BranchTrueFalseTotal
unless $force_quote 40 694 734
1471  
1472 # Replace exactly the safely-quotable divergent leaves (the True/False type
1473 # divergence, and the seven parse-unambiguous non-finite str leaves) with
1474 # unique random sentinels, in a COPY of each document. A sentinel is an
1475 # ordinary string the guard passes; every OTHER divergent leaf is left in
1476 # place and still reaches the guard below and is refused. The digest was
1477 # computed over the original tree in File::SOPS::_compute_mac before emit, so
1478 # this copy touches no digest byte and no key's sort position.
1479 694 my %sentinel;
1480 my @quoted = map {
1481 694 _sentinel_quotable_leaves($docs[$_], \%sentinel, [], $_)
1482 } 0 .. $#docs;
1483  
1484 # Nothing to quote -> today's single Dump, byte-identical.
1485 694 ▶ return _emit_docs($class, \@docs, $reject_scalar) unless %sentinel;
Branch: 1 branch
BranchTrueFalseTotal
unless %sentinel 672 22 694
1486  
1487 # The guard runs here on the sentinel'd copy. A remaining non-safe divergent
1488 # leaf croaks exactly as today -- a refused document is refused whether or not
1489 # it also held a quotable leaf -- and that croak propagates unchanged.
1490 22 my $yaml = _emit_docs($class, \@quoted, $reject_scalar);
1491  
1492 # Surgery + FAIL-CLOSED verification (docs/adr/0070). On any miss the whole
1493 # surgery is abandoned and the ORIGINAL tree is emitted the old way, which
1494 # reproduces today's exact refusal/carp for these leaves. A file that failed
1495 # verification is never shipped.
1496 22 my $surgical = _quote_sentinels($yaml, \%sentinel);
1497 22 ▶ return defined $surgical ? $surgical
Branch: 1 branch
BranchTrueFalseTotal
defined $surgical ? : 20 2 22
1498 : _emit_docs($class, \@docs, $reject_scalar);
1499 }
1500  
1501 # The one Dump call, unchanged from before docs/adr/0070. Each document is run
1502 # through canonical_float_tree on its own, so each keeps its own sorted key order
1503 # (the MAC's encrypt side rides on that, docs/adr/0001); YAML::XS::Dump then emits
1504 # the whole list as one stream, prepending `---` to EVERY document -- N documents
1505 # joined by `---` with no leading empty document, which is the separator rule
1506 # (docs/adr/0033 point 5). $reject_scalar is the caller's foreign-resolution
1507 # guard, or undef for a plaintext emit.
1508 736 ▶sub _emit_docs {
Subroutine _emit_docs: called CC=2 SCAR=6.9
1509 736 my ($class, $docs, $reject_scalar) = @_;
1510  
1511 736 local $YAML::XS::Boolean = $BOOLEAN_MODE;
1512 return Dump(map {
1513 736 ▶ File::SOPS::Encrypted->canonical_float_tree(
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$reject_scalar ? : 611 128 739
1514 $_,
1515 roundtrips => \&_float_roundtrips,
1516 carrier => \&_float_carrier,
1517 reject => \&_reject_unwritable_leaf,
1518 ($reject_scalar ? (reject_scalar => $reject_scalar) : ()),
1519 )
1520 } @$docs);
1521 }
1522  
1523 # docs/adr/0070: a COPY of $node with every safely-quotable leaf replaced by a
1524 # unique random sentinel, recording sentinel => { value, doc, path } for the
1525 # post-Dump surgery. Containers are rebuilt (new hashes/arrays); leaves are
1526 # shared, so the caller's tree is never mutated. No cycle guard: canonical_float_tree
1527 # has none either, so a cyclic document already hangs downstream (k110) and
1528 # this adds no new behaviour there.
1529 82554 ▶sub _sentinel_quotable_leaves {
Subroutine _sentinel_quotable_leaves: called CC=4 SCAR=13.9
1530 93 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
1531 82554 my ($node, $sentinel, $path, $doc) = @_;
1532  
1533 82554 ▶ if (ref $node eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node eq "HASH") 72278 10276 82554
1534 return { map {
1535 72278 push @$path, $_;
1536 81310 my $r = _sentinel_quotable_leaves($node->{$_}, $sentinel, $path, $doc);
1537 81310 pop @$path;
1538 81310 ($_ => $r);
1539 } keys %$node };
1540 }
1541 10276 ▶ if (ref $node eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node eq "ARRAY") 2870 7406 10276
1542 return [ map {
1543 2870 push @$path, $_;
1544 547 my $r = _sentinel_quotable_leaves($node->[$_], $sentinel, $path, $doc);
1545 547 pop @$path;
1546 547 $r;
1547 } 0 .. $#$node ];
1548 }
1549  
1550 7406 ▶ return $node unless _is_quotable_leaf($node, $path);
Branch: 1 branch
BranchTrueFalseTotal
unless _is_quotable_leaf($node, $path) 7381 25 7406
1551  
1552 25 my $token = _fresh_sentinel($sentinel);
1553 25 $sentinel->{$token} = { value => $node, doc => $doc, path => [ @$path ] };
1554 25 return $token;
1555 }
1556  
1557 # Is this leaf one of docs/adr/0070's nine safely-quotable rows? Reuses the
1558 # guard's own verdict, so there is no second model of Go:
1559 #
1560 # * a `type` divergence -- True/False, a str here and a bool to Go. The digest
1561 # bytes already agree (`True` both sides), so quoting is MAC-neutral and only
1562 # removes the divergence (docs/adr/0019). Measured: _foreign_resolution_token
1563 # returns 'type' for exactly True/False and nothing else, because any other
1564 # spelling Go reads as a bool (TRUE, FALSE) disagrees on bytes and is 'mac'.
1565 # * a `mac` divergence whose token is one of the seven spellings
1566 # %QUOTABLE_NON_FINITE holds and whose leaf is a str -- unambiguously from a
1567 # quoted or caller source (docs/adr/0026, 0034), so quoting states its real
1568 # type.
1569 #
1570 # Everything else -- the sixteen ambiguous rows, an int/float `0755`, and every
1571 # adversarial neighbour -- returns 0 and is left for the guard.
1572 7492 ▶sub _is_quotable_leaf {
Subroutine _is_quotable_leaf: called CC=7 SCAR=19.5
1573 7492 my ($leaf, $path) = @_;
1574 7492 ▶ return 0 unless defined $leaf;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $leaf 10 7482 7492
1575  
1576 7482 my ($token, $kind) = _foreign_resolution_token($leaf, $path, undef);
1577 7482 ▶ return 0 unless defined $token;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $token 7357 125 7482
1578  
1579 125 ▶ return 1 if $kind eq 'type';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "type" 19 106 125
1580 return 1 if $kind eq 'mac'
1581 106 ▶ && $QUOTABLE_NON_FINITE{$token}
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "mac" and $QUOTABLE_NON_FINITE{$token} and "File::SOPS::Encrypted"->detect_type($leaf) eq "str" 15 91 106
Condition83%5/6
$kind eq "mac" and $QUOTABLE_NON_FINITE{$token} and "File::SOPS::Encrypted"->detect_type($leaf) eq "str"
!ll&&!rl&&r
85615
$kind eq "mac" and $QUOTABLE_NON_FINITE{$token}
!ll&&!rl&&r
08521
MC/DC66%2/3
$kind eq "mac" and $QUOTABLE_NON_FINITE{$token} and "File::SOPS::Encrypted"->detect_type($leaf) eq "str"
$kind eq "mac" $QUOTABLE_NON_FINITE{$token} "File::SOPS::Encrypted"->detect_type($leaf) eq "str"
Truth table75%3/4
A and B and C
A= $kind eq "mac"B= $QUOTABLE_NON_FINITE{$token}C= "File::SOPS::Encrypted"->detect_type($leaf) eq "str"
ABCresult
0XX0
10X0
1100
1111
1582 && File::SOPS::Encrypted->detect_type($leaf) eq 'str';
1583 91 return 0;
1584 }
1585  
1586 # A unique random 128-bit sentinel token. Spaceless and alphanumeric, so
1587 # YAML::XS emits it BARE and on ONE line at any depth (a YAML plain scalar folds
1588 # only at a space, and there is none), and its first byte `S` is one Go's
1589 # resolver never looks at, so the guard passes it as an ordinary string.
1590 # Collision with document text is astronomically improbable at 128 bits AND
1591 # caught by the occurrence-count check in _quote_sentinels, which fails closed.
1592 25 ▶sub _fresh_sentinel {
Subroutine _fresh_sentinel: called CC=2 SCAR=7.0
1593 25 my ($sentinel) = @_;
1594 25 my @hex = (0 .. 9, 'a' .. 'f');
1595 25 while (1) {
1596 my $token = 'SOPSQUOTE'
1597 25 . join('', map { $hex[int rand 16] } 1 .. 32)
1598 . 'ENDSOPSQUOTE';
1599 25 ▶ return $token unless exists $sentinel->{$token};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $sentinel->{$token} 25 0 25
1600 }
1601 }
1602  
1603 # The generalisation of _quote_sops_timestamp: replace each sentinel token in the
1604 # finished YAML with the original value rendered as a double-quoted scalar, then
1605 # verify FAIL CLOSED. Returns the surgical text, or undef to fall back to today's
1606 # refusal/carp -- never a document that did not verify.
1607 #
1608 # Two checks, both of which docs/adr/0070 requires:
1609 # 1. each sentinel occurs exactly once (0 or >1 abandons the whole surgery --
1610 # the 0 case is the only way a spaceless sentinel could go missing, e.g. an
1611 # emitter that folded it, and a >1 the only way a 128-bit token could
1612 # collide);
1613 # 2. the finished document re-Loads and each forced leaf, at its recorded
1614 # position, is byte-for-byte the original string.
1615 # The second is stronger than a count: it reads the emitted bytes back the way a
1616 # reader will, so a substitution that produced a different value cannot pass.
1617 22 ▶sub _quote_sentinels {
Subroutine _quote_sentinels: called CC=10 SCAR=23.7
1618 22 my ($yaml, $sentinel) = @_;
1619  
1620 22 my $out = $yaml;
1621 22 for my $token (keys %$sentinel) {
1622 25 my $count = () = ($out =~ /\Q$token\E/g);
1623 25 ▶ return undef unless $count == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $count == 1 0 25 25
1624 25 my $quoted = _yaml_double_quote($sentinel->{$token}{value});
1625 25 $out =~ s/\Q$token\E/$quoted/;
1626 }
1627  
1628 22 my @back = do {
1629 22 local $YAML::XS::Boolean = $BOOLEAN_MODE;
1630 22 my @d = eval { Load($out) };
1631 22 ▶ return undef if $@ || !@d;
Branch: 1 branch
BranchTrueFalseTotal
if $@ or not @d 0 22 22
Condition33%1/3
$@ or not @d
l!l&&r!l&&!r
0022
MC/DC0%0/2
$@ or not @d
$@ not @d
Truth table33%1/3
A or not(B)
A= $@B= not @d
ABresult
1X1
011
000
1632 22 @d;
1633 };
1634  
1635 22 for my $token (keys %$sentinel) {
1636 25 my $entry = $sentinel->{$token};
1637 25 ▶ return undef unless $entry->{doc} <= $#back;
Branch: 1 branch
BranchTrueFalseTotal
unless $entry->{"doc"} <= $#back 0 25 25
1638 25 my $leaf = _navigate_path($back[$entry->{doc}], $entry->{path});
1639 25 ▶ return undef unless defined $leaf && !ref $leaf;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $leaf and not ref $leaf 2 23 25
Condition66%2/3
defined $leaf and not ref $leaf
!ll&&!rl&&r
2023
MC/DC50%1/2
defined $leaf and not ref $leaf
defined $leaf not ref $leaf
Truth table66%2/3
A and not(B)
A= defined $leafB= not ref $leaf
ABresult
0X0
100
111
1640 23 ▶ return undef unless $leaf eq $entry->{value};
Branch: 1 branch
BranchTrueFalseTotal
unless $leaf eq $entry->{"value"} 0 23 23
1641 }
1642  
1643 20 return $out;
1644 }
1645  
1646 # Walk a re-Loaded tree to the leaf at $path (hash keys and array indices
1647 # interleaved, as _sentinel_quotable_leaves recorded them). undef on any
1648 # structural surprise, which fails the verification closed.
1649 23 ▶sub _navigate_path {
Subroutine _navigate_path: called CC=7 SCAR=25.7
1650 23 my ($node, $path) = @_;
1651 23 for my $step (@$path) {
1652 25 ▶ return undef unless ref $node;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $node 0 25 25
1653 25 ▶ if (ref $node eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $node eq 'HASH') { } 25 0 25
elsif (ref $node eq 'ARRAY') { } 0 0 0
1654 25 ▶ return undef unless exists $node->{$step};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $node->{$step} 0 25 25
1655 25 $node = $node->{$step};
1656 }
1657 elsif (ref $node eq 'ARRAY') {
1658 0 ▶ return undef unless $step <= $#$node;
Branch: 1 branch
BranchTrueFalseTotal
unless $step <= $node->$#* 0 0 0
1659 0 $node = $node->[$step];
1660 }
1661 0 else { return undef }
1662 }
1663 23 return $node;
1664 }
1665  
1666 # The original value as a YAML double-quoted scalar that Loads back to the exact
1667 # string. The nine safe rows are all plain ASCII (`.inf`, `True`, ...), so the
1668 # escape branches below are defensive: a value with a space, quote, backslash or
1669 # control character never reaches here, because _emitted_plain_scalar returns
1670 # undef for it (it is not a bare token) and _is_quotable_leaf then returns 0.
1671 25 ▶sub _yaml_double_quote {
Subroutine _yaml_double_quote: called CC=1 SCAR=0.0
1672 25 my ($s) = @_;
1673 25 my $out = $s;
1674 25 $out =~ s/\\/\\\\/g;
1675 25 $out =~ s/"/\\"/g;
1676 25 $out =~ s/\t/\\t/g;
1677 25 $out =~ s/\n/\\n/g;
1678 25 $out =~ s/\r/\\r/g;
1679 0 $out =~ s/([\x00-\x08\x0b\x0c\x0e-\x1f])/sprintf('\\x%02X', ord $1)/ge;
1680 25 return '"' . $out . '"';
1681 }
1682  
1683 # A referenced leaf YAML::XS cannot write as the text the digest covers.
1684 #
1685 # detect_type calls every blessed leaf but a JSON::PP::Boolean `str`, so the
1686 # digest covers its STRINGIFICATION. YAML::XS writes it as a Perl-specific
1687 # tagged structure instead -- measured against sops 3.13.3, one document per
1688 # row, leaf under _unencrypted:
1689 #
1690 # Math::BigFloat->new("1.5") !!perl/hash:Math::BigFloat + guts exit 51
1691 # bless {a=>1}, 'Foo' !!perl/hash:Foo + guts exit 51
1692 # an object overloading "" !!perl/hash:Overloaded + guts exit 51
1693 # bless \$s, 'Bar' !!perl/scalar:Bar x exit 51
1694 # sub { 1 } !!perl/code '{ "DUMMY" }' exit 51
1695 # \1 (unblessed) !!perl/ref + `=: 1` exit 51
1696 # qr/abc/ !!perl/regexp (?^:abc) exit 0 (!)
1697 #
1698 # All seven fail their own MAC check here. qr// is the one sops accepts, because
1699 # yaml.v3 resolves the unknown tag to the scalar text -- which is what we
1700 # digested -- while YAML::XS reconstructs a Regexp from it, so File::SOPS cannot
1701 # read back what it just wrote. Both halves of the same disagreement.
1702 #
1703 # JSON has refused all of these since before ADR 0006 (Cpanel::JSON::XS will not
1704 # encode a blessed reference without allow_blessed/convert_blessed/allow_tags),
1705 # which is the asymmetry this closes. See docs/adr/0008.
1706 #
1707 # The exception is the EXACT class, not ->isa: detect_type accepts a
1708 # JSON::PP::Boolean subclass as bool, but YAML::XS writes one as
1709 # `!!perl/scalar:MyBool 1` while the digest still says True -- the same defect
1710 # wearing the whitelist. The exact class is what $YAML::XS::Boolean = 'JSON::PP'
1711 # knows how to write, so it is the only reference that survives this emitter.
1712 #
1713 # Unblessed refs are in scope deliberately: \1 and a coderef fail identically,
1714 # and the callback already has them in hand.
1715 #
1716 # Not in assert_representable: that runs on the verify side too, and over
1717 # leaves that are about to become ENC[...] strings. A blessed leaf in an
1718 # ENCRYPTED slot works in both formats today (type:str, plaintext = the same
1719 # stringification) and must keep working.
1720 #
1721 # $where is the leaf's key path from canonical_float_tree, in the shape the MAC
1722 # walk's messages already use. It goes in FRONT of the message: the class alone
1723 # told a caller what was wrong and left finding it a manual search (k68).
1724 69 ▶sub _reject_unwritable_leaf {
Subroutine _reject_unwritable_leaf: called CC=4 SCAR=13.9
1725 69 my ($node, $where) = @_;
1726  
1727 69 ▶ return if ref($node) eq 'JSON::PP::Boolean';
Branch: 1 branch
BranchTrueFalseTotal
if ref $node eq "JSON::PP::Boolean" 62 7 69
1728  
1729 # A comment leaf reaching the emitter AS A VALUE. Two ways in, and the
1730 # answer is the same for both: an unencrypted slot in a document being
1731 # serialized (sops leaves such a comment as a plain `# ...` LINE, measured),
1732 # and a PLAINTEXT emit -- decrypt_file and edit -- where every leaf is
1733 # written as itself. YAML::XS can write neither, having no way to emit a
1734 # comment at all; and a comment line written into an editor's buffer would
1735 # be dropped by YAML::XS on the way back in, so writing one would be a
1736 # silent loss rather than a round trip. Its own message, because the
1737 # !!perl/-tagged-structure sentence below is true of it and tells the caller
1738 # nothing. See docs/adr/0041.
1739 7 ▶ croak "$where: cannot write a sops comment into this document. A comment "
Branch: 1 branch
BranchTrueFalseTotal
if "File::SOPS::Encrypted"->is_comment($node) 4 3 7
1740 . "is a leaf only where it is ENCRYPTED into a sequence entry -- the "
1741 . "one shape sops writes -- and this document would have to carry it "
1742 . "as plain text, which YAML::XS cannot emit as a comment (it has no "
1743 . "way to write one) and would not read back as a comment either. "
1744 . "That is why decrypt_file and edit refuse a document with a comment "
1745 . "in it rather than dropping the comment on the way through: use "
1746 . "decrypt, which hands back the comment as a File::SOPS::Comment, or "
1747 . "read the file with sops"
1748 if File::SOPS::Encrypted->is_comment($node);
1749  
1750 3 ▶ my $what = blessed($node) ? "a leaf blessed into " . ref($node)
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($node) ? : 3 0 3
1751 : "an unblessed " . ref($node) . " reference";
1752  
1753 3 croak "$where: cannot write $what to a SOPS document: YAML::XS writes it "
1754 . "as a Perl-specific !!perl/ tagged structure while the digest covers its "
1755 . "stringification, so the document and its own MAC would state "
1756 . "different things and neither sops nor this module could read the "
1757 . "file. Pass a plain Perl scalar, or the string you want stored. A "
1758 . "boolean has to be an exact JSON::PP::Boolean (JSON->true / "
1759 . "JSON->false); a subclass of it is written as a tag as well";
1760 }
1761  
1762 ###############################################################################
1763 # The reader on the other side of the file (k86, docs/adr/0013)
1764 #
1765 # Everything above asks THIS distribution's emitter what it does. This asks what
1766 # Go's gopkg.in/yaml.v3 -- the parser sops uses -- makes of the bytes we are
1767 # about to write, because sops recomputes the MAC from the values ITS parser
1768 # resolves. YAML::XS is libyaml, whose resolver is YAML 1.1 as libyaml
1769 # implements it; yaml.v3's is neither 1.1 nor 1.2 but its own. Where the two
1770 # land on different values, the document and its own MAC state different things.
1771 #
1772 # Measured against sops 3.13.3, leaf under _unencrypted, one document per row:
1773 #
1774 # source we read Go reads sops -d
1775 # 0755 int 755 493 exit 51 <- `mode: 0755`, the real case
1776 # 010 int 10 8 exit 51
1777 # 007 int 7 7 exit 0 <- agrees, 7 is 7 in both bases
1778 # 08 int 8 float 8 exit 0 <- agrees, same digest bytes
1779 # 0o10 str "0o10" int 8 exit 51 <- the mirror case: WE say str
1780 # 0x1f str int 31 exit 51
1781 # 1_000 str int 1000 exit 51
1782 # .inf str +Inf exit 51
1783 # Null str null exit 51
1784 # TRUE str bool exit 51
1785 # True str "True" bool exit 0 <- agrees, Go digests `True`
1786 # 2015-01-01 str time exit 51 <- rendered 2015-01-01T00:00:00Z
1787 # 2015-01-01T12:00:00Z str time exit 0 <- rendered identically
1788 #
1789 # sops itself resolves a plaintext `mode: 0755` to the INTEGER 493 and writes
1790 # that, so the spelling never survives a `sops -e` -- which is why the read path
1791 # needs nothing here, and why the message can name 493 as what to pass instead.
1792 #
1793 # This is NOT typing by text (ADR 0002). detect_type still reads the SV and
1794 # nothing else, and this runs after it. What is inspected here is what a foreign
1795 # parser will make of bytes -- a question the SV cannot answer, because the SV is
1796 # on this side of the file. _quote_sops_timestamp two hundred lines up has
1797 # matched a text pattern in the emitted document for the same reason since 0.003.
1798  
1799 # Go's resolveTable: the first byte decides whether the resolver looks at a
1800 # plain scalar at all. Anything else is a string to it, immediately -- which is
1801 # what keeps `localhost` and `supersecret` from paying for any of this.
1802 91 my $GO_LOOKS_AT = qr/\A[-+.0-9yYnNtTfFoO~]/;
1803  
1804 # Go's resolveMap, mapped to the bytes sops's ToBytes derives from each value.
1805 # A bool is Title-cased (the same rule Encrypted::value_to_bytes follows) and a
1806 # null contributes nothing -- measured: a sops-written `x_unencrypted: null`
1807 # verifies against this module's own digest, which covers the empty string.
1808 91 my %GO_CONSTANT = (
1809 'true' => 'True', 'True' => 'True', 'TRUE' => 'True',
1810 'false' => 'False', 'False' => 'False', 'FALSE' => 'False',
1811 '' => '', '~' => '',
1812 'null' => '', 'Null' => '', 'NULL' => '',
1813 '.inf' => '+Inf', '.Inf' => '+Inf', '.INF' => '+Inf',
1814 '+.inf' => '+Inf', '+.Inf' => '+Inf', '+.INF' => '+Inf',
1815 '-.inf' => '-Inf', '-.Inf' => '-Inf', '-.INF' => '-Inf',
1816 '.nan' => 'NaN', '.NaN' => 'NaN', '.NAN' => 'NaN',
1817 );
1818  
1819 # The DOUBLE go-yaml resolves one of those tokens to, or undef for a token it
1820 # does not resolve to a number at all. Derived from %GO_CONSTANT's own byte
1821 # string rather than from a second list of spellings: there is one token list
1822 # in this module, and a copy of it is how a repair and the guard it depends on
1823 # drift apart (ADR 0002's defect class, and k89's shape one level down).
1824 #
1825 # It lives HERE rather than beside its caller because it reads %GO_CONSTANT,
1826 # and a `my` hash is not in scope above its own declaration. See
1827 # _restore_plain_infinities, k105 and docs/adr/0026.
1828 # The four bytes a repairable token cannot be written without. Built from the
1829 # same %GO_CONSTANT keys, so widening that table widens this with it.
1830 91 my $GO_NON_FINITE_TEXT = do {
1831 91 my @token = grep { $GO_CONSTANT{$_} =~ /\A(?:[-+]Inf|NaN)\z/ } keys %GO_CONSTANT;
1832 91 my %tail = map { (substr($_, -4) => 1) } @token;
1833 91 my $alt = join '|', map { quotemeta } sort keys %tail;
1834 91 qr/(?:$alt)/;
1835 };
1836  
1837 916 ▶sub _go_non_finite_in_text {
Subroutine _go_non_finite_in_text: called CC=2 SCAR=6.9
1838 916 ▶ return $_[0] =~ $GO_NON_FINITE_TEXT ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ /$GO_NON_FINITE_TEXT/ ? : 219 697 916
1839 }
1840  
1841 584 ▶sub _go_non_finite_double {
Subroutine _go_non_finite_double: called CC=5 SCAR=16.1
1842 584 my ($token) = @_;
1843  
1844 584 my $bytes = $GO_CONSTANT{$token};
1845 584 ▶ return undef unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 26 558 584
1846  
1847 558 ▶ return $bytes eq '+Inf' ? $POSITIVE_INFINITY
Branch: 3 branches
BranchTrueFalseTotal
$bytes eq '+Inf' ? : 289 269 558
$bytes eq '-Inf' ? : 134 135 269
$bytes eq 'NaN' ? : 134 1 135
1848 : $bytes eq '-Inf' ? -$POSITIVE_INFINITY
1849 : $bytes eq 'NaN' ? $POSITIVE_INFINITY - $POSITIVE_INFINITY
1850 : undef;
1851 }
1852  
1853 # strconv.ParseInt/ParseUint with base 0, as a digit string. The magnitude is
1854 # accumulated in Perl's own integer space, guarded by a STRING comparison
1855 # against the base's uint64 maximum -- dividing to test for overflow is exactly
1856 # where a double stops being exact, and a wrong answer here is a document
1857 # refused or written for the wrong reason.
1858 91 my %GO_BASE_MAX = (
1859 2 => '1111111111111111111111111111111111111111111111111111111111111111',
1860 8 => '1777777777777777777777',
1861 10 => '18446744073709551615',
1862 16 => 'ffffffffffffffff',
1863 );
1864 91 my $INT64_MAGNITUDE = 9223372036854775808; # 2**63: int64 min is -this
1865  
1866 181 ▶sub _go_digits {
Subroutine _go_digits: called CC=5 SCAR=16.5
1867 181 my ($digits, $base) = @_;
1868  
1869 181 (my $d = lc $digits) =~ s/\A0+(?=.)//;
1870 181 my $max = $GO_BASE_MAX{$base};
1871 181 ▶ return undef if length($d) > length($max);
Branch: 1 branch
BranchTrueFalseTotal
if length $d > length $max 0 181 181
1872 181 ▶ return undef if length($d) == length($max) && $d gt $max;
Branch: 1 branch
BranchTrueFalseTotal
if length $d == length $max and $d gt $max 0 181 181
Condition66%2/3
length $d == length $max and $d gt $max
!ll&&!rl&&r
17650
MC/DC0%0/2
length $d == length $max and $d gt $max
length $d == length $max $d gt $max
Truth table66%2/3
A and B
A= length $d == length $maxB= $d gt $max
ABresult
0X0
100
111
1873  
1874 181 my $v = 0;
1875 181 $v = $v * $base + index('0123456789abcdef', $_) for split //, $d;
1876 181 return $v;
1877 }
1878  
1879 # undef: not an integer to Go. 'RANGE': an integer it reads as a uint64, which
1880 # sops has no case for -- measured, `sops -e` on a plaintext 9223372036854775808
1881 # fails with `Cannot walk value, unknown type: uint64`, exit 23. Otherwise the
1882 # decimal text sops would digest.
1883 282 ▶sub _go_int {
Subroutine _go_int: called CC=14 SCAR=26.4
1884 282 my ($p) = @_;
1885  
1886 282 ▶ my $neg = ($p =~ s/\A-//) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$p =~ s/\A-// ? : 23 259 282
1887 282 $p =~ s/\A\+//;
1888 282 ▶ return undef unless length $p;
Branch: 1 branch
BranchTrueFalseTotal
unless length $p 0 282 282
1889  
1890 282 my $v;
1891 282 ▶ if ($p =~ /\A0[xX]([0-9a-fA-F]+)\z/) { $v = _go_digits($1, 16) }
Branch: 5 branches
BranchTrueFalseTotal
if ($p =~ /\A0[xX]([0-9a-fA-F]+)\z/) { } 14 268 282
elsif ($p =~ /\A0[bB]([01]+)\z/) { } 5 263 268
elsif ($p =~ /\A0[oO]([0-7]+)\z/) { } 15 248 263
elsif ($p =~ /\A0([0-7]*)\z/) { } 83 165 248
elsif ($p =~ /\A[1-9][0-9]*\z/) { } 64 101 165
1892 5 elsif ($p =~ /\A0[bB]([01]+)\z/) { $v = _go_digits($1, 2) }
1893 15 elsif ($p =~ /\A0[oO]([0-7]+)\z/) { $v = _go_digits($1, 8) }
1894 83 elsif ($p =~ /\A0([0-7]*)\z/) { $v = _go_digits($1, 8) }
1895 64 elsif ($p =~ /\A[1-9][0-9]*\z/) { $v = _go_digits($p, 10) }
1896 101 else { return undef }
1897  
1898 181 ▶ return undef unless defined $v; # past uint64: Go falls through to float
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 181 181
1899 # `-0` is the integer 0 to Go, sign and all: strconv.Itoa(0) is `0`, and a
1900 # document holding `-0` verifies against a digest covering `0` (measured,
1901 # exit 0). The sign only survives on a FLOAT, which is ADR 0006's -0.0.
1902 181 ▶ return $neg && $v ? "-$v" : "$v"
Branch: 3 branches
BranchTrueFalseTotal
if $neg ? $v <= $INT64_MAGNITUDE : $v < $INT64_MAGNITUDE 176 5 181
$neg ? : 9 172 181
$neg && $v ? : 6 170 176
Condition100%3/3
$neg and $v
!ll&&!rl&&r
16736
MC/DC100%2/2
$neg and $v
$neg $v
Truth table100%3/3
A and B
A= $negB= $v
ABresult
0X0
100
111
1903 if $neg ? $v <= $INT64_MAGNITUDE : $v < $INT64_MAGNITUDE;
1904 5 ▶ return undef if $neg; # ParseUint rejects a sign
Branch: 1 branch
BranchTrueFalseTotal
if $neg 0 5 5
1905 5 return 'RANGE';
1906 }
1907  
1908 # strconv.ParseFloat, through the one conversion this distribution has for a
1909 # double. The CANONICAL TEXT decides whether Go got a number, never a numeric
1910 # comparison of the scalar: `$nv == 0` sets the public IOK on an integral NV and
1911 # takes the sign off -0.0 with it, which is ADR 0002's contamination in the one
1912 # place that must not have it.
1913 #
1914 # The copy is pack/unpack for the same reason, and this one was learned twice.
1915 # It was `value_to_bytes($p * 1.0)` until k89, and Perl's arithmetic settles
1916 # a token like `-0.0e0` on its INTEGER path: the model answered 0, this module
1917 # answered 0, the guard saw agreement, and a document sops -d rejects with exit
1918 # 51 was written silently. A model that shares a conversion with the code it
1919 # checks can only catch the cases where the two happen to differ. Measured, the
1920 # same token scalar three times in one process:
1921 #
1922 # $p * 1.0 0 | 0 | 0 0 + $p 0 | 0 | 0
1923 # $p * 1 0 | 0 | 0 $p - 0.0 0 | 0 | 0
1924 # unpack('d', pack('d', $p)) -0 | -0 | -0
1925 #
1926 # `-0.0` WITHOUT an exponent survives `* 1.0` as an NV, which is why the guard
1927 # was right for it and why this gap outlived ADR 0013. See ADR 0015 and the
1928 # k89 amendment in ADR 0013.
1929 69 ▶sub _go_float {
Subroutine _go_float: called CC=2 SCAR=7.0
1930 69 my ($p) = @_;
1931  
1932 69 my $bytes = File::SOPS::Encrypted->value_to_bytes(unpack('d', pack('d', $p)));
1933 69 ▶ return undef if $bytes =~ /\A[-+]Inf\z/; # Go: ErrRange, so not a float to it
Branch: 1 branch
BranchTrueFalseTotal
if $bytes =~ /\A[-+]Inf\z/ 0 69 69
1934 69 return $bytes;
1935 }
1936  
1937 # Go's parseTimestamp: four layouts, and sops digests what comes out of it as
1938 # RFC3339 NANO -- always a capital T, `Z` for a zero offset, and a fractional
1939 # second that keeps at most nine digits and no trailing zero. So a token agrees
1940 # with itself only when it is already spelled exactly that way; every other shape
1941 # Go PARSES renders differently, and every shape it does not parse is a string to
1942 # it and agrees for free. Measured, leaf under _unencrypted:
1943 #
1944 # 2015-01-01T12:00:00Z exit 0 <- already RFC3339
1945 # 2015-01-01T12:00:00.5Z exit 0 <- Nano keeps the fraction
1946 # 2015-01-01T12:00:00.123456789Z exit 0
1947 # 2015-01-01T12:00:00.50Z exit 51 <- trailing zero trimmed
1948 # 2015-01-01T12:00:00.0Z exit 51 <- fraction disappears entirely
1949 # 2015-01-01T12:00:00.1234567891Z exit 51 <- truncated to nine digits
1950 # 2015-01-01T12:00:00+00:00 exit 51 <- a zero offset renders as Z
1951 # 2015-01-01 exit 51 <- becomes 2015-01-01T00:00:00Z
1952 # 2015-1-01T12:00:00Z exit 51 <- a short field is padded
1953 # 2016-02-29 exit 51 <- a real date, so it is parsed
1954 # 2015-02-29 exit 0 <- not a date, so Go leaves a string
1955 # 2015-01-01T24:00:00Z exit 0 <- hour 24: same, a string
1956 #
1957 # The calendar check is what tells 2016-02-29 from 2015-02-29 -- one is a date
1958 # and the other is not -- and it is why `2024-13-45` and `1234-5678` are not
1959 # refused either.
1960 577 ▶sub _go_timestamp {
Subroutine _go_timestamp: called CC=18 SCAR=29.5
1961 577 my ($s) = @_;
1962  
1963 577 my ($y, $mo, $d, $h, $mi, $sec, $frac, $zone);
1964 577 ▶ if ($s =~ /\A([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})[Tt]([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})(?:\.([0-9]+))?(Z|[-+][0-9]{2}:[0-9]{2})\z/) {
Branch: 3 branches
BranchTrueFalseTotal
if ($s =~ /\A([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})[Tt]([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})(?:\.([0-9]+))?(Z|[-+][0-9]{2}:[0-9]{2})\z/) { } 550 27 577
elsif ($s =~ /\A([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})(?:\.([0-9]+))?\z/) { } 3 24 27
elsif ($s =~ /\A([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})\z/) { } 13 11 24
1965 550 ($y, $mo, $d, $h, $mi, $sec, $frac, $zone) = ($1, $2, $3, $4, $5, $6, $7, $8);
1966 }
1967 elsif ($s =~ /\A([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})(?:\.([0-9]+))?\z/) {
1968 3 ($y, $mo, $d, $h, $mi, $sec, $frac, $zone) = ($1, $2, $3, $4, $5, $6, $7, 'Z');
1969 }
1970 elsif ($s =~ /\A([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})\z/) {
1971 13 ($y, $mo, $d, $h, $mi, $sec, $frac, $zone) = ($1, $2, $3, 0, 0, 0, undef, 'Z');
1972 }
1973 11 else { return undef }
1974  
1975 566 ▶ return undef if $mo < 1 || $mo > 12 || $d < 1 || $h > 23 || $mi > 59 || $sec > 59;
Branch: 1 branch
BranchTrueFalseTotal
if $mo < 1 or $mo > 12 or $d < 1 or $h > 23 or $mi > 59 or $sec > 59 1 565 566
Condition53%8/15
$mo < 1 or $mo > 12 or $d < 1 or $h > 23 or $mi > 59 or $sec > 59
l!l&&r!l&&!r
10565
$mo < 1 or $mo > 12 or $d < 1 or $h > 23 or $mi > 59
l!l&&r!l&&!r
10565
$mo < 1 or $mo > 12 or $d < 1 or $h > 23
l!l&&r!l&&!r
01565
$mo < 1 or $mo > 12 or $d < 1
l!l&&r!l&&!r
00566
$mo < 1 or $mo > 12
l!l&&r!l&&!r
00566
MC/DC16%1/6
$mo < 1 or $mo > 12 or $d < 1 or $h > 23 or $mi > 59 or $sec > 59
$mo < 1 $mo > 12 $d < 1 $h > 23 $mi > 59 $sec > 59
Truth table28%2/7
A or B or C or D or E or F
A= $mo < 1B= $mo > 12C= $d < 1D= $h > 23E= $mi > 59F= $sec > 59
ABCDEFresult
1XXXXX1
01XXXX1
001XXX1
0001XX1
00001X1
0000011
0000000
1976 565 my @length = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
1977 565 ▶ my $last = $mo == 2 && (($y % 4 == 0 && $y % 100 != 0) || $y % 400 == 0)
Branch: 1 branch
BranchTrueFalseTotal
$mo == 2 && ($y % 4 == 0 && $y % 100 != 0 || $y % 400 == 0) ? : 1 564 565
Condition77%7/9
$mo == 2 and $y % 4 == 0 && $y % 100 != 0 || $y % 400 == 0
!ll&&!rl&&r
56311
$y % 4 == 0 and $y % 100 != 0 or $y % 400 == 0
l!l&&r!l&&!r
101
$y % 4 == 0 and $y % 100 != 0
!ll&&!rl&&r
101
MC/DC50%2/4
$mo == 2 and $y % 4 == 0 && $y % 100 != 0 || $y % 400 == 0
$mo == 2 $y % 4 == 0 $y % 100 != 0 $y % 400 == 0
Truth table50%3/6
A and B and C or D
A= $mo == 2B= $y % 4 == 0C= $y % 100 != 0D= $y % 400 == 0
ABCDresult
0XXX0
10X00
11000
111X1
10X11
11011
1978 ? 29 : $length[$mo - 1];
1979 565 ▶ return undef if $d > $last;
Branch: 1 branch
BranchTrueFalseTotal
if $d > $last 1 564 565
1980  
1981 564 my $nano = '';
1982 564 ▶ if (defined $frac) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $frac) 18 546 564
1983 18 (my $digits = substr($frac, 0, 9)) =~ s/0+\z//;
1984 18 ▶ $nano = ".$digits" if length $digits;
Branch: 1 branch
BranchTrueFalseTotal
if length $digits 14 4 18
1985 }
1986 564 ▶ $zone = 'Z' if $zone =~ /\A[-+]00:00\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $zone =~ /\A[-+]00:00\z/ 8 556 564
1987 564 return sprintf('%04d-%02d-%02dT%02d:%02d:%02d%s%s',
1988 $y, $mo, $d, $h, $mi, $sec, $nano, $zone);
1989 }
1990  
1991 # The bytes sops digests for this token when it stands BARE in a YAML document,
1992 # or undef for "this module cannot prove what Go does with it".
1993 #
1994 # A model, and treated as one: written from yaml.v3's resolve() and sops's
1995 # ToBytes, and verified branch by branch against the binary rather than trusted.
1996 # There is no oracle to ask instead -- the reader is in another process, in
1997 # another language, and YAML::PP, this distribution's second parser, resolves
1998 # 0755 as 755 like libyaml and unlike Go, so it agrees with the side that is
1999 # already wrong.
2000 618 ▶sub _go_scalar_bytes {
Subroutine _go_scalar_bytes: called CC=14 SCAR=27.3
2001 618 my ($s) = @_;
2002  
2003 618 ▶ return '' unless length $s;
Branch: 1 branch
BranchTrueFalseTotal
unless length $s 0 618 618
2004 618 ▶ return $s unless $s =~ $GO_LOOKS_AT;
Branch: 1 branch
BranchTrueFalseTotal
unless $s =~ /$GO_LOOKS_AT/ 0 618 618
2005 618 ▶ return $GO_CONSTANT{$s} if exists $GO_CONSTANT{$s};
Branch: 1 branch
BranchTrueFalseTotal
if exists $GO_CONSTANT{$s} 188 430 618
2006  
2007 430 my $first = substr($s, 0, 1);
2008  
2009 # Hinted only because it could have been a constant, and it was not.
2010 430 ▶ return $s if index('yYnNtTfFoO~', $first) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if index("yYnNtTfFoO~", $first) != -1 105 325 430
2011  
2012 # Go's case '.': ParseFloat on the token as it stands, underscores included --
2013 # they are part of a Go float literal, but only BETWEEN digits, which is why
2014 # `._5` is a string to it and `.5_0` is the number 0.5. `.`, `..`,
2015 # `.gitignore` and `.env` match nothing here and stay strings, as they are on
2016 # both sides (measured, exit 0).
2017 325 ▶ if ($first eq '.') {
Branch: 1 branch
BranchTrueFalseTotal
if ($first eq ".") 5 320 325
2018 5 (my $stripped = $s) =~ tr/_//d;
2019 5 ▶ return _go_float($stripped) // $s
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /\A\.[0-9]+(?:_[0-9]+)*(?:[eE][-+]?[0-9]+(?:_[0-9]+)*)?\z/ 0 5 5
Condition0%0/3
_go_float($stripped) // $s
l!l&&r!l&&!r
000
MC/DC0%0/2
_go_float($stripped) // $s
_go_float($stripped) $s
Truth table0%0/3
A // B
A= _go_float($stripped)B= $s
ABresult
1X1
011
000
2020 if $s =~ /\A\.[0-9]+(?:_[0-9]+)*(?:[eE][-+]?[0-9]+(?:_[0-9]+)*)?\z/;
2021 5 return $s;
2022 }
2023  
2024 # A timestamp is tried before any number, and only for exactly four leading
2025 # digits followed by `-` (Go's own quick check), so `12345-01-01` is not one.
2026 320 ▶ return _go_timestamp($s) // $s if $s =~ /\A[0-9]{4}-/;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /\A[0-9]{4}-/ 38 282 320
Condition66%2/3
_go_timestamp($s) // $s
l!l&&r!l&&!r
2990
MC/DC0%0/2
_go_timestamp($s) // $s
_go_timestamp($s) $s
Truth table66%2/3
A // B
A= _go_timestamp($s)B= $s
ABresult
1X1
011
000
2027  
2028 282 my $plain = $s;
2029 282 $plain =~ tr/_//d; # Go strips every underscore first
2030  
2031 282 my $int = _go_int($plain);
2032 282 ▶ if (defined $int) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $int) 181 101 282
2033 181 ▶ return undef if $int eq 'RANGE';
Branch: 1 branch
BranchTrueFalseTotal
if $int eq "RANGE" 5 176 181
2034 176 return $int;
2035 }
2036  
2037 # yamlStyleFloat, the regexp resolve.go gates ParseFloat with.
2038 101 ▶ return _go_float($plain) // $s
Branch: 1 branch
BranchTrueFalseTotal
if $plain =~ /\A[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+)?\z/ 69 32 101
Condition33%1/3
_go_float($plain) // $s
l!l&&r!l&&!r
6900
MC/DC0%0/2
_go_float($plain) // $s
_go_float($plain) $s
Truth table33%1/3
A // B
A= _go_float($plain)B= $s
ABresult
1X1
011
000
2039 if $plain =~ /\A[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+)?\z/;
2040  
2041 32 return $s;
2042 }
2043  
2044 # What YAML::XS actually writes for this leaf, when it writes it as a bare
2045 # single-line plain scalar -- and undef when it does not, because a quoted or
2046 # block scalar is a string to every YAML reader and cannot be resolved into
2047 # anything else. Measured rather than modelled: libyaml quotes a string its OWN
2048 # resolver would read as a number, a boolean or a null ('007', '5432', 'yes',
2049 # '1:30' all come back quoted), and that is most of the reason this guard fires
2050 # as rarely as it does.
2051 677 ▶sub _emitted_plain_scalar {
Subroutine _emitted_plain_scalar: called CC=4 SCAR=13.9
2052 677 my ($leaf) = @_;
2053  
2054 677 local $YAML::XS::Boolean = $BOOLEAN_MODE;
2055 677 ▶ my $dump = eval { Dump({ v => $leaf }) };
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
2056 677 ▶ return undef unless defined $dump && $dump =~ /\A---\nv: (.*)\n\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dump and $dump =~ /\A---\nv: (.*)\n\z/ 4 673 677
Condition66%2/3
defined $dump and $dump =~ /\A---\nv: (.*)\n\z/
!ll&&!rl&&r
04673
MC/DC50%1/2
defined $dump and $dump =~ /\A---\nv: (.*)\n\z/
defined $dump $dump =~ /\A---\nv: (.*)\n\z/
Truth table66%2/3
A and B
A= defined $dumpB= $dump =~ /\A---\nv: (.*)\n\z/
ABresult
0X0
100
111
2057  
2058 673 my $token = $1;
2059 673 ▶ return undef if $token =~ /\A['"|>&*!]/;
Branch: 1 branch
BranchTrueFalseTotal
if $token =~ /\A['"|>&*!]/ 9 664 673
2060 664 return $token;
2061 }
2062  
2063 602 ▶sub _go_agrees {
Subroutine _go_agrees: called CC=3 SCAR=11.0
2064 602 my ($token, $text) = @_;
2065  
2066 602 my $bytes = _go_scalar_bytes($token);
2067 602 ▶ return defined $bytes && $bytes eq $text ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $bytes && $bytes eq $text ? : 440 162 602
Condition100%3/3
defined $bytes and $bytes eq $text
!ll&&!rl&&r
4158440
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
2068 }
2069  
2070 # WHY the two disagree, for the message. A property of the spelling, never the
2071 # spelling itself: an error goes into bug reports.
2072 56 ▶sub _foreign_resolution_reason {
Subroutine _foreign_resolution_reason: called CC=8 SCAR=20.8
2073 56 my ($token) = @_;
2074  
2075 56 ▶ return 'a leading-zero integer, which libyaml reads as decimal and Go as octal'
Branch: 1 branch
BranchTrueFalseTotal
if $token =~ /\A[-+]?0[0-9]+\z/ 14 42 56
2076 if $token =~ /\A[-+]?0[0-9]+\z/;
2077 42 ▶ return 'a 0o / 0x / 0b prefixed number, which Go resolves and libyaml does not'
Branch: 1 branch
BranchTrueFalseTotal
if $token =~ /\A[-+]?0[obxOBX]/ 15 27 42
2078 if $token =~ /\A[-+]?0[obxOBX]/;
2079 27 ▶ return 'a number written with _ digit separators, which Go strips and libyaml does not'
Branch: 1 branch
BranchTrueFalseTotal
if $token =~ /_/ 7 20 27
2080 if $token =~ /_/;
2081 20 ▶ return 'a date or timestamp, which Go resolves to a time and renders back in RFC3339'
Branch: 1 branch
BranchTrueFalseTotal
if $token =~ /\A[0-9]{4}-/ 7 13 20
2082 if $token =~ /\A[0-9]{4}-/;
2083 return 'a YAML 1.2 constant -- an infinity, a not-a-number, a null, or a '
2084 . 'boolean spelled in a case libyaml leaves a string'
2085 13 ▶ if $token =~ /\A[-+]?\./ || exists $GO_CONSTANT{$token};
Branch: 1 branch
BranchTrueFalseTotal
if $token =~ /\A[-+]?\./ or exists $GO_CONSTANT{$token} 12 1 13
Condition100%3/3
$token =~ /\A[-+]?\./ or exists $GO_CONSTANT{$token}
l!l&&r!l&&!r
1111
MC/DC100%2/2
$token =~ /\A[-+]?\./ or exists $GO_CONSTANT{$token}
$token =~ /\A[-+]?\./ exists $GO_CONSTANT{$token}
Truth table100%3/3
A or B
A= $token =~ /\A[-+]?\./B= exists $GO_CONSTANT{$token}
ABresult
1X1
011
000
2086 1 ▶ return 'a number outside the int64 range, which sops refuses to write at all'
Branch: 1 branch
BranchTrueFalseTotal
unless defined _go_scalar_bytes($token) 1 0 1
2087 unless defined _go_scalar_bytes($token);
2088 0 return 'a spelling the two resolvers do not agree on';
2089 }
2090  
2091 # Could Go's resolver look at what the emitter will write for this leaf? A gate,
2092 # never an answer: it decides whether the emit below is worth paying for, and
2093 # the verdict is taken from the token that emit returns.
2094 #
2095 # The stringification stands in for the token here, and it may: for a leaf that
2096 # is not a boolean the two are the same string, or the token is quoted. Probed
2097 # over 2119 non-bool leaves -- every printable ASCII character alone and in
2098 # either position, 600 integers, 900 floats over 30 orders of magnitude, the
2099 # int64 and subnormal edges, dualvars, embedded newlines, leading whitespace,
2100 # non-ASCII -- 2 tokens start with a different byte, and both are the UTF-8
2101 # encoding of a non-ASCII first character. Neither can matter: every UTF-8 byte
2102 # is >= \x80 and every byte in $GO_LOOKS_AT is ASCII.
2103 #
2104 # A BOOLEAN is the exception and gets the second clause. Its stringification is
2105 # `1` or the empty string while both emitters write a bare `true`/`false`
2106 # (docs/adr/0016), so the empty one slipped past this gate entirely. detect_type
2107 # is the same ladder the digest goes through and the same predicate the emitters
2108 # use -- not a second answer to the question of what a boolean is.
2109 9095 ▶sub _go_might_look_at {
Subroutine _go_might_look_at: called CC=3 SCAR=11.0
2110 9095 my ($leaf) = @_;
2111  
2112 9095 ▶ return 1 if "$leaf" =~ $GO_LOOKS_AT;
Branch: 1 branch
BranchTrueFalseTotal
if "$leaf" =~ /$GO_LOOKS_AT/ 595 8500 9095
2113 8500 ▶ return File::SOPS::Encrypted->detect_type($leaf) eq 'bool' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
'File::SOPS::Encrypted'->detect_type($leaf) eq 'bool' ? : 18 8482 8500
2114 }
2115  
2116 # The token this emitter writes for a leaf whose SPELLING this module cannot
2117 # prove Go resolves the way it does, and WHICH KIND of disagreement it is --
2118 # and the empty list when there is nothing to say.
2119 #
2120 # 'mac' Go derives different BYTES from the token, so the document would
2121 # state one value and its own MAC cover another.
2122 # 'type' Go derives the same bytes and a different TYPE. The MAC holds and
2123 # sops reads the file; what it reads is not what this module reads.
2124 #
2125 # ONE check, three verdicts. What a document does with the answer depends on
2126 # whether its MAC covers the leaf (refuse: the file would fail its own MAC) or
2127 # not (warn: the two implementations simply read different values). A 'type'
2128 # disagreement is never refused -- the MAC covers the same bytes either way and
2129 # there is nothing to refuse -- and since docs/adr/0070 the mac_covered path
2130 # force-quotes the safe set (True/False among it) BEFORE this check runs, so a
2131 # 'type' leaf reaches the check, and is warned about, only under
2132 # mac_only_encrypted. A second copy of the check for a second verdict is the
2133 # defect class this whole layer keeps producing, so there is one. See
2134 # docs/adr/0018, docs/adr/0019 and docs/adr/0070.
2135 #
2136 # Runs on the encrypt path only, and never over the `sops` branch: the digest
2137 # does not cover the metadata, and the one leaf there that Go resolves
2138 # differently -- lastmodified, which it reads as a time -- is already handled,
2139 # by _quote_sops_timestamp and the other way round, by quoting it.
2140 #
2141 # Encrypted slots cannot reach this at all: _encrypt_tree has replaced every
2142 # encrypted leaf with an ENC[...] string long before the emitter runs, and that
2143 # string starts with `E`, which no resolver looks twice at.
2144 14935 ▶sub _foreign_resolution_token {
Subroutine _foreign_resolution_token: called CC=8 SCAR=20.8
2145 14935 my ($leaf, $path, $text) = @_;
2146  
2147 14935 ▶ return if @$path && $path->[0] eq 'sops';
Branch: 1 branch
BranchTrueFalseTotal
if @$path and $path->[0] eq "sops" 5840 9095 14935
Condition66%2/3
@$path and $path->[0] eq "sops"
!ll&&!rl&&r
090955840
MC/DC50%1/2
@$path and $path->[0] eq "sops"
@$path $path->[0] eq "sops"
Truth table66%2/3
A and B
A= @$pathB= $path->[0] eq "sops"
ABresult
0X0
100
111
2148 9095 ▶ return unless _go_might_look_at($leaf);
Branch: 1 branch
BranchTrueFalseTotal
unless _go_might_look_at($leaf) 8482 613 9095
2149  
2150 # WHAT THE EMITTER WRITES is the only thing Go gets to resolve, so it is the
2151 # only thing asked about. The leaf's stringification decided this until
2152 # k91 -- it is the same string for every leaf class but a boolean, and
2153 # for a boolean it was wrong in both directions: k90 reached a document
2154 # through exactly that step, because `1` resolved to the `1` the digest then
2155 # covered and the guard returned before asking the emitter anything. A
2156 # quoted or multi-line scalar is a string to every YAML reader, and undef
2157 # here says so. See docs/adr/0017.
2158 613 my $token = _emitted_plain_scalar($leaf);
2159 613 ▶ return unless defined $token;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $token 11 602 613
2160  
2161 # THE one conversion -- the text the MAC digest covers. The walk hands it
2162 # over where it already derived one (and for a carrier that is the ORIGINAL
2163 # value's text, which is what the digest has); otherwise it comes from the
2164 # same method on the same scalar. Never a second rendering derived here.
2165 602 ▶ $text //= File::SOPS::Encrypted->value_to_bytes($leaf);
Condition66%2/3
$text //= "File::SOPS::Encrypted"->value_to_bytes($leaf)
l!l&&r!l&&!r
775250
MC/DC0%0/2
$text //= "File::SOPS::Encrypted"->value_to_bytes($leaf)
$text "File::SOPS::Encrypted"->value_to_bytes($leaf)
Truth table66%2/3
A //= B
A= $textB= "File::SOPS::Encrypted"->value_to_bytes($leaf)
ABresult
1X1
011
000
2166 602 ▶ return ($token, 'mac') unless _go_agrees($token, $text);
Branch: 1 branch
BranchTrueFalseTotal
unless _go_agrees($token, $text) 162 440 602
2167  
2168 # The bytes agree and the TYPE does not. A second axis, invisible to
2169 # everything above: the digest cannot see it, so neither could this guard
2170 # until k92. See docs/adr/0019.
2171 440 ▶ return ($token, 'type') if _go_retypes($leaf, $token);
Branch: 1 branch
BranchTrueFalseTotal
if _go_retypes($leaf, $token) 21 419 440
2172  
2173 419 return;
2174 }
2175  
2176 # The tokens Go resolves to a boolean, derived from the one table rather than
2177 # listed a second time next to it.
2178 546 my %GO_BOOL_TOKEN = map { $_ => 1 }
2179 91 ▶ grep { $GO_CONSTANT{$_} eq 'True' || $GO_CONSTANT{$_} eq 'False' }
Condition100%3/3
$GO_CONSTANT{$_} eq 'True' || $GO_CONSTANT{$_} eq 'False'
l!l&&r!l&&!r
2732731547
MC/DC100%2/2
$GO_CONSTANT{$_} eq 'True' || $GO_CONSTANT{$_} eq 'False'
$GO_CONSTANT{$_} eq 'True' $GO_CONSTANT{$_} eq 'False'
Truth table100%3/3
A || B
A= $GO_CONSTANT{$_} eq 'True'B= $GO_CONSTANT{$_} eq 'False'
ABresult
1X1
011
000
2180 keys %GO_CONSTANT;
2181  
2182 # Does Go read a BOOLEAN out of a token whose bytes already agree with the
2183 # digest? Only `True` and `False` can be here: libyaml quotes `true` and
2184 # `false` (its own resolver knows them), and `TRUE` / `FALSE` disagree on bytes
2185 # -- sops digests a boolean Title-cased -- so they are refused one step up.
2186 #
2187 # What that leaves is a string here and a bool to sops, in a document neither of
2188 # them complains about: measured, sops -d exit 0 and `true` in its output. It is
2189 # not stable, either -- `sops rotate`, `sops set` and `sops edit` each write the
2190 # resolved value back as a bare `true`, after which this module reads a boolean
2191 # too, so the caller's string is gone.
2192 #
2193 # Both authorities are the ones already in use: %GO_CONSTANT for what Go makes
2194 # of the token, detect_type for what the leaf is. A leaf that really is a
2195 # boolean writes `true` and is read as one on both sides -- nothing to say.
2196 440 ▶sub _go_retypes {
Subroutine _go_retypes: called CC=3 SCAR=11.0
2197 440 my ($leaf, $token) = @_;
2198  
2199 440 ▶ return 0 unless $GO_BOOL_TOKEN{$token};
Branch: 1 branch
BranchTrueFalseTotal
unless $GO_BOOL_TOKEN{$token} 355 85 440
2200 85 ▶ return File::SOPS::Encrypted->detect_type($leaf) eq 'bool' ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
'File::SOPS::Encrypted'->detect_type($leaf) eq 'bool' ? : 64 21 85
2201 }
2202  
2203 # The MAC holds and the two implementations still read different things, so
2204 # there is nothing to refuse and something to say. The message does not depend
2205 # on the MAC mode, which is why one sub serves both call sites. Since
2206 # docs/adr/0070 the mac_covered path force-quotes a True/False leaf before the
2207 # guard runs, so in normal operation this carp fires only under
2208 # mac_only_encrypted; the mac_covered site (_reject_foreign_resolution) reaches
2209 # it only on the fail-closed fallback, when the sentinel surgery is abandoned.
2210 # See docs/adr/0019, docs/adr/0070 and k92.
2211 2 ▶sub _carp_foreign_retyping {
Subroutine _carp_foreign_retyping: called CC=1 SCAR=0.0
2212 2 my ($where) = @_;
2213  
2214 2 carp "$where: this leaf is a string here and a boolean to sops. libyaml "
2215 . "leaves the spelling a string while Go's yaml.v3 resolves it as a "
2216 . "boolean, and both digest the same bytes, so the MAC holds and sops "
2217 . "reads the file (measured, sops -d exit 0). What differs is the type: "
2218 . "sops hands the value on as a boolean, and any sops write-back "
2219 . "(rotate, set, edit) rewrites the spelling to a bare true/false, after "
2220 . "which this module reads a boolean as well. Encrypt the leaf -- an "
2221 . "ENC[...] string carries the text verbatim and is a string to both -- "
2222 . "or write the document as JSON, where every string is quoted";
2223 }
2224  
2225 # WHAT TO DO ABOUT IT depends on what the leaf IS, and until k135 the
2226 # message answered for an `int` leaf whatever it was handed.
2227 #
2228 # For a NUMERIC leaf the sentence is right and re-measured against sops 3.13.3:
2229 # a plaintext `mode: 0755` really does leave `sops -e` as the integer 493, the
2230 # spelling does not survive in any form, and passing the decimal produces the
2231 # document sops itself would have written.
2232 #
2233 # For a leaf that is ALREADY A STRING it was wrong in both halves. Given the
2234 # string, sops resolves nothing -- measured, one document per spelling: a
2235 # plaintext `v_unencrypted: "1_000"` leaves `sops -e` as `v_unencrypted:
2236 # "1_000"`, double-quoted and intact, and `sops -d` reads it back at exit 0 for
2237 # all 22 spellings of this class. And there is no decimal to pass, because the
2238 # value is not a number: what is missing is a way to write a string as anything
2239 # but this bare token, which YAML::XS does not have (no tag, no forced-quote
2240 # hook -- probed over every SV shape and every setting of
2241 # $YAML::XS::QuoteNumericStrings; a dualvar carrier makes it WORSE, writing even
2242 # `0755` bare). YAML::XS cannot quote it directly, so the fifteen ambiguous
2243 # spellings of this class -- whose bare and quoted sources are indistinguishable
2244 # -- stay refused (docs/adr/0008), and this message names the two remedies
2245 # measured to work for all 22 of the class: encrypt it (22 of 22 sops -d exit 0)
2246 # or write the document as JSON (22 of 22). The other seven -- the
2247 # parse-unambiguous non-finite str spellings -- no longer reach this message:
2248 # since k99/docs/adr/0070 the emitter force-quotes them through a fail-closed
2249 # sentinel substitution and writes them, rather than refusing. See
2250 # docs/adr/0039, k135, docs/adr/0070 and k99.
2251 #
2252 # detect_type is the ladder the digest already goes through, not a second
2253 # opinion about what the leaf is -- and not a pattern on its text.
2254 47 ▶sub _foreign_resolution_remedy {
Subroutine _foreign_resolution_remedy: called CC=2 SCAR=6.9
2255 47 my ($leaf) = @_;
2256  
2257 47 ▶ return "This leaf is already a STRING here, and sops does not resolve a "
Branch: 1 branch
BranchTrueFalseTotal
if "File::SOPS::Encrypted"->detect_type($leaf) eq "str" 36 11 47
2258 . "string away: it writes one double-quoted and reads it back "
2259 . "(measured, sops -d exit 0). What this emitter cannot do is write it "
2260 . "that way -- YAML::XS has no per-scalar style control, so the only "
2261 . "token it produces for this leaf is the bare one Go resolves into "
2262 . "something else, and there is no other spelling of the same string to "
2263 . "pass instead. Encrypt the leaf -- an ENC[...] string carries it "
2264 . "verbatim and is unaffected by this rule -- or write the document as "
2265 . "JSON, where every string is quoted"
2266 if File::SOPS::Encrypted->detect_type($leaf) eq 'str';
2267  
2268 11 return "sops itself resolves such a spelling when it writes: a plaintext "
2269 . "`mode: 0755` becomes the integer 493 in its output, and that decimal "
2270 . "is what to pass here. To keep the spelling as text, encrypt the leaf "
2271 . "-- an ENC[...] string carries it verbatim and is unaffected by this "
2272 . "rule";
2273 }
2274  
2275 # The document carries a MAC that covers this leaf, so the disagreement is with
2276 # the file's own verification and there is nothing to write.
2277 7144 ▶sub _reject_foreign_resolution {
Subroutine _reject_foreign_resolution: called CC=3 SCAR=11.0
2278 7144 my ($leaf, $where, $path, $text) = @_;
2279  
2280 7144 my ($token, $kind) = _foreign_resolution_token($leaf, $path, $text);
2281 7144 ▶ return unless defined $token;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $token 7096 48 7144
2282 48 ▶ return _carp_foreign_retyping($where) if $kind eq 'type';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "type" 1 47 48
2283  
2284 47 croak "$where: cannot write this leaf to a SOPS YAML document: its spelling "
2285 . "is " . _foreign_resolution_reason($token) . ". The MAC digest covers "
2286 . "the value this module resolves, while sops re-reads the document with "
2287 . "Go's yaml.v3 and resolves a different one, so the file would fail its "
2288 . "own MAC and neither sops nor this module could read it back (measured, "
2289 . "sops -d exit 51). " . _foreign_resolution_remedy($leaf);
2290 }
2291  
2292 # mac_only_encrypted: the digest covers encrypted values only, so this leaf
2293 # cannot make the document disagree with its own MAC and refusing it would
2294 # refuse a file that works. What is left is that the two implementations read
2295 # different VALUES out of a document neither of them complains about -- measured
2296 # for `mode_unencrypted: 0755`, sops -d exit 0 and it reads 493 where this
2297 # module reads 755. Nothing tells the caller that but this line. See k87
2298 # and docs/adr/0018.
2299 #
2300 # carp rather than warn, for the same reason the refusals croak: the line worth
2301 # printing is the caller's, and @CARP_NOT above already walks out of the emitter
2302 # and the walk. The value never appears here -- a warning goes to logs.
2303 309 ▶sub _warn_foreign_resolution {
Subroutine _warn_foreign_resolution: called CC=3 SCAR=11.0
2304 309 my ($leaf, $where, $path, $text) = @_;
2305  
2306 309 my ($token, $kind) = _foreign_resolution_token($leaf, $path, $text);
2307 309 ▶ return unless defined $token;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $token 299 10 309
2308 10 ▶ return _carp_foreign_retyping($where) if $kind eq 'type';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "type" 1 9 10
2309  
2310 9 carp "$where: this leaf's spelling is " . _foreign_resolution_reason($token)
2311 . ", so sops resolves a different value from the one this module reads. "
2312 . "With mac_only_encrypted set the MAC does not cover this leaf, so "
2313 . "nothing will fail -- the document is written and sops reads it. "
2314 . _foreign_resolution_warning_remedy($leaf);
2315 }
2316  
2317 # The same split as the refusal's, and for the same measured reason: there is no
2318 # value to pass for a leaf that is already a string, because the string IS the
2319 # value and the emitter cannot write it quoted. See docs/adr/0039 and k135.
2320 9 ▶sub _foreign_resolution_warning_remedy {
Subroutine _foreign_resolution_warning_remedy: called CC=2 SCAR=6.9
2321 9 my ($leaf) = @_;
2322  
2323 9 ▶ return "This leaf is already a string here, and sops writes such a string "
Branch: 1 branch
BranchTrueFalseTotal
if "File::SOPS::Encrypted"->detect_type($leaf) eq "str" 5 4 9
2324 . "double-quoted rather than resolving it away -- this emitter cannot, "
2325 . "because YAML::XS has no per-scalar style control, so there is no "
2326 . "value to pass instead. Encrypt the leaf, or write the document as "
2327 . "JSON where every string is quoted, to make the two agree"
2328 if File::SOPS::Encrypted->detect_type($leaf) eq 'str';
2329  
2330 4 return "Pass the value sops itself would write (measured: a `mode: 0755` is "
2331 . "493 to sops and 755 here), or encrypt the leaf, to make the two agree";
2332 }
2333  
2334 ###############################################################################
2335  
2336 # Does YAML::XS's own rendering of this float come back as the same double?
2337 #
2338 # Measured, not modelled: the value goes through the real Dump and the real
2339 # Load. YAML::XS renders a float by Perl stringification, which is ~15
2340 # significant digits, so 0.1+0.2 comes back as 0.3 -- a different number from
2341 # the one value_to_bytes digested, and a document that fails its own MAC.
2342 #
2343 # It answers YES far more often than that suggests, and that is the point:
2344 # YAML::XS retains the PV of every float it PARSES and emits it verbatim, so a
2345 # value read from a document round-trips by construction and keeps the exact
2346 # bytes it arrived with. Only floats that reach us as bare NVs -- computed by
2347 # the caller, or parsed out of JSON -- ever need the carrier.
2348 #
2349 # Equality is decided by value_to_bytes on both sides rather than by ==, so it
2350 # means the same thing the digest means. == cannot tell -0.0 from 0.0.
2351 66 ▶sub _float_roundtrips {
Subroutine _float_roundtrips: called CC=3 SCAR=11.0
2352 66 my ($value, $text) = @_;
2353  
2354 66 ▶ my $back = eval { Load(Dump({ v => $value }))->{v} };
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
2355 66 ▶ return 0 unless defined $back;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $back 0 66 66
2356 66 ▶ 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 ? : 57 9 66
2357 }
2358  
2359 # A dualvar's numeric half keeps the value a float for anything that looks at
2360 # the SV; YAML::XS writes the string half, unquoted, as a plain scalar.
2361 #
2362 # Note what this is: a raw-text primitive with no guard rail. YAML::XS emits
2363 # whatever the PV says -- dualvar(0.3, 'hello') writes `v: hello` -- so this is
2364 # safe only because $text came from value_to_bytes. Do not derive it here.
2365 #
2366 # The ONE exception, and the only place in this distribution where a written
2367 # decimal is not value_to_bytes's output verbatim: a negative zero. Its
2368 # canonical text is `-0`, which YAML resolves as an INTEGER -- Go's yaml.v3 and
2369 # YAML::XS agree on that -- so a document carrying `-0` is digested as `0` by
2370 # every reader while our MAC covers `-0`. Measured against sops 3.13.3, one
2371 # document per spelling, leaf under _unencrypted, digest `-0`:
2372 #
2373 # -0 sops -d exit 51 (MAC mismatch) self-MAC FAIL <- k62
2374 # !!float -0 sops -d exit 51 self-MAC FAIL
2375 # -0.0 sops -d exit 0, reads back -0 self-MAC OK <- this
2376 # -0. sops -d exit 0 self-MAC OK
2377 # -0.0e0 sops -d exit 0 self-MAC OK <- k89
2378 #
2379 # sops cannot write this value either: `sops -e` on a plaintext `-0.0` emits
2380 # `-0` and then rejects its own file with exit 51, in YAML and in JSON alike.
2381 # So `-0.0` is not "the bytes sops writes", it is the only spelling both
2382 # implementations read as the double the digest covers -- which is exactly what
2383 # ADR 0006 asks of an emitted decimal, and it says so: the text has to parse
2384 # back to the same double, not to be spelled canonically.
2385 #
2386 # Narrow on purpose. `-0` is the only canonical float text an integer
2387 # resolution changes the digest of: every other integral one digests the same
2388 # whether Go reads it as an int or a float (`3` is `3` either way), and every
2389 # float that needs a fraction already carries a `.`. A general "append .0"
2390 # would move bytes for cases nobody has measured.
2391 27 ▶sub _float_carrier {
Subroutine _float_carrier: called CC=2 SCAR=6.9
2392 27 my ($value, $text) = @_;
2393 27 ▶ return dualvar($value, $text eq '-0' ? '-0.0' : $text);
Branch: 1 branch
BranchTrueFalseTotal
$text eq '-0' ? : 3 24 27
2394 }
2395  
2396  
2397 779 ▶sub format_name { 'yaml' }
Subroutine format_name: called CC=1 SCAR=0.0
Pod documented
2398  
2399  
2400 0 ▶sub file_extensions { qw(yaml yml) }
Subroutine file_extensions: not called CC=1 SCAR=6.9
Pod documented
2401  
2402  
2403 0 ▶sub detect {
Subroutine detect: not called CC=2 SCAR=17.9
Pod documented
2404 0 my ($class, $filename) = @_;
2405 0 ▶ return 1 if $filename =~ /\.ya?ml$/i;
Branch: 1 branch
BranchTrueFalseTotal
if $filename =~ /\.ya?ml$/i 0 0 0
2406 0 return 0;
2407 }
2408  
2409  
2410  
2411 91 1;
2412  
2413 __END__
« blib/lib/File/SOPS/Format/ENV.pm ↑ Summary blib/lib/File/SOPS/Comment.pm »