File Coverage

File:bin/fuzz-harness-generator
Coverage:47.5%

linestmtbrancondsubtimecode
1#!/usr/bin/env perl
2
3
57
57
57
97059
42
744
use strict;
4
57
57
57
61
22
893
use warnings;
5
57
57
57
7915
347158
71
use autodie qw(:all);
6
7
57
57
57
439031
20457
1072
use FindBin;
8
57
57
57
8289
12185
101
use lib "$FindBin::Bin/../lib";
9
10
57
57
57
23947
63
1150
use App::Test::Generator;
11
57
57
57
7716
52
588
use App::Test::Generator::Mutation::Feedback;
12
57
57
57
96
35
265
use File::Spec;
13
57
57
57
58
24
1416
use File::Temp;
14
57
57
57
14458
191241
75
use Getopt::Long qw(GetOptions);
15
57
57
57
12858
761470
2387
use Pod::Usage;
16
57
57
57
107
29
41999
use YAML::XS qw(LoadFile);
17
18# Derive prove from $^X so we always use the same perl installation that
19# invoked this script, even when $PATH resolves to a different system perl.
20
57
3283755
my ($prove_vol, $prove_dir) = (File::Spec->splitpath($^X))[0, 1];
21
57
361
my $prove = File::Spec->catpath($prove_vol, $prove_dir, 'prove');
22
23 - 122
=head1 NAME

fuzz-harness-generator - Generate fuzzing + corpus-based test harnesses from test schemas

=head1 SYNOPSIS

  fuzz-harness-generator [-r] [--strict-documented] [-o output_file] input.yaml
  fuzz-harness-generator --mutation-results mutation.json -o t/fuzz.t input.yaml
  fuzz-harness-generator --dry-run input.yaml
  fuzz-harness-generator --replay-corpus schemas/corpus/ -o t/fuzz_replay.t
  fuzz-harness-generator --replay-corpus schemas/corpus/translate.json -o t/fuzz_replay.t

=head1 DESCRIPTION

This tool generates a test file that fuzzes and validates a target module's function or method,
using both randomized fuzz cases and a static corpus cases (Perl or YAML).

It can also generate regression test files from corpus JSON files previously
written by C<extract-schemas --fuzz>, using C<--replay-corpus>.

A starter C<input.yaml> can be created using C<extract-schemas> which is also in this package.

=head1 OPTIONS

=over 4

=item B<--help>

Show this help.

=item B<--input>

The input configuration file

=item B<--output>

The (optional) output file.

=item B<--dry-run>

Validate the input configuration and schema extraction without writing any output files or running tests.

=item B<--run>

Call C<prove> on the output file.

C<fuzz-harness-generator -r t/conf/data_text_append.conf> will, therefore, dynamically create and run tests on the C<append> method of L<Data::Text>

=item B<--strict-documented>

Fail the generated harness when fuzzing finds a routine that contradicts a
POD-derived constraint: a bound, a C<memberof> list or a C<matches> pattern.
By default the harness runs in advisory mode: an outside value is still
tried, and a routine that accepts it is reported as accepting a value its
POD says is invalid, but the run does not fail.  This option makes each
recorded contradiction a failing test.

=item B<--mutation-results> FILE

Feed surviving mutants back into harness generation.  FILE is the JSON report
written by C<test-generator-mutate --json>.  A surviving numeric-boundary
mutant is traced to the comparison it mutated, and that comparison becomes a
C<min> or C<max> constraint on the matching input field, so the generated
harness exercises the boundary the test suite missed.  Existing constraints
are never replaced, and survivors that do not describe a numeric comparison
are listed for review.  Only survivors belonging to the schema's C<module>
are used.

=item B<--replay-corpus> PATH

Instead of generating a fuzz harness, generate a regression test file from
one or more corpus JSON files previously written by C<extract-schemas --fuzz>.

PATH may be either:

=over 4

=item * A single corpus file, e.g. C<schemas/corpus/translate.json>

=item * A directory, e.g. C<schemas/corpus/> - all C<*.json> files in that
directory will be included

=back

The generated test file contains one failing test per bug recorded in the
corpus. Each test calls the target method with the exact input that previously
caused a crash and expects it B<not> to die. Tests will be red until the
underlying bug is fixed, at which point they go green and stay green -
acting as permanent regression tests.

Only corpus entries with recorded bugs are included. Clean corpus entries
(inputs that did not cause a bug) are ignored.

=item B<--version>

Prints the version of L<App::Test::Generator>

=back

=cut
123
124
57
258
my $infile;
125my $outfile;
126
57
0
my $help;
127
57
0
my $run;
128
57
0
my $verbose;
129
57
0
my $version;
130
57
0
my $dry_run;
131
57
0
my $replay_corpus;
132
57
0
my $strict_documented;
133
57
0
my $mutation_results;
134
135
57
135
Getopt::Long::Configure('bundling');
136
137
57
1122
GetOptions(
138        'help|h'          => \$help,
139        'input|i=s'       => \$infile,
140        'dry-run|n'       => \$dry_run,
141        'output|o=s'      => \$outfile,
142        'run|r'           => \$run,
143        'strict-documented' => \$strict_documented,
144        'mutation-results=s' => \$mutation_results,
145        'verbose|v'       => \$verbose,
146        'version|V'       => \$version,
147        'replay-corpus|R=s' => \$replay_corpus,
148) or pod2usage(2);
149
150
57
24434
pod2usage(-exitval => 0, -verbose => 1) if($help);
151
152
55
71
if($version) {
153
1
3
        print $App::Test::Generator::VERSION, "\n";
154
1
40
        exit 0;
155}
156
157# ---------------------------------------------------------------------------
158# --replay-corpus mode: generate a regression .t from corpus bug entries
159# ---------------------------------------------------------------------------
160
161
54
72
if($replay_corpus) {
162
0
0
        pod2usage('--replay-corpus cannot be combined with --dry-run') if $dry_run;
163
0
0
        pod2usage('--replay-corpus cannot be combined with --input')   if $infile;
164
165
0
0
        my @corpus_files = _collect_corpus_files($replay_corpus);
166
0
0
        die "No corpus JSON files found at: $replay_corpus\n" unless @corpus_files;
167
168
0
0
        my $tap = _generate_replay_tap(@corpus_files);
169
170
0
0
        if($outfile) {
171
0
0
                open(my $fh, '>', $outfile)
172                        or die "Cannot write to $outfile: $!";
173
0
0
                print $fh $tap;
174
0
0
                close $fh;
175
0
0
                chmod 0755, $outfile;
176
0
0
                print "Replay test written to: $outfile\n";
177
0
0
                if($run) {
178
0
0
                        exit system($prove, '-l', $outfile) >> 8;
179                }
180        } else {
181
0
0
                print $tap;
182        }
183
0
0
        exit 0;
184}
185
186
54
93
if($infile && @ARGV) {
187
0
0
        pod2usage('Specify input file either as argument or via --input, not both');
188}
189
190
54
70
if($infile) {
191
4
4
5
6
        my $schema = eval { LoadFile($infile) };
192
4
292
        if($@) {
193
1
71
                die "Cannot parse '$infile' as YAML: $@";
194        }
195
3
4
        unless(ref($schema) eq 'HASH') {
196
0
0
                die "Input file '$infile' does not contain a YAML hash";
197        }
198
3
10
        unless($schema->{function}) {
199
0
0
                die "Input file '$infile' is missing required 'function' key";
200        }
201}
202
203
53
147
$infile ||= shift @ARGV or pod2usage('No config file given');
204
205
53
94
if($dry_run && $run) {
206
0
0
        pod2usage('--dry-run cannot be used with --run');
207}
208
209
53
81
if($dry_run && $outfile) {
210
1
42
        warn '--dry-run specified; --output will be ignored';
211}
212
213
53
62
if($verbose) {
214
0
0
        $ENV{'TEST_VERBOSE'} = 1;
215}
216
217
53
67
if($run && !$outfile) {
218
0
0
        my ($fh, $tmp) = File::Temp::tempfile();
219
0
0
        close $fh;
220
221
0
0
        _generate_harness($infile, $tmp, $strict_documented, $mutation_results);
222
223
0
0
        exit system($prove, '-l', $tmp) >> 8;
224}
225
226
53
1000
if($dry_run) {
227
2
4
        my ($fh, $tmp) = File::Temp::tempfile();
228
2
440
        close $fh;
229
230        eval {
231
2
3
                _generate_harness($infile, $tmp, $strict_documented, $mutation_results);
232
2
114
                1;
233
2
679
        } or do {
234
0
0
                die "Dry-run failed for $infile: $@";
235        };
236
237
2
4
        unlink $tmp;
238
2
723
        print "Dry-run OK: $infile parsed and validated successfully\n";
239
2
86
        exit 0;
240} elsif($outfile && -e $outfile && !$run) {
241
0
0
        warn "Overwriting existing file: $outfile";
242}
243
244
51
127
_generate_harness($infile, $outfile, $strict_documented, $mutation_results);
245
246
51
2721
if($outfile) {
247
51
147
        chmod 0755, $outfile if($outfile =~ /\.(pl|cgi)$/);
248
51
62
        if($run) {
249                # Use list form to avoid shell interpolation of $outfile
250
0
0
                system($prove, '-l', $outfile);
251        }
252}
253
254
51
2168
exit 0;
255
256# --------------------------------------------------
257# _generate_harness
258#
259# Generate a fuzz harness, carrying the CLI's
260#     --strict-documented choice into the generated
261#     test file so that later prove runs behave
262#     the same way.
263#
264# Entry:      $infile  - schema file.
265#             $outfile - where to write the harness.
266#             $strict  - true to fail on documented-bound
267#                        contradictions.
268#             $mutation_results - optional path to the JSON
269#                        written by test-generator-mutate;
270#                        surviving boundary mutants become
271#                        schema constraints, and what was
272#                        applied is summarised here.
273#
274# Exit:       Returns nothing; generate() may croak.
275# --------------------------------------------------
276sub _generate_harness {
277
53
74
        my ($infile, $outfile, $strict, $mutation_results) = @_;
278
279
53
65
        if(defined($mutation_results)) {
280
1
3
                _report_mutation_feedback($infile, $mutation_results);
281        }
282
283
53
341
        return App::Test::Generator->generate({
284                input_file => $infile,
285                output_file => $outfile,
286                strict_documented => $strict ? 1 : 0,
287                (defined($mutation_results) ? (mutation_results => $mutation_results) : ()),
288        });
289}
290
291# --------------------------------------------------
292# _report_mutation_feedback
293#
294# Print what the survivors propose before the harness is
295# written, so a run that adds no constraints says so.
296#
297# Entry:      $infile  - schema file.
298#             $mutation_results - mutation results JSON.
299#
300# Exit:       Returns nothing; reads both files.
301# --------------------------------------------------
302sub _report_mutation_feedback {
303
1
1
        my ($infile, $mutation_results) = @_;
304
305
1
1
        my $schema = LoadFile($infile);
306        my $feedback = App::Test::Generator::Mutation::Feedback->new(
307                mutation_results => $mutation_results,
308
1
70
                (defined($schema->{module}) ? (module => $schema->{module}) : ()),
309        );
310
311
1
1
        my $proposals = $feedback->proposals;
312
1
1
        my $applied   = $feedback->apply_to_schema($schema);
313
314        printf "Mutation feedback: %d survivor(s), %d constraint(s) applied\n",
315
1
1
1
0
1
4
                scalar(@{$proposals}), scalar(@{$applied});
316
317
1
1
1
1
        foreach my $change (@{$applied}) {
318                printf "  %s: %s = %s (survivor %s)\n",
319                        $change->{field}, $change->{constraint}, $change->{value},
320
2
4
                        $change->{survivor_id};
321        }
322
323
1
1
0
1
        foreach my $proposal (@{$proposals}) {
324
3
2
                next unless $proposal->{kind} eq 'manual';
325                printf "  manual: %s line %s - %s\n",
326                        $proposal->{file}, $proposal->{line} // '?',
327
1
10
                        $proposal->{description} // $proposal->{survivor_id};
328        }
329}
330
331# ---------------------------------------------------------------------------
332# Helpers for --replay-corpus
333# ---------------------------------------------------------------------------
334
335# --------------------------------------------------
336# _collect_corpus_files
337#
338# Collect the list of corpus JSON files
339#     to process for --replay-corpus mode.
340#     Accepts either a single file path or
341#     a directory, returning all *.json files
342#     found in the directory case.
343#
344# Entry:      $path - filesystem path to either a
345#                     single .json file or a directory
346#                     containing .json files.
347#
348# Exit:       Returns a sorted list of file paths.
349#             Returns an empty list if the path does
350#             not exist or contains no .json files.
351#
352# Notes:      Directory globbing matches only *.json
353#             files at the top level of the directory;
354#             subdirectories are not recursed into.
355# --------------------------------------------------
356sub _collect_corpus_files {
357
0
        my ($path) = @_;
358
359
0
        if(-f $path) {
360
0
                return ($path);
361        } elsif(-d $path) {
362
0
                my @files = glob(File::Spec->catfile($path, '*.json'));
363
0
                return sort @files;
364        }
365
366
0
        return ();
367}
368
369# --------------------------------------------------
370# _generate_replay_tap
371#
372# Purpose:    Read one or more corpus JSON files and
373#             produce a complete .t file as a string.
374#             Each bug entry in the corpus becomes
375#             one lives_ok test that calls the target
376#             method with the exact input that
377#             previously caused a crash, asserting
378#             that it no longer dies.
379#
380# Entry:      @corpus_files - list of paths to corpus
381#                             JSON files as returned
382#                             by _collect_corpus_files.
383#
384# Exit:       Returns the complete .t file content as
385#             a string. Never returns undef.
386#             Returns a skip_all plan if no bugs are
387#             found across all corpus files.
388#
389# Side effects: Reads corpus JSON files from disk.
390#               Attempts to load JSON::MaybeXS or
391#               JSON via block eval.
392#
393# Notes:      Corpus files that cannot be parsed are
394#             skipped with a warning rather than
395#             aborting the entire run.
396#             Clean corpus entries (those without
397#             recorded bugs) are silently ignored —
398#             only entries with a 'bugs' array are
399#             processed.
400#             The module name for each test is
401#             inferred from the YAML schema file
402#             alongside the corpus file via
403#             _infer_module_from_schema. Falls back
404#             to 'UNKNOWN::Module' if not found.
405# --------------------------------------------------
406sub _generate_replay_tap {
407
0
        my (@corpus_files) = @_;
408
409        # Prefer JSON::MaybeXS for correctness; fall back to JSON
410
0
        my $json_module;
411
0
        for my $mod (qw(JSON::MaybeXS JSON)) {
412
0
0
0
                eval { require $mod; 1 } and $json_module = $mod and last;
413        }
414
0
        die "No JSON module available; install JSON or JSON::MaybeXS\n"
415                unless $json_module;
416
417        # Collect all bugs across all corpus files into a flat list
418
0
        my @tests;
419
420
0
        for my $file (@corpus_files) {
421
0
                open(my $fh, '<', $file)
422                        or die "Cannot read $file: $!";
423
0
                my $data = eval {
424
0
0
0
                        $json_module->new->decode(do { local $/; <$fh> })
425                };
426
0
                close $fh;
427
428
0
                if($@) {
429
0
                        warn "Skipping $file: could not parse JSON: $@\n";
430
0
                        next;
431                }
432
433
0
                my $bugs = $data->{'bugs'} // [];
434
0
0
                next unless @{$bugs};
435
436                # Derive method name from filename: translate.json -> translate
437
0
                my (undef, undef, $fname) = File::Spec->splitpath($file);
438
0
                (my $method = $fname) =~ s/\.json$//;
439
440                # Look up the module name from the companion schema file;
441                # fall back to a placeholder if the schema cannot be found
442
0
                my $module = _infer_module_from_schema($file, $method)
443                        // 'UNKNOWN::Module';
444
445
0
0
                for my $bug (@{$bugs}) {
446                        push @tests, {
447                                module => $module,
448                                method => $method,
449                                input  => $bug->{'input'},
450
0
                                error  => $bug->{'error'},
451                                file   => $file,
452                        };
453                }
454        }
455
456        # Build the .t header — include Test::Exception up front since
457        # lives_ok is always needed when there are tests to emit
458
0
        my $t = <<'HEADER';
459#!/usr/bin/env perl
460# Auto-generated by fuzz-harness-generator --replay-corpus
461# DO NOT EDIT - regenerate from corpus files instead
462use strict;
463use warnings;
464use Test::More;
465use Test::Exception;
466HEADER
467
468
0
        my $test_count = scalar @tests;
469
470
0
        if($test_count == 0) {
471
0
                $t .= "\nplan skip_all => 'No bugs recorded in corpus files';\n";
472
0
                return $t;
473        }
474
475        # Emit one use statement per unique module (excluding the placeholder)
476
0
0
        my %modules = map { $_->{'module'} => 1 } @tests;
477
0
        for my $mod (sort keys %modules) {
478
0
                next if $mod eq 'UNKNOWN::Module';
479
0
                $t .= "use $mod;\n";
480        }
481
482
0
        $t .= "\nplan tests => $test_count;\n\n";
483
484
0
        for my $i (0 .. $#tests) {
485
0
                my $test  = $tests[$i];
486
0
                my $n     = $i + 1;
487
0
                my $input = _format_input($test->{'input'});
488
0
                my $label = "$test->{'method'} does not die on input from $test->{'file'}";
489
490                # Flatten and escape the original error for use as a comment
491
0
                (my $orig_error = $test->{'error'} // '') =~ s/\n/ /g;
492
0
                $orig_error =~ s/'/\\'/g;
493
494
0
                $t .= "# Corpus bug: $orig_error\n";
495
0
                $t .= "lives_ok { $test->{'module'}\->$test->{'method'}($input) }\n";
496
0
                $t .= "    '$label';\n\n";
497        }
498
499
0
        return $t;
500}
501
502# --------------------------------------------------
503# _format_input
504#
505# Purpose:    Format a scalar input value as a Perl
506#             literal string suitable for embedding
507#             directly in generated test source code.
508#
509# Entry:      $input - the input value to format.
510#                      May be undef, a numeric string,
511#                      or an arbitrary string.
512#
513# Exit:       Returns a Perl literal string:
514#               'undef'     if $input is undef
515#               bare number if $input looks numeric
516#               single-quoted string otherwise, with
517#               backslashes and single quotes escaped.
518#
519# Side effects: None.
520#
521# Notes:      Only scalar inputs are handled — corpus
522#             entries with arrayref or hashref inputs
523#             are not currently supported and will be
524#             formatted as a single-quoted string of
525#             the stringified reference, which will
526#             not reproduce the original input.
527# --------------------------------------------------
528sub _format_input {
529
0
        my ($input) = @_;
530
531
0
        return 'undef' unless defined $input;
532
533        # Emit bare numeric literals without quoting
534
0
        return $input if $input =~ /^-?(?:\d+\.?\d*|\.\d+)$/;
535
536        # Escape backslashes first, then single quotes, to avoid
537        # double-escaping when both appear in the same string
538
0
        (my $escaped = $input) =~ s/\\/\\\\/g;
539
0
        $escaped =~ s/'/\\'/g;
540
541
0
        return "'$escaped'";
542}
543
544# --------------------------------------------------
545# _infer_module_from_schema
546#
547# Purpose:    Attempt to determine the Perl module
548#             name for a given corpus method by
549#             locating and reading the companion YAML
550#             schema file that sits alongside the
551#             corpus directory.
552#
553# Entry:      $corpus_file - path to the corpus JSON
554#                            file, e.g.
555#                            schemas/corpus/translate.json
556#             $method      - the method name derived
557#                            from the corpus filename,
558#                            e.g. 'translate'
559#
560# Exit:       Returns the module name string if found,
561#             or undef if no companion schema file
562#             exists or the schema contains no
563#             'module:' line.
564#
565# Side effects: Reads schema files from disk.
566#
567# Notes:      The corpus is expected to live one
568#             directory below the schemas directory,
569#             e.g. schemas/corpus/ alongside
570#             schemas/translate.yaml. This function
571#             walks up one level from the corpus
572#             directory to find the schema.
573#             Both .yaml and .yml extensions are
574#             tried, in that order.
575# --------------------------------------------------
576sub _infer_module_from_schema {
577
0
        my ($corpus_file, $method) = @_;
578
579
0
        my (undef, $corpus_dir) = File::Spec->splitpath($corpus_file);
580
581        # Walk up one directory from corpus/ to reach the schemas/ dir
582
0
        my $schema_dir = File::Spec->catdir($corpus_dir, File::Spec->updir());
583
584
0
        for my $ext (qw(yaml yml)) {
585
0
                my $schema_file = File::Spec->catfile($schema_dir, "$method.$ext");
586
0
                next unless -f $schema_file;
587
588
0
                open(my $fh, '<', $schema_file) or next;
589
0
                while(<$fh>) {
590
0
                        if(/^module:\s*(\S+)/) {
591
0
                                close $fh;
592
0
                                return $1;
593                        }
594                }
595
0
                close $fh;
596        }
597
598
0
        return undef;
599}
600