blib/lib/File/SOPS.pm

filter: Statementstmt 98.2% 788 / 802 Branchbran 85.4% 393 / 460 Conditioncond 69.6% 211 / 303 MC/DCmcdc 44.3% 82 / 185 Subroutinesub 98.9% 94 / 95 Podpod 100% 9 / 9 totaltotal 85.0% 1577 / 1854 CC 367 SCAR 23.0
CC
367
Cov
89%
_encrypt_tree
26.0
_decrypt_tree
21.0
_verify_mac
20.7
CRAP 10.0
« blib/lib/File/SOPS/Metadata.pm ↑ Summary blib/lib/File/SOPS/Format/INI.pm »
1 package File::SOPS;
2 # ABSTRACT: Perl implementation of Mozilla SOPS encrypted file format
3  
4 80 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 80 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 80 ▶use Cwd ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 80 ▶use Fcntl qw(O_CREAT O_EXCL O_WRONLY);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 80 ▶use File::Basename qw(basename);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 80 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 80 ▶use File::Temp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 80 ▶use Scalar::Util qw(blessed refaddr);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 80 ▶use Text::ParseWords qw(shellwords);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 80 ▶use Digest::SHA qw(sha512);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 # Nothing below calls encode_json, decode_json or JSON(), and namespace::clean
15 # strips all three from this package.
16 #
17 # This line used to be load-bearing for the WIRE FORMAT: loading JSON::MaybeXS
18 # here, ahead of File::SOPS::Encrypted pulling in CryptX (which loads JSON.pm,
19 # and with it JSON::XS), was what decided the JSON backend for the process, and
20 # the backends do not emit or parse the same floats. It is not that any more --
21 # k56 / docs/adr/0005 -- because Format::JSON now names Cpanel::JSON::XS
22 # instead of inheriting whatever the calling program happened to bind. The
23 # ordering here no longer reaches a document.
24 #
25 # What is left is JSON::PP::Boolean for JSON->true/false, and that comes from
26 # File::SOPS::Encrypted's and File::SOPS::Metadata's own `use JSON::MaybeXS`,
27 # in the same files as the calls that need it (all three backends bless into
28 # JSON::PP::Boolean, so it is backend-independent). So this line is now a
29 # genuinely unused import -- which is what k49 first claimed and could not
30 # act on. Removing it is the API lane's call, not a wire question.
31 80 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 # Used directly by _load_creation_rules to read a .sops.yaml, which is a config
33 # file rather than a SOPS document and so does not go through Format::YAML.
34 80 ▶use YAML::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
35 # No YAML::PP here any more. The order-preserving reparse the MAC needs is
36 # the format handler's, not this module's -- see _parse_in_document_order
37 # and docs/adr/0036.
38 80 ▶use File::SOPS::Encrypted;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 80 ▶use File::SOPS::Metadata;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 80 ▶use File::SOPS::Backend::Age;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 80 ▶use File::SOPS::Format::YAML;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 80 ▶use File::SOPS::Format::JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 80 ▶use File::SOPS::Format::ENV;
Subroutine BEGIN: called CC=1 SCAR=0.0
44 80 ▶use File::SOPS::Format::INI;
Subroutine BEGIN: called CC=1 SCAR=0.0
45 80 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
46  
47 80 our $VERSION = '0.003';
48  
49  
50 80 my %FORMATS = (
51 yaml => 'File::SOPS::Format::YAML',
52 yml => 'File::SOPS::Format::YAML',
53 json => 'File::SOPS::Format::JSON',
54 env => 'File::SOPS::Format::ENV',
55 # sops's own name for the format, accepted for the same reason `yml` is:
56 # a caller who knows it from `--input-type dotenv` should not have to
57 # translate. format_name stays 'env'.
58 dotenv => 'File::SOPS::Format::ENV',
59 ini => 'File::SOPS::Format::INI',
60 );
61  
62 # Whether a top-level `sops` entry in $data collides with the format's
63 # metadata namespace. YAML and JSON write their metadata section under that
64 # exact key, so a caller-supplied value would be overwritten -- the failure
65 # mode k18 describes. ENV and INI do not: ENV's metadata is in flat
66 # `sops_*` keys, INI's is in a `[sops]` section, so `data->{sops}` is a
67 # legitimate entry there (k157). Each handler's own serialize-time
68 # guard is the defensive double-check for direct callers of `serialize`;
69 # this hash is the source of truth for the format-blind guard in encrypt().
70 80 my %RESERVES_SOPS_KEY = (
71 'File::SOPS::Format::YAML' => 1,
72 'File::SOPS::Format::JSON' => 1,
73 'File::SOPS::Format::ENV' => 0,
74 'File::SOPS::Format::INI' => 0,
75 );
76  
77 # Everything that describes HOW a document gets encrypted, as opposed to what
78 # gets encrypted or for whom. encrypt and encrypt_file must accept exactly the
79 # same set or the file API silently offers less than the string API does.
80 80 my @ENCRYPTION_OPTIONS = (
81 @File::SOPS::Metadata::ENCRYPTION_RULES,
82 'mac_only_encrypted',
83 'metadata',
84 );
85  
86 sub encrypt {
87 699 ▶ my ($class, %args) = @_;
Subroutine encrypt: called CC=15 SCAR=28.1
Pod documented
88 699 ▶ my $data = $args{data} // croak "data required";
Condition33%1/3
$args{"data"} // croak("data required")
l!l&&r!l&&!r
69900
MC/DC0%0/2
$args{"data"} // croak("data required")
$args{"data"} croak("data required")
Truth table33%1/3
A // B
A= $args{"data"}B= croak("data required")
ABresult
1X1
011
000
89 699 ▶ my $recipients = $args{recipients} // croak "recipients required";
Condition33%1/3
$args{"recipients"} // croak("recipients required")
l!l&&r!l&&!r
69900
MC/DC0%0/2
$args{"recipients"} // croak("recipients required")
$args{"recipients"} croak("recipients required")
Truth table33%1/3
A // B
A= $args{"recipients"}B= croak("recipients required")
ABresult
1X1
011
000
90 699 ▶ my $format = $args{format} // 'yaml';
Condition100%2/2
$args{"format"} // "yaml"
l!l
68019
MC/DC100%1/1
$args{"format"} // "yaml"
$args{"format"}
Truth table100%2/2
A
A= $args{"format"}
Aresult
11
00
91  
92 # A single document is a HashRef; a multi-document YAML stream is an ArrayRef
93 # of HashRefs, one per document (docs/adr/0033 Decision 1, k31). The
94 # ArrayRef form is purely additive -- until 0.003 it raised "data must be a
95 # hash ref" -- and what round-trips is the FILE: a one-element ArrayRef
96 # writes a one-document file byte-identical to the same bare HashRef.
97 699 ▶ croak "data must be a hash ref, or an array ref of hash refs for a "
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" or ref $data eq "ARRAY" 0 699 699
Condition66%2/3
ref $data eq "HASH" or ref $data eq "ARRAY"
l!l&&r!l&&!r
659400
MC/DC0%0/2
ref $data eq "HASH" or ref $data eq "ARRAY"
ref $data eq "HASH" ref $data eq "ARRAY"
Truth table66%2/3
A or B
A= ref $data eq "HASH"B= ref $data eq "ARRAY"
ABresult
1X1
011
000
98 . "multi-document stream"
99 unless ref($data) eq 'HASH' || ref($data) eq 'ARRAY';
100 699 ▶ croak "recipients must be an array ref" unless ref($recipients) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recipients eq "ARRAY" 0 699 699
101  
102 699 ▶ my @documents = ref $data eq 'ARRAY' ? @$data : ($data);
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'ARRAY' ? : 40 659 699
103 699 ▶ croak "data must not be an empty array ref" unless @documents;
Branch: 1 branch
BranchTrueFalseTotal
unless @documents 0 699 699
104  
105 # Resolved BEFORE the sops-key guard: the guard defers to the format handler
106 # to decide whether a top-level `sops` entry collides with its metadata
107 # namespace. YAML and JSON reserve that exact name; ENV and INI do not
108 # (k157), so a bare `sops` data key is legitimate there.
109 699 ▶ my $format_class = $FORMATS{$format} // croak "Unknown format: $format";
Condition33%1/3
$FORMATS{$format} // croak("Unknown format: $format")
l!l&&r!l&&!r
69900
MC/DC0%0/2
$FORMATS{$format} // croak("Unknown format: $format")
$FORMATS{$format} croak("Unknown format: $format")
Truth table33%1/3
A // B
A= $FORMATS{$format}B= croak("Unknown format: $format")
ABresult
1X1
011
000
110  
111 # Per-document guards (docs/adr/0033 Decision 4). Each document is validated
112 # and walked on its own: a tree that contains itself has no document to
113 # write and would recurse until the process died, and the expansion guard
114 # runs second and depends on it (its census memo fills on the way out, so a
115 # cycle would hang it). ONE $active/$clean pair is shared across documents --
116 # the ancestor set is unwound on the way out, so a HashRef a caller
117 # legitimately shares between two documents is a DAG, not a cycle, and is not
118 # refused; sharing $clean is a win. Depth and the alias budget stay
119 # per-document because each document is entered by its own top-level call,
120 # never the document list walked as a container. A single document is one
121 # iteration, byte-identical to before.
122 699 my ($active, $clean) = ({}, {});
123 699 for my $doc (@documents) {
124 700 ▶ croak "each document in data must be a hash ref" unless ref $doc eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $doc eq "HASH" 0 700 700
125 croak _sops_key_reserved('data') if exists $doc->{sops}
126 700 ▶ && $RESERVES_SOPS_KEY{$format_class};
Branch: 1 branch
BranchTrueFalseTotal
if exists $doc->{"sops"} and $RESERVES_SOPS_KEY{$format_class} 5 695 700
Condition100%3/3
exists $doc->{"sops"} and $RESERVES_SOPS_KEY{$format_class}
!ll&&!rl&&r
68965
MC/DC100%2/2
exists $doc->{"sops"} and $RESERVES_SOPS_KEY{$format_class}
exists $doc->{"sops"} $RESERVES_SOPS_KEY{$format_class}
Truth table100%3/3
A and B
A= exists $doc->{"sops"}B= $RESERVES_SOPS_KEY{$format_class}
ABresult
0X0
100
111
127 695 _assert_acyclic($doc, [], $active, $clean);
128 693 _assert_expansion_bounded($doc);
129 }
130  
131 # Generate random 256-bit data key. The one CSPRNG in this distribution
132 # lives next to the per-value nonce that shares its failure mode; see the
133 # comment on File::SOPS::Encrypted::_random_bytes for why a short return
134 # has to be caught there and cannot be caught anywhere else.
135 685 my $data_key = File::SOPS::Encrypted::_random_bytes(32);
136  
137 # Create metadata
138 681 my $metadata = _metadata_for_encrypt(\%args);
139 672 $metadata->update_lastmodified;
140  
141 # Encrypt data key for each recipient
142 672 my $encrypted_keys = File::SOPS::Backend::Age->encrypt_data_key(
143 data_key => $data_key,
144 recipients => $recipients,
145 );
146 671 $metadata->age($encrypted_keys);
147  
148 # Compute MAC over plaintext values BEFORE encryption (SOPS behavior).
149 # _compute_mac spans every document in the list, in document order, each
150 # contributing its own key order -- one digest over the whole stream
151 # (docs/adr/0033 point 3). A single document is byte-identical.
152 671 my $mac = _compute_mac($data, $data_key, $metadata);
153 626 $metadata->mac($mac);
154  
155 # Only YAML has a document stream. Writing more than one document to a format
156 # that has none would drop all but the first -- the k14 defect class,
157 # which sops commits silently (docs/adr/0033 Decision 3, N1). Refuse instead,
158 # naming the count and the target. A single document reaches every format.
159 626 _assert_format_supports_stream($format_class, scalar @documents);
160  
161 # Encrypt every document's values under the one data key, then hand the list
162 # to the emitter, which attaches the ONE metadata block to each document
163 # byte-identically and joins them with `---` (docs/adr/0033 points 1, 5).
164 # A single document passes a bare HashRef and is byte-identical to before --
165 # serialize reduces a one-element list to the same single Dump either way,
166 # and _encrypt_tree wants the document HashRef, never the ArrayRef wrapper
167 # (docs/adr/0033 Decision 1, proven byte-identical).
168 626 my @encrypted = map { _encrypt_tree($_, $data_key, $metadata, []) } @documents;
169  
170 622 ▶ return $format_class->serialize(
Branch: 1 branch
BranchTrueFalseTotal
@encrypted == 1 ? : 621 1 622
171 data => (@encrypted == 1 ? $encrypted[0] : \@encrypted),
172 metadata => $metadata,
173 );
174 }
175  
176  
177 sub decrypt {
178 493 ▶ my ($class, %args) = @_;
Subroutine decrypt: called CC=11 SCAR=24.7
Pod documented
179 493 ▶ my $encrypted = $args{encrypted} // croak "encrypted required";
Condition33%1/3
$args{"encrypted"} // croak("encrypted required")
l!l&&r!l&&!r
49300
MC/DC0%0/2
$args{"encrypted"} // croak("encrypted required")
$args{"encrypted"} croak("encrypted required")
Truth table33%1/3
A // B
A= $args{"encrypted"}B= croak("encrypted required")
ABresult
1X1
011
000
180 493 ▶ my $identities = $args{identities} // croak "identities required";
Condition33%1/3
$args{"identities"} // croak("identities required")
l!l&&r!l&&!r
49300
MC/DC0%0/2
$args{"identities"} // croak("identities required")
$args{"identities"} croak("identities required")
Truth table33%1/3
A // B
A= $args{"identities"}B= croak("identities required")
ABresult
1X1
011
000
181 493 my $format = $args{format};
182  
183 493 ▶ croak "identities must be an array ref" unless ref($identities) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $identities eq "ARRAY" 0 493 493
184  
185 # Auto-detect format if not specified
186 493 ▶ $format //= _detect_format($encrypted);
Condition66%2/3
$format //= _detect_format($encrypted)
l!l&&r!l&&!r
3531400
MC/DC0%0/2
$format //= _detect_format($encrypted)
$format _detect_format($encrypted)
Truth table66%2/3
A //= B
A= $formatB= _detect_format($encrypted)
ABresult
1X1
011
000
187  
188 493 ▶ my $format_class = $FORMATS{$format} // croak "Unknown format: $format";
Condition33%1/3
$FORMATS{$format} // croak("Unknown format: $format")
l!l&&r!l&&!r
49300
MC/DC0%0/2
$FORMATS{$format} // croak("Unknown format: $format")
$FORMATS{$format} croak("Unknown format: $format")
Truth table33%1/3
A // B
A= $FORMATS{$format}B= croak("Unknown format: $format")
ABresult
1X1
011
000
189  
190 # Parse the encrypted content. The third value is the DOCUMENT LIST: one
191 # element for a single document (byte-identical to before), N for a
192 # multi-document YAML stream (docs/adr/0033, k31). $data is a synonym
193 # for $documents->[0]. Only the YAML handler returns the list at all -- JSON,
194 # ENV and INI have no document stream and return two values -- so a missing
195 # third value is normalised to the single-document list every walk below
196 # expects.
197 493 my ($data, $metadata, $documents) = $format_class->parse($encrypted);
198 491 ▶ $documents = [$data] unless ref $documents eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $documents eq "ARRAY" 82 409 491
199 491 my $multi = @$documents > 1;
200  
201 # Asked here, ahead of both the metadata check and the data key, because
202 # that is the order sops answers in: its unmarshalling error precedes
203 # everything, and a cyclic document with no usable identity reports the
204 # cycle rather than the missing key. Measured, the same holds for the
205 # alias bomb: sops -d reports the aliasing, not the key. The order of the
206 # two is load-bearing, see _expansion_census.
207 #
208 # One document per top-level call, never the document list as a container:
209 # each document carries its own depth and alias budget (docs/adr/0033
210 # Decision 4, N4). One $active/$clean pair is shared -- the ancestor set is
211 # unwound on the way out, so it stays correct across documents, and sharing
212 # $clean is a win. A single document is one iteration, identical to before.
213 491 my ($active, $clean) = ({}, {});
214 491 for my $doc (@$documents) {
215 493 _assert_acyclic($doc, [], $active, $clean);
216 493 _assert_expansion_bounded($doc);
217 }
218  
219 # Metadata is taken from the FIRST document only (docs/adr/0033 point 2). A
220 # stream carrying a sops section only in a later document therefore surfaces
221 # no metadata and is refused right here, which is `sops metadata not found`
222 # at sops -- rather than being read as though it had none at all.
223 484 ▶ croak "No SOPS metadata found" unless $metadata;
Branch: 1 branch
BranchTrueFalseTotal
unless $metadata 1 483 484
224  
225 # Decrypt data key using age backend
226 483 my $data_key = File::SOPS::Backend::Age->decrypt_data_key(
227 age_keys => $metadata->age,
228 identities => $identities,
229 );
230  
231 # Decrypt every document's values. One metadata block, one data key, applied
232 # to each document -- the same tree walk per document.
233 482 my @decrypted = map { _decrypt_tree($_, $data_key, $metadata, []) } @$documents;
234  
235 # One MAC over ALL documents in document order (docs/adr/0033 point 3). The
236 # document list is passed as `data`; _verify_mac pairs each document's key
237 # order (from the order-preserving reparse) with its own values by index. A
238 # single-document list is byte-identical to passing the bare HashRef.
239 _verify_mac(
240 document => $encrypted,
241 data => $documents,
242 data_key => $data_key,
243 metadata => $metadata,
244 format_class => $format_class,
245 466 ▶ ) unless $args{ignore_mac};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"ignore_mac"} 452 14 466
246  
247 # A stream really holding more than one document comes back as an ArrayRef
248 # of HashRefs; one document stays a bare HashRef (docs/adr/0033 Decision 1).
249 # What round-trips is the FILE, not the Perl container: encrypt given a
250 # one-element ArrayRef writes a one-document file that reads back here as a
251 # HashRef.
252 439 ▶ return $multi ? \@decrypted : $decrypted[0];
Branch: 1 branch
BranchTrueFalseTotal
$multi ? : 1 438 439
253 }
254  
255  
256 sub encrypt_file {
257 45 ▶ my ($class, %args) = @_;
Subroutine encrypt_file: called CC=7 SCAR=20.5
Pod documented
258 45 ▶ my $input = $args{input} // croak "input required";
Condition33%1/3
$args{"input"} // croak("input required")
l!l&&r!l&&!r
4500
MC/DC0%0/2
$args{"input"} // croak("input required")
$args{"input"} croak("input required")
Truth table33%1/3
A // B
A= $args{"input"}B= croak("input required")
ABresult
1X1
011
000
259 45 ▶ my $output = $args{output} // $args{input};
Condition66%2/3
$args{"output"} // $args{"input"}
l!l&&r!l&&!r
4230
MC/DC0%0/2
$args{"output"} // $args{"input"}
$args{"output"} $args{"input"}
Truth table66%2/3
A // B
A= $args{"output"}B= $args{"input"}
ABresult
1X1
011
000
260 45 ▶ my $recipients = $args{recipients} // croak "recipients required";
Condition33%1/3
$args{"recipients"} // croak("recipients required")
l!l&&r!l&&!r
4500
MC/DC0%0/2
$args{"recipients"} // croak("recipients required")
$args{"recipients"} croak("recipients required")
Truth table33%1/3
A // B
A= $args{"recipients"}B= croak("recipients required")
ABresult
1X1
011
000
261 45 my $format = $args{format};
262  
263 # Auto-detect format from filename
264 45 ▶ $format //= _detect_format_from_filename($input);
Condition33%1/3
$format //= _detect_format_from_filename($input)
l!l&&r!l&&!r
0450
MC/DC0%0/2
$format //= _detect_format_from_filename($input)
$format _detect_format_from_filename($input)
Truth table33%1/3
A //= B
A= $formatB= _detect_format_from_filename($input)
ABresult
1X1
011
000
265  
266 45 my $content = _read_file($input, 'input file');
267  
268 # Parse to get data structure.
269 #
270 # parse() SPLITS OFF the sops section, so by the time $data reaches
271 # encrypt() an already-encrypted input is indistinguishable from a plain
272 # tree of ENC[...] strings -- which encrypt would happily wrap a second
273 # time. $metadata being defined is exactly "the input had a top-level sops
274 # entry", which is the condition sops itself refuses on.
275 45 my ($data, $metadata, $documents) = _format_class($format)->parse($content);
276 39 ▶ croak _sops_key_reserved("input file '$input'") if $metadata;
Branch: 1 branch
BranchTrueFalseTotal
if $metadata 4 35 39
277  
278 # Forward the WHOLE document list, so a multi-document YAML input is
279 # encrypted as the stream it is rather than as its first document alone
280 # (docs/adr/0033, k31). Only YAML returns a list; JSON, ENV and INI
281 # return no third value, so $data (the single document) is forwarded there.
282 # A single-document YAML input forwards a one-element list, byte-identical.
283 35 ▶ my $encrypted = $class->encrypt(
Branch: 1 branch
BranchTrueFalseTotal
ref $documents eq 'ARRAY' ? : 27 8 35
284 data => (ref $documents eq 'ARRAY' ? $documents : $data),
285 recipients => $recipients,
286 format => $format,
287 _encryption_options(\%args),
288 );
289  
290 31 _replace_file($output, $encrypted);
291  
292 29 return 1;
293 }
294  
295  
296 sub encrypt_in_place {
297 23 ▶ my ($class, %args) = @_;
Subroutine encrypt_in_place: called CC=6 SCAR=18.2
Pod documented
298 23 ▶ my $file = $args{file} // croak "file required";
Condition66%2/3
$args{"file"} // croak("file required")
l!l&&r!l&&!r
2210
MC/DC0%0/2
$args{"file"} // croak("file required")
$args{"file"} croak("file required")
Truth table33%1/3
A // B
A= $args{"file"}B= croak("file required")
ABresult
1X1
011
000
299 22 ▶ my $recipients = $args{recipients} // croak "recipients required";
Condition66%2/3
$args{"recipients"} // croak("recipients required")
l!l&&r!l&&!r
2110
MC/DC0%0/2
$args{"recipients"} // croak("recipients required")
$args{"recipients"} croak("recipients required")
Truth table33%1/3
A // B
A= $args{"recipients"}B= croak("recipients required")
ABresult
1X1
011
000
300 21 ▶ my $format = $args{format} // _detect_format_from_filename($file);
Condition33%1/3
$args{"format"} // _detect_format_from_filename($file)
l!l&&r!l&&!r
0210
MC/DC0%0/2
$args{"format"} // _detect_format_from_filename($file)
$args{"format"} _detect_format_from_filename($file)
Truth table33%1/3
A // B
A= $args{"format"}B= _detect_format_from_filename($file)
ABresult
1X1
011
000
301  
302 21 my $content = _read_file($file, 'file');
303  
304 # Same guard as encrypt_file, and it matters more here: there is no
305 # separate output file to inspect afterwards, so an unnoticed double
306 # encryption would have overwritten the only copy.
307 20 my ($data, $metadata, $documents) = _format_class($format)->parse($content);
308 14 ▶ croak _sops_key_reserved("file '$file'") if $metadata;
Branch: 1 branch
BranchTrueFalseTotal
if $metadata 2 12 14
309  
310 # Forward the whole document list (see encrypt_file), so an in-place encrypt
311 # of a multi-document YAML file rewrites every document rather than replacing
312 # the file with its first one -- the k14 loss this ticket exists to fix.
313 12 ▶ my $encrypted = $class->encrypt(
Branch: 1 branch
BranchTrueFalseTotal
ref $documents eq 'ARRAY' ? : 10 2 12
314 data => (ref $documents eq 'ARRAY' ? $documents : $data),
315 recipients => $recipients,
316 format => $format,
317 _encryption_options(\%args),
318 );
319  
320 9 _replace_file($file, $encrypted);
321  
322 8 return 1;
323 }
324  
325  
326 sub decrypt_file {
327 35 ▶ my ($class, %args) = @_;
Subroutine decrypt_file: called CC=5 SCAR=17.4
Pod documented
328 35 ▶ my $input = $args{input} // croak "input required";
Condition33%1/3
$args{"input"} // croak("input required")
l!l&&r!l&&!r
3500
MC/DC0%0/2
$args{"input"} // croak("input required")
$args{"input"} croak("input required")
Truth table33%1/3
A // B
A= $args{"input"}B= croak("input required")
ABresult
1X1
011
000
329 35 ▶ my $output = $args{output} // croak "output required";
Condition33%1/3
$args{"output"} // croak("output required")
l!l&&r!l&&!r
3500
MC/DC0%0/2
$args{"output"} // croak("output required")
$args{"output"} croak("output required")
Truth table33%1/3
A // B
A= $args{"output"}B= croak("output required")
ABresult
1X1
011
000
330 35 ▶ my $identities = $args{identities} // croak "identities required";
Condition33%1/3
$args{"identities"} // croak("identities required")
l!l&&r!l&&!r
3500
MC/DC0%0/2
$args{"identities"} // croak("identities required")
$args{"identities"} croak("identities required")
Truth table33%1/3
A // B
A= $args{"identities"}B= croak("identities required")
ABresult
1X1
011
000
331 35 my $format = $args{format};
332  
333 35 ▶ $format //= _detect_format_from_filename($input);
Condition66%2/3
$format //= _detect_format_from_filename($input)
l!l&&r!l&&!r
4310
MC/DC0%0/2
$format //= _detect_format_from_filename($input)
$format _detect_format_from_filename($input)
Truth table66%2/3
A //= B
A= $formatB= _detect_format_from_filename($input)
ABresult
1X1
011
000
334  
335 35 my $content = _read_file($input, 'input file');
336  
337 # Decrypt
338 my $data = $class->decrypt(
339 encrypted => $content,
340 identities => $identities,
341 format => $format,
342 ignore_mac => $args{ignore_mac},
343 35 );
344  
345 34 my $decrypted = _serialize_plaintext($data, $format);
346  
347 32 _replace_file($output, $decrypted);
348  
349 31 return 1;
350 }
351  
352  
353 sub extract {
354 28 ▶ my ($class, %args) = @_;
Subroutine extract: called CC=11 SCAR=27.0
Pod documented
355 28 ▶ my $file = $args{file} // croak "file required";
Condition33%1/3
$args{"file"} // croak("file required")
l!l&&r!l&&!r
2800
MC/DC0%0/2
$args{"file"} // croak("file required")
$args{"file"} croak("file required")
Truth table33%1/3
A // B
A= $args{"file"}B= croak("file required")
ABresult
1X1
011
000
356 28 ▶ my $path = $args{path} // croak "path required";
Condition33%1/3
$args{"path"} // croak("path required")
l!l&&r!l&&!r
2800
MC/DC0%0/2
$args{"path"} // croak("path required")
$args{"path"} croak("path required")
Truth table33%1/3
A // B
A= $args{"path"}B= croak("path required")
ABresult
1X1
011
000
357 28 ▶ my $identities = $args{identities} // croak "identities required";
Condition33%1/3
$args{"identities"} // croak("identities required")
l!l&&r!l&&!r
2800
MC/DC0%0/2
$args{"identities"} // croak("identities required")
$args{"identities"} croak("identities required")
Truth table33%1/3
A // B
A= $args{"identities"}B= croak("identities required")
ABresult
1X1
011
000
358 28 my $format = $args{format};
359  
360 28 ▶ $format //= _detect_format_from_filename($file);
Condition33%1/3
$format //= _detect_format_from_filename($file)
l!l&&r!l&&!r
0280
MC/DC0%0/2
$format //= _detect_format_from_filename($file)
$format _detect_format_from_filename($file)
Truth table33%1/3
A //= B
A= $formatB= _detect_format_from_filename($file)
ABresult
1X1
011
000
361  
362 28 my $content = _read_file($file, 'file');
363  
364 28 ▶ my $document = $args{document} // 0;
Condition100%2/2
$args{"document"} // 0
l!l
127
MC/DC100%1/1
$args{"document"} // 0
$args{"document"}
Truth table100%2/2
A
A= $args{"document"}
Aresult
11
00
365 28 ▶ croak "document must be a non-negative integer, not '$document'"
Branch: 1 branch
BranchTrueFalseTotal
unless $document =~ /\A\d+\z/ 0 28 28
366 unless $document =~ /\A\d+\z/;
367  
368 my $data = $class->decrypt(
369 encrypted => $content,
370 identities => $identities,
371 format => $format,
372 ignore_mac => $args{ignore_mac},
373 28 );
374  
375 # A single-document file decrypts to a HashRef, a multi-document stream to an
376 # ArrayRef of them (docs/adr/0033, k31). The path language stays sops's
377 # -- applied to the ONE document `document` names -- because sops has no
378 # document axis and cannot grow one: a leading integer already means "the Nth
379 # key of document 0" there (docs/adr/0033 N2). So `document` is a separate
380 # argument, defaulting to 0, and it addresses the stream by index.
381 25 ▶ my @docs = ref $data eq 'ARRAY' ? @$data : ($data);
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'ARRAY' ? : 0 25 25
382 25 ▶ croak sprintf(
Branch: 2 branches
BranchTrueFalseTotal
if $document > $#docs 1 24 25
@docs == 1 ? : 1 0 1
383 "document => %d is beyond the last document of '%s': the file has %d "
384 . "document%s (indices 0..%d)",
385 $document, $file, scalar @docs,
386 (@docs == 1 ? '' : 's'), $#docs)
387 if $document > $#docs;
388  
389 # Navigate WITHIN the named document; never fall through to a later one
390 # looking for a key, which would turn a caller's typo into a plausible answer
391 # from the wrong document. The path-not-found error names which document was
392 # searched, so a mistake in `document` does not read as a mistake in `path`.
393 24 ▶ my $where_doc = @docs > 1 ? "document $document" : undef;
Branch: 1 branch
BranchTrueFalseTotal
@docs > 1 ? : 0 24 24
394  
395 # A float leaf goes out carrying its canonical decimal as its string form: a
396 # decrypted float is a bare NV, so printing it went through Perl's 15
397 # significant digits and lost the digits the document actually holds (karr
398 # k61, ADR 0010). Only this leaf -- a dualvar inside a tree changes what the
399 # emitters write, so nothing that returns a tree does this, and a branch
400 # extract returns comes back untouched.
401 24 return File::SOPS::Encrypted->canonical_float_dualvar(
402 _extract_path($docs[$document], $path, $where_doc));
403 }
404  
405  
406 sub rotate {
407 44 ▶ my ($class, %args) = @_;
Subroutine rotate: called CC=6 SCAR=18.8
Pod documented
408 44 ▶ my $file = $args{file} // croak "file required";
Condition33%1/3
$args{"file"} // croak("file required")
l!l&&r!l&&!r
4400
MC/DC0%0/2
$args{"file"} // croak("file required")
$args{"file"} croak("file required")
Truth table33%1/3
A // B
A= $args{"file"}B= croak("file required")
ABresult
1X1
011
000
409 44 ▶ my $identities = $args{identities} // croak "identities required";
Condition33%1/3
$args{"identities"} // croak("identities required")
l!l&&r!l&&!r
4400
MC/DC0%0/2
$args{"identities"} // croak("identities required")
$args{"identities"} croak("identities required")
Truth table33%1/3
A // B
A= $args{"identities"}B= croak("identities required")
ABresult
1X1
011
000
410 44 my $recipients = $args{recipients};
411 44 my $format = $args{format};
412  
413 44 ▶ $format //= _detect_format_from_filename($file);
Condition33%1/3
$format //= _detect_format_from_filename($file)
l!l&&r!l&&!r
0440
MC/DC0%0/2
$format //= _detect_format_from_filename($file)
$format _detect_format_from_filename($file)
Truth table33%1/3
A //= B
A= $formatB= _detect_format_from_filename($file)
ABresult
1X1
011
000
414  
415 44 my $content = _read_file($file, 'file');
416  
417 44 my (undef, $metadata) = _format_class($format)->parse($content);
418 43 ▶ croak "No SOPS metadata found in '$file'" unless $metadata;
Branch: 1 branch
BranchTrueFalseTotal
unless $metadata 0 43 43
419  
420 43 _assert_rekeyable($metadata, $file, verb => 'rotate', noun => 'Rotation');
421  
422 # Same question as edit's, and asked in the same place: the read below no
423 # longer refuses a rule RE2 cannot compile, so the refusal for writing
424 # under one belongs ahead of it rather than after the whole document has
425 # been decrypted. docs/adr/0051.
426 37 $metadata->assert_rule_regexes_agree;
427  
428 # Get current recipients if not specified
429 36 ▶ unless ($recipients) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($recipients) 36 0 36
430 36 $recipients = [ map { $_->{recipient} } @{$metadata->age} ];
431 }
432  
433 # Decrypt
434 my $data = $class->decrypt(
435 encrypted => $content,
436 identities => $identities,
437 format => $format,
438 ignore_mac => $args{ignore_mac},
439 36 );
440  
441 # docs/adr/0046's guard stood here and is gone: the decryption above is
442 # rule-driven now (docs/adr/0049), so a leaf the rule excludes comes back
443 # as its own ENC[...] text and the re-encryption writes that text -- there
444 # is no plaintext left for this method to leak. A document whose rule and
445 # whose stored values disagree fails on the MAC, inside decrypt, which is
446 # where sops fails it.
447  
448 # Re-encrypt with new data key, under the rules this document already had
449 23 my $encrypted = $class->encrypt(
450 data => $data,
451 recipients => $recipients,
452 format => $format,
453 metadata => $metadata,
454 );
455  
456 23 _replace_file($file, $encrypted);
457  
458 22 return 1;
459 }
460  
461  
462 sub edit {
463 28 ▶ my ($class, %args) = @_;
Subroutine edit: called CC=9 SCAR=22.0
Pod documented
464 28 ▶ my $file = $args{file} // croak "file required";
Condition66%2/3
$args{"file"} // croak("file required")
l!l&&r!l&&!r
2710
MC/DC0%0/2
$args{"file"} // croak("file required")
$args{"file"} croak("file required")
Truth table33%1/3
A // B
A= $args{"file"}B= croak("file required")
ABresult
1X1
011
000
465 27 ▶ my $identities = $args{identities} // croak "identities required";
Condition66%2/3
$args{"identities"} // croak("identities required")
l!l&&r!l&&!r
2610
MC/DC0%0/2
$args{"identities"} // croak("identities required")
$args{"identities"} croak("identities required")
Truth table33%1/3
A // B
A= $args{"identities"}B= croak("identities required")
ABresult
1X1
011
000
466 26 ▶ my $format = $args{format} // _detect_format_from_filename($file);
Condition66%2/3
$args{"format"} // _detect_format_from_filename($file)
l!l&&r!l&&!r
2240
MC/DC0%0/2
$args{"format"} // _detect_format_from_filename($file)
$args{"format"} _detect_format_from_filename($file)
Truth table66%2/3
A // B
A= $args{"format"}B= _detect_format_from_filename($file)
ABresult
1X1
011
000
467  
468 # Resolved BEFORE anything is decrypted: an unusable editor must not be
469 # discovered with a plaintext copy of the document already on disk.
470 26 my @editor = _editor_command($args{editor});
471  
472 24 my $content = _read_file($file, 'file');
473  
474 24 my (undef, $metadata, $documents) = _format_class($format)->parse($content);
475 24 ▶ croak "No SOPS metadata found in '$file'" unless $metadata;
Branch: 1 branch
BranchTrueFalseTotal
unless $metadata 1 23 24
476  
477 # edit on a multi-document stream is deliberately NOT enabled. Reading and
478 # writing streams both work now, so the mechanics would fall out -- but edit
479 # re-encrypts under a NEW data key (unlike sops edit, k41), and
480 # docs/adr/0033 explicitly leaves edit-on-a-stream semantics open ("What this
481 # does not decide"). Shipping a working edit here would settle k41 by
482 # accident, so it is refused instead, before the whole file is decrypted and
483 # its plaintext written to a temp file for the editor. See _refuse_edit_multidoc.
484 23 _refuse_edit_multidoc($documents);
485  
486 # Re-encryption here generates a NEW data key, exactly as rotate does, so
487 # it inherits rotate's refusal: a document also wrapped for pgp or a KMS
488 # would come back out with those recipients silently dropped.
489 23 _assert_rekeyable($metadata, $file, verb => 'edit', noun => 'Editing');
490  
491 # And the document's own rule has to be one we can write under, asked HERE
492 # rather than left to the re-encryption at the bottom. The read below now
493 # goes through for a rule RE2 cannot compile (docs/adr/0051), so without
494 # this the editor would open, the user would type, and the refusal would
495 # arrive afterwards -- with their edit in a temp file and nowhere else.
496 22 $metadata->assert_rule_regexes_agree;
497  
498 my $data = $class->decrypt(
499 encrypted => $content,
500 identities => $identities,
501 format => $format,
502 ignore_mac => $args{ignore_mac},
503 21 );
504  
505 # docs/adr/0046's guard stood here too and is gone for rotate's reason
506 # (docs/adr/0049). What replaces it is still ahead of the editor: the
507 # decryption above is where such a document now stops, on its MAC.
508  
509 18 my $before = _serialize_plaintext($data, $format);
510 18 my $after = _edit_text($before, $file, \@editor);
511  
512 # Nothing was changed: leave the file alone entirely rather than rewriting
513 # an identical document under a new data key, MAC and lastmodified. sops
514 # stops here too ("File has not changed, exiting.", exit code 200).
515 16 ▶ return 0 unless defined $after;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $after 3 13 16
516  
517 13 my ($edited, $edited_metadata) = do {
518 13 my @parsed = eval { _format_class($format)->parse($after) };
519 13 my $err = $@;
520  
521 # A top-level `sops` entry of the user's own is NOT a parse failure and
522 # must not be reported as one -- `sops: mine` parses perfectly, it just
523 # cannot be encrypted over a metadata section that goes in the same
524 # place, and the remedy is to rename one key rather than to hunt for a
525 # syntax error that is not there.
526 #
527 # parse() reports the two shapes of that entry differently: a mapping
528 # comes back as metadata, and every other shape (a scalar, a list, an
529 # explicit null) is refused inside parse() by
530 # File::SOPS::Metadata::from_hash, so it arrives here as an exception
531 # and has to be sorted back out of the parse branch. Both shapes end at
532 # the same croak.
533 #
534 # sops draws the line in exactly this place, with two distinct messages
535 # (measured on 3.13.3 in editor mode): "Could not load tree, probably
536 # due to invalid syntax" for text that does not parse, and "Tree not
537 # valid for encryption" plus the reserved-key text for a top-level
538 # `sops` entry -- for a scalar, a list, a null and a mapping alike.
539 13 ▶ croak _edited_sops_key_reserved($file) if _is_sops_not_a_mapping($err);
Branch: 1 branch
BranchTrueFalseTotal
if _is_sops_not_a_mapping($err) 3 10 13
540  
541 10 ▶ croak "The edited document does not parse (" . _reason($err) . "). "
Branch: 1 branch
BranchTrueFalseTotal
if $err 2 8 10
542 . "'$file' is unchanged, and the edited text has been discarded "
543 . "together with the temporary file it was in -- there is no copy "
544 . "of it left. sops keeps the editor open until the document "
545 . "parses; this method cannot, because it may have no terminal to "
546 . "return to."
547 if $err;
548  
549 # If the editor turned the document into a multi-document stream, refuse
550 # it for the same reason a multi-document original is refused above:
551 # edit-on-a-stream semantics are undecided (k41, docs/adr/0033), not
552 # that the write cannot be done. $parsed[2] is the document list parse()
553 # returns as its third value.
554 8 _refuse_edit_multidoc($parsed[2]);
555  
556 8 @parsed;
557 };
558  
559 8 ▶ croak _edited_sops_key_reserved($file) if $edited_metadata;
Branch: 1 branch
BranchTrueFalseTotal
if $edited_metadata 1 7 8
560  
561 my $encrypted = $class->encrypt(
562 data => $edited,
563 7 recipients => [ map { $_->{recipient} } @{ $metadata->age } ],
564 format => $format,
565 metadata => $metadata,
566 );
567  
568 7 _replace_file($file, $encrypted);
569  
570 6 return 1;
571 }
572  
573  
574 # The config file, spelled exactly. Measured against sops 3.13.3: a .sops.yml
575 # is NOT read, and is warned about -- `ignoring "../.sops.yml" when searching
576 # for config file; the config file must be called ".sops.yaml"`.
577 80 our $CONFIG_FILE_NAME = '.sops.yaml';
578  
579 # Creation-rule fields that name key material this distribution cannot produce.
580 #
581 # These are the CONFIG file's names, which are NOT the sops section's names:
582 # `azure_keyvault` and `hc_vault_transit_uri` here against `azure_kv` and
583 # `hc_vault` there. Measured against sops 3.13.3 by putting an unusable key in
584 # each field of a matching rule -- these five make it try to wrap the data key
585 # and fail on the key, while `aws_kms`, `azure_kv` and `hc_vault` in a creation
586 # rule are ignored entirely. Taking the list from
587 # @File::SOPS::Metadata::KEY_MATERIAL_FIELDS instead would therefore have let
588 # azure_keyvault and hc_vault_transit_uri walk straight through the guard.
589 #
590 # key_groups and shamir_threshold are here for the same reason one step on:
591 # both change how the data key is split and wrapped, sops writes
592 # shamir_threshold into the document it produces (measured), and a document
593 # this encrypted while ignoring them would be wrapped for age alone.
594 80 my @UNIMPLEMENTED_RULE_FIELDS = qw(
595 pgp kms gcp_kms azure_keyvault hc_vault_transit_uri
596 key_groups shamir_threshold
597 );
598  
599 sub creation_rules_for {
600 85 ▶ my ($class, %args) = @_;
Subroutine creation_rules_for: called CC=5 SCAR=16.1
Pod documented
601 85 ▶ my $file = $args{file} // croak "file required";
Condition66%2/3
$args{"file"} // croak("file required")
l!l&&r!l&&!r
8401
MC/DC0%0/2
$args{"file"} // croak("file required")
$args{"file"} croak("file required")
Truth table33%1/3
A // B
A= $args{"file"}B= croak("file required")
ABresult
1X1
011
000
602  
603 84 my $target = _clean_abs_path($file);
604  
605 84 my $config = $args{config};
606 84 ▶ unless (defined $config) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $config) 81 3 84
607 81 $config = _find_config_file($target);
608 81 ▶ croak "No $CONFIG_FILE_NAME found for '$file': looked in '"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $config 1 80 81
609 . _dir_of($target) . "' and in every directory above it, up to the "
610 . "filesystem root. Pass recipients to encrypt yourself, or "
611 . "config => '/path/to/$CONFIG_FILE_NAME' to name one. (sops stops "
612 . "here too: \"config file not found, or has no creation rules, and "
613 . "no keys provided through command line options\".)"
614 unless defined $config;
615 }
616  
617 83 my $rules = _load_creation_rules($config);
618 78 my $subject = _rule_subject_path($target, $config);
619  
620 78 my ($rule, $index) = _first_matching_rule($rules, $subject, $config);
621 56 ▶ croak "No creation rule in '$config' matches '$subject'. A rule matches "
Branch: 1 branch
BranchTrueFalseTotal
unless $rule 2 54 56
622 . "when its path_regex matches that path -- which is '$file' resolved "
623 . "and taken relative to the directory holding the config file -- or "
624 . "when it has no path_regex at all, which is how a catch-all rule is "
625 . "written. (sops stops here too: \"error loading config: no matching "
626 . "creation rules found\".)"
627 unless $rule;
628  
629 54 return _creation_rule_args($rule, $config, $index);
630 }
631  
632  
633 # Internal helpers
634  
635 sub _format_class {
636 203 ▶ my ($format) = @_;
Subroutine _format_class: called CC=2 SCAR=8.1
637 203 ▶ return $FORMATS{$format} // croak "Unknown format: $format";
Condition33%1/3
$FORMATS{$format} // croak("Unknown format: $format")
l!l&&r!l&&!r
20300
MC/DC0%0/2
$FORMATS{$format} // croak("Unknown format: $format")
$FORMATS{$format} croak("Unknown format: $format")
Truth table33%1/3
A // B
A= $FORMATS{$format}B= croak("Unknown format: $format")
ABresult
1X1
011
000
638 }
639  
640 # --- .sops.yaml creation rules -------------------------------------------
641 #
642 # Everything below is path arithmetic and a regex match. No wire bytes, no MAC,
643 # no crypto: this decides which recipients and which encryption rule a file is
644 # encrypted under, and then the ordinary encrypt path does the work.
645  
646 # An absolute path the way Go's filepath.Abs + Clean makes one: relative to the
647 # current directory, with '.' and '..' resolved TEXTUALLY, and without touching
648 # the filesystem. Cwd::abs_path is deliberately not used -- it resolves
649 # symlinks, and sops does not: measured on 3.13.3, encrypting a symlink matches
650 # a path_regex against the LINK's path, not the target's. It also requires the
651 # file to exist, and a file about to be created still needs its rules.
652 sub _clean_abs_path {
653 162 ▶ my ($path) = @_;
Subroutine _clean_abs_path: called CC=5 SCAR=16.1
654  
655 162 my ($vol, $dirs, $file) = File::Spec->splitpath(File::Spec->rel2abs($path));
656  
657 162 my @parts;
658 162 for my $part (File::Spec->splitdir($dirs), $file) {
659 1037 ▶ next if !length $part || $part eq File::Spec->curdir;
Branch: 1 branch
BranchTrueFalseTotal
if not length $part or $part eq "File::Spec"->curdir 324 713 1037
Condition66%2/3
not length $part or $part eq "File::Spec"->curdir
l!l&&r!l&&!r
3240713
MC/DC50%1/2
not length $part or $part eq "File::Spec"->curdir
not length $part $part eq "File::Spec"->curdir
Truth table66%2/3
not(A) or B
A= not length $partB= $part eq "File::Spec"->curdir
ABresult
1X1
011
000
660 713 ▶ if ($part eq File::Spec->updir) { pop @parts; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($part eq "File::Spec"->updir) 1 712 713
661 712 push @parts, $part;
662 }
663  
664 162 return File::Spec->catpath($vol,
665 File::Spec->catdir(File::Spec->rootdir, @parts), '');
666 }
667  
668 sub _dir_of {
669 79 ▶ my ($abs) = @_;
Subroutine _dir_of: called CC=1 SCAR=0.0
670 79 my ($vol, $dirs) = File::Spec->splitpath($abs);
671 79 return File::Spec->canonpath(File::Spec->catpath($vol, $dirs, ''));
672 }
673  
674 # The nearest .sops.yaml at or above the file's own directory, or undef.
675 #
676 # The search starts at the FILE, where sops starts it at the current working
677 # directory (measured on 3.13.3; see creation_rules_for for why this deviates).
678 # Nothing stops the walk short of the root -- not .git, not $HOME -- which is
679 # what sops does.
680 sub _find_config_file {
681 81 ▶ my ($target) = @_;
Subroutine _find_config_file: called CC=3 SCAR=11.0
682  
683 81 my ($vol, $dirs) = File::Spec->splitpath($target);
684 81 my @parts = grep { length } File::Spec->splitdir($dirs);
685  
686 81 while (1) {
687 121 my $dir = File::Spec->catpath($vol,
688 File::Spec->catdir(File::Spec->rootdir, @parts), '');
689 121 my $candidate = File::Spec->catfile($dir, $CONFIG_FILE_NAME);
690 121 ▶ return $candidate if -f $candidate;
Branch: 1 branch
BranchTrueFalseTotal
if -f $candidate 80 41 121
691 41 ▶ last unless @parts;
Branch: 1 branch
BranchTrueFalseTotal
unless @parts 1 40 41
692 40 pop @parts;
693 }
694  
695 1 return undef;
696 }
697  
698 # The string path_regex is matched against: the file relative to the directory
699 # holding the config file, or -- when it is not under that directory at all --
700 # the absolute path. Measured on sops 3.13.3, both halves of it: a config at
701 # the top of a tree matches `a/b/c/secrets.yaml` however the file was named and
702 # from wherever sops was run, and a file outside the config's directory matches
703 # `^/` rather than `^\.\./`.
704 #
705 # With the config found by walking up from the file, the second case cannot
706 # arise -- the file is under the config's directory by construction. It is
707 # reachable only through an explicit `config`.
708 sub _rule_subject_path {
709 78 ▶ my ($target, $config) = @_;
Subroutine _rule_subject_path: called CC=3 SCAR=11.0
710  
711 78 my $rel = File::Spec->abs2rel($target, _dir_of(_clean_abs_path($config)));
712 78 my ($first) = File::Spec->splitdir($rel);
713  
714 78 ▶ return $target if !length $rel || $first eq File::Spec->updir;
Branch: 1 branch
BranchTrueFalseTotal
if not length $rel or $first eq "File::Spec"->updir 1 77 78
Condition66%2/3
not length $rel or $first eq "File::Spec"->updir
l!l&&r!l&&!r
0177
MC/DC50%1/2
not length $rel or $first eq "File::Spec"->updir
not length $rel $first eq "File::Spec"->updir
Truth table66%2/3
not(A) or B
A= not length $relB= $first eq "File::Spec"->updir
ABresult
1X1
011
000
715 77 return $rel;
716 }
717  
718 sub _load_creation_rules {
719 83 ▶ my ($config) = @_;
Subroutine _load_creation_rules: called CC=9 SCAR=22.1
720  
721 83 my $content = _read_file($config, 'config file');
722  
723 # LIST context, as the format handlers use it: YAML::XS::Load in scalar
724 # context returns the LAST document of a multi-document stream, which for a
725 # config file would silently honour one half of it.
726 82 my @docs = eval { YAML::XS::Load($content) };
727 82 ▶ croak "Cannot parse config file '$config' (" . _reason($@) . "). sops "
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 81 82
728 . "stops on the same file with \"error loading config: Could not "
729 . "unmarshal config file\"."
730 if $@;
731  
732 81 ▶ croak "Config file '$config' holds " . scalar(@docs) . " YAML documents; a "
Branch: 1 branch
BranchTrueFalseTotal
if @docs > 1 0 81 81
733 . "$CONFIG_FILE_NAME is a single mapping"
734 if @docs > 1;
735  
736 81 ▶ my $conf = @docs ? $docs[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
@docs ? : 80 1 81
737  
738 croak "Config file '$config' has no creation_rules, so there is nothing "
739 . "in it that says who a file should be encrypted for. (sops reports "
740 . "\"config file not found, or has no creation rules, and no keys "
741 . "provided through command line options\".)"
742 81 ▶ if !defined $conf || (ref $conf eq 'HASH' && !defined $conf->{creation_rules});
Branch: 1 branch
BranchTrueFalseTotal
if not defined $conf or ref $conf eq "HASH" and not defined $conf->{"creation_rules"} 2 79 81
Condition83%5/6
not defined $conf or ref $conf eq "HASH" and not defined $conf->{"creation_rules"}
l!l&&r!l&&!r
1179
ref $conf eq "HASH" and not defined $conf->{"creation_rules"}
!ll&&!rl&&r
0791
MC/DC66%2/3
not defined $conf or ref $conf eq "HASH" and not defined $conf->{"creation_rules"}
not defined $conf ref $conf eq "HASH" not defined $conf->{"creation_rules"}
Truth table75%3/4
not(A) or B and not(C)
A= not defined $confB= ref $conf eq "HASH"C= not defined $conf->{"creation_rules"}
ABCresult
1XX1
0111
00X0
0100
743  
744 79 ▶ croak "Config file '$config' is not a mapping" unless ref $conf eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $conf eq "HASH" 0 79 79
745  
746 79 my $rules = $conf->{creation_rules};
747 79 ▶ croak "creation_rules in '$config' is not a list"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rules eq "ARRAY" 1 78 79
748 unless ref $rules eq 'ARRAY';
749  
750 78 return $rules;
751 }
752  
753 sub _first_matching_rule {
754 78 ▶ my ($rules, $subject, $config) = @_;
Subroutine _first_matching_rule: called CC=11 SCAR=24.0
755  
756 78 my $index = 0;
757 78 for my $rule (@$rules) {
758 81 $index++;
759  
760 81 ▶ croak "Creation rule $index in '$config' is not a mapping"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rule eq "HASH" 0 81 81
761 unless ref $rule eq 'HASH';
762  
763 81 my $regex = $rule->{path_regex};
764  
765 # No path_regex is a catch-all, which is how the last rule in a
766 # .sops.yaml is usually written. Same in sops.
767 81 ▶ return ($rule, $index) unless defined $regex && length $regex;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $regex and length $regex 40 41 81
Condition66%2/3
defined $regex and length $regex
!ll&&!rl&&r
40041
MC/DC50%1/2
defined $regex and length $regex
defined $regex length $regex
Truth table66%2/3
A and B
A= defined $regexB= length $regex
ABresult
0X0
100
111
768  
769 41 ▶ my $matched = eval { $subject =~ /$regex/ ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$subject =~ /$regex/ ? : 15 25 40
770 41 ▶ croak "Cannot use the path_regex of creation rule $index in '$config' "
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 40 41
771 . "as a regular expression (" . _reason($@) . "). It is compiled as "
772 . "a Perl regex here and with Go's RE2 by sops, which accept "
773 . "different things -- sops reports this one too, as \"error "
774 . "parsing regexp\"."
775 if $@;
776  
777 # sops compiles the same string with Go RE2, which is not the same
778 # dialect. A pattern the two dialects do not agree on -- one RE2
779 # rejects, or one both take and read differently -- silently selects
780 # a different rule in sops (or none), so the two tools disagree
781 # without either one saying so. The scan is the one in Metadata
782 # (k164): it is escape-aware, character-class aware, and reads
783 # every construct's RE2 verdict off the .sops.yaml oracle rather than
784 # guessing. We translate the kind into a path_regex-specific message
785 # because sops's behaviour here is different -- it REPORTS the
786 # unsupported case as "error parsing regexp" rather than discarding
787 # the compile error -- and the two croaks describe different things.
788 40 my ($construct, $kind) = _re2_path_regex_diagnosis($regex);
789 40 ▶ if ($construct) {
Branch: 1 branch
BranchTrueFalseTotal
if ($construct) 21 19 40
790 21 ▶ my $shown = length($regex) > 60
Branch: 1 branch
BranchTrueFalseTotal
length $regex > 60 ? : 0 21 21
791 ? substr($regex, 0, 57) . '...'
792 : $regex;
793 21 ▶ croak "Creation rule $index in '$config' has a path_regex "
Branch: 1 branch
BranchTrueFalseTotal
$kind eq 'different' ? : 3 18 21
794 . "('$shown') that uses $construct, "
795 . ($kind eq 'different'
796 ? "which Go RE2 and Perl both accept but read "
797 . "DIFFERENTLY, so this side would select a different "
798 . "rule than sops. "
799 : "which Go RE2 does not support and sops will refuse "
800 . "to compile. ")
801 . "Either rewrite the pattern in constructs both dialects "
802 . "agree on, or drop the rule. See the POD on "
803 . "creation_rules_for.";
804 }
805  
806 19 ▶ return ($rule, $index) if $matched;
Branch: 1 branch
BranchTrueFalseTotal
if $matched 14 5 19
807 }
808  
809 2 return;
810 }
811  
812 # What in this path_regex, if any, the two regex dialects do not agree on.
813 # Returns the construct name and the kind of disagreement (the same two
814 # Metadata::_re2_divergent_construct returns: 'unsupported' for a construct
815 # RE2 cannot compile, 'different' for one both take and read apart), or
816 # the empty list when the pattern is in both dialects.
817 #
818 # The scan is the one in Metadata.pm (k161 / docs/adr/0048, broadened
819 # by k164 to also cover the path_regex case). The narrow check this
820 # replaces (k53) named lookarounds and backreferences only; atomic
821 # groups, possessive quantifiers, \Z, \K, the (?x) family and the rest of
822 # the RE2-rejected set were still being taken here and silently picking a
823 # different rule at sops -- measured on sops 3.13.3 against a .sops.yaml
824 # path_regex: each one of those triggers "error parsing regexp" at exit 1
825 # there.
826 sub _re2_path_regex_diagnosis {
827 40 ▶ my ($regex) = @_;
Subroutine _re2_path_regex_diagnosis: called CC=1 SCAR=0.0
828  
829 40 my @divergent = File::SOPS::Metadata::_re2_divergent_construct($regex);
830 40 return @divergent;
831 }
832  
833 # Is a creation rule's field set, in the sense Go's zero value gives it? An
834 # empty string, an empty list and an absent key are all "not set".
835 sub _rule_field_set {
836 648 ▶ my ($rule, $name) = @_;
Subroutine _rule_field_set: called CC=4 SCAR=13.9
837  
838 648 my $value = $rule->{$name};
839 648 ▶ return 0 unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 610 38 648
840 38 ▶ return scalar @$value if ref $value eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $value eq "ARRAY" 1 37 38
841 37 ▶ return scalar keys %$value if ref $value eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $value eq "HASH" 0 37 37
842 37 return length $value;
843 }
844  
845 # A creation rule's `age`, as a list of recipients. Comma-separated, or a YAML
846 # list, or a list of comma-separated strings; whitespace around each recipient
847 # is dropped, which is what makes the folded `age: >-` form work. A NEWLINE is
848 # not a separator: measured on sops 3.13.3, a literal block of recipients with
849 # no commas reaches age as one string and fails to parse.
850 sub _age_recipients {
851 47 ▶ my ($value, $config, $index) = @_;
Subroutine _age_recipients: called CC=8 SCAR=21.0
852  
853 47 ▶ return () unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1 46 47
854  
855 46 my @out;
856 46 ▶ for my $entry (ref $value eq 'ARRAY' ? @$value : $value) {
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'ARRAY' ? : 2 44 46
857 47 ▶ croak "The age entry of creation rule $index in '$config' holds a "
Branch: 1 branch
BranchTrueFalseTotal
if ref $entry 0 47 47
858 . lc(ref $entry) . " reference; it takes a recipient, a "
859 . "comma-separated list of them, or a YAML list"
860 if ref $entry;
861 47 ▶ next unless defined $entry;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry 0 47 47
862  
863 47 for my $recipient (split /,/, $entry) {
864 50 $recipient =~ s/\A\s+//;
865 50 $recipient =~ s/\s+\z//;
866 50 ▶ push @out, $recipient if length $recipient;
Branch: 1 branch
BranchTrueFalseTotal
if length $recipient 50 0 50
867 }
868 }
869  
870 46 return @out;
871 }
872  
873 sub _creation_rule_args {
874 54 ▶ my ($rule, $config, $index) = @_;
Subroutine _creation_rule_args: called CC=8 SCAR=20.8
875  
876 54 my @unimplemented = grep { _rule_field_set($rule, $_) }
877 @UNIMPLEMENTED_RULE_FIELDS;
878  
879 54 ▶ croak "Refusing to encrypt under creation rule $index in '$config': it "
Branch: 1 branch
BranchTrueFalseTotal
if @unimplemented 7 47 54
880 . "names key material this distribution cannot produce ("
881 . join(', ', @unimplemented) . ") -- age is the only backend "
882 . "implemented here. sops "
883 . "wraps the data key for every backend a rule names, so encrypting "
884 . "under this rule while ignoring those fields would write a document "
885 . "the config says several parties can read and only the age "
886 . "recipients actually can, and report success. Encrypt such a file "
887 . "with the sops CLI, or pass recipients to encrypt yourself."
888 if @unimplemented;
889  
890 47 my @recipients = _age_recipients($rule->{age}, $config, $index);
891 47 ▶ croak "Creation rule $index in '$config' matches, but names no age "
Branch: 1 branch
BranchTrueFalseTotal
unless @recipients 2 45 47
892 . "recipient, so there is nobody to encrypt for. (sops stops on the "
893 . "same rule with \"Could not generate data key: [empty key group "
894 . "provided]\".)"
895 unless @recipients;
896  
897 45 my %args = (recipients => \@recipients);
898  
899 # The same mutual exclusion File::SOPS::Metadata enforces on a document,
900 # asked here so the message can name the config file rather than the
901 # document that could not be built out of it. sops refuses such a rule at
902 # config-load time too, listing the same six names.
903 45 my @rules = grep { _rule_field_set($rule, $_) }
904 @File::SOPS::Metadata::ENCRYPTION_RULES,
905 @File::SOPS::Metadata::UNSUPPORTED_ENCRYPTION_RULES;
906  
907 45 ▶ croak "Creation rule $index in '$config' uses more than one of "
Branch: 1 branch
BranchTrueFalseTotal
if @rules > 1 1 44 45
908 . join(', ', @File::SOPS::Metadata::ENCRYPTION_RULES,
909 @File::SOPS::Metadata::UNSUPPORTED_ENCRYPTION_RULES)
910 . " (got " . join(' and ', @rules) . "); they select which values get "
911 . "encrypted and at most one may be given. sops refuses the same rule."
912 if @rules > 1;
913  
914 44 ▶ if (my ($name) = @rules) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($name) = @rules) 29 15 44
915 croak "Refusing to encrypt under creation rule $index in '$config': "
916 . "'$name' selects values by their comment, and neither of this "
917 . "distribution's parsers keeps comments, so every value would be "
918 . "classified wrongly. Use the sops CLI for files that config "
919 . "covers."
920 29 ▶ if grep { $_ eq $name }
Branch: 1 branch
BranchTrueFalseTotal
if grep {$_ eq $name;} @File::SOPS::Metadata::UNSUPPORTED_ENCRYPTION_RULES 2 27 29
921 @File::SOPS::Metadata::UNSUPPORTED_ENCRYPTION_RULES;
922  
923 27 $args{$name} = $rule->{$name};
924 }
925  
926 $args{mac_only_encrypted} = $rule->{mac_only_encrypted} ? 1 : 0
927 42 ▶ if exists $rule->{mac_only_encrypted};
Branch: 2 branches
BranchTrueFalseTotal
if exists $rule->{"mac_only_encrypted"} 2 40 42
$rule->{'mac_only_encrypted'} ? : 1 1 2
928  
929 42 return %args;
930 }
931  
932 sub _read_file {
933 296 ▶ my ($path, $what) = @_;
Subroutine _read_file: called CC=2 SCAR=6.9
934  
935 296 ▶ open my $fh, '<:raw', $path
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $path or croak("Cannot open $what '${path}': $!") 2 294 296
936 or croak "Cannot open $what '$path': $!";
937 294 my $content = do { local $/; <$fh> };
938 294 close $fh;
939  
940 294 return $content;
941 }
942  
943 # The plaintext form of a decrypted tree: what decrypt_file writes out and what
944 # edit hands to the editor. Both have to agree, because edit compares the text
945 # it wrote with the text it gets back to decide whether anything changed.
946 #
947 # It is the format handler's own emitter, with no metadata section -- the same
948 # sub the handler's serialize() dumps through. Until k35 this WAS a second
949 # emitter, because the handlers only offered "serialize a document WITH its sops
950 # section", and it kept its options in sync with theirs by hand: a copy of
951 # JSON::MaybeXS->new(utf8/pretty/canonical) for JSON, and for YAML a boolean
952 # mode that at first was not set here at all and worked only because loading
953 # File::SOPS::Format::YAML assigned $YAML::XS::Boolean process-wide. Those
954 # options decide sorted key order, which the MAC's encrypt side depends on, so
955 # the twin was one edit away from a document that fails its own digest.
956 sub _serialize_plaintext {
957 57 ▶ my ($data, $format) = @_;
Subroutine _serialize_plaintext: called CC=2 SCAR=6.9
958  
959 # _format_class croaks on an unknown format, before anything is written.
960 57 my $format_class = _format_class($format);
961  
962 # A decrypted multi-document stream (docs/adr/0033, k31) is an ArrayRef
963 # of documents. This is the one boundary where a decrypted stream meets a
964 # plaintext output format, so Decision 3 -- the refusal to convert a stream
965 # to a format that has no document stream (JSON, ENV, INI) rather than drop
966 # all but its first document as sops does silently -- lives here as well as
967 # on the encrypt path. A YAML target emits the stream through emit().
968 57 ▶ my @docs = ref $data eq 'ARRAY' ? @$data : ($data);
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'ARRAY' ? : 5 52 57
969 57 _assert_format_supports_stream($format_class, scalar @docs);
970  
971 54 return $format_class->emit($data);
972 }
973  
974 # Decision 3 (docs/adr/0033, k14): a multi-document stream can only be
975 # written as YAML. Every other format has no document stream, so writing one to
976 # it would drop all but the first document -- which sops does silently, exit 0
977 # (N1). We refuse instead, naming the count and the target. Shared by the
978 # encrypt (serialize) path and the decrypt_file (emit) path so the two agree. A
979 # single document (or none) reaches every format and passes straight through.
980 sub _assert_format_supports_stream {
981 683 ▶ my ($format_class, $count) = @_;
Subroutine _assert_format_supports_stream: called CC=4 SCAR=13.9
982  
983 683 ▶ return if $count <= 1;
Branch: 1 branch
BranchTrueFalseTotal
if $count <= 1 677 6 683
984  
985 6 ▶ my $name = $format_class->can('format_name')
Branch: 1 branch
BranchTrueFalseTotal
$format_class->can('format_name') ? : 6 0 6
986 ? $format_class->format_name : "$format_class";
987 6 ▶ return if $name eq 'yaml';
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "yaml" 3 3 6
988  
989 3 croak sprintf(
990 "cannot write a multi-document stream (%d documents) as %s: that format "
991 . "has no document stream, so all but the first document would be lost. "
992 . "sops drops them silently here; this library refuses instead "
993 . "(docs/adr/0033 Decision 3, k14). Use YAML, or write one document "
994 . "at a time.",
995 $count, $name);
996 }
997  
998 # Write $content to $path, atomically: the content goes to a temporary file in
999 # the SAME directory (so the rename cannot cross a filesystem) and that file is
1000 # renamed over the target. Nothing observes a partial write, and a failure
1001 # anywhere before the rename leaves whatever was there untouched.
1002 #
1003 # EVERY method here that writes a file goes through this, whether the target
1004 # exists or not. Until 0.003 only encrypt_in_place and edit did: encrypt_file,
1005 # decrypt_file and rotate opened the target with '>', which truncates it before
1006 # the first byte is written, and then checked neither the print nor the close --
1007 # so a write that ran out of disk left an empty file and returned success.
1008 # encrypt_file defaults output to input and rotate always writes back over the
1009 # file it read, so what that destroyed was the only copy.
1010 #
1011 # This is where this distribution differs from sops, which truncates the file
1012 # and rewrites it. Truncate-and-rewrite keeps the inode -- hard links and the
1013 # open handle someone else holds see the new content -- at the price of
1014 # destroying the file if the write stops half way. On a file whose only copy is
1015 # about to be replaced by a re-encryption of itself, that trade goes the other
1016 # way round.
1017 #
1018 # A symlink is resolved first, so the target is replaced rather than the link;
1019 # measured against sops 3.13.3, `sops -e -i` on a symlink leaves the link alone
1020 # and rewrites the target too. Hard links to the target are NOT preserved; they
1021 # keep the old content, and that is documented on the methods that call this.
1022 sub _replace_file {
1023 102 ▶ my ($path, $content) = @_;
Subroutine _replace_file: called CC=15 SCAR=28.5
1024  
1025 102 ▶ my $target = -l $path ? (Cwd::abs_path($path) // $path) : $path;
Branch: 1 branch
BranchTrueFalseTotal
-l $path ? : 2 100 102
Condition33%1/3
Cwd::abs_path($path) // $path
l!l&&r!l&&!r
200
MC/DC0%0/2
Cwd::abs_path($path) // $path
Cwd::abs_path($path) $path
Truth table33%1/3
A // B
A= Cwd::abs_path($path)B= $path
ABresult
1X1
011
000
1026  
1027 # k46: sops -e -i refuses a read-only file with EACCES; the atomic
1028 # write was happy because rename() checks the directory, not the file.
1029 # This is a behaviour change introduced by the atomic write itself, where
1030 # the old open '>' would have failed on the chmod for free. Match sops
1031 # and refuse here, before any work -- a different inode is no
1032 # consolation when the file was deliberately read-only.
1033 102 ▶ croak "Could not open in-place file for writing: $target: permission denied"
Branch: 1 branch
BranchTrueFalseTotal
if -e $target and not -w $target 5 97 102
Condition100%3/3
-e $target and not -w $target
!ll&&!rl&&r
55425
MC/DC100%2/2
-e $target and not -w $target
-e $target not -w $target
Truth table100%3/3
A and not(B)
A= -e $targetB= not -w $target
ABresult
0X0
100
111
1034 if -e $target && !-w $target;
1035  
1036 97 ▶ return _write_through($target, $content) if -e $target && !-f $target;
Branch: 1 branch
BranchTrueFalseTotal
if -e $target and not -f $target 1 96 97
Condition100%3/3
-e $target and not -f $target
!ll&&!rl&&r
55411
MC/DC100%2/2
-e $target and not -f $target
-e $target not -f $target
Truth table100%3/3
A and not(B)
A= -e $targetB= not -f $target
ABresult
0X0
100
111
1037  
1038 # The mode to end up with: the one the file already has, or -- when there
1039 # is no file yet -- the one open '>' would have given it. File::Temp
1040 # creates 0600, so without this, preserving a deliberately group-readable
1041 # file would quietly tighten it and routing a write path through here would
1042 # be a permissions change as well as an atomicity one. sops's --output
1043 # creates at 0666 against the umask as well (measured: 0644 under umask
1044 # 022), and leaves an existing file's mode alone.
1045 96 my $existing = (stat $target)[2];
1046 96 ▶ my $mode = defined $existing ? $existing & 07777 : 0666 & ~umask;
Branch: 1 branch
BranchTrueFalseTotal
defined $existing ? : 41 55 96
1047  
1048 96 my ($vol, $dir, $base) = File::Spec->splitpath($target);
1049 96 ▶ $dir = File::Spec->curdir unless length $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless length $dir 0 96 96
1050  
1051 # tempfile() croaks with its own wording when the directory is missing or
1052 # unwritable. That used to be "Cannot open output file '...': $!" and has
1053 # to stay something that names the file the caller asked for.
1054 96 my ($fh, $tmp) = eval {
1055 96 File::Temp::tempfile(
1056 ".$base.sops-XXXXXXXX",
1057 DIR => File::Spec->catpath($vol, $dir, ''),
1058 UNLINK => 0,
1059 );
1060 };
1061 96 ▶ croak "Cannot create a temporary file next to '$target' to write it "
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fh 1 95 96
1062 . "atomically (" . _reason($@) . ")"
1063 unless defined $fh;
1064  
1065 95 my $ok = eval {
1066 95 binmode $fh, ':raw';
1067 95 ▶ print {$fh} $content
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} $content or croak("Cannot write to temporary file '${tmp}': $!") 0 95 95
1068 or croak "Cannot write to temporary file '$tmp': $!";
1069 95 ▶ close $fh
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("Cannot write to temporary file '${tmp}': $!") 0 95 95
1070 or croak "Cannot write to temporary file '$tmp': $!";
1071  
1072 95 ▶ chmod $mode, $tmp
Branch: 1 branch
BranchTrueFalseTotal
chmod $mode, $tmp or croak("Cannot set permissions on '${tmp}': $!") 0 95 95
1073 or croak "Cannot set permissions on '$tmp': $!";
1074  
1075 95 ▶ rename $tmp, $target
Branch: 1 branch
BranchTrueFalseTotal
rename $tmp, $target or croak("Cannot replace '${target}' with '${tmp}': $!") 0 95 95
1076 or croak "Cannot replace '$target' with '$tmp': $!";
1077 95 1;
1078 };
1079  
1080 95 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 95 95
1081 0 my $err = $@;
1082 0 close $fh;
1083 0 unlink $tmp;
1084 0 croak $err;
1085 }
1086  
1087 95 return 1;
1088 }
1089  
1090 # The one target temp-file-and-rename cannot serve: something that exists and
1091 # is not a regular file -- /dev/stdout, /dev/null, a fifo. There is no previous
1092 # content to protect there, and renaming over it would replace the device or
1093 # the fifo itself with an ordinary file. `sops --output /dev/stdout` works, so
1094 # this has to keep working.
1095 #
1096 # Every step is checked, unlike the open/print/close this replaced elsewhere:
1097 # an unreported short write was half of what made that path dangerous.
1098 sub _write_through {
1099 1 ▶ my ($path, $content) = @_;
Subroutine _write_through: called CC=4 SCAR=16.1
1100  
1101 1 ▶ open my $fh, '>:raw', $path
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $path or croak("Cannot open output file '${path}': $!") 0 1 1
1102 or croak "Cannot open output file '$path': $!";
1103 1 print {$fh} $content
1104 1 ▶ or do { my $err = $!; close $fh; croak "Cannot write to '$path': $err" };
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} $content or do { my $err = $!; close $fh; croak("Cannot write to '${path}': $err") } 0 1 1
1105 1 ▶ close $fh
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("Cannot write to '${path}': $!") 0 1 1
1106 or croak "Cannot write to '$path': $!";
1107  
1108 1 return 1;
1109 }
1110  
1111 # The editor to run, as a list, without a shell in between. A string is split
1112 # the way a shell would split it -- `EDITOR="code --wait"` is a command with an
1113 # argument, not a program with a space in its name -- which is what sops does
1114 # with $EDITOR as well.
1115 sub _editor_command {
1116 26 ▶ my ($editor) = @_;
Subroutine _editor_command: called CC=7 SCAR=19.5
1117  
1118 26 ▶ $editor //= $ENV{EDITOR};
Condition100%3/3
$editor //= $ENV{"EDITOR"}
l!l&&r!l&&!r
2321
MC/DC100%2/2
$editor //= $ENV{"EDITOR"}
$editor $ENV{"EDITOR"}
Truth table100%3/3
A //= B
A= $editorB= $ENV{"EDITOR"}
ABresult
1X1
011
000
1119  
1120 26 ▶ croak "No editor to run: pass editor => 'vim' to edit, or set the EDITOR "
Branch: 1 branch
BranchTrueFalseTotal
unless defined $editor and length $editor 1 25 26
Condition66%2/3
defined $editor and length $editor
!ll&&!rl&&r
1025
MC/DC50%1/2
defined $editor and length $editor
defined $editor length $editor
Truth table66%2/3
A and B
A= defined $editorB= length $editor
ABresult
0X0
100
111
1121 . "environment variable. (sops falls back to vim, nano or vi when "
1122 . "EDITOR is unset; this does not, because a library that opens an "
1123 . "interactive editor nobody asked for hangs an unattended script "
1124 . "instead of failing it.)"
1125 unless defined $editor && length $editor;
1126  
1127 25 ▶ my @command = ref $editor eq 'ARRAY' ? @$editor : shellwords($editor);
Branch: 1 branch
BranchTrueFalseTotal
ref $editor eq 'ARRAY' ? : 21 4 25
1128 25 ▶ croak "The editor command '" . (ref $editor eq 'ARRAY' ? join(' ', @$editor) : $editor)
Branch: 2 branches
BranchTrueFalseTotal
unless @command 1 24 25
ref $editor eq 'ARRAY' ? : 0 1 1
1129 . "' is empty once split into words"
1130 unless @command;
1131  
1132 24 return @command;
1133 }
1134  
1135 # Put $text in front of the editor and return what came back, or undef if it
1136 # was left byte for byte identical.
1137 #
1138 # The plaintext lives in a directory of its own for as long as this call, and
1139 # no longer. File::Temp's object removes the tree when $tmpdir goes out of
1140 # scope, which covers returning and dying alike; the handlers below cover being
1141 # signalled, where the default disposition would terminate the process without
1142 # running a destructor.
1143 #
1144 # SIGINT is deliberately in that list even though Ctrl-C during the editor does
1145 # not arrive here: perl's system() ignores SIGINT for the duration of the child
1146 # (perlfunc), so the interrupt reaches the EDITOR and comes back as a non-zero
1147 # wait status, which the croak below turns into ordinary unwinding. The handler
1148 # is for a SIGINT arriving in the rest of this call.
1149 sub _edit_text {
1150 18 ▶ my ($text, $file, $editor) = @_;
Subroutine _edit_text: called CC=6 SCAR=18.6
1151  
1152 18 my $tmpdir = File::Temp->newdir(TEMPLATE => 'file-sops-edit-XXXXXXXX',
1153 TMPDIR => 1);
1154  
1155 my $on_signal = sub {
1156 0 ▶ my ($signal) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1157 0 undef $tmpdir; # removes the plaintext, now
1158 0 $SIG{$signal} = 'DEFAULT'; # and then die of the signal we were sent
1159 0 kill $signal, $$;
1160 18 };
1161 18 local $SIG{INT} = $on_signal;
1162 18 local $SIG{TERM} = $on_signal;
1163 18 local $SIG{HUP} = $on_signal;
1164  
1165 # Same basename as the original, so the editor's filetype detection sees
1166 # the extension it expects. sops does this too.
1167 18 my $path = File::Spec->catfile("$tmpdir", basename($file));
1168  
1169 18 ▶ sysopen my $fh, $path, O_WRONLY | O_CREAT | O_EXCL, 0600
Branch: 1 branch
BranchTrueFalseTotal
sysopen my $fh, $path, 193, 384 or croak("Cannot create temporary file '${path}': $!") 0 18 18
1170 or croak "Cannot create temporary file '$path': $!";
1171 18 binmode $fh, ':raw';
1172 18 ▶ print {$fh} $text or croak "Cannot write temporary file '$path': $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} $text or croak("Cannot write temporary file '${path}': $!") 0 18 18
1173 18 ▶ close $fh or croak "Cannot write temporary file '$path': $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("Cannot write temporary file '${path}': $!") 0 18 18
1174  
1175 18 my $status = system(@$editor, $path);
1176 18 ▶ croak "Editor (" . join(' ', @$editor) . ") " . _wait_status($status)
Branch: 1 branch
BranchTrueFalseTotal
if $status != 0 2 16 18
1177 . "; '$file' is unchanged"
1178 if $status != 0;
1179  
1180 16 my $edited = _read_file($path, 'edited file');
1181  
1182 16 ▶ return undef if $edited eq $text;
Branch: 1 branch
BranchTrueFalseTotal
if $edited eq $text 3 13 16
1183 13 return $edited;
1184 }
1185  
1186 # What system() reported, in words. $? is the wait status, not an exit code.
1187 sub _wait_status {
1188 2 ▶ my ($status) = @_;
Subroutine _wait_status: called CC=3 SCAR=11.4
1189  
1190 2 ▶ return "could not be run: $!" if $status == -1;
Branch: 1 branch
BranchTrueFalseTotal
if $status == -1 0 2 2
1191 2 ▶ return "was killed by signal " . ($status & 127) if $status & 127;
Branch: 1 branch
BranchTrueFalseTotal
if $status & 127 0 2 2
1192 2 return "exited with status " . ($status >> 8);
1193 }
1194  
1195 # The top-level `sops` key is reserved for the metadata section, and there is
1196 # no way to encrypt a document that already uses it: serialization assigns the
1197 # metadata into that key unconditionally, so the user's value is overwritten --
1198 # after the digest has already covered it, which leaves a document that fails
1199 # its own MAC on the very next read.
1200 #
1201 # sops refuses the same thing, before encrypting anything, with exit code 203:
1202 #
1203 # The file you have provided contains a top-level entry called 'sops' [...]
1204 # SOPS uses a top-level entry called 'sops' to store the metadata required to
1205 # decrypt the file. For this reason, SOPS can not encrypt files that already
1206 # contain such an entry.
1207 #
1208 # It makes no distinction between "already encrypted" and "a user key that
1209 # happens to be called sops" -- and neither do we, because from the outside
1210 # they are the same document.
1211 #
1212 # The advice deliberately names NEITHER `edit` NOR `rotate`: the same guard
1213 # fires from inside both (rotate via the encrypt() below, edit by the same
1214 # path), and pointing the user at the method that just refused them is worse
1215 # than not pointing at anything. The remedies are documented under those
1216 # methods; the message here says what is wrong and what to do about it.
1217 sub _sops_key_reserved {
1218 11 ▶ my ($what) = @_;
Subroutine _sops_key_reserved: called CC=1 SCAR=0.0
1219 return
1220 11 "$what contains a top-level 'sops' entry, which is reserved for the "
1221 . "SOPS metadata section. Encrypting would overwrite it and produce a "
1222 . "document that fails its own MAC verification. This usually means the "
1223 . "input is already encrypted -- decrypt it first if you want to change "
1224 . "its contents or re-key it. If it really is plaintext, rename the "
1225 . "entry. (sops refuses such a file too, with exit code 203.)";
1226 }
1227  
1228 # The same refusal for text that came back from an editor, which is a different
1229 # situation with a different remedy: the document was just typed, nothing has
1230 # been written yet, and pointing the user at edit -- which is where they
1231 # already are -- would be no help at all.
1232 #
1233 # Both ways an edited document can carry the entry end here. See edit.
1234 sub _edited_sops_key_reserved {
1235 4 ▶ my ($file) = @_;
Subroutine _edited_sops_key_reserved: called CC=1 SCAR=0.0
1236 return
1237 4 "The edited document has a top-level 'sops' entry. That name is "
1238 . "reserved for the metadata section, which is written back "
1239 . "automatically -- remove it and edit again. '$file' is unchanged.";
1240 }
1241  
1242 # Is this exception the "top-level 'sops' entry is not a mapping" refusal?
1243 #
1244 # That refusal lives in File::SOPS::Metadata::from_hash, which the format
1245 # handlers call from inside parse(), so a caller of parse() receives it as an
1246 # exception -- indistinguishable, without this, from the document not parsing.
1247 # edit is the only caller that has to tell the two apart.
1248 #
1249 # Keying on the message coupled this to another module's wording, deliberately
1250 # and in preference to the alternatives: a syntax-only parse in the format
1251 # handlers, or a typed exception, both reach well past the one call site that
1252 # needs the distinction. t/17-in-place-and-edit.t pins both branches, so a
1253 # rewording in Metadata.pm fails a test rather than quietly restoring the
1254 # regression this replaced (k47) -- edit reporting a document that parses
1255 # as one that does not.
1256 sub _is_sops_not_a_mapping {
1257 13 ▶ my ($err) = @_;
Subroutine _is_sops_not_a_mapping: called CC=2 SCAR=7.1
1258 13 ▶ return defined $err && $err =~ /\Athe top-level 'sops' entry is\b/;
Condition66%2/3
defined $err && $err =~ /\Athe top-level 'sops' entry is\b/
!ll&&!rl&&r
0103
MC/DC50%1/2
defined $err && $err =~ /\Athe top-level 'sops' entry is\b/
defined $err $err =~ /\Athe top-level 'sops' entry is\b/
Truth table66%2/3
A && B
A= defined $errB= $err =~ /\Athe top-level 'sops' entry is\b/
ABresult
0X0
100
111
1259 }
1260  
1261 # Say WHERE something went wrong. A generic failure in a document of a hundred
1262 # leaves costs an afternoon; the key path costs nothing to carry and is the
1263 # only thing that makes the message actionable.
1264 #
1265 # The path is made of KEYS, which a SOPS document leaves readable by design.
1266 # Nothing derived from the plaintext, the data key or an age identity is ever
1267 # interpolated into an error -- an error message goes to logs and bug reports,
1268 # and a value that leaks there was not encrypted for any practical purpose.
1269 sub _at_path {
1270 61 ▶ my ($path, $err) = @_;
Subroutine _at_path: called CC=3 SCAR=12.5
1271 61 ▶ my $where = ($path && @$path) ? join(':', @$path) : '(document root)';
Branch: 1 branch
BranchTrueFalseTotal
$path && @$path ? : 61 0 61
Condition33%1/3
$path and @$path
!ll&&!rl&&r
0061
MC/DC0%0/2
$path and @$path
$path @$path
Truth table33%1/3
A and B
A= $pathB= @$path
ABresult
0X0
100
111
1272 61 return "$where: " . _reason($err);
1273 }
1274  
1275 # An inner error's own text, without the file and line croak appended to it --
1276 # the outer croak supplies a fresh one. Empty $@ becomes something readable
1277 # rather than an empty pair of parentheses.
1278 sub _reason {
1279 67 ▶ my ($err) = @_;
Subroutine _reason: called CC=4 SCAR=14.1
1280 67 ▶ return 'no reason given' unless defined $err && length $err;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $err and length $err 1 66 67
Condition66%2/3
defined $err and length $err
!ll&&!rl&&r
0166
MC/DC50%1/2
defined $err and length $err
defined $err length $err
Truth table66%2/3
A and B
A= defined $errB= length $err
ABresult
0X0
100
111
1281 66 $err =~ s/\s+at\s+\S+\s+line\s+\d+\.?\s*\z//;
1282 66 ▶ return length($err) ? $err : 'no reason given';
Branch: 1 branch
BranchTrueFalseTotal
length $err ? : 66 0 66
1283 }
1284  
1285 # The metadata a fresh encryption starts from. Only the encryption POLICY can
1286 # be carried in from a caller: a new data key is about to be generated, so
1287 # every wrapped copy of the old one, the MAC over the old values and the
1288 # lastmodified that authenticates it are all regenerated regardless of what
1289 # was handed over.
1290 sub _metadata_for_encrypt {
1291 681 ▶ my ($args) = @_;
Subroutine _metadata_for_encrypt: called CC=7 SCAR=19.6
1292  
1293 681 my @given = grep { exists $args->{$_} } @File::SOPS::Metadata::ENCRYPTION_RULES;
1294  
1295 681 my %attr;
1296 681 ▶ if (defined(my $template = $args->{metadata})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $template = $args->{"metadata"})) 33 648 681
1297 33 ▶ croak "metadata must be a File::SOPS::Metadata object"
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($template) and $template->isa("File::SOPS::Metadata") 0 33 33
Condition33%1/3
builtin::blessed($template) and $template->isa("File::SOPS::Metadata")
!ll&&!rl&&r
0033
MC/DC0%0/2
builtin::blessed($template) and $template->isa("File::SOPS::Metadata")
builtin::blessed($template) $template->isa("File::SOPS::Metadata")
Truth table33%1/3
A and B
A= builtin::blessed($template)B= $template->isa("File::SOPS::Metadata")
ABresult
0X0
100
111
1298 unless blessed($template)
1299 && $template->isa('File::SOPS::Metadata');
1300  
1301 33 %attr = $template->policy_args;
1302  
1303 # An explicit rule REPLACES the template's rather than joining it: the
1304 # rules are mutually exclusive, so merging the two could only ever
1305 # build a document sops refuses.
1306 33 ▶ delete @attr{@File::SOPS::Metadata::ENCRYPTION_RULES} if @given;
Branch: 1 branch
BranchTrueFalseTotal
if @given 1 32 33
1307 }
1308  
1309 681 $attr{$_} = $args->{$_} for @given;
1310 $attr{mac_only_encrypted} = $args->{mac_only_encrypted}
1311 681 ▶ if defined $args->{mac_only_encrypted};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"mac_only_encrypted"} 38 643 681
1312  
1313 681 my $metadata = File::SOPS::Metadata->new(%attr);
1314 680 _assert_rules_supported($metadata);
1315  
1316 672 return $metadata;
1317 }
1318  
1319 # Refuse to WRITE a document under a rule we cannot apply. Writing under a rule
1320 # we ignore would leave values in plaintext that the rule says to encrypt, or
1321 # the reverse, in a file that looks perfectly well-formed.
1322 #
1323 # Reading such a document is a SEPARATE question and is answered separately --
1324 # decryption has been rule-driven since docs/adr/0049, so the rule is consulted
1325 # there too, and where sops's own answer is reproducible the read path
1326 # reproduces it rather than refusing. docs/adr/0051 is why the regex half of
1327 # this lives behind a method of its own instead of inside the match.
1328 sub _assert_rules_supported {
1329 680 ▶ my ($metadata) = @_;
Subroutine _assert_rules_supported: called CC=4 SCAR=13.9
1330  
1331 680 for my $rule (@File::SOPS::Metadata::UNSUPPORTED_ENCRYPTION_RULES) {
1332 1360 my $value = $metadata->rule_value($rule);
1333 1360 ▶ next unless defined $value && length $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and length $value 1359 1 1360
Condition66%2/3
defined $value and length $value
!ll&&!rl&&r
135901
MC/DC50%1/2
defined $value and length $value
defined $value length $value
Truth table66%2/3
A and B
A= defined $valueB= length $value
ABresult
0X0
100
111
1334 1 croak "Refusing to encrypt under '$rule': it selects values by their "
1335 . "comment, and neither of this distribution's parsers keeps "
1336 . "comments, so every value would be classified wrongly. Use the "
1337 . "sops CLI for documents that use it.";
1338 }
1339  
1340 # Asked HERE, once, rather than at the point of match. At the point of
1341 # match it fired from inside the leaf walk, so `encrypt` reported a rule
1342 # problem under whichever leaf the walk happened to reach first --
1343 # `bar: Cannot use '(?=f)foo' as the unencrypted_regex ...`, where `bar`
1344 # has nothing to do with it (k166). It is also the whole of what makes
1345 # the read path free to answer differently.
1346 679 $metadata->assert_rule_regexes_agree;
1347  
1348 672 return 1;
1349 }
1350  
1351 # age is the only backend implemented here, so a document holding key material
1352 # for another one cannot be re-keyed: the new data key can be wrapped for its
1353 # age recipients and for nobody else. Both ways out of that are wrong, and the
1354 # quiet one is the worse -- dropping the entries revokes those recipients'
1355 # access while reporting success, and keeping them leaves a wrapped copy of a
1356 # key that no longer decrypts anything, which fails later and further away.
1357 #
1358 # Every operation that generates a new data key has to ask this, which is
1359 # rotate and edit; the wording differs only in the verb.
1360 sub _assert_rekeyable {
1361 66 ▶ my ($metadata, $file, %words) = @_;
Subroutine _assert_rekeyable: called CC=2 SCAR=6.9
1362  
1363 66 my @foreign = grep { $_ ne 'age' } $metadata->key_material_fields;
1364 66 ▶ return 1 unless @foreign;
Branch: 1 branch
BranchTrueFalseTotal
unless @foreign 59 7 66
1365  
1366 7 croak "Refusing to $words{verb} '$file': its sops section holds key material "
1367 . "this distribution cannot re-encrypt (" . join(', ', @foreign) . "). "
1368 . "$words{noun} generates a new data key, so those entries would be "
1369 . "silently dropped and the recipients behind them would lose access. "
1370 . "\u$words{verb} this file with the sops CLI, or, if losing them is "
1371 . "what you want, say so explicitly with decrypt followed by encrypt.";
1372 }
1373  
1374 # --- how deep a document may be -----------------------------------------
1375 #
1376 # Every walk in this file recurses, and each of them carries the two lines
1377 # below: `no warnings 'recursion'` and a depth it refuses to pass. The two
1378 # belong together and neither works alone.
1379 #
1380 # Perl warns "Deep recursion on subroutine" once a sub is 100 frames deep. That
1381 # threshold is fixed and is about perl, not about the document: a 265-level
1382 # document sops accepts is ordinary input here, and it produced 505 warning
1383 # lines and 63 KB on STDERR for a correct encrypt (measured, k117) -- a
1384 # successful operation that reads like a crash. The warning is silenced where
1385 # it is noise, per walk rather than per file, so nothing outside these walks
1386 # loses it.
1387 #
1388 # What the warning was also doing -- being the only thing that ever said a walk
1389 # had lost its footing -- is replaced here by a bound that is part of the
1390 # contract instead of a side effect of perl's stack accounting.
1391 #
1392 # The number is sops's, not ours, measured against sops 3.13.3 on documents
1393 # built as `a: {a: {a: ... }}` and `a: [[[ ... ]]]`, counting CONTAINERS from
1394 # the document's own root mapping:
1395 #
1396 # go-yaml (sops -e, sops -d) 10001 accepted, 10002 refused
1397 # "yaml: exceeded max depth of 10000"
1398 # encoding/json (sops -e) 10000 accepted, 10001 refused
1399 # "invalid character '{' exceeded max depth"
1400 #
1401 # and, as with the cycle and the alias bomb, the -d refusal comes out AHEAD of
1402 # the key: the same over-deep encrypted file with no age identity available
1403 # still reports the depth.
1404 #
1405 # 10000 is therefore the deepest a document can be and still be readable in
1406 # BOTH formats, and that is the number here. It is one level tighter than
1407 # go-yaml alone on the YAML side, deliberately: the alternative is writing a
1408 # JSON file that sops cannot read back, and refusing loudly is the cheaper of
1409 # the two errors. It is the same shape of decision as docs/adr/0027 -- take the
1410 # reference's own limit rather than invent one -- and the same reason.
1411 #
1412 # The bound is only a bound if reaching it is affordable, which is why the
1413 # walks below carry the path as ONE array that is pushed and popped rather than
1414 # copying it per level. Copying made a walk quadratic in depth: 4000 levels
1415 # took 101s and 410 MB in _sorted_leaves alone, so a refusal at 10000 would
1416 # have arrived minutes and gigabytes later -- a hang with a message attached.
1417 # Shared and unwound, the same walk reaches 10000 in 17ms and 24 MB (measured).
1418 #
1419 # It is a variable and not a constant on purpose, and t/41 is the reason. That
1420 # file bounds a runaway walk -- k110's, a document that contains itself --
1421 # by dying at a depth no fixture of its own reaches, and until now it borrowed
1422 # perl's fixed threshold of 100 for that. It cannot borrow it any more, because
1423 # the line above silences it. So the bound it borrows instead is this one, and
1424 # a caller reading untrusted documents can use it the same way. Lowering it
1425 # refuses deep documents earlier than sops does; raising it writes documents
1426 # sops will not read.
1427 80 our $MAX_DEPTH = 10_000;
1428  
1429 sub _assert_depth {
1430 463910 ▶ my ($depth) = @_;
Subroutine _assert_depth: called CC=2 SCAR=6.9
1431  
1432 463910 ▶ return 1 if $depth <= $MAX_DEPTH;
Branch: 1 branch
BranchTrueFalseTotal
if $depth <= $File::SOPS::MAX_DEPTH 463902 8 463910
1433  
1434 8 croak "this document nests containers more than $MAX_DEPTH deep, which is "
1435 . "as deep as this library walks. sops stops as well: go-yaml refuses "
1436 . "past 10001 nested containers with \"yaml: exceeded max depth of "
1437 . "10000\", and Go's JSON encoder past 10000 with \"exceeded max "
1438 . "depth\" -- in both directions, and ahead of the data key. The path "
1439 . "is not named here because it is thousands of keys long.";
1440 }
1441  
1442 # A container that is its own ancestor has no finite set of values, so there is
1443 # nothing to encrypt, nothing to hash and no document to write. Nothing
1444 # upstream of here stops one: the two YAML parsers this library uses disagree
1445 # about it, YAML::XS building the cycle and handing it over while YAML::PP
1446 # refuses the alias outright. So Format::YAML->parse returns a live Perl cycle,
1447 # and every walk below it -- _sorted_leaves, _encrypt_tree, _decrypt_tree,
1448 # _document_leaves -- recursed until the process was killed. A hang tells the
1449 # caller nothing, cannot be caught, and where the document came from outside is
1450 # resource exhaustion by a file. See k110 and docs/adr/0025.
1451 #
1452 # Refusing is what the reference implementation does, in BOTH directions.
1453 # Measured against sops 3.13.3 on `root: &a` / ` b: *a`:
1454 #
1455 # sops -e -> Error unmarshalling file: yaml: anchor 'a' value contains itself
1456 # (exit 2)
1457 # sops -d -> yaml: anchor 'a' value contains itself (exit 1)
1458 #
1459 # and the -d refusal comes out AHEAD of the key error -- the same document with
1460 # no age identity available still reports the cycle, not "Failed to get the
1461 # data key" -- which is why the decrypt side asks this before unwrapping the
1462 # data key rather than after.
1463 #
1464 # Terminating is not on its own an answer, which is why there is no visited set
1465 # in the walks instead. A walk that skipped the second visit would emit a
1466 # document with the alias expanded once and a digest taken over a tree that is
1467 # not the one the file describes: a wrong answer, quietly, which is the defect
1468 # class this layer keeps producing.
1469 #
1470 # The check is an ANCESTOR set, not a visited set, and that difference is the
1471 # whole guard. A plain visited set would also refuse a shared but ACYCLIC
1472 # subtree -- what an ordinary, non-recursive anchor builds -- and sops accepts
1473 # those and expands them: measured, `base: &b` / ` p: 1` / `other: *b`
1474 # encrypts to two independent ENC values and decrypts back to both. $active
1475 # holds the current path and is unwound on the way back up; $clean holds the
1476 # nodes already proven acyclic, so a diamond is walked once rather than once
1477 # per path through it.
1478 sub _assert_acyclic {
1479 80 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
1480 57852 ▶ my ($node, $path, $active, $clean, $depth) = @_;
Subroutine _assert_acyclic: called CC=9 SCAR=22.0
1481  
1482 57852 ▶ return 1 unless ref $node eq 'HASH' || ref $node eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $node eq "HASH" or ref $node eq "ARRAY" 8495 49357 57852
Condition100%3/3
ref $node eq "HASH" or ref $node eq "ARRAY"
l!l&&r!l&&!r
492201378495
MC/DC100%2/2
ref $node eq "HASH" or ref $node eq "ARRAY"
ref $node eq "HASH" ref $node eq "ARRAY"
Truth table100%3/3
A or B
A= ref $node eq "HASH"B= ref $node eq "ARRAY"
ABresult
1X1
011
000
1483  
1484 # $clean makes this walk O(nodes) rather than O(paths), and that memo also
1485 # means the depth counted here is the depth of the FIRST path to a shared
1486 # subtree, not the deepest. It is not the only place the bound is asked:
1487 # the walks that expand aliases rather than memoising them -- _sorted_leaves,
1488 # _encrypt_tree, _decrypt_tree -- see the deeper path and refuse it there.
1489 49357 ▶ $depth = ($depth // 0) + 1;
Condition100%2/2
$depth // 0
l!l
481651192
MC/DC100%1/1
$depth // 0
$depth
Truth table100%2/2
A
A= $depth
Aresult
11
00
1490 49357 _assert_depth($depth);
1491  
1492 49354 my $addr = refaddr($node);
1493 49354 ▶ return 1 if $clean->{$addr};
Branch: 1 branch
BranchTrueFalseTotal
if $clean->{$addr} 1034 48320 49354
1494  
1495 croak _at_path($path, "this value contains itself, so the document has no "
1496 . "finite set of values to encrypt or to hash. A YAML anchor nested "
1497 . "inside its own value produces one, and so does a Perl structure "
1498 . "passed to encrypt that refers back to itself. sops refuses the same "
1499 . "document: \"yaml: anchor 'a' value contains itself\". An anchor that "
1500 . "is merely reused is fine and is not this.")
1501 48320 ▶ if $active->{$addr};
Branch: 1 branch
BranchTrueFalseTotal
if $active->{$addr} 0 48320 48320
1502  
1503 48320 $active->{$addr} = 1;
1504  
1505 48320 ▶ if (ref $node eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node eq 'HASH') { } 48195 125 48320
1506 # One path array, pushed and popped, not a copy per level: see the
1507 # depth comment above for what the copy cost at depth.
1508 48195 for my $k (sort keys %$node) {
1509 56411 push @$path, $k;
1510 56411 _assert_acyclic($node->{$k}, $path, $active, $clean, $depth);
1511 46311 pop @$path;
1512 }
1513 }
1514 else {
1515 # An array contributes no path component anywhere else in this library
1516 # and does not gain one here just because this path is a diagnostic.
1517 125 _assert_acyclic($_, $path, $active, $clean, $depth) for @$node;
1518 }
1519  
1520 38220 delete $active->{$addr};
1521 38220 $clean->{$addr} = 1;
1522  
1523 38220 return 1;
1524 }
1525  
1526 # An acyclic document can still have no finite walk to it. Aliases that are
1527 # merely SHARED, not recursive, expand into a tree with 2**N leaves, so
1528 # _assert_acyclic above correctly does not fire -- the document really is
1529 # acyclic -- and every walk below it explodes anyway. Measured at 25 levels,
1530 # 727 bytes of YAML: encrypt_file did not return, and the walk climbs about a
1531 # gigabyte of RSS every three seconds. See k112 and docs/adr/0027.
1532 #
1533 # The blowup is entirely ours. YAML::XS resolves an alias to the SAME Perl
1534 # reference rather than to a copy, so Load returns a linear DAG -- 200 levels
1535 # in 0.7ms -- and only _sorted_leaves, _encrypt_tree and _decrypt_tree expand
1536 # it. There is therefore nothing to catch at parse time and nothing to
1537 # pre-filter on the raw bytes; the guard belongs here, next to the other one,
1538 # where it also covers the origin that has no parser at all: a caller handing
1539 # encrypt the same hash reference from several places.
1540 #
1541 # Refusing is what the reference implementation does, in BOTH directions.
1542 # Measured against sops 3.13.3:
1543 #
1544 # sops -e -> Error unmarshalling file: yaml: document contains excessive
1545 # aliasing (exit 2)
1546 # sops -d -> yaml: document contains excessive aliasing (exit 1)
1547 #
1548 # and, as with the cycle, the -d refusal comes out ahead of the key error.
1549 #
1550 # go-yaml's budget is a RATIO, not a count, and that distinction is the whole
1551 # guard. Bisected against the binary in four differently shaped families, it
1552 # accepts a 206,104-node expansion and refuses an 8,146-node one: what it
1553 # measures is how far the expansion exceeds the document that produced it.
1554 # A cap on expanded nodes would therefore refuse files sops accepts, which is
1555 # the one error this layer must not make. So the counters below are go-yaml's
1556 # counters, in go-yaml's units, and the constants are its constants.
1557 80 my $ALIAS_RATIO_RANGE_LOW = 400_000;
1558 80 my $ALIAS_RATIO_RANGE_HIGH = 4_000_000;
1559  
1560 # The expansion is exponential, so its count overflows a double long before it
1561 # overflows patience. Saturating keeps the arithmetic exact where it matters:
1562 # past the high range the allowance is a flat 0.10 and nothing above the
1563 # ceiling can change an answer.
1564 80 my $EXPANSION_CEILING = 1_000_000_000;
1565  
1566 sub _allowed_alias_ratio {
1567 27 ▶ my ($decoded) = @_;
Subroutine _allowed_alias_ratio: called CC=3 SCAR=11.0
1568  
1569 27 ▶ return 0.99 if $decoded <= $ALIAS_RATIO_RANGE_LOW;
Branch: 1 branch
BranchTrueFalseTotal
if $decoded <= $ALIAS_RATIO_RANGE_LOW 25 2 27
1570 2 ▶ return 0.10 if $decoded >= $ALIAS_RATIO_RANGE_HIGH;
Branch: 1 branch
BranchTrueFalseTotal
if $decoded >= $ALIAS_RATIO_RANGE_HIGH 1 1 2
1571 1 return 0.99 - 0.89 * (($decoded - $ALIAS_RATIO_RANGE_LOW)
1572 / ($ALIAS_RATIO_RANGE_HIGH - $ALIAS_RATIO_RANGE_LOW));
1573 }
1574  
1575 # Returns the expanded node count and the expanded CONTAINER count for $node,
1576 # and accumulates the written document's own shape in $written. Memoised on
1577 # refaddr, which is what makes it O(distinct nodes) on a DAG whose expansion is
1578 # exponential -- the same reason _assert_acyclic keeps a $clean set. The memo
1579 # is not a cycle guard: it is filled on the way OUT, so a cycle would recurse
1580 # forever here. _assert_acyclic runs first and that ordering is load-bearing.
1581 sub _expansion_census {
1582 80 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
1583 90966 ▶ my ($node, $memo, $written, $depth) = @_;
Subroutine _expansion_census: called CC=11 SCAR=24.0
1584  
1585 90966 ▶ return (1, 0) unless ref $node eq 'HASH' || ref $node eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $node eq "HASH" or ref $node eq "ARRAY" 33603 57363 90966
Condition100%3/3
ref $node eq "HASH" or ref $node eq "ARRAY"
l!l&&r!l&&!r
52226513733603
MC/DC100%2/2
ref $node eq "HASH" or ref $node eq "ARRAY"
ref $node eq "HASH" ref $node eq "ARRAY"
Truth table100%3/3
A or B
A= ref $node eq "HASH"B= ref $node eq "ARRAY"
ABresult
1X1
011
000
1586  
1587 57363 ▶ $depth = ($depth // 0) + 1;
Condition100%2/2
$depth // 0
l!l
561621201
MC/DC100%1/1
$depth // 0
$depth
Truth table100%2/2
A
A= $depth
Aresult
11
00
1588 57363 _assert_depth($depth);
1589  
1590 57362 my $addr = refaddr($node);
1591 57362 ▶ return @{$memo->{$addr}} if $memo->{$addr};
Branch: 1 branch
BranchTrueFalseTotal
if $memo->{$addr} 8487 48875 57362
1592  
1593 48875 $written->{containers}++;
1594  
1595 48875 my ($nodes, $containers) = (1, 1);
1596 48875 my @children;
1597 48875 ▶ if (ref $node eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node eq 'HASH') { } 43750 5125 48875
1598 # go-yaml decodes a mapping key as a node in its own right, so this
1599 # counts one too. The units have to be its units or the ratio is not
1600 # its ratio. A sequence has no keys and gains nothing here.
1601 43750 my $keys = scalar keys %$node;
1602 43750 $written->{keys} += $keys;
1603 43750 $nodes += $keys;
1604 43750 @children = values %$node;
1605 }
1606 else {
1607 5125 @children = @$node;
1608 }
1609  
1610 48875 for my $child (@children) {
1611 89765 ▶ if (ref $child eq 'HASH' || ref $child eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $child eq 'HASH' or ref $child eq 'ARRAY') { } 56162 33603 89765
Condition100%3/3
ref $child eq "HASH" or ref $child eq "ARRAY"
l!l&&r!l&&!r
51025513733603
MC/DC100%2/2
ref $child eq "HASH" or ref $child eq "ARRAY"
ref $child eq "HASH" ref $child eq "ARRAY"
Truth table100%3/3
A or B
A= ref $child eq "HASH"B= ref $child eq "ARRAY"
ABresult
1X1
011
000
1612 56162 $written->{edges}++;
1613 }
1614 else {
1615 33603 $written->{leaves}++;
1616 }
1617 89765 my ($child_nodes, $child_containers)
1618 = _expansion_census($child, $memo, $written, $depth);
1619 89715 $nodes += $child_nodes;
1620 89715 $containers += $child_containers;
1621 89715 ▶ $nodes = $EXPANSION_CEILING if $nodes > $EXPANSION_CEILING;
Branch: 1 branch
BranchTrueFalseTotal
if $nodes > $EXPANSION_CEILING 0 89715 89715
1622 89715 ▶ $containers = $EXPANSION_CEILING if $containers > $EXPANSION_CEILING;
Branch: 1 branch
BranchTrueFalseTotal
if $containers > $EXPANSION_CEILING 0 89715 89715
1623 }
1624  
1625 48825 $memo->{$addr} = [$nodes, $containers];
1626 48825 return ($nodes, $containers);
1627 }
1628  
1629 sub _assert_expansion_bounded {
1630 1201 ▶ my ($node) = @_;
Subroutine _assert_expansion_bounded: called CC=5 SCAR=16.2
1631  
1632 1201 my %written = (containers => 0, keys => 0, leaves => 0, edges => 0);
1633 1201 my ($nodes, $containers) = _expansion_census($node, {}, \%written);
1634  
1635 # go-yaml's decodeCount: every node of the EXPANDED tree, plus the alias
1636 # node it passes through on the way into each repeated container. Every
1637 # expanded container but the root arrives through exactly one edge, and
1638 # exactly $written{containers} - 1 of those edges are anchor definitions
1639 # rather than aliases. Plus one for the document node itself.
1640 1200 my $decoded = $nodes + $containers - $written{containers} + 1;
1641 1200 ▶ $decoded = $EXPANSION_CEILING if $decoded > $EXPANSION_CEILING;
Branch: 1 branch
BranchTrueFalseTotal
if $decoded > $EXPANSION_CEILING 0 1200 1200
1642  
1643 # go-yaml's non-alias count: the document as WRITTEN -- the document node,
1644 # every distinct container, its keys and its scalar values, and one alias
1645 # node for each reference beyond a container's own definition.
1646 my $as_written = 1 + $written{containers} + $written{keys}
1647 1200 + $written{leaves} + ($written{edges} - ($written{containers} - 1));
1648  
1649 1200 my $aliased = $decoded - $as_written;
1650  
1651 1200 ▶ return 1 unless $aliased > 100
Branch: 1 branch
BranchTrueFalseTotal
unless $aliased > 100 and $decoded > 1000 and $aliased / $decoded > _allowed_alias_ratio($decoded) 7 20 27
Condition83%5/6
$aliased > 100 and $decoded > 1000 and $aliased / $decoded > _allowed_alias_ratio($decoded)
!ll&&!rl&&r
1173720
$aliased > 100 and $decoded > 1000
!ll&&!rl&&r
1173027
MC/DC66%2/3
$aliased > 100 and $decoded > 1000 and $aliased / $decoded > _allowed_alias_ratio($decoded)
$aliased > 100 $decoded > 1000 $aliased / $decoded > _allowed_alias_ratio($decoded)
Truth table75%3/4
A and B and C
A= $aliased > 100B= $decoded > 1000C= $aliased / $decoded > _allowed_alias_ratio($decoded)
ABCresult
0XX0
10X0
1100
1111
1652 && $decoded > 1000
1653 && $aliased / $decoded > _allowed_alias_ratio($decoded);
1654  
1655 20 croak "this document expands to " . $decoded . " values from the "
1656 . $as_written . " it holds, which is the alias bomb sops refuses: "
1657 . "\"yaml: document contains excessive aliasing\". A YAML anchor "
1658 . "referenced from inside another anchor's value doubles the document "
1659 . "at every level, and a structure passed to encrypt that holds one "
1660 . "reference in several places does the same with no YAML involved. "
1661 . "Reusing an anchor is ordinary and is not this: sops allows an "
1662 . "expansion of up to 100 times what the document holds -- less as "
1663 . "the expansion itself grows past 400000 values -- and refuses this "
1664 . "one at " . sprintf('%.0f', $decoded / $as_written) . " times.";
1665 }
1666  
1667 sub _encryption_options {
1668 47 ▶ my ($args) = @_;
Subroutine _encryption_options: called CC=1 SCAR=0.0
1669 8 return map { $_ => $args->{$_} }
1670 47 grep { exists $args->{$_} } @ENCRYPTION_OPTIONS;
1671 }
1672  
1673 ###############################################################################
1674 # THE COMMENT BUCKET, and it is a PATH rule rather than a name (docs/adr/0047)
1675 #
1676 # sops walks a branch with the branch's own path, and a comment is an ITEM of
1677 # that branch whose key is Go's Comment struct -- so it contributes NO path
1678 # component where an ordinary key does. Measured against sops 3.13.3: a comment
1679 # inside an ini section `[db]` authenticates under `db:`, never `db::`, and
1680 # `db::` is what a genuine empty key nested in a mapping authenticates under.
1681 #
1682 # The two are the same thing only where the branch is the document ROOT: there
1683 # Go's join produces `:`, which _path_to_aad spells `['']`, and that is why
1684 # File::SOPS::Format::ENV can keep a dotenv document's comments under a real,
1685 # empty KEY. Format::INI's branches are sections and cannot.
1686 #
1687 # So: a `''` key whose value is a sequence of COMMENTS adds no path component
1688 # when the path is already non-empty. Deliberately narrow --
1689 #
1690 # * `@$path` non-empty, so the dotenv bucket at the root keeps the `''`
1691 # component it needs and nothing about that format moves;
1692 # * the value must be a non-empty ARRAY of comments, so `{ map => { '' =>
1693 # 'v' } }` keeps `map::`, which is the AAD sops gives it, measured.
1694 #
1695 # The one shape whose AAD moves is a mapping key `''` holding a list of nothing
1696 # but comments, below the top level. It is a shape sops cannot write, and THAT
1697 # -- not agreement -- is what makes the rule safe. Measured on 3.13.3: where a
1698 # genuine empty key holds a list carrying a comment AND a value, sops
1699 # authenticates the comment under `db::`, so the rule must not fire there, and
1700 # the all-comments test is exactly what keeps it from firing. A list of nothing
1701 # but comments never comes back out of sops, because a comment leaf exists only
1702 # where a node follows it in the same sequence -- measured over head, trailing,
1703 # consecutive and lone comments: every sequence sops wrote held at least one
1704 # non-comment element, and a comment with no node to attach to was hoisted to
1705 # the parent branch or dropped. A document that trips this rule was therefore
1706 # built by a caller by hand, and there we diverge from sops deliberately: the
1707 # two readings of `''` are the same bytes on the wire, so nothing at this layer
1708 # can tell them apart.
1709 ###############################################################################
1710 80 our $COMMENT_BUCKET_KEY = '';
1711  
1712 # Two shapes for a comment leaf, both load-bearing for the bucket predicate:
1713 #
1714 # * a File::SOPS::Comment object -- the plaintext tree's spelling;
1715 # * a plain string whose text parses as ENC[...,type:comment] -- the wire
1716 # tree's spelling, and what decrypt returns at a path the encryption
1717 # rule EXCLUDES (rule-first decrypt, ADR 0049).
1718 #
1719 # Both have to answer YES here, for the same reason: the walks agree about
1720 # the path they build. Where the bucket predicate returns NO the bucket key
1721 # ADDS a path component, and the two walks answer `should_encrypt_path`
1722 # about different paths. A plain value at `db:` is one AAD; the same value
1723 # at `db::` (the bucket key appended) is another. The leaf walks don't
1724 # share the bucket predicate -- one sub rather than two -- because a path
1725 # they disagree on writes a document this library writes and then cannot
1726 # read (measured, with `^$`: rotate declined a file encrypt had just
1727 # written). The Comment-object half is recognised by _is_comment_leaf
1728 # regardless of the data-key gate; the wire half is recognised by the same
1729 # predicate k168 added to the leaf guard -- `!ref && encrypted_type
1730 # eq 'comment'` -- which the data-key gate does not need because the
1731 # predicate never decrypts. docs/adr/0059, k172.
1732 sub _is_comment_bucket {
1733 20 ▶ my ($value) = @_;
Subroutine _is_comment_bucket: called CC=8 SCAR=20.9
1734  
1735 20 ▶ return 0 unless ref $value eq 'ARRAY' && @$value;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "ARRAY" and @$value 1 19 20
Condition66%2/3
ref $value eq "ARRAY" and @$value
!ll&&!rl&&r
1019
MC/DC50%1/2
ref $value eq "ARRAY" and @$value
ref $value eq "ARRAY" @$value
Truth table66%2/3
A and B
A= ref $value eq "ARRAY"B= @$value
ABresult
0X0
100
111
1736 19 for my $item (@$value) {
1737 21 ▶ next if File::SOPS::Encrypted->is_comment($item);
Branch: 1 branch
BranchTrueFalseTotal
if "File::SOPS::Encrypted"->is_comment($item) 9 12 21
1738 12 ▶ next if !ref $item
Branch: 1 branch
BranchTrueFalseTotal
if not ref $item and ("File::SOPS::Encrypted"->encrypted_type($item) // "") eq "comment" 11 1 12
Condition80%4/5
not ref $item and ("File::SOPS::Encrypted"->encrypted_type($item) // "") eq "comment"
!ll&&!rl&&r
0111
"File::SOPS::Encrypted"->encrypted_type($item) // ""
l!l
111
MC/DC50%1/2
not ref $item and ("File::SOPS::Encrypted"->encrypted_type($item) // "") eq "comment"
not ref $item "File::SOPS::Encrypted"->encrypted_type($item)
Truth table66%2/3
not(A) and B
A= not ref $itemB= "File::SOPS::Encrypted"->encrypted_type($item)
ABresult
0X0
100
111
1739 && (File::SOPS::Encrypted->encrypted_type($item) // '')
1740 eq 'comment';
1741 1 return 0;
1742 }
1743 18 return 1;
1744 }
1745  
1746 # THE predicate, asked by every walk that builds a path -- _encrypt_tree and
1747 # _decrypt_tree. One sub rather than the same three lines twice over: since
1748 # docs/adr/0049 both walks ask the encryption rule about the path they build,
1749 # so a component one of them adds and the other does not is a document this
1750 # library writes and then cannot read. The rule decides which AAD a value is
1751 # encrypted under and which path the encryption rules are asked about, and a
1752 # walk that answers it differently from _encrypt_tree produces a document this
1753 # library writes and then refuses (measured, with unencrypted_regex `^$`:
1754 # rotate declined a file encrypt had just written).
1755 sub _adds_no_path_component {
1756 186708 ▶ my ($key, $path, $value, $on_the_wire) = @_;
Subroutine _adds_no_path_component: called CC=3 SCAR=11.0
1757  
1758 186708 ▶ return $key eq $COMMENT_BUCKET_KEY
Condition100%6/6
$key eq $File::SOPS::COMMENT_BUCKET_KEY && @$path && _is_comment_bucket($value)
!ll&&!rl&&r
186693114
$key eq $File::SOPS::COMMENT_BUCKET_KEY and @$path
!ll&&!rl&&r
186690315
MC/DC100%3/3
$key eq $File::SOPS::COMMENT_BUCKET_KEY && @$path && _is_comment_bucket($value)
$key eq $File::SOPS::COMMENT_BUCKET_KEY @$path _is_comment_bucket($value)
Truth table100%4/4
A and B && C
A= $key eq $File::SOPS::COMMENT_BUCKET_KEYB= @$pathC= _is_comment_bucket($value)
ABCresult
0XX0
10X0
1100
1111
1759 && @$path
1760 && _is_comment_bucket($value);
1761 }
1762  
1763 sub _encrypt_tree {
1764 80 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
1765 111841 ▶ my ($node, $key, $metadata, $path, $depth) = @_;
Subroutine _encrypt_tree: called CC=26 SCAR=32.6
1766  
1767 111841 ▶ $depth = ($depth // 0) + 1;
Condition100%2/2
$depth // 0
l!l
111210631
MC/DC100%1/1
$depth // 0
$depth
Truth table100%2/2
A
A= $depth
Aresult
11
00
1768 111841 ▶ _assert_depth($depth) if ref $node eq 'HASH' || ref $node eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $node eq "HASH" or ref $node eq "ARRAY" 106924 4917 111841
Condition100%3/3
ref $node eq "HASH" or ref $node eq "ARRAY"
l!l&&r!l&&!r
106879454917
MC/DC100%2/2
ref $node eq "HASH" or ref $node eq "ARRAY"
ref $node eq "HASH" ref $node eq "ARRAY"
Truth table100%3/3
A or B
A= ref $node eq "HASH"B= ref $node eq "ARRAY"
ABresult
1X1
011
000
1769  
1770 111840 ▶ if (ref $node eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $node eq 'HASH') { } 106878 4962 111840
elsif (ref $node eq 'ARRAY') { } 45 4917 4962
1771 106878 my %result;
1772 106878 for my $k (keys %$node) {
1773 # The walk descends unconditionally and the rules are applied at
1774 # the leaf, against the WHOLE path. Deciding per level and
1775 # skipping the subtree is the same answer for the unencrypted
1776 # rules -- an excluded branch stays excluded all the way down --
1777 # but not for the encrypted ones, where the reference
1778 # implementation encrypts a leaf as soon as SOME component of its
1779 # path matches. Measured against sops 3.13.3 with
1780 # --encrypted-suffix _enc: everything under a `top_enc:` block is
1781 # encrypted, and a `nested_enc:` under a plain parent is too.
1782 # docs/adr/0047: the comment bucket is the branch itself, so it
1783 # adds no path component. See $COMMENT_BUCKET_KEY above.
1784 111135 my $bucket = _adds_no_path_component($k, $path, $node->{$k});
1785 111135 ▶ push @$path, $k unless $bucket;
Branch: 1 branch
BranchTrueFalseTotal
unless $bucket 111127 8 111135
1786 # A comment is a SEQUENCE entry or nothing. sops attaches a comment
1787 # to the node that follows it, so above a mapping key it stays a
1788 # comment LINE and no store writes one into a mapping value slot.
1789 # Measured against sops 3.13.3 with this guard lifted: the document
1790 # is read at exit 0 and the key comes back holding Go's yaml.Comment
1791 # struct -- `value:` and `inline:` under the key, where the caller
1792 # meant a comment. Silent, and in a file this library wrote. The
1793 # twin of the check in _decrypt_tree; see docs/adr/0041.
1794 croak _at_path($path, "a comment cannot be a mapping value. sops "
1795 . "attaches a comment to the node that FOLLOWS it, so the only "
1796 . "place a SOPS document holds one as a leaf is a sequence "
1797 . "entry -- above a mapping key it is a comment LINE, which no "
1798 . "emitter here can write. Written into this slot the document "
1799 . "would still be read by sops at exit 0, with the key holding "
1800 . "a dump of Go's comment struct instead of a value (measured "
1801 . "against sops 3.13.3). Put the comment in a list, or leave it "
1802 . "out")
1803 111135 ▶ if File::SOPS::Encrypted->is_comment($node->{$k});
Branch: 1 branch
BranchTrueFalseTotal
if "File::SOPS::Encrypted"->is_comment($node->{$k}) 3 111132 111135
1804 111132 $result{$k} = _encrypt_tree($node->{$k}, $key, $metadata, $path,
1805 $depth);
1806 111081 ▶ pop @$path unless $bucket;
Branch: 1 branch
BranchTrueFalseTotal
unless $bucket 111073 8 111081
1807 }
1808 106824 return \%result;
1809 }
1810 elsif (ref $node eq 'ARRAY') {
1811 # A wire-bucket of ENC[...,type:comment] strings must NOT descend into
1812 # the list -- the leaf code path would fire k168 on every item
1813 # the rule EXCLUDES (because each item is a plain string whose text
1814 # spells an ENC-comment token), and at any path it would re-encrypt
1815 # the token as a plain type:str and lose the comment label. Both
1816 # halves of that break a comment line this library previously wrote,
1817 # so the walk returns the bucket list as-is. The Comment-object half
1818 # is intentionally NOT in scope here: a Comment object at a SELECTED
1819 # path still descends so the walk can encrypt it, which is what
1820 # makes the round trip produce ENC-comment strings on the way out.
1821 # docs/adr/0059, k172.
1822 45 my $is_wire_bucket = 1;
1823 45 for my $item (@$node) {
1824 45 ▶ if (ref $item
Branch: 1 branch
BranchTrueFalseTotal
if (ref $item or ("File::SOPS::Encrypted"->encrypted_type($item) // "") ne "comment") 43 2 45
Condition100%5/5
ref $item or ("File::SOPS::Encrypted"->encrypted_type($item) // "") ne "comment"
l!l&&r!l&&!r
21222
"File::SOPS::Encrypted"->encrypted_type($item) // ""
l!l
222
MC/DC100%2/2
ref $item or ("File::SOPS::Encrypted"->encrypted_type($item) // "") ne "comment"
ref $item "File::SOPS::Encrypted"->encrypted_type($item)
Truth table100%3/3
A or B
A= ref $itemB= "File::SOPS::Encrypted"->encrypted_type($item)
ABresult
1X1
011
000
1825 || (File::SOPS::Encrypted->encrypted_type($item) // '')
1826 ne 'comment') {
1827 43 $is_wire_bucket = 0;
1828 43 last;
1829 }
1830 }
1831 45 ▶ return $node if $is_wire_bucket;
Branch: 1 branch
BranchTrueFalseTotal
if $is_wire_bucket 2 43 45
1832 43 my @result;
1833 43 for my $item (@$node) {
1834 # SOPS does NOT add array index to path - all array elements share parent's path
1835 78 push @result, _encrypt_tree($item, $key, $metadata, $path, $depth);
1836 }
1837 43 return \@result;
1838 }
1839 else {
1840 # A leaf the rules exclude is written as it stands. It is still
1841 # covered by the MAC, so it is readable but authenticated.
1842 #
1843 # EXCEPT a leaf whose text parses as ENC[...,type:comment]: the
1844 # encrypt side writes it as a plain type:str and hashes its text
1845 # into the digest, but on the read side _is_comment_leaf (with
1846 # $data_key defined) treats the same text as a comment and drops
1847 # it from the digest -- a document that fails its own MAC, produced
1848 # by this library at exit 0. The File::SOPS::Comment half of the
1849 # same shape is caught by the mapping-loop guard above (ADR 0041);
1850 # this one is the wire half, reached because the caller passed a
1851 # plain string rather than a Comment object. docs/adr/0056,
1852 # k168.
1853 4917 ▶ croak _at_path($path, "a caller string whose text parses as an "
Branch: 1 branch
BranchTrueFalseTotal
if not $metadata->should_encrypt_path($path) || ref $node and ("File::SOPS::Encrypted"->encrypted_type($node) // "") eq "comment" 1 4916 4917
Condition100%8/8
not $metadata->should_encrypt_path($path) || ref $node and ("File::SOPS::Encrypted"->encrypted_type($node) // "") eq "comment"
!ll&&!rl&&r
46482681
$metadata->should_encrypt_path($path) || ref $node
l!l&&r!l&&!r
463018269
"File::SOPS::Encrypted"->encrypted_type($node) // ""
l!l
4265
MC/DC100%3/3
not $metadata->should_encrypt_path($path) || ref $node and ("File::SOPS::Encrypted"->encrypted_type($node) // "") eq "comment"
$metadata->should_encrypt_path($path) ref $node "File::SOPS::Encrypted"->encrypted_type($node)
Truth table100%4/4
not(A || B) and C
A= $metadata->should_encrypt_path($path)B= ref $nodeC= "File::SOPS::Encrypted"->encrypted_type($node)
ABCresult
1XX0
01X0
0000
0011
1854 . "ENC[...,type:comment] token cannot stand as a value at a "
1855 . "path the encryption rule EXCLUDES: this library writes the "
1856 . "literal as a plain type:str and hashes its text into the "
1857 . "MAC, but the read side (_is_comment_leaf with \$data_key "
1858 . "defined) drops the same text from the digest, so the "
1859 . "document fails its own MAC at the next decrypt. sops reads "
1860 . "the document but ignores the leaf at the same level -- "
1861 . "which is why the symptom on decrypt is 'Authentication "
1862 . "failed' rather than 'MAC mismatch'. Replace the string "
1863 . "with a File::SOPS::Comment in a SEQUENCE position, or "
1864 . "rename the key so the rule no longer excludes it")
1865 if !$metadata->should_encrypt_path($path)
1866 && !ref $node
1867 && (File::SOPS::Encrypted->encrypted_type($node) // '')
1868 eq 'comment';
1869  
1870 4916 ▶ return $node unless $metadata->should_encrypt_path($path);
Branch: 1 branch
BranchTrueFalseTotal
unless $metadata->should_encrypt_path($path) 286 4630 4916
1871  
1872 # Leaf value - encrypt it
1873 # SOPS doesn't encrypt empty values; they stay in the document AS THEY
1874 # ARE. A null stays a null and an empty string stays an empty string.
1875 # Returning '' for both turned every null in the input into an empty
1876 # string, where sops leaves a null alone in YAML and in JSON alike
1877 # (measured: `a: null` comes back out of `sops -d` as `a: null`). The
1878 # digest does not notice, because Go hashes a nil as nothing and so do
1879 # we -- but the value the caller stored came back changed, which is the
1880 # one thing this library exists not to do.
1881 #
1882 # The !blessed() guard is load-bearing: JSON::PP::Boolean overloads eq,
1883 # and JSON->false eq '' is TRUE (while it stringifies to '0'). Without
1884 # the guard every false boolean was skipped here and written to the file
1885 # as a plaintext '', after _compute_mac had already hashed 'False' --
1886 # so the document failed its own MAC check on the next read. sops
1887 # encrypts false as type:bool with plaintext 'False'.
1888 #
1889 # The type check is the same rule for the other false boolean, which is
1890 # NOT blessed and so walks straight past that guard: Perl's own boolean
1891 # SV (!!0, $x > 9, builtin::false), whose PV really is the empty string.
1892 # Same defect, same symptom -- a plaintext '' in the document against a
1893 # digest of 'False', sops -d exit 51 -- and it went unnoticed because
1894 # k90 was filed from the unencrypted slot. The eq runs first, so
1895 # the type ladder is consulted only for a leaf that does stringify
1896 # empty. See docs/adr/0016.
1897 4630 ▶ return undef if !defined $node;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node 3 4627 4630
1898 4627 ▶ return '' if !blessed($node) && $node eq ''
Branch: 1 branch
BranchTrueFalseTotal
if not builtin::blessed($node) and $node eq "" and "File::SOPS::Encrypted"->detect_type($node) ne "bool" 4 4623 4627
Condition100%6/6
not builtin::blessed($node) and $node eq "" and "File::SOPS::Encrypted"->detect_type($node) ne "bool"
!ll&&!rl&&r
4599244
not builtin::blessed($node) and $node eq ""
!ll&&!rl&&r
52454728
MC/DC100%3/3
not builtin::blessed($node) and $node eq "" and "File::SOPS::Encrypted"->detect_type($node) ne "bool"
not builtin::blessed($node) $node eq "" "File::SOPS::Encrypted"->detect_type($node) ne "bool"
Truth table100%4/4
not(A) and B and C
A= not builtin::blessed($node)B= $node eq ""C= "File::SOPS::Encrypted"->detect_type($node) ne "bool"
ABCresult
0XX0
10X0
1100
1111
1899 && File::SOPS::Encrypted->detect_type($node) ne 'bool';
1900  
1901 4623 my $aad = _path_to_aad($path);
1902 4623 ▶ my $enc = eval {
Branch: 1 branch
BranchTrueFalseTotal
my $enc = eval { do { "File::SOPS::Encrypted"->encrypt_value("value", $node, "key", $key, "aad", $aad) } } or croak(_at_path($path, $@)) 0 4623 4623
1903 4623 File::SOPS::Encrypted->encrypt_value(
1904 value => $node,
1905 key => $key,
1906 aad => $aad,
1907 );
1908 } or croak _at_path($path, $@);
1909 4623 return $enc->to_string;
1910 }
1911 }
1912  
1913 sub _decrypt_tree {
1914 80 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
1915 76200 ▶ my ($node, $key, $metadata, $path, $depth) = @_;
Subroutine _decrypt_tree: called CC=21 SCAR=30.4
1916  
1917 76200 ▶ $depth = ($depth // 0) + 1;
Condition100%2/2
$depth // 0
l!l
75712488
MC/DC100%1/1
$depth // 0
$depth
Truth table100%2/2
A
A= $depth
Aresult
11
00
1918 76200 ▶ _assert_depth($depth) if ref $node eq 'HASH' || ref $node eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $node eq "HASH" or ref $node eq "ARRAY" 71673 4527 76200
Condition100%3/3
ref $node eq "HASH" or ref $node eq "ARRAY"
l!l&&r!l&&!r
71607664527
MC/DC100%2/2
ref $node eq "HASH" or ref $node eq "ARRAY"
ref $node eq "HASH" ref $node eq "ARRAY"
Truth table100%3/3
A or B
A= ref $node eq "HASH"B= ref $node eq "ARRAY"
ABresult
1X1
011
000
1919  
1920 76199 ▶ if (ref $node eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $node eq 'HASH') { } 71606 4593 76199
elsif (ref $node eq 'ARRAY') { } 66 4527 4593
1921 71606 my %result;
1922 71606 for my $k (keys %$node) {
1923 # docs/adr/0047, the read-side twin of the rule in _encrypt_tree.
1924 # $key IS the data key here, so a bucket of ENC[...,type:comment]
1925 # strings is recognised as one.
1926 75573 my $bucket = _adds_no_path_component($k, $path, $node->{$k}, $key);
1927 75573 ▶ push @$path, $k unless $bucket;
Branch: 1 branch
BranchTrueFalseTotal
unless $bucket 75567 6 75573
1928 # The read-side twin of _encrypt_tree's guard, and the whole of what
1929 # is left of docs/adr/0024's refusal. A comment leaf in a SEQUENCE
1930 # is read and kept (that is the only shape any sops store writes);
1931 # one in a mapping VALUE slot is a document no store produces, and
1932 # sops reads it as a dump of Go's comment struct rather than as a
1933 # value. Refused here rather than in a format handler because it is
1934 # not a format's rule -- the same document is read through the JSON
1935 # handler, which had no such guard at all. docs/adr/0041.
1936 croak _at_path($path, "this document holds a sops comment "
1937 . "(type:comment) as a mapping value, which is not a shape any "
1938 . "SOPS store writes: a comment is attached to the node that "
1939 . "FOLLOWS it, so above a mapping key it stays a comment LINE "
1940 . "and only a comment above a SEQUENCE entry becomes a leaf. "
1941 . "Read with sops this leaf does not come back as a value "
1942 . "either -- it comes back as a dump of Go's comment struct. "
1943 . "Remove it from the document, or read the file with sops")
1944 if !ref $node->{$k}
1945 75573 ▶ && (File::SOPS::Encrypted->encrypted_type($node->{$k}) // '')
Branch: 1 branch
BranchTrueFalseTotal
if not ref $node->{$k} and ("File::SOPS::Encrypted"->encrypted_type($node->{$k}) // "") eq "comment" 2 75571 75573
Condition100%5/5
not ref $node->{$k} and ("File::SOPS::Encrypted"->encrypted_type($node->{$k}) // "") eq "comment"
!ll&&!rl&&r
7119743742
"File::SOPS::Encrypted"->encrypted_type($node->{$k}) // ""
l!l
4003373
MC/DC100%2/2
not ref $node->{$k} and ("File::SOPS::Encrypted"->encrypted_type($node->{$k}) // "") eq "comment"
not ref $node->{$k} "File::SOPS::Encrypted"->encrypted_type($node->{$k})
Truth table100%3/3
not(A) and B
A= not ref $node->{$k}B= "File::SOPS::Encrypted"->encrypted_type($node->{$k})
ABresult
0X0
100
111
1946 eq 'comment';
1947 75571 $result{$k} = _decrypt_tree($node->{$k}, $key, $metadata, $path,
1948 $depth);
1949 75507 ▶ pop @$path unless $bucket;
Branch: 1 branch
BranchTrueFalseTotal
unless $bucket 75501 6 75507
1950 }
1951 71540 return \%result;
1952 }
1953 elsif (ref $node eq 'ARRAY') {
1954 66 my @result;
1955 66 for my $item (@$node) {
1956 # SOPS does NOT add array index to path - all array elements share parent's path
1957 141 push @result, _decrypt_tree($item, $key, $metadata, $path, $depth);
1958 }
1959 66 return \@result;
1960 }
1961 else {
1962 # RULE-FIRST, which is how sops reads a document: the rule decides
1963 # what a leaf IS, and the leaf's own text never gets a vote. An
1964 # excluded leaf is a literal value whatever it spells -- ENC[...]
1965 # included -- and the digest sees that text, which is what
1966 # _mac_bytes and _digested_leaves below had to learn with it.
1967 #
1968 # Asking the LEAF instead is what let rotate and edit write an
1969 # excluded value's plaintext back into the file at exit 0 (k150),
1970 # which docs/adr/0046 closed with a guard on the write path and handed
1971 # the mechanism here. Measured on sops 3.13.3 over 4 formats x 4 rule
1972 # fields x 4 cells, all 64 answering alike: an ENC[...] leaf the rule
1973 # excludes is exit 51 (its own text is in the digest -- read straight
1974 # off sops's `computed` figure), and a bare leaf the rule selects is
1975 # exit 25. docs/adr/0049.
1976 4527 ▶ return $node unless $metadata->should_encrypt_path($path);
Branch: 1 branch
BranchTrueFalseTotal
unless $metadata->should_encrypt_path($path) 447 4073 4520
1977  
1978 # A SELECTED slot holds an encrypted string, and sops leaves exactly
1979 # four shapes alone there rather than refusing them (measured in all
1980 # four formats, exit 0 each):
1981 #
1982 # * a null -- Go's walk returns before the cipher is reached;
1983 # * an empty string -- the cipher itself short-circuits it;
1984 # * a comment, which sops warns about and keeps;
1985 # * an empty list or mapping, which holds no leaf and never arrives.
1986 #
1987 # The first two are the only shapes _encrypt_tree writes bare into a
1988 # selected slot, so they are also what keeps a document THIS library
1989 # wrote readable. !ref guards the eq: JSON::PP::Boolean overloads it
1990 # and JSON->false eq '' is true.
1991 4073 ▶ return $node if !defined $node;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node 3 4070 4073
1992 4070 ▶ return $node if !ref $node && $node eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not ref $node and $node eq "" 5 4065 4070
Condition100%3/3
not ref $node and $node eq ""
!ll&&!rl&&r
340625
MC/DC100%2/2
not ref $node and $node eq ""
not ref $node $node eq ""
Truth table100%3/3
not(A) and B
A= not ref $nodeB= $node eq ""
ABresult
0X0
100
111
1993 4065 ▶ if (File::SOPS::Encrypted->is_comment($node)) {
Branch: 1 branch
BranchTrueFalseTotal
if ("File::SOPS::Encrypted"->is_comment($node)) 3 4062 4065
1994 # A PLAINTEXT comment stands in a slot the rule ENCRYPTS. sops keeps
1995 # it at exit 0 -- one of the four bare shapes above -- but it also
1996 # warns, because a comment in an encrypted slot can hold a secret in
1997 # the clear and there is nothing to authenticate it. Measured on
1998 # sops 3.13.3 (yaml, ini, dotenv): warning on the DECRYPT path only,
1999 # `Found possibly unencrypted comment in file`; the encrypt path
2000 # encrypts it into a type:comment leaf and says nothing. This is the
2001 # decrypt path, so this is where the warning belongs. Advisory only:
2002 # nothing here moves -- the comment is returned unchanged and the MAC
2003 # walk never reaches this branch. docs/adr/0067; the carp precedent
2004 # is docs/adr/0018 and the OUTCOME (the comment is kept) is one of
2005 # docs/adr/0049's four exceptions. The comment TEXT is NOT quoted --
2006 # it may be the secret this warns about, and a value that leaks into
2007 # a log was not encrypted for any practical purpose.
2008 3 carp _at_path($path, "a plaintext comment stands in a slot this "
2009 . "document's encryption rule marks as encrypted. It is kept "
2010 . "as it stands, but it is not encrypted and not "
2011 . "authenticated, so it may hold a secret in the clear. sops "
2012 . "reads the same document at exit 0 and warns the same way "
2013 . "(measured against sops 3.13.3: `Found possibly unencrypted "
2014 . "comment in file`). Re-encrypting the document (rotate, edit, "
2015 . "encrypt_in_place, or decrypt_file plus encrypt_file) turns "
2016 . "the comment into an encrypted type:comment leaf");
2017 3 return $node;
2018 }
2019  
2020 # The other direction of the same disagreement, and the one sops's
2021 # walk reaches first: bare where the rule says encrypted. Read as a
2022 # literal it was silently ENCRYPTED by the next write -- a value that
2023 # was readable, turned into ciphertext under a key the caller may not
2024 # keep. sops stops at exit 25 with `Input string <value> does not
2025 # match sops' data format`; the value is NOT quoted here, because a
2026 # leaf that is bare where the rule says encrypted is a secret in the
2027 # clear and an error message goes to bug reports.
2028 4062 ▶ croak _at_path($path, "this document's own encryption rule says this "
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $node and "File::SOPS::Encrypted"->is_encrypted($node) 6 4056 4062
Condition66%2/3
not ref $node and "File::SOPS::Encrypted"->is_encrypted($node)
!ll&&!rl&&r
064056
MC/DC50%1/2
not ref $node and "File::SOPS::Encrypted"->is_encrypted($node)
not ref $node "File::SOPS::Encrypted"->is_encrypted($node)
Truth table66%2/3
not(A) and B
A= not ref $nodeB= "File::SOPS::Encrypted"->is_encrypted($node)
ABresult
0X0
100
111
2029 . "value is encrypted, but the file holds it as a plain value, "
2030 . "so there is nothing here to decrypt. sops refuses the same "
2031 . "document rather than reading it (measured on 3.13.3: exit 25, "
2032 . "'Input string ... does not match sops' data format'), because "
2033 . "it decrypts rule-first. Correct the rule -- in the sops "
2034 . "section, or in the .sops.yaml the file was encrypted under -- "
2035 . "so that it matches the values that really are encrypted. Only "
2036 . "an empty value, a null and a comment may stand bare in an "
2037 . "encrypted slot")
2038 unless !ref $node && File::SOPS::Encrypted->is_encrypted($node);
2039  
2040 4056 my $aad = _path_to_aad($path);
2041 4056 my @value = eval {
2042 4056 my $enc = File::SOPS::Encrypted->parse($node);
2043 4056 (scalar $enc->decrypt_value(key => $key, aad => $aad));
2044 };
2045 4056 ▶ croak _at_path($path, $@) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 4055 4056
2046 4055 return $value[0];
2047 }
2048 }
2049  
2050 sub _path_to_aad {
2051 12712 ▶ my ($path) = @_;
Subroutine _path_to_aad: called CC=2 SCAR=6.9
2052 # Go builds the AAD as strings.Join(path, ":") + ":". An undef path is a
2053 # caller bug (the walks always pass an arrayref, possibly empty); answering
2054 # "" there keeps a missing argument from masking the bug as a quiet AAD
2055 # mismatch. An empty arrayref is the document ROOT, where Go answers ":"
2056 # and this routine answers ":" -- the join below produces it. The four
2057 # format handlers all build a non-empty path before they reach a leaf, so
2058 # the empty case is unreachable today, but a future format that walks the
2059 # root would land here and the answer has to match sops.
2060 12712 ▶ return '' unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 1 12711 12712
2061 # SOPS format: path components joined with ":" plus trailing ":"
2062 #
2063 # This is a CHARACTER string -- the components are keys straight out of the
2064 # parser. UTF-8 encoding it is File::SOPS::Encrypted's job, done once at the
2065 # cipher boundary (_utf8_bytes) so that encrypt_value, decrypt_bytes and the
2066 # MAC's decrypt_bytes call cannot drift apart on it. Do not encode here as
2067 # well; that would double-encode every non-ASCII key.
2068 12711 return join(':', @$path) . ':';
2069 }
2070  
2071 # --- MAC ----------------------------------------------------------------
2072 #
2073 # The MAC is a SHA-512 over the plaintext of EVERY leaf in the document -- no
2074 # keys, no paths -- uppercase hex, itself AES-GCM encrypted with lastmodified
2075 # as AAD. Two things about it are easy to get wrong and impossible to notice
2076 # from inside this library, because both sides of a self-produced file agree
2077 # with each other while disagreeing with sops:
2078 #
2079 # 1. It covers unencrypted values too. Values excluded from encryption by
2080 # unencrypted_suffix (or any of the other rules) are hashed exactly like
2081 # encrypted ones. Only mac_only_encrypted changes that, and then the
2082 # digest additionally starts from a fixed 32-byte block so the two
2083 # settings can never collide.
2084 #
2085 # 2. It is order dependent, and the order is DOCUMENT order. The encrypt
2086 # side has only a Perl hash to walk, whose iteration order is randomized,
2087 # so it walks sorted -- which is correct precisely because both
2088 # serializers emit sorted keys (see t/05-format-key-order.t). The decrypt
2089 # side must reproduce whatever order the producer used, and for a file
2090 # written by sops that is the order of the original document, not sorted
2091 # order. Hence _document_leaves, which recovers key order from an
2092 # order-preserving reparse of the raw text.
2093 #
2094 # Both directions funnel into _mac_digest so the two rules above are stated
2095 # once. What differs is only how the leaves are collected and what a leaf's
2096 # bytes are.
2097  
2098 # MACOnlyEncryptedInitialization, verbatim from sops.go.
2099 80 our $MAC_ONLY_ENCRYPTED_INIT = pack 'C*',
2100 0x8a, 0x3f, 0xd2, 0xad, 0x54, 0xce, 0x66, 0x52,
2101 0x7b, 0x10, 0x34, 0xf3, 0xd1, 0x47, 0xbe, 0x0b,
2102 0x0b, 0x97, 0x5b, 0x3b, 0xf4, 0x4f, 0x72, 0xc6,
2103 0xfd, 0xad, 0xec, 0x81, 0x76, 0xf2, 0x7d, 0x69;
2104  
2105 # The leaves the digest covers, which is not every leaf: a COMMENT is not a
2106 # value, and sops hashes none of them. Measured against sops 3.13.3 in seven
2107 # ways -- deleting a comment leaf from an encrypted file leaves `sops -d` at
2108 # exit 0 in YAML, INI and ENV where deleting a value gives exit 51; three
2109 # documents with identical values and different comments have byte-identical
2110 # MAC plaintext; relabelling a type:str value to type:comment takes it OUT of
2111 # what sops digests; and the digest taken here over four sops-written documents
2112 # matches the one they store EXACTLY when the comment leaves are dropped, with
2113 # --mac-only-encrypted and beside an _unencrypted subtree included.
2114 #
2115 # Applied to the collected leaves rather than inside _mac_digest, so that the
2116 # representability sweep in _compute_mac and the leaf COUNT in the MAC error
2117 # message speak about the same list the digest was taken over. See
2118 # docs/adr/0041.
2119 #
2120 # Since docs/adr/0049 the wire half has a condition, and it is not tidiness:
2121 # see _wire_comment_reads_as_a_comment below.
2122 sub _digested_leaves {
2123 1125 ▶ my ($leaves, $data_key, $metadata) = @_;
Subroutine _digested_leaves: called CC=2 SCAR=6.9
2124 return [ grep {
2125 1125 my ($path, $value) = @$_;
2126 8936 ▶ !_is_comment_leaf($value,
Branch: 1 branch
BranchTrueFalseTotal
_wire_comment_reads_as_a_comment($path, $data_key, $metadata) ? : 4058 4878 8936
2127 _wire_comment_reads_as_a_comment($path, $data_key, $metadata)
2128 ? $data_key : undef);
2129 } @$leaves ];
2130 }
2131  
2132 # Whether an ENC[...,type:comment] string sitting at $path comes back out of
2133 # the file as a COMMENT or as a value -- which is what decides whether the
2134 # digest covers it, because sops digests no comment and does digest a value.
2135 #
2136 # It has two answers because the wire has two shapes for a comment, and only
2137 # one of them is a value slot:
2138 #
2139 # * In a FLAT store a comment is a comment LINE -- `#ENC[...]` in dotenv,
2140 # `; ENC[...]` in ini -- so the store reads it as a comment before any rule
2141 # is consulted, and no rule can turn it into a value. This handler's
2142 # spelling for such a line is the comment bucket, a `''` KEY, so a leaf
2143 # whose last path component is that key is a comment line whatever the rule
2144 # says. See $COMMENT_BUCKET_KEY and docs/adr/0045 / docs/adr/0047.
2145 # * In YAML a comment is an ordinary SEQUENCE ENTRY holding the ENC[...]
2146 # string, and it becomes a comment only where something decrypts it -- so
2147 # at a path the rule EXCLUDES it stays a string and is digested as one.
2148 #
2149 # Measured on sops 3.13.3, one rule-swapped document per format put through
2150 # both hypotheses with the MAC recomputed each way (`sops -d` exit code):
2151 #
2152 # comment digested comment skipped
2153 # yaml 0 51
2154 # ini 51 0
2155 # dotenv 51 0
2156 #
2157 # The encrypt side has no data key and no wire shapes, and answers nothing
2158 # here.
2159 sub _wire_comment_reads_as_a_comment {
2160 8936 ▶ my ($path, $data_key, $metadata) = @_;
Subroutine _wire_comment_reads_as_a_comment: called CC=6 SCAR=18.0
2161  
2162 8936 ▶ return 0 unless defined $data_key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data_key 4712 4224 8936
2163 4224 ▶ return 1 if @$path && $path->[-1] eq $COMMENT_BUCKET_KEY;
Branch: 1 branch
BranchTrueFalseTotal
if @$path and $path->[-1] eq $File::SOPS::COMMENT_BUCKET_KEY 8 4216 4224
Condition66%2/3
@$path and $path->[-1] eq $File::SOPS::COMMENT_BUCKET_KEY
!ll&&!rl&&r
042168
MC/DC50%1/2
@$path and $path->[-1] eq $File::SOPS::COMMENT_BUCKET_KEY
@$path $path->[-1] eq $File::SOPS::COMMENT_BUCKET_KEY
Truth table66%2/3
A and B
A= @$pathB= $path->[-1] eq $File::SOPS::COMMENT_BUCKET_KEY
ABresult
0X0
100
111
2164 4216 ▶ return !$metadata || $metadata->should_encrypt_path($path) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
!$metadata || $metadata->should_encrypt_path($path) ? : 4050 166 4216
Condition66%2/3
not $metadata or $metadata->should_encrypt_path($path)
l!l&&r!l&&!r
04050166
MC/DC50%1/2
not $metadata or $metadata->should_encrypt_path($path)
not $metadata $metadata->should_encrypt_path($path)
Truth table66%2/3
not(A) or B
A= not $metadataB= $metadata->should_encrypt_path($path)
ABresult
1X1
011
000
2165 }
2166  
2167 # A comment wears two shapes and they are NOT one question. In a plaintext tree
2168 # it is a File::SOPS::Comment; in the tree the FILE holds it is an
2169 # ENC[...,type:comment] string. The wire half is read only where the tree really
2170 # is the file's -- $data_key defined, which is the same discriminator _mac_bytes
2171 # already decrypts under, and the decrypt side is the only side that has one.
2172 #
2173 # The gate is load-bearing rather than tidy. Without it, a caller's plain string
2174 # that happens to spell ENC[...,type:comment] would be dropped from the digest
2175 # here while _encrypt_tree writes it into the document as an ordinary type:str
2176 # value -- a document that fails its own MAC, produced by this library, which is
2177 # the exact defect class the one-conversion rule exists to prevent.
2178 #
2179 # The wire half decodes nothing (encrypted_type reads the one anchored regex),
2180 # so a comment whose ciphertext is damaged still stays out of the digest --
2181 # which is what sops does with one, measured.
2182 sub _is_comment_leaf {
2183 8936 ▶ my ($value, $data_key) = @_;
Subroutine _is_comment_leaf: called CC=5 SCAR=16.1
2184  
2185 8936 ▶ return 1 if File::SOPS::Encrypted->is_comment($value);
Branch: 1 branch
BranchTrueFalseTotal
if "File::SOPS::Encrypted"->is_comment($value) 25 8911 8936
2186 8911 ▶ return 0 unless defined $data_key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data_key 4855 4056 8911
2187 4056 ▶ return (File::SOPS::Encrypted->encrypted_type($value) // '') eq 'comment'
Branch: 1 branch
BranchTrueFalseTotal
('File::SOPS::Encrypted'->encrypted_type($value) // '') eq 'comment' ? : 20 4036 4056
Condition100%2/2
"File::SOPS::Encrypted"->encrypted_type($value) // ""
l!l
40488
MC/DC100%1/1
"File::SOPS::Encrypted"->encrypted_type($value) // ""
"File::SOPS::Encrypted"->encrypted_type($value)
Truth table100%2/2
A
A= "File::SOPS::Encrypted"->encrypted_type($value)
Aresult
11
00
2188 ? 1 : 0;
2189 }
2190  
2191 sub _compute_mac {
2192 671 ▶ my ($data, $key, $metadata) = @_;
Subroutine _compute_mac: called CC=6 SCAR=17.9
2193  
2194 # $data is one document tree today, and an ArrayRef of document trees once
2195 # the api lane assembles a multi-document write (docs/adr/0033, k31).
2196 # Each document contributes its leaves in its own sorted-key order, in
2197 # document order, and the digest is over the concatenation (measured: one
2198 # MAC over all documents in order). Each document is entered by its OWN
2199 # top-level _sorted_leaves call, so the document list is never walked as a
2200 # container and no document is charged a depth level for the wrapper
2201 # (docs/adr/0033 Decision 4). A single HashRef is [$data], byte-identical.
2202 671 ▶ my @documents = ref $data eq 'ARRAY' ? @$data : ($data);
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'ARRAY' ? : 35 636 671
2203 671 my @collected;
2204 671 push @collected, @{ _sorted_leaves($_, [], []) } for @documents;
2205  
2206 671 my $leaves = _digested_leaves(\@collected);
2207  
2208 # Every leaf this document will contain has to be one both implementations
2209 # can write and read back. Checked HERE, before anything is emitted,
2210 # because this is the only walk on the encrypt side that sees every leaf --
2211 # including the ones the encryption rules exclude, which reach the document
2212 # verbatim and are the case Go rejects hardest (a uint64 stops `sops -d`
2213 # outright in YAML and produces a MAC mismatch in JSON). Doing it in
2214 # encrypt_value would miss exactly those, and doing it in value_to_bytes
2215 # would also reject legitimate sops documents on the READ side, where the
2216 # same walk is used to verify.
2217 # THE SLOT goes with the leaf, because one of the questions
2218 # assert_representable answers depends on it: an ENCRYPTED slot's wire form
2219 # for a non-finite float is type:float and the plaintext Go's
2220 # strconv.FormatFloat writes, which is what `sops -e` produces in both
2221 # formats, while an UNENCRYPTED one has only the plain YAML token go-yaml
2222 # resolves -- and no token at all in JSON. This walk is where that
2223 # difference is knowable at all: the encryption rules live in the metadata,
2224 # and by the time the emitters run an encrypted leaf is an ENC[...] string.
2225 # The same predicate _encrypt_tree encrypts by, asked of the same path.
2226 # See docs/adr/0040 and k122.
2227 671 for my $leaf (@$leaves) {
2228 4688 my ($path, $value) = @$leaf;
2229 4688 ▶ eval { File::SOPS::Encrypted->assert_representable($value,
Branch: 1 branch
BranchTrueFalseTotal
eval { do { "File::SOPS::Encrypted"->assert_representable($value, "encrypted", $metadata->should_encrypt_path($path)); 1 } } or croak(_at_path($path, $@)) 45 4643 4688
2230 4643 encrypted => $metadata->should_encrypt_path($path)); 1 }
2231 or croak _at_path($path, $@);
2232 }
2233  
2234 626 my $mac_value = _mac_digest(
2235 leaves => $leaves,
2236 metadata => $metadata,
2237 );
2238  
2239 626 ▶ my $enc = File::SOPS::Encrypted->encrypt_value(
Condition50%1/2
$metadata->lastmodified // ""
l!l
6260
MC/DC0%0/1
$metadata->lastmodified // ""
$metadata->lastmodified
Truth table50%1/2
A
A= $metadata->lastmodified
Aresult
11
00
2240 value => $mac_value,
2241 key => $key,
2242 # AAD is the lastmodified timestamp in RFC3339 format
2243 aad => $metadata->lastmodified // '',
2244 type => 'str',
2245 );
2246  
2247 626 return $enc->to_string;
2248 }
2249  
2250 sub _verify_mac {
2251 458 ▶ my (%args) = @_;
Subroutine _verify_mac: called CC=20 SCAR=30.3
2252 458 my $metadata = $args{metadata};
2253 458 my $data_key = $args{data_key};
2254  
2255 458 my $stored = $metadata->mac;
2256 458 ▶ croak "File has no MAC - refusing to return unverified data "
Branch: 1 branch
BranchTrueFalseTotal
unless defined $stored and length $stored 2 456 458
Condition100%3/3
defined $stored and length $stored
!ll&&!rl&&r
11456
MC/DC100%2/2
defined $stored and length $stored
defined $stored length $stored
Truth table100%3/3
A and B
A= defined $storedB= length $stored
ABresult
0X0
100
111
2257 . "(pass ignore_mac => 1 to override)"
2258 unless defined $stored && length $stored;
2259  
2260 # parse() now dies on a well-shaped ENC value whose base64 is not valid,
2261 # rather than decoding it to something shorter. Catch it here so the
2262 # message still says WHICH value was unreadable -- the sops section's mac,
2263 # not some leaf.
2264 456 my $mac_enc = eval { File::SOPS::Encrypted->parse($stored) };
2265 456 ▶ croak "Cannot parse MAC (" . _reason($@) . ") - refusing to return "
Branch: 1 branch
BranchTrueFalseTotal
unless $mac_enc 1 455 456
2266 . "unverified data (pass ignore_mac => 1 to override)"
2267 unless $mac_enc;
2268  
2269 455 my $expected = eval {
2270 455 ▶ $mac_enc->decrypt_bytes(key => $data_key, aad => $metadata->lastmodified // '')
Condition50%1/2
$metadata->lastmodified // ""
l!l
4550
MC/DC0%0/1
$metadata->lastmodified // ""
$metadata->lastmodified
Truth table50%1/2
A
A= $metadata->lastmodified
Aresult
11
00
2271 };
2272 455 ▶ croak "Cannot decrypt MAC - refusing to return unverified data "
Branch: 1 branch
BranchTrueFalseTotal
unless defined $expected 6 449 455
2273 . "(pass ignore_mac => 1 to override)"
2274 unless defined $expected;
2275  
2276 # Document order where we can recover it, sorted order otherwise -- which
2277 # is the same thing for every file this library writes. Getting the order
2278 # wrong can only make verification fail, never wrongly succeed.
2279 #
2280 # The format class is the one that PARSED this document, passed in rather
2281 # than guessed, so the order and the values can never come from two
2282 # different readings of the same text.
2283 449 my $ordered = _parse_in_document_order($args{document}, $args{format_class});
2284  
2285 # $ordered is a HashRef for one document, an ArrayRef of ordered documents
2286 # for a stream (docs/adr/0033, k31), or undef when order could not be
2287 # recovered. $args{data} mirrors it: one tree today, a list of trees once
2288 # the api lane assembles a multi-document decrypt. The three shapes are
2289 # normalised to a leaf list here.
2290 449 ▶ my @data_docs = ref $args{data} eq 'ARRAY' ? @{$args{data}} : ($args{data});
Branch: 1 branch
BranchTrueFalseTotal
ref $args{'data'} eq 'ARRAY' ? : 443 6 449
2291 449 my @collected;
2292 449 ▶ if (ref $ordered eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $ordered eq 'ARRAY') { } 1 448 449
elsif ($ordered) { } 447 1 448
2293 # Document order from the reparse, values from the tree, PAIRED BY
2294 # INDEX -- document i's order with document i's values, each in its own
2295 # key order. A count disagreement between the two readers means the
2296 # order cannot be trusted, so fall back to sorted (which can make
2297 # verification fail, never wrongly succeed) rather than mispair.
2298 1 ▶ if (@$ordered == @data_docs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$ordered == @data_docs) { } 1 0 1
2299 push @collected,
2300 2 @{ _document_leaves($ordered->[$_], $data_docs[$_], [], []) }
2301 1 for 0 .. $#$ordered;
2302 }
2303 else {
2304 0 $ordered = undef;
2305 }
2306 }
2307 elsif ($ordered) {
2308 # One document, byte-identical to the pre-multi-document path.
2309 447 @collected = @{ _document_leaves($ordered, $data_docs[0], [], []) };
2310 }
2311  
2312 449 ▶ unless (@collected || $ordered) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@collected or $ordered) 1 448 449
Condition66%2/3
@collected or $ordered
l!l&&r!l&&!r
44801
MC/DC50%1/2
@collected or $ordered
@collected $ordered
Truth table66%2/3
A or B
A= @collectedB= $ordered
ABresult
1X1
011
000
2313 # No recoverable order: sorted-key order, each document walked by its
2314 # own top-level call so the list is never charged a wrapper depth level.
2315 1 push @collected, @{ _sorted_leaves($_, [], []) } for @data_docs;
2316 }
2317  
2318 449 my $leaves = _digested_leaves(\@collected, $data_key, $metadata);
2319  
2320 449 my $computed = _mac_digest(
2321 leaves => $leaves,
2322 metadata => $metadata,
2323 data_key => $data_key,
2324 );
2325  
2326 # Say what was checked. Neither digest is printed: it is a SHA-512 over the
2327 # concatenated plaintexts of the whole document, and a document with one
2328 # short secret in it is brute-forceable from that hash. sops prints both;
2329 # we print the shape of the check instead, which is the part that tells you
2330 # where to look. Nothing here is derived from a value, a data key or an age
2331 # identity.
2332 # A HINT for documents this library refuses but sops wrote and sops -d
2333 # also refuses -- ENV and INI have no type label, so sops's display form
2334 # for a typed value lands in the file as bare bytes that disagree with
2335 # what the digest covers. The text alone is ambiguous with a string of
2336 # the same spelling (which sops -d reads at exit 0), so the hint is
2337 # phrased as "consistent with" rather than as a confirmed cause, and
2338 # not added for any other format. See docs/adr/0052 and k174.
2339 449 my $hint = _mac_failure_sops_display_hint($args{data}, $metadata, $args{format_class});
2340  
2341 # A second hedged hint for the sops-written bare `-0` case: any float
2342 # that underflows to negative zero on Go's side is written as `-0` (or
2343 # `-0.0`), and yaml.v3 / json.v2 read `-0` back as int 0, so the file
2344 # fails its own MAC and `sops -d` refuses it too. We never write this
2345 # shape (ADR 0014 ships `-0.0`), so the hint only fires for files
2346 # sops produced. Scans raw document text, not the parsed tree -- by
2347 # the time the tree is in hand the `-0` has become int 0 and the
2348 # signal is gone. See docs/adr/0063 and k121.
2349 449 ▶ if ($hint eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($hint eq "") 449 0 449
2350 449 $hint = _mac_failure_sops_negzero_hint($args{document}, $args{format_class});
2351 }
2352  
2353 449 ▶ croak sprintf(
Branch: 5 branches
BranchTrueFalseTotal
unless $expected eq $computed 21 428 449
@$leaves == 1 ? : 2 19 21
$ordered ? : 21 0 21
$metadata->mac_only_encrypted ? : 0 21 21
$hint ? : 0 21 21
2354 "MAC verification failed: the digest over %d leaf value%s in %s "
2355 . "order does not match the one stored in the sops section%s. The "
2356 . "document has been altered since it was written, or was written by "
2357 . "something that computes the digest differently.%s Pass ignore_mac "
2358 . "=> 1 to read it anyway -- what you get back is decrypted but not "
2359 . "authenticated.",
2360 scalar @$leaves,
2361 (@$leaves == 1 ? '' : 's'),
2362 ($ordered ? 'document' : 'sorted-key'),
2363 ($metadata->mac_only_encrypted ? ', with mac_only_encrypted set' : ''),
2364 ($hint ? ' ' . $hint : ''),
2365 ) unless $expected eq $computed;
2366  
2367 428 return 1;
2368 }
2369  
2370 # Hedged hint appended to the MAC verification refusal: when the format is
2371 # untyped (env, ini) and a leaf carried in an UNENCRYPTED slot reads as one of
2372 # the wire text spellings Go's printer writes for a typed value, the file is
2373 # consistent with one sops wrote and `sops -d` also cannot open. Two
2374 # qualifications make the wording a "consistent with" rather than a finding.
2375 #
2376 # 1. The text is AMBIGUOUS with a literal string of the same spelling -- the
2377 # string "true" and the bool true are byte-identical on the wire, and
2378 # a sops-write containing a string "true" in an unencrypted slot is read
2379 # back at exit 0. A hint that named this as the cause without that
2380 # qualification would misdiagnose those documents.
2381 # 2. The check is on the PARSED tree the rest of the library is working
2382 # with, not on the document bytes -- a document whose wire form is a
2383 # display form but whose parser normalises it before _verify_mac can
2384 # see it (none of the four current handlers do this for env/ini) would
2385 # not match here. That is named, not fixed, because repairing the text
2386 # on read would change what a re-write emits (docs/adr/0052).
2387 #
2388 # Returns the empty string for every other format or shape. The walker is
2389 # kept narrow on purpose: only what the detection rule in docs/adr/0052
2390 # section 3 names.
2391 sub _mac_failure_sops_display_hint {
2392 456 ▶ my ($data, $metadata, $format_class) = @_;
Subroutine _mac_failure_sops_display_hint: called CC=7 SCAR=19.5
2393  
2394 456 ▶ return '' unless $format_class;
Branch: 1 branch
BranchTrueFalseTotal
unless $format_class 1 455 456
2395 # The real handlers all declare format_name; defensive check so a mock
2396 # handler in t/51 (LineFormat, ReversedLineFormat, DeclinesOrder) does
2397 # not change behaviour here.
2398 455 ▶ return '' unless $format_class->can('format_name');
Branch: 1 branch
BranchTrueFalseTotal
unless $format_class->can("format_name") 5 450 455
2399 450 my $name = $format_class->format_name;
2400 450 ▶ return '' unless $name eq 'env' || $name eq 'ini';
Branch: 1 branch
BranchTrueFalseTotal
unless $name eq "env" or $name eq "ini" 433 17 450
Condition100%3/3
$name eq "env" or $name eq "ini"
l!l&&r!l&&!r
107433
MC/DC100%2/2
$name eq "env" or $name eq "ini"
$name eq "env" $name eq "ini"
Truth table100%3/3
A or B
A= $name eq "env"B= $name eq "ini"
ABresult
1X1
011
000
2401  
2402 17 my $matches = [ _scan_sops_display_forms($data, $metadata, []) ];
2403 17 ▶ return '' unless @$matches;
Branch: 1 branch
BranchTrueFalseTotal
unless @$matches 16 1 17
2404  
2405 1 my ($path, $text) = @{$matches->[0]};
2406 1 ▶ my $where = @$path ? join(':', @$path) : '(document root)';
Branch: 1 branch
BranchTrueFalseTotal
@$path ? : 1 0 1
2407  
2408 1 return sprintf(
2409 'The document also carries an unencrypted value at %s whose text (%s) '
2410 . 'is a Go display form sops writes into an %s slot for a typed value '
2411 . '(bool, null, or float); the MAC covers the typed value rather than '
2412 . 'the displayed text, and `sops -d` rejects the same document. The '
2413 . 'text alone is ambiguous with a string of the same spelling -- '
2414 . 'which sops reads at exit 0 -- so this only indicates a consistent '
2415 . 'cause, not a confirmed one.',
2416 $where, $text, $name,
2417 );
2418 }
2419  
2420 # Hedged hint for the sops-written bare `-0` case (k121 / docs/adr/0063).
2421 # Go's float printer writes any underflowed negative zero as the bare token
2422 # `-0` (or `-0.0`); yaml.v3 and json.v2 read `-0` back as int 0, so the
2423 # document fails its own MAC and `sops -d` reports exit 51. We never emit
2424 # this shape (ADR 0014 ships `-0.0`), so the hint only fires for files sops
2425 # produced -- the signal is in the document text, not the parsed tree (the
2426 # tree has int 0 and the original sign is gone).
2427 #
2428 # Two qualifications keep the wording a "consistent with" rather than a
2429 # finding, matching _mac_failure_sops_display_hint:
2430 #
2431 # 1. The regex matches the literal token `-0(\.0+)?` anywhere in the
2432 # document text. A user with a key named `lastoffset: -0` would match
2433 # the regex but for a different reason; the hint names the sops bug
2434 # without claiming it is the cause.
2435 # 2. ENV and INI carry values as plain strings, so a bare `-0` there is
2436 # the string "-0" and the digest agrees with what gets read. Only
2437 # yaml and json have typed values, so only those formats can carry the
2438 # bug.
2439 #
2440 # Returns the empty string for every other format or shape.
2441 sub _mac_failure_sops_negzero_hint {
2442 456 ▶ my ($document, $format_class) = @_;
Subroutine _mac_failure_sops_negzero_hint: called CC=7 SCAR=19.5
2443  
2444 456 ▶ return '' unless $format_class && $format_class->can('format_name');
Branch: 1 branch
BranchTrueFalseTotal
unless $format_class and $format_class->can("format_name") 5 451 456
Condition100%3/3
$format_class and $format_class->can("format_name")
!ll&&!rl&&r
14451
MC/DC100%2/2
$format_class and $format_class->can("format_name")
$format_class $format_class->can("format_name")
Truth table100%3/3
A and B
A= $format_classB= $format_class->can("format_name")
ABresult
0X0
100
111
2445 451 my $name = $format_class->format_name;
2446 451 ▶ return '' unless $name eq 'yaml' || $name eq 'json';
Branch: 1 branch
BranchTrueFalseTotal
unless $name eq "yaml" or $name eq "json" 16 435 451
Condition100%3/3
$name eq "yaml" or $name eq "json"
l!l&&r!l&&!r
3696616
MC/DC100%2/2
$name eq "yaml" or $name eq "json"
$name eq "yaml" $name eq "json"
Truth table100%3/3
A or B
A= $name eq "yaml"B= $name eq "json"
ABresult
1X1
011
000
2447  
2448 # The sops section itself does not carry this shape: age recipients are
2449 # base32, the mac is ENC[...], the lastmodified is ISO 8601, the version
2450 # is a dotted triplet, and base64 alphabet is A-Za-z0-9+/= (no `-`).
2451 # So a raw substring match over the whole document is safe.
2452 #
2453 # The lookahead (?![0-9.eE]) keeps a digit, a period, or an exponent
2454 # marker right after the candidate from being part of the same token:
2455 # -01, -0.5, -0e3, -0E3 are NOT the bug shape and must not match.
2456 # -0.0 / -0.00 / -0.000 all match (the .0+ repeat consumes every
2457 # trailing zero, then the lookahead sees a token boundary).
2458 435 ▶ return '' unless defined $document
Branch: 1 branch
BranchTrueFalseTotal
unless defined $document and $document =~ /-0(?:\.0+)*(?![0-9.eE])/ 430 5 435
Condition66%2/3
defined $document and $document =~ /-0(?:\.0+)*(?![0-9.eE])/
!ll&&!rl&&r
04305
MC/DC50%1/2
defined $document and $document =~ /-0(?:\.0+)*(?![0-9.eE])/
defined $document $document =~ /-0(?:\.0+)*(?![0-9.eE])/
Truth table66%2/3
A and B
A= defined $documentB= $document =~ /-0(?:\.0+)*(?![0-9.eE])/
ABresult
0X0
100
111
2459 && $document =~ /-0(?:\.0+)*(?![0-9.eE])/;
2460  
2461 5 return 'The document also carries a bare `-0` token in an unencrypted '
2462 . 'value -- a known sops shape: any float that underflows to '
2463 . 'negative zero is written as `-0` but parses back as int 0, '
2464 . 'so the file fails its own MAC and `sops -d` also refuses it.';
2465 }
2466  
2467 sub _scan_sops_display_forms {
2468 88 ▶ my ($node, $metadata, $path) = @_;
Subroutine _scan_sops_display_forms: called CC=10 SCAR=23.3
2469 80 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
2470  
2471 88 ▶ if (ref $node eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node eq "HASH") 26 62 88
2472 26 my @found;
2473 26 for my $k (keys %$node) {
2474 51 push @$path, $k;
2475 51 push @found, _scan_sops_display_forms($node->{$k}, $metadata, $path);
2476 51 pop @$path;
2477 }
2478 26 return @found;
2479 }
2480 62 ▶ if (ref $node eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node eq "ARRAY") 20 42 62
2481 20 my @found;
2482 20 push @found, _scan_sops_display_forms($_, $metadata, $path) for @$node;
2483 20 return @found;
2484 }
2485  
2486 # Filter to UNENCRYPTED leaves: an encrypted slot holds an ENC[...] blob
2487 # whose plaintext the digest covers, never the wire text, so the detection
2488 # rule below cannot fire on an encrypted leaf's stringify.
2489 42 ▶ return () if $metadata->should_encrypt_path($path);
Branch: 1 branch
BranchTrueFalseTotal
if $metadata->should_encrypt_path($path) 35 7 42
2490 7 ▶ return () if !defined $node || ref $node || blessed $node;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $node or ref $node or builtin::blessed($node) 0 7 7
Condition33%2/6
not defined $node or ref $node or builtin::blessed($node)
l!l&&r!l&&!r
007
not defined $node or ref $node
l!l&&r!l&&!r
007
MC/DC0%0/3
not defined $node or ref $node or builtin::blessed($node)
not defined $node ref $node builtin::blessed($node)
Truth table25%1/4
not(A) or B or C
A= not defined $nodeB= ref $nodeC= builtin::blessed($node)
ABCresult
1XX1
01X1
0011
0000
2491 7 my $text = "$node";
2492  
2493 7 ▶ return () unless _is_sops_display_form_text($text);
Branch: 1 branch
BranchTrueFalseTotal
unless _is_sops_display_form_text($text) 6 1 7
2494 1 return [ [@$path], $text ];
2495 }
2496  
2497 # The wire text sops's Go printer writes for a typed value when the store has
2498 # no type label: dotenv and INI. Four families cover every Go print form
2499 # measured against sops 3.13.3 (docs/adr/0052):
2500 #
2501 # true -- bool
2502 # false -- bool
2503 # <nil> -- null
2504 # N.0 -- a float whose textual rendering has a fractional zero
2505 # mE[+-]k -- a float whose textual rendering is in exponent form
2506 # (Go prints small exponents as decimal, so 1e2 -> 100.0,
2507 # which the N.0 family catches; 1.5e-5 -> 1.5E-05)
2508 sub _is_sops_display_form_text {
2509 7 ▶ my ($text) = @_;
Subroutine _is_sops_display_form_text: called CC=6 SCAR=18.7
2510 7 ▶ return 1 if $text eq 'true' || $text eq 'false';
Branch: 1 branch
BranchTrueFalseTotal
if $text eq "true" or $text eq "false" 1 6 7
Condition66%2/3
$text eq "true" or $text eq "false"
l!l&&r!l&&!r
106
MC/DC50%1/2
$text eq "true" or $text eq "false"
$text eq "true" $text eq "false"
Truth table66%2/3
A or B
A= $text eq "true"B= $text eq "false"
ABresult
1X1
011
000
2511 6 ▶ return 1 if $text eq '<nil>';
Branch: 1 branch
BranchTrueFalseTotal
if $text eq "<nil>" 0 6 6
2512 6 ▶ return 1 if $text =~ /\A-?[0-9]+\.0\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /\A-?[0-9]+\.0\z/ 0 6 6
2513 6 ▶ return 1 if $text =~ /\A-?[0-9.]+E[+-][0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /\A-?[0-9.]+E[+-][0-9]+\z/ 0 6 6
2514 6 return 0;
2515 }
2516  
2517 sub _mac_digest {
2518 1075 ▶ my (%args) = @_;
Subroutine _mac_digest: called CC=7 SCAR=19.5
2519 1075 my $leaves = $args{leaves};
2520 1075 my $metadata = $args{metadata};
2521 1075 my $data_key = $args{data_key}; # decrypt side only
2522  
2523 1075 ▶ my $only_encrypted = $metadata && $metadata->mac_only_encrypted;
Condition66%2/3
$metadata && $metadata->mac_only_encrypted
!ll&&!rl&&r
0102253
MC/DC50%1/2
$metadata && $metadata->mac_only_encrypted
$metadata $metadata->mac_only_encrypted
Truth table66%2/3
A && B
A= $metadataB= $metadata->mac_only_encrypted
ABresult
0X0
100
111
2524  
2525 1075 my $ctx = Digest::SHA->new(512);
2526 1075 ▶ $ctx->add($MAC_ONLY_ENCRYPTED_INIT) if $only_encrypted;
Branch: 1 branch
BranchTrueFalseTotal
if $only_encrypted 53 1022 1075
2527  
2528 1075 for my $leaf (@$leaves) {
2529 8833 my ($path, $value) = @$leaf;
2530 # Asked ONCE per leaf and handed on, because it now answers two
2531 # questions and they must not be able to disagree: which leaves
2532 # mac_only_encrypted covers, and whether this one is ciphertext at all
2533 # (docs/adr/0049).
2534 8833 ▶ my $selected = !$metadata || $metadata->should_encrypt_path($path);
Condition66%2/3
!$metadata || $metadata->should_encrypt_path($path)
l!l&&r!l&&!r
08380453
MC/DC50%1/2
!$metadata || $metadata->should_encrypt_path($path)
!$metadata $metadata->should_encrypt_path($path)
Truth table66%2/3
not(A) || B
A= !$metadataB= $metadata->should_encrypt_path($path)
ABresult
1X1
011
000
2535 8833 ▶ next if $only_encrypted && !$selected;
Branch: 1 branch
BranchTrueFalseTotal
if $only_encrypted and not $selected 40 8793 8833
Condition100%3/3
$only_encrypted and not $selected
!ll&&!rl&&r
87306340
MC/DC100%2/2
$only_encrypted and not $selected
$only_encrypted not $selected
Truth table100%3/3
A and not(B)
A= $only_encryptedB= not $selected
ABresult
0X0
100
111
2536 8793 $ctx->add(_mac_bytes($value, $path, $data_key, $selected));
2537 }
2538  
2539 # Uppercase hex digest (SOPS format)
2540 1075 return uc($ctx->hexdigest);
2541 }
2542  
2543 sub _mac_bytes {
2544 8793 ▶ my ($value, $path, $data_key, $selected) = @_;
Subroutine _mac_bytes: called CC=9 SCAR=22.1
2545  
2546 8793 ▶ $selected = 1 unless defined $selected;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $selected 0 8793 8793
2547  
2548 # Decrypt side. Hash the authenticated plaintext exactly as it came off
2549 # the cipher: running it back through decrypt_value's type conversion
2550 # would hash '007' as 7 and Go's 100000000000000000000 as 1e+20, and the
2551 # document would fail its own MAC. type:bool is the one case that needs
2552 # normalising, because SOPS's ToBytes titlecases the boolean it parsed
2553 # rather than echoing the spelling it was given.
2554 #
2555 # $selected is the encryption rule's answer for this path, and it is what
2556 # decides whether the leaf is ciphertext at all -- _decrypt_tree's rule,
2557 # asked here so the digest covers what the tree walk returned. Where the
2558 # rule EXCLUDES the leaf, its ENC[...] text is a literal and goes into the
2559 # digest as it stands. Read off sops's own `computed` figure on a MAC
2560 # mismatch: SHA-512 of the ENC[...] string, byte for byte, and repairing
2561 # the stored MAC to that digest makes `sops -d` exit 0. docs/adr/0049.
2562 8793 ▶ if ($selected && defined $data_key
Branch: 1 branch
BranchTrueFalseTotal
if ($selected and defined $data_key and "File::SOPS::Encrypted"->is_encrypted($value)) 4028 4765 8793
Condition100%6/6
$selected and defined $data_key and "File::SOPS::Encrypted"->is_encrypted($value)
!ll&&!rl&&r
475784028
$selected and defined $data_key
!ll&&!rl&&r
41343444036
MC/DC100%3/3
$selected and defined $data_key and "File::SOPS::Encrypted"->is_encrypted($value)
$selected defined $data_key "File::SOPS::Encrypted"->is_encrypted($value)
Truth table100%4/4
A and B and C
A= $selectedB= defined $data_keyC= "File::SOPS::Encrypted"->is_encrypted($value)
ABCresult
0XX0
10X0
1100
1111
2563 && File::SOPS::Encrypted->is_encrypted($value)) {
2564 # A value that will not parse or will not decrypt used to be skipped
2565 # here, so the digest quietly covered a different document than the one
2566 # on disk and the only symptom was "MAC verification failed" with no
2567 # indication of which leaf caused it. That is what made every other MAC
2568 # defect in this distribution expensive to find. Fail at the leaf, and
2569 # say which leaf.
2570 4028 my ($bytes, $type) = do {
2571 4028 my @r = eval {
2572 4028 my $enc = File::SOPS::Encrypted->parse($value);
2573 4028 ($enc->decrypt_bytes(key => $data_key, aad => _path_to_aad($path)),
2574 $enc->type);
2575 };
2576 4028 ▶ croak _at_path($path, $@) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 4028 4028
2577 4028 @r;
2578 };
2579 4028 ▶ return $bytes unless $type eq 'bool';
Branch: 1 branch
BranchTrueFalseTotal
unless $type eq "bool" 3964 64 4028
2580 64 ▶ return (lc($bytes) eq 'true' || $bytes eq '1') ? 'True' : 'False';
Branch: 1 branch
BranchTrueFalseTotal
lc $bytes eq 'true' || $bytes eq '1' ? : 33 31 64
Condition66%2/3
lc $bytes eq "true" or $bytes eq 1
l!l&&r!l&&!r
33031
MC/DC50%1/2
lc $bytes eq "true" or $bytes eq 1
lc $bytes eq "true" $bytes eq 1
Truth table66%2/3
A or B
A= lc $bytes eq "true"B= $bytes eq 1
ABresult
1X1
011
000
2581 }
2582  
2583 # Encrypt side, and unencrypted leaves on the decrypt side.
2584 4765 return _value_to_bytes($value);
2585 }
2586  
2587 # Leaves in sorted-key order: [ [ \@path, $value ], ... ]
2588 sub _sorted_leaves {
2589 80 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
2590 111954 ▶ my ($node, $path, $out, $depth) = @_;
Subroutine _sorted_leaves: called CC=8 SCAR=20.8
2591  
2592 111954 ▶ $depth = ($depth // 0) + 1;
Condition100%2/2
$depth // 0
l!l
111277677
MC/DC100%1/1
$depth // 0
$depth
Truth table100%2/2
A
A= $depth
Aresult
11
00
2593 111954 ▶ _assert_depth($depth) if ref $node eq 'HASH' || ref $node eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $node eq "HASH" or ref $node eq "ARRAY" 106972 4982 111954
Condition100%3/3
ref $node eq "HASH" or ref $node eq "ARRAY"
l!l&&r!l&&!r
106927454982
MC/DC100%2/2
ref $node eq "HASH" or ref $node eq "ARRAY"
ref $node eq "HASH" ref $node eq "ARRAY"
Truth table100%3/3
A or B
A= ref $node eq "HASH"B= ref $node eq "ARRAY"
ABresult
1X1
011
000
2594  
2595 111953 ▶ if (ref $node eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $node eq 'HASH') { } 106926 5027 111953
elsif (ref $node eq 'ARRAY') { } 45 4982 5027
2596 106926 for my $k (sort keys %$node) {
2597 111197 push @$path, $k;
2598 111197 _sorted_leaves($node->{$k}, $path, $out, $depth);
2599 111147 pop @$path;
2600 }
2601 }
2602 elsif (ref $node eq 'ARRAY') {
2603 # SOPS does NOT add array index to path - all elements share parent's
2604 45 _sorted_leaves($_, $path, $out, $depth) for @$node;
2605 }
2606 else {
2607 # The COPY is taken here and only here: $path is one array walked down
2608 # and back up, so a leaf that kept the reference would end up holding
2609 # whatever the walk was looking at when it finished.
2610 4982 push @$out, [ [@$path], $node ];
2611 }
2612  
2613 111903 return $out;
2614 }
2615  
2616 # Leaves in document order. $ordered is the same document reparsed with key
2617 # order preserved and supplies the order; $node is the tree the rest of the
2618 # library is working with and supplies the values, so the digest never sees a
2619 # value the second parser resolved differently.
2620 #
2621 # A structural disagreement between the two is REPORTED, at the path it happens
2622 # at. It used to return the leaves collected so far, which is not "verification
2623 # fails" but "verification is performed over part of the document" -- and since
2624 # a missing key contributed an undef leaf, which hashes as nothing, that could
2625 # still produce a matching digest. Even when it did fail, the only symptom was
2626 # a bare "MAC verification failed" with no hint that half the tree had been
2627 # dropped before the digest was taken.
2628 sub _document_leaves {
2629 80 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
2630 76104 ▶ my ($ordered, $node, $path, $out, $depth) = @_;
Subroutine _document_leaves: called CC=14 SCAR=27.1
2631  
2632 76104 ▶ $depth = ($depth // 0) + 1;
Condition100%2/2
$depth // 0
l!l
75651453
MC/DC100%1/1
$depth // 0
$depth
Truth table100%2/2
A
A= $depth
Aresult
11
00
2633 76104 ▶ _assert_depth($depth) if ref $ordered eq 'HASH' || ref $ordered eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $ordered eq "HASH" or ref $ordered eq "ARRAY" 71621 4483 76104
Condition100%3/3
ref $ordered eq "HASH" or ref $ordered eq "ARRAY"
l!l&&r!l&&!r
71560614483
MC/DC100%2/2
ref $ordered eq "HASH" or ref $ordered eq "ARRAY"
ref $ordered eq "HASH" ref $ordered eq "ARRAY"
Truth table100%3/3
A or B
A= ref $ordered eq "HASH"B= ref $ordered eq "ARRAY"
ABresult
1X1
011
000
2634  
2635 76103 ▶ if (ref $ordered eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $ordered eq 'HASH') { } 71559 4544 76103
elsif (ref $ordered eq 'ARRAY') { } 61 4483 4544
2636 71559 ▶ croak _at_path($path, "the document has a mapping here but the parsed "
Branch: 1 branch
BranchTrueFalseTotal
unless ref $node eq "HASH" 0 71559 71559
2637 . "tree does not, so the digest cannot be built over the same "
2638 . "values the file contains")
2639 unless ref $node eq 'HASH';
2640  
2641 71559 for my $k (keys %$ordered) {
2642 croak _at_path([@$path, $k], "present in the document but not in "
2643 . "the parsed tree")
2644 75518 ▶ unless exists $node->{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $node->{$k} 0 75518 75518
2645 75518 push @$path, $k;
2646 75518 _document_leaves($ordered->{$k}, $node->{$k}, $path, $out, $depth);
2647 75468 pop @$path;
2648 }
2649 }
2650 elsif (ref $ordered eq 'ARRAY') {
2651 61 ▶ croak _at_path($path, "the document has a sequence here but the parsed "
Branch: 1 branch
BranchTrueFalseTotal
unless ref $node eq "ARRAY" 0 61 61
2652 . "tree does not")
2653 unless ref $node eq 'ARRAY';
2654 61 ▶ croak _at_path($path, sprintf("the document has %d entries here but "
Branch: 1 branch
BranchTrueFalseTotal
unless @$ordered == @$node 0 61 61
2655 . "the parsed tree has %d", scalar @$ordered, scalar @$node))
2656 unless @$ordered == @$node;
2657  
2658 _document_leaves($ordered->[$_], $node->[$_], $path, $out, $depth)
2659 61 for 0 .. $#$ordered;
2660 }
2661 else {
2662 # Only a CONTAINER here is a disagreement. A blessed scalar is a leaf:
2663 # a JSON::PP::Boolean is what the format parsers hand back for a bare
2664 # true/false, while the order-preserving reparse yields a plain scalar
2665 # for the same node -- the two disagree about the boolean's
2666 # REPRESENTATION, never about the document's shape, and $ordered is
2667 # consulted for order only.
2668 4483 ▶ croak _at_path($path, "the document has a scalar here but the parsed "
Branch: 1 branch
BranchTrueFalseTotal
if ref $node eq "HASH" or ref $node eq "ARRAY" 0 4483 4483
Condition33%1/3
ref $node eq "HASH" or ref $node eq "ARRAY"
l!l&&r!l&&!r
004483
MC/DC0%0/2
ref $node eq "HASH" or ref $node eq "ARRAY"
ref $node eq "HASH" ref $node eq "ARRAY"
Truth table33%1/3
A or B
A= ref $node eq "HASH"B= ref $node eq "ARRAY"
ABresult
1X1
011
000
2669 . "tree has a " . lc(ref $node))
2670 if ref $node eq 'HASH' || ref $node eq 'ARRAY';
2671  
2672 # A copy, for the same reason _sorted_leaves takes one: $path is shared
2673 # and unwound.
2674 4483 push @$out, [ [@$path], $node ];
2675 }
2676  
2677 76053 return $out;
2678 }
2679  
2680 # The order-preserving reparse that supplies _document_leaves with the
2681 # document's key order -- ASKED OF THE FORMAT HANDLER, not performed here.
2682 #
2683 # The mechanism is one thing, but it has two halves and only one of them is
2684 # format-independent. Reading a document's key order out of raw text is
2685 # entirely format knowledge: which reader can parse it, what "one document"
2686 # means for it, and WHERE its metadata sits (a `sops` mapping in YAML and JSON,
2687 # top-level `sops_*` keys in an env file, a `[sops]` section in an ini one).
2688 # Walking that order against the real tree and hashing what it points at is
2689 # not. So the handler answers the first question and this module owns the
2690 # second. See docs/adr/0036, which refines docs/adr/0001 rather than replacing
2691 # it: YAML::PP still supplies order and nothing else, and still supplies it for
2692 # both formats -- it is now Format::YAML that says so.
2693 #
2694 # THE CONTRACT a handler's parse_in_document_order must meet, in full:
2695 #
2696 # * Take the raw document text. Return a HashRef of the same SHAPE as the
2697 # handler's own parse() -- mappings where parse() has mappings, sequences
2698 # of the same length, leaves where parse() has leaves. The VALUES are never
2699 # read, only the shape, so a scalar the two readers resolve differently
2700 # cannot move a digest.
2701 # * Every mapping in it must iterate its KEYS in document order. Perl's plain
2702 # hash cannot do that, so a handler whose parser has no order-preserving
2703 # mode has to supply the ordering itself -- a tied hash is the whole of
2704 # what "order-preserving" means here.
2705 # * The metadata section must already be gone.
2706 # * Decline -- return nothing, or die -- when the text cannot be read that
2707 # way. Declining is safe; guessing is not.
2708 #
2709 # FAILING SAFE IS THE PROPERTY THAT MATTERS. Losing the order costs a fallback
2710 # to sorted keys, which is the same order for every file this library writes
2711 # and a failed verification for one it does not. Getting the order WRONG can
2712 # only make verification fail too, never wrongly succeed -- the digest is over
2713 # the same values either way. That is why every failure below returns undef
2714 # instead of raising: a handler that cannot read its own document must not be
2715 # able to turn a MAC check into an error the caller reads as corruption.
2716 #
2717 # The one thing that is NOT a document problem is a format class that cannot do
2718 # this at all. That is a hole in this distribution, not in the file, and it
2719 # would degrade every document in that format to sorted order silently -- which
2720 # is precisely the failure k74 exists to prevent for env and ini. It is
2721 # loud.
2722 sub _parse_in_document_order {
2723 463 ▶ my ($content, $format_class) = @_;
Subroutine _parse_in_document_order: called CC=9 SCAR=22.1
2724 463 ▶ return unless defined $content;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 1 462 463
2725  
2726 # The historical one-argument form: no format class means the YAML
2727 # handler, which is what read both formats before this split and still
2728 # reads both (see File::SOPS::Format::JSON::parse_in_document_order).
2729 462 ▶ $format_class ||= $FORMATS{yaml};
Condition66%2/3
$format_class ||= $FORMATS{"yaml"}
l!l&&r!l&&!r
45570
MC/DC0%0/2
$format_class ||= $FORMATS{"yaml"}
$format_class $FORMATS{"yaml"}
Truth table66%2/3
A ||= B
A= $format_classB= $FORMATS{"yaml"}
ABresult
1X1
011
000
2730  
2731 462 ▶ croak "Format handler $format_class cannot recover document key order "
Branch: 1 branch
BranchTrueFalseTotal
unless $format_class->can("parse_in_document_order") 1 461 462
2732 . "(no parse_in_document_order method), so the MAC could only be "
2733 . "checked in sorted key order -- which is not the order a document "
2734 . "in this format is written in"
2735 unless $format_class->can('parse_in_document_order');
2736  
2737 461 my $ordered = eval { $format_class->parse_in_document_order($content) };
2738  
2739 # A single document is a HashRef, byte-identical to before. A multi-document
2740 # stream is an ArrayRef of ordered documents (docs/adr/0033, k31): the
2741 # handler reads the stream in list context, so document i's order pairs with
2742 # document i's values in _verify_mac. Either shape is validated here; a
2743 # handler that cannot read the text returns neither and falls back to
2744 # sorted order.
2745 461 ▶ if (ref $ordered eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $ordered eq "ARRAY") 3 458 461
2746 3 ▶ return unless @$ordered;
Branch: 1 branch
BranchTrueFalseTotal
unless @$ordered 0 3 3
2747 3 for my $doc (@$ordered) {
2748 6 ▶ return unless ref $doc eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $doc eq "HASH" 0 6 6
2749 }
2750 3 return $ordered;
2751 }
2752  
2753 458 ▶ return unless ref $ordered eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ordered eq "HASH" 5 453 458
2754 453 return $ordered;
2755 }
2756  
2757 # edit on a multi-document YAML stream is refused -- not because the write
2758 # cannot be done (it can, since k31 step 5), but because its semantics are
2759 # undecided. edit re-encrypts under a NEW data key where sops edit keeps the
2760 # existing one (k41), and docs/adr/0033 deliberately leaves edit-on-a-stream
2761 # open under "What this does not decide". Enabling it here would settle k41
2762 # by accident, so both edit paths -- a multi-document original, and a
2763 # single-document file the editor turns into a stream -- refuse here. A
2764 # single-document file (or a format with no document stream) has a list of one,
2765 # or none, and passes straight through.
2766 sub _refuse_edit_multidoc {
2767 31 ▶ my ($documents) = @_;
Subroutine _refuse_edit_multidoc: called CC=3 SCAR=12.5
2768  
2769 31 ▶ return unless ref $documents eq 'ARRAY' && @$documents > 1;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $documents eq "ARRAY" and @$documents > 1 31 0 31
Condition66%2/3
ref $documents eq "ARRAY" and @$documents > 1
!ll&&!rl&&r
1300
MC/DC0%0/2
ref $documents eq "ARRAY" and @$documents > 1
ref $documents eq "ARRAY" @$documents > 1
Truth table66%2/3
A and B
A= ref $documents eq "ARRAY"B= @$documents > 1
ABresult
0X0
100
111
2770  
2771 0 croak sprintf(
2772 "edit on a multi-document YAML stream (%d documents) is not supported: "
2773 . "edit re-encrypts under a NEW data key (unlike sops edit, k41), "
2774 . "and docs/adr/0033 deliberately leaves edit-on-a-stream semantics "
2775 . "open. Reading and writing streams both work -- use decrypt and "
2776 . "encrypt to change one, or resolve k41 first.",
2777 scalar @$documents
2778 );
2779 }
2780  
2781 # The MAC digest input for a value, which is by definition the same bytes the
2782 # cipher gets. This used to be a second implementation of the type ladder and
2783 # the value->bytes conversion, kept byte-identical to
2784 # File::SOPS::Encrypted's by hand. It never was: when the two drifted the
2785 # ciphertext and the digest were consistently wrong TOGETHER, so every
2786 # self-produced file verified and only the Go binary disagreed. There is now
2787 # one implementation, and this is a call to it.
2788 sub _value_to_bytes {
2789 4765 ▶ my ($value) = @_;
Subroutine _value_to_bytes: called CC=1 SCAR=0.0
2790 4765 return File::SOPS::Encrypted->value_to_bytes($value);
2791 }
2792  
2793 sub _extract_path {
2794 24 ▶ my ($data, $path, $doc_label) = @_;
Subroutine _extract_path: called CC=10 SCAR=23.1
2795  
2796 24 my @parts = _split_path($path);
2797  
2798 # $doc_label names which document is being searched, and appears in every
2799 # navigation failure only when a document axis is in play (a multi-document
2800 # stream, docs/adr/0033). For a single-document file it is undef and the
2801 # messages are byte-identical to before -- so a mistake in `document` reads
2802 # as one, not as a typo in `path`, without changing the single-document
2803 # wording every existing caller sees.
2804 24 ▶ my $in_doc = defined $doc_label ? " in $doc_label" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $doc_label ? : 0 24 24
2805  
2806 # Navigation failure is an error at EVERY depth. It used to be an error
2807 # only when nested: a missing top-level key fell through the loop and came
2808 # back as undef, indistinguishable from a key whose value really is null.
2809 # sops answers the same question the same way at every level --
2810 # `error truncating tree: component ['nope'] not found`, exit 1.
2811 24 my $current = $data;
2812 24 my @walked;
2813 24 for my $part (@parts) {
2814 42 ▶ my $where = @walked ? join(':', @walked) : '(document root)';
Branch: 1 branch
BranchTrueFalseTotal
@walked ? : 18 24 42
2815  
2816 42 ▶ if (ref $current eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $current eq 'HASH') { } 32 10 42
elsif (ref $current eq 'ARRAY' and $part =~ /\A\d+\z/) { } 9 1 10
2817 croak "Cannot navigate path '$path'$in_doc: component '$part' not "
2818 . "found under $where"
2819 32 ▶ unless exists $current->{$part};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $current->{$part} 4 28 32
2820 28 $current = $current->{$part};
2821 }
2822 ▶ elsif (ref $current eq 'ARRAY' && $part =~ /\A\d+\z/) {
Condition66%2/3
ref $current eq "ARRAY" and $part =~ /\A\d+\z/
!ll&&!rl&&r
109
MC/DC50%1/2
ref $current eq "ARRAY" and $part =~ /\A\d+\z/
ref $current eq "ARRAY" $part =~ /\A\d+\z/
Truth table66%2/3
A and B
A= ref $current eq "ARRAY"B= $part =~ /\A\d+\z/
ABresult
0X0
100
111
2823 9 ▶ croak "Cannot navigate path '$path'$in_doc: index $part is out of "
Branch: 1 branch
BranchTrueFalseTotal
unless $part <= $current->$#* 1 8 9
2824 . "range at $where"
2825 unless $part <= $#$current;
2826 8 $current = $current->[$part];
2827 }
2828 else {
2829 1 ▶ croak "Cannot navigate path '$path'$in_doc: $where is not a "
Branch: 1 branch
BranchTrueFalseTotal
ref $current eq 'ARRAY' ? : 0 1 1
2830 . (ref($current) eq 'ARRAY' ? "list index" : "collection")
2831 . ", so it has no component '$part'";
2832 }
2833  
2834 36 push @walked, $part;
2835 }
2836  
2837 18 return $current;
2838 }
2839  
2840 # ["database"]["password"], ['database'][0], or database.password / .items.0
2841 #
2842 # The bracket form used to be matched with /\["([^"]+)"\]/g, which only knows
2843 # QUOTED keys -- so the documented ["items"][0] matched only the first
2844 # component and extract handed back the whole arrayref instead of the element.
2845 # An unquoted component is what an index looks like, and it is the form sops
2846 # itself accepts: `sops -d --extract '["items"][0]'` returns the element.
2847 sub _split_path {
2848 24 ▶ my ($path) = @_;
Subroutine _split_path: called CC=6 SCAR=18.3
2849  
2850 24 ▶ unless ($path =~ /\A\[/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($path =~ /\A\[/) 4 20 24
2851 4 $path =~ s/\A\.//;
2852 4 return split /\./, $path;
2853 }
2854  
2855 20 my @parts;
2856 20 my $rest = $path;
2857 20 ▶ while (length $rest) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $rest) 35 20 55
2858 35 ▶ $rest =~ s{\A \[ (?: "([^"]*)" | '([^']*)' | ([^\[\]]+) ) \] }{}x
Branch: 1 branch
BranchTrueFalseTotal
$rest =~ s/\A \[ (?: "([^"]*)" | '([^']*)' | ([^\[\]]+) ) \] //x or croak("Cannot parse path '${path}' at '${rest}': expected " . q[["key"], ['key'] or [index]]) 0 35 35
2859 or croak "Cannot parse path '$path' at '$rest': expected "
2860 . qq{["key"], ['key'] or [index]};
2861 35 ▶ push @parts, $1 // $2 // $3;
Condition50%3/6
($1 // $2) // $3
l!l&&r!l&&!r
4200
$1 // $2
l!l&&r!l&&!r
3320
MC/DC0%0/3
($1 // $2) // $3
$1 $2 $3
Truth table50%2/4
A // B // C
A= $1B= $2C= $3
ABCresult
1XX1
01X1
0011
0000
2862 }
2863  
2864 20 return @parts;
2865 }
2866  
2867 sub _detect_format {
2868 144 ▶ my ($content) = @_;
Subroutine _detect_format: called CC=4 SCAR=13.9
2869  
2870 # Try to detect based on content
2871 144 ▶ if ($content =~ /^\s*\{/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content =~ /^\s*\{/) 10 134 144
2872 10 return 'json';
2873 }
2874 # Asked of the handler rather than spelled here: what an env document looks
2875 # like includes where its metadata sits, and `sops_` has one spelling in
2876 # this distribution (File::SOPS::Metadata::Flat's prefix). This sub is only
2877 # ever asked about ENCRYPTED content, which is what makes the question
2878 # answerable at all -- a plaintext .env and a plaintext .properties file
2879 # are the same bytes.
2880 134 ▶ return 'env' if File::SOPS::Format::ENV->detect_content($content);
Branch: 1 branch
BranchTrueFalseTotal
if "File::SOPS::Format::ENV"->detect_content($content) 6 128 134
2881 # Asked AFTER env for the same reason env is asked after JSON: an ini
2882 # document is recognised by a `[sops]` section, and a dotenv document is
2883 # recognised by a `sops_` key, so neither can answer for the other -- but
2884 # any `key: value` line scans as an ini pair, so this is the widest
2885 # grammar of the three and goes last.
2886 128 ▶ return 'ini' if File::SOPS::Format::INI->detect_content($content);
Branch: 1 branch
BranchTrueFalseTotal
if "File::SOPS::Format::INI"->detect_content($content) 3 125 128
2887 125 return 'yaml';
2888 }
2889  
2890 sub _detect_format_from_filename {
2891 196 ▶ my ($filename) = @_;
Subroutine _detect_format_from_filename: called CC=5 SCAR=16.2
2892  
2893 196 ▶ return 'json' if $filename =~ /\.json$/i;
Branch: 1 branch
BranchTrueFalseTotal
if $filename =~ /\.json$/i 21 175 196
2894 175 ▶ return 'yaml' if $filename =~ /\.ya?ml$/i;
Branch: 1 branch
BranchTrueFalseTotal
if $filename =~ /\.ya?ml$/i 165 10 175
2895 10 ▶ return 'env' if $filename =~ /\.env$/i;
Branch: 1 branch
BranchTrueFalseTotal
if $filename =~ /\.env$/i 6 4 10
2896 4 ▶ return 'ini' if $filename =~ /\.ini$/i;
Branch: 1 branch
BranchTrueFalseTotal
if $filename =~ /\.ini$/i 4 0 4
2897 0 return 'yaml';
2898 }
2899  
2900  
2901 80 1;
2902  
2903 __END__
« blib/lib/File/SOPS/Metadata.pm ↑ Summary blib/lib/File/SOPS/Format/INI.pm »