blib/lib/File/SOPS.pm

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