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