chiark / gitweb /
dgit-repos-policy-debian: Break out vsn_in_our_history (nfc)
[dgit.git] / infra / dgit-repos-policy-debian
1 #!/usr/bin/perl -w
2 # dgit repos policy hook script for Debian
3
4 use strict;
5 $SIG{__WARN__} = sub { die $_[0]; };
6
7 use POSIX;
8 use JSON;
9 use File::Temp qw(tempfile);
10 use DBI;
11 use IPC::Open2;
12 use Data::Dumper;
13
14 use Debian::Dgit qw(:DEFAULT :policyflags);
15 use Debian::Dgit::Policy::Debian;
16
17 initdebug('%');
18 enabledebuglevel $ENV{'DGIT_DRS_DEBUG'};
19
20 END { $? = 127; } # deliberate exit uses _exit
21
22 our $distro = shift @ARGV // die "need DISTRO";
23 our $repos = shift @ARGV // die "need DGIT-REPOS-DIR";
24 our $dgitlive = shift @ARGV // die "need DGIT-LIVE-DIR";
25 our $distrodir = shift @ARGV // die "need DISTRO-DIR";
26 our $action = shift @ARGV // die "need ACTION";
27
28 our $publicmode = 02775;
29 our $new_upload_propagation_slop = 3600*4 + 100;# fixme config;
30
31 our $poldbh;
32 our $pkg;
33 our $pkgdir;
34 our ($pkg_exists,$pkg_secret);
35
36 our $stderr;
37
38 our ($version,$suite,$tagname);
39 our %deliberately;
40
41 # We assume that it is not possible for NEW to have a version older
42 # than sid.
43
44 # Whenever pushing, we check for
45 #   source-package-local tainted history
46 #   global tainted history
47 #   can be overridden by --deliberately except for an admin prohib taint
48
49 # ALL of the following apply only if history is secret:
50
51 # if NEW has no version, or a version which is not in our history[1]
52 #   (always)
53 #   check all suites
54 #   if any suite's version is in our history[1], publish our history
55 #   otherwise discard our history,
56 #     tainting --deliberately-include-questionable-history
57
58 # if NEW has a version which is in our history[1]
59 #   (on push only)
60 #   require explicit specification of one of
61 #     --deliberately-include-questionable-history
62 #     --deliberately-not-fast-forward
63 #       (latter will taint old NEW version --d-i-q-h)
64 #   (otherwise)
65 #   leave it be
66
67 # [1] looking for the relevant git tag for the version number and not
68 #    caring what that tag refers to.
69 #
70 # A wrinkle: if we approved a push recently, we treat NEW as having
71 # a version which is in our history.  This is because the package may
72 # still be being uploaded.  (We record this using the timestamp of the
73 # package's git repo directory.)
74
75 # We aim for the following invariants and properties:
76 #
77 # - .dsc of published dgit package will have corresponding publicly
78 #   visible dgit-repo (soon)
79 #
80 # - when a new package is rejected we help maintainer avoid
81 #   accidentally including bad objects in published dgit history
82 #
83 # - .dsc of NEW dgit package has corresponding dgit-repo but not
84 #   publicly readable
85
86 sub apiquery ($) {
87     my ($subpath) = @_;
88     local $/=undef;
89     my $dgit = "$dgitlive/dgit";
90     $dgit = "dgit" if !stat_exists $dgit;
91     my $cmd = "$dgit -d$distro \$DGIT_TEST_OPTS";
92     $cmd .= " -".("D" x $debuglevel) if $debuglevel;
93     $cmd .= " archive-api-query $subpath";
94     printdebug "apiquery $cmd\n";
95     $!=0; $?=0; my $json = `$cmd`;
96     defined $json && !$? or die "$subpath $! $?";
97     my $r = decode_json $json;
98     my $d = new Data::Dumper([$r], [qw(r)]);
99     printdebug "apiquery $subpath | ", $d->Dump() if $debuglevel>=2;
100     return $r;
101 }
102
103 sub vsn_in_our_history ($) {
104     my ($vsn) = @_;
105
106     my $tagref = "refs/tags/".debiantag $vsn, $distro;
107     printdebug " checking history  vsn=$vsn tagref=$tagref\n";
108     $?=0; my $r = system qw(git show-ref --verify --quiet), $tagref;
109     return 1 if !$r;
110     return 0 if $r==256;
111     die "$pkg tagref $tagref $? $!";
112 }
113
114 sub specific_suite_has_suitable_vsn ($$) {
115     my ($suite, $vsn_check) = @_; # tests $vsn_check->($version)
116     my $in_suite = apiquery "dsc_in_suite/$suite/$pkg";
117     foreach my $entry (@$in_suite) {
118         my $vsn = $entry->{version};
119         die "$pkg ?" unless defined $vsn;
120         printdebug " checking history found suite=$suite vsn=$vsn\n";
121         return 1 if $vsn_check->($vsn);
122     }
123     return 0;
124 }
125
126 sub new_has_vsn_in_our_history () {
127     return specific_suite_has_suitable_vsn('new', \&vsn_in_our_history);
128 }
129
130 sub good_suite_has_suitable_vsn ($) {
131     my ($vsn_check) = @_; # as for specific_suite_has_specific_vsn
132     my $suites = apiquery "suites";
133     foreach my $suitei (@$suites) {
134         my $suite = $suitei->{name};
135         die unless defined $suite;
136         next if $suite =~ m/\bnew$/;
137         return 1 if specific_suite_has_suitable_vsn($suite, $vsn_check);
138     }
139     return 0;
140 }
141
142 sub statpackage () {
143     $pkgdir = "$repos/$pkg.git";
144     if (!stat_exists $pkgdir) {
145         printdebug "statpackage $pkg => ENOENT\n";
146         $pkg_exists = 0;
147     } else {
148         $pkg_exists = 1;
149         $pkg_secret = !!(~(stat _)[2] & 05);
150         printdebug "statpackage $pkg => exists, secret=$pkg_secret.\n";
151     }
152 }
153
154 sub getpackage () {
155     die unless @ARGV >= 1;
156     $pkg = shift @ARGV;
157     die unless $pkg =~ m/^$package_re$/;
158
159     statpackage();
160 }
161
162 sub add_taint ($$) {
163     my ($refobj, $reason) = @_;
164
165     printdebug "TAINTING $refobj\n",
166         (map { "\%| $_" } split "\n", $reason),
167         "\n";
168
169     my $tf = new File::Temp or die $!;
170     print $tf "$refobj^0\n" or die $!;
171     flush $tf or die $!;
172     seek $tf,0,0 or die $!;
173
174     my $gcfpid = open GCF, "-|";
175     defined $gcfpid or die $!;
176     if (!$gcfpid) {
177         open STDIN, "<&", $tf or die $!;
178         exec 'git', 'cat-file', '--batch';
179         die $!;
180     }
181
182     close $tf or die $!;
183     $_ = <GCF>;
184     defined $_ or die;
185     m/^(\w+) (\w+) (\d+)\n/ or die "$_ ?";
186     my $gitobjid = $1;
187     my $gitobjtype = $2;
188     my $bytes = $3;
189
190     my $gitobjdata;
191     if ($gitobjtype eq 'commit' or $gitobjtype eq 'tag') {
192         $!=0; read GCF, $gitobjdata, $bytes == $bytes
193             or die "$gitobjid $bytes $!";
194     }
195     close GCF;
196
197     $poldbh->do("INSERT INTO taints".
198                 " (package, gitobjid, gitobjtype, gitobjdata, time, comment)".
199                 " VALUES (?,?,?,?,?,?)", {},
200                 $pkg, $gitobjid, $gitobjtype, $gitobjdata, time, $reason);
201
202     my $taint_id = $poldbh->last_insert_id(undef,undef,"taints","taint_id");
203     die unless defined $taint_id;
204
205     $poldbh->do("INSERT INTO taintoverrides".
206                 " (taint_id, deliberately)".
207                 " VALUES (?, '--deliberately-include-questionable-history')", 
208                 {}, $taint_id);
209 }
210
211 sub add_taint_by_tag ($$) {
212     my ($tagname,$refobjid) = @_;
213     add_taint($refobjid,
214               "tag $tagname referred to this object in git tree but all".
215               " previously pushed versions were found to have been".
216               " removed from NEW (ie, rejected) (or never arrived)");
217 }
218
219 sub check_package () {
220     return 0 unless $pkg_exists;
221     return 0 unless $pkg_secret;
222
223     printdebug "check_package\n";
224
225     chdir $pkgdir or die "$pkgdir $!";
226
227     stat '.' or die "$pkgdir $!";
228     my $mtime = ((stat _)[9]);
229     my $age = time -  $mtime;
230     printdebug "check_package age=$age\n";
231
232     if (good_suite_has_suitable_vsn(\&vsn_in_our_history)) {
233         chmod $publicmode, "." or die $!;
234         $pkg_secret = 0;
235         return 0;
236     }
237
238     return 0 if $age < $new_upload_propagation_slop;
239
240     return 0 if new_has_vsn_in_our_history();
241
242     printdebug "check_package secret, deleted, tainting\n";
243
244     git_for_each_ref('refs/tags', sub {
245         my ($objid,$objtype,$fullrefname,$tagname) = @_;
246         add_taint_by_tag($tagname,$objid);
247     });
248
249     return FRESHREPO;
250 }
251
252 sub action_check_package () {
253     getpackage();
254     return check_package();
255 }
256
257 sub getpushinfo () {
258     die unless @ARGV >= 4;
259     $version = shift @ARGV;
260     $suite = shift @ARGV;
261     $tagname = shift @ARGV;
262     my $delibs = shift @ARGV;
263     foreach my $delib (split /\,/, $delibs) {
264         $deliberately{$delib} = 1;
265     }
266 }
267
268 sub deliberately ($) { return $deliberately{"--deliberately-$_[0]"}; }
269
270 sub action_push () {
271     getpackage();
272     getpushinfo();
273
274     check_package(); # might make package public, or might add taints
275
276     return 0 unless $pkg_exists;
277     return 0 unless $pkg_secret;
278
279     # we suppose that NEW has a version which is already in our
280     # history, as otherwise the repo would have been blown away
281
282     if (deliberately('not-fast-forward')) {
283         add_taint(server_ref($suite),
284                   "rewound suite $suite; --deliberately-not-fast-forward".
285                   " specified in signed tag $tagname for upload of".
286                   " version $version");
287         return NOFFCHECK|FRESHREPO;
288     }
289     if (deliberately('include-questionable-history')) {
290         return 0;
291     }
292     die "\nPackage is in NEW and has not been accepted or rejected yet;".
293         " use a --deliberately option to specify whether you are".
294         " keeping or discarding the previously pushed history. ".
295         " Please RTFM dgit(1).\n\n";
296 }
297
298 sub action_push_confirm () {
299     getpackage();
300     getpushinfo();
301     die unless @ARGV >= 1;
302     my $freshrepo = shift @ARGV;
303
304     my $initq = $poldbh->prepare(<<END);
305         SELECT taint_id, gitobjid FROM taints t
306             WHERE (package = ? OR package = '')
307 END
308     $initq->execute($pkg);
309
310     my @objscatcmd = qw(git);
311     push @objscatcmd, qw(--git-dir), $freshrepo if length $freshrepo;
312     push @objscatcmd, qw(cat-file --batch);
313     debugcmd '|',@objscatcmd if $debuglevel>=2;
314
315     my @taintids;
316     my $chkinput = tempfile();
317     while (my $taint = $initq->fetchrow_hashref()) {
318         push @taintids, $taint->{taint_id};
319         print $chkinput $taint->{gitobjid}, "\n" or die $!;
320         printdebug '|> ', $taint->{gitobjid}, "\n" if $debuglevel>=2;
321     }
322     flush $chkinput or die $!;
323     seek $chkinput,0,0 or die $!;
324
325     my $checkpid = open CHKOUT, "-|" // die $!;
326     if (!$checkpid) {
327         open STDIN, "<&", $chkinput or die $!;
328         exec @objscatcmd or die $!;
329     }
330
331     my ($taintinfoq,$overridesanyq,$untaintq,$overridesq);
332
333     my $overridesstmt = <<END;
334         SELECT deliberately FROM taintoverrides WHERE (
335             1=0
336 END
337     my @overridesv = sort keys %deliberately;
338     $overridesstmt .= <<END foreach @overridesv;
339             OR deliberately = ?
340 END
341     $overridesstmt .= <<END;
342         ) AND taint_id = ?
343         ORDER BY deliberately ASC
344 END
345
346     my $mustreject=0;
347
348     while (my $taintid = shift @taintids) {
349         # git cat-file prints a spurious newline after it gets EOF
350         # This is not documented.  I guess it might go away.  So we
351         # just read what we expect and then let it get SIGPIPE.
352         $!=0; $_ = <CHKOUT>;
353         die "$? $!" unless defined $_;
354         printdebug "|< ", $_ if $debuglevel>=2;
355
356         next if m/^\w+ missing$/;
357         die "$_ ?" unless m/^(\w+) (\w+) (\d+)\s/;
358         my ($objid,$objtype,$nbytes) = ($1,$2,$3);
359
360         my $drop;
361         (read CHKOUT, $drop, $nbytes) == $nbytes or die;
362
363         $taintinfoq ||= $poldbh->prepare(<<END);
364             SELECT package, time, comment FROM taints WHERE taint_id =  ?
365 END
366         $taintinfoq->execute($taintid);
367
368         my $ti = $taintinfoq->fetchrow_hashref();
369         die unless $ti;
370
371         my $timeshow = defined $ti->{time}
372             ? " at time ".strftime("%Y-%m-%d %H:%M:%S Z", gmtime $ti->{time})
373             : "";
374         my $pkgshow = length $ti->{package}
375             ? "package $ti->{package}"
376             : "any package";
377
378         $stderr .= <<END;
379
380 History contains tainted $objtype $objid
381 Taint recorded$timeshow for $pkgshow
382 Reason: $ti->{comment}
383 END
384
385         printdebug "SQL overrides: @overridesv $taintid /\n$overridesstmt\n";
386
387         $overridesq ||= $poldbh->prepare($overridesstmt);
388         $overridesq->execute(@overridesv, $taintid);
389         my ($ovwhy) = $overridesq->fetchrow_array();
390         if (!defined $ovwhy) {
391             $overridesanyq ||= $poldbh->prepare(<<END);
392                 SELECT 1 FROM taintoverrides WHERE taint_id = ? LIMIT 1
393 END
394             $overridesanyq->execute($taintid);
395             my ($ovany) = $overridesanyq->fetchrow_array();
396             $stderr .= $ovany ? <<END : <<END;
397 Could be forced using --deliberately.  Consult documentation.
398 END
399 Uncorrectable error.  If confused, consult administrator.
400 END
401             $mustreject = 1;
402         } else {
403             $stderr .= <<END;
404 Forcing due to --deliberately-$ovwhy
405 END
406             $untaintq ||= $poldbh->prepare(<<END);
407                 DELETE FROM taints WHERE taint_id = ?
408 END
409             $untaintq->execute($taintid);
410         }
411     }
412     close CHKOUT;
413
414     if ($mustreject) {
415         $stderr .= <<END;
416
417 Rejecting push due to questionable history.
418 END
419         return 1;
420     }
421
422     if (length $freshrepo) {
423         if (!good_suite_has_suitable_vsn(\&vsn_in_our_history)) {
424             stat $freshrepo or die "$freshrepo $!";
425             my $oldmode = ((stat _)[2]);
426             my $oldwrites = $oldmode & 0222;
427             # remove r and x bits which have corresponding w bits clear
428             my $newmode = $oldmode &
429                 (~0555 | ($oldwrites << 1) | ($oldwrites >> 1));
430             printdebug sprintf "chmod %#o (was %#o) %s\n",
431                 $newmode, $oldmode, $freshrepo;
432             chmod $newmode, $freshrepo or die $!;
433             utime undef, undef, $freshrepo or die $!;
434         }
435     }
436
437     return 0;
438 }
439
440 sub action_check_list () {
441     opendir L, "$repos" or die "$repos $!";
442     while (defined (my $dent = readdir L)) {
443         next unless $dent =~ m/^($package_re)\.git$/;
444         $pkg = $1;
445         statpackage();
446         next unless $pkg_exists;
447         next unless $pkg_secret;
448         print "$pkg\n" or die $!;
449     }
450     closedir L or die $!;
451     close STDOUT or die $!;
452     return 0;
453 }
454
455 $action =~ y/-/_/;
456 my $fn = ${*::}{"action_$action"};
457 if (!$fn) {
458     printdebug "dgit-repos-policy-debian: unknown action $action\n";
459     exit 0;
460 }
461
462 my $sleepy=0;
463 my $rcode;
464
465 my $db_busy_exception= 'Debian::Dgit::Policy::Debian::DB_BUSY';
466
467 my @orgargv = @ARGV;
468
469 for (;;) {
470     @ARGV = @orgargv;
471     eval {
472         poldb_setup(poldb_path($repos), sub {
473             $poldbh->{HandleError} = sub {
474                 return 0 unless $poldbh->err == 5; # SQLITE_BUSY, not in .pm :-(
475                 die bless { }, $db_busy_exception;
476             };
477
478             eval ($ENV{'DGIT_RPD_TEST_DBLOOP_HOOK'}//'');
479             die $@ if length $@;
480             # used by tests/tests/debpolicy-dbretry
481         });
482
483         $stderr = '';
484
485         $rcode = $fn->();
486         die unless defined $rcode;
487
488         $poldbh->commit;
489     };
490     last unless length $@;
491     die $@ unless ref $@ eq $db_busy_exception;
492
493     die if $sleepy >= 20;
494     $sleepy++;
495     print STDERR "[policy database busy, retrying (${sleepy}s)]\n";
496
497     eval { $poldbh->rollback; };
498 }
499
500 print STDERR $stderr or die $!;
501 flush STDERR or die $!;
502 _exit $rcode;