chiark / gitweb /
Test suite: Make it possible to call t-policy more than once (moving t-dsd out of it)
[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 $cmd = "$dgitlive/dgit -d$distro \$DGIT_TEST_OPTS";
90     $cmd .= " -".("D" x $debuglevel) if $debuglevel;
91     $cmd .= " archive-api-query $subpath";
92     printdebug "apiquery $cmd\n";
93     $!=0; $?=0; my $json = `$cmd`;
94     defined $json && !$? or die "$subpath $! $?";
95     my $r = decode_json $json;
96     my $d = new Data::Dumper([$r], [qw(r)]);
97     printdebug "apiquery $subpath | ", $d->Dump() if $debuglevel>=2;
98     return $r;
99 }
100
101 sub specific_suite_has_vsn_in_our_history ($) {
102     my ($suite) = @_;
103     my $in_suite = apiquery "dsc_in_suite/$suite/$pkg";
104     foreach my $entry (@$in_suite) {
105         my $vsn = $entry->{version};
106         die "$pkg ?" unless defined $vsn;
107         my $tagref = "refs/tags/".debiantag $vsn;
108         printdebug " checking history suite=$suite vsn=$vsn tagref=$tagref\n";
109         $?=0; my $r = system qw(git show-ref --verify --quiet), $tagref;
110         return 1 if !$r;
111         next if $r==256;
112         die "$pkg tagref $tagref $? $!";
113     }
114     return 0;
115 }
116
117 sub new_has_vsn_in_our_history () {
118     return specific_suite_has_vsn_in_our_history('new');
119 }
120
121 sub good_suite_has_vsn_in_our_history () {
122     my $suites = apiquery "suites";
123     foreach my $suitei (@$suites) {
124         my $suite = $suitei->{name};
125         die unless defined $suite;
126         next if $suite =~ m/\bnew$/;
127         return 1 if specific_suite_has_vsn_in_our_history($suite);
128     }
129     return 0;
130 }
131
132 sub statpackage () {
133     $pkgdir = "$repos/$pkg.git";
134     if (!stat_exists $pkgdir) {
135         printdebug "statpackage $pkg => ENOENT\n";
136         $pkg_exists = 0;
137     } else {
138         $pkg_exists = 1;
139         $pkg_secret = !!(~(stat _)[2] & 05);
140         printdebug "statpackage $pkg => exists, secret=$pkg_secret.\n";
141     }
142 }
143
144 sub getpackage () {
145     die unless @ARGV >= 1;
146     $pkg = shift @ARGV;
147     die unless $pkg =~ m/^$package_re$/;
148
149     statpackage();
150 }
151
152 sub add_taint ($$) {
153     my ($refobj, $reason) = @_;
154
155     printdebug "TAINTING $refobj\n",
156         (map { "\%| $_" } split "\n", $reason),
157         "\n";
158
159     my $tf = new File::Temp or die $!;
160     print $tf "$refobj^0\n" or die $!;
161     flush $tf or die $!;
162     seek $tf,0,0 or die $!;
163
164     my $gcfpid = open GCF, "-|";
165     defined $gcfpid or die $!;
166     if (!$gcfpid) {
167         open STDIN, "<&", $tf or die $!;
168         exec 'git', 'cat-file', '--batch';
169         die $!;
170     }
171
172     close $tf or die $!;
173     $_ = <GCF>;
174     defined $_ or die;
175     m/^(\w+) (\w+) (\d+)\n/ or die "$_ ?";
176     my $gitobjid = $1;
177     my $gitobjtype = $2;
178     my $bytes = $3;
179
180     my $gitobjdata;
181     if ($gitobjtype eq 'commit' or $gitobjtype eq 'tag') {
182         $!=0; read GCF, $gitobjdata, $bytes == $bytes
183             or die "$gitobjid $bytes $!";
184     }
185     close GCF;
186
187     $poldbh->do("INSERT INTO taints".
188                 " (package, gitobjid, gitobjtype, gitobjdata, time, comment)".
189                 " VALUES (?,?,?,?,?,?)", {},
190                 $pkg, $gitobjid, $gitobjtype, $gitobjdata, time, $reason);
191
192     my $taint_id = $poldbh->last_insert_id(undef,undef,"taints","taint_id");
193     die unless defined $taint_id;
194
195     $poldbh->do("INSERT INTO taintoverrides".
196                 " (taint_id, deliberately)".
197                 " VALUES (?, '--deliberately-include-questionable-history')", 
198                 {}, $taint_id);
199 }
200
201 sub add_taint_by_tag ($$) {
202     my ($tagname,$refobjid) = @_;
203     add_taint($refobjid,
204               "tag $tagname referred to this object in git tree but all".
205               " previously pushed versions were found to have been".
206               " removed from NEW (ie, rejected) (or never arrived)");
207 }
208
209 sub action_check_package () {
210     getpackage();
211     return 0 unless $pkg_exists;
212     return 0 unless $pkg_secret;
213
214     printdebug "check_package\n";
215
216     chdir $pkgdir or die "$pkgdir $!";
217
218     stat '.' or die "$pkgdir $!";
219     my $mtime = ((stat _)[9]);
220     my $age = time -  $mtime;
221     printdebug "check_package age=$age\n";
222
223     return 0 if $age < $new_upload_propagation_slop;
224
225     return 0 if new_has_vsn_in_our_history();
226
227     if (good_suite_has_vsn_in_our_history) {
228         chmod $publicmode, "." or die $!;
229         return 0;
230     }
231
232     printdebug "check_package secret, deleted, tainting\n";
233
234     git_for_each_ref('refs/tags', sub {
235         my ($objid,$objtype,$fullrefname,$tagname) = @_;
236         add_taint_by_tag($tagname,$objid);
237     });
238
239     return FRESHREPO;
240 }
241
242 sub getpushinfo () {
243     die unless @ARGV >= 4;
244     $version = shift @ARGV;
245     $suite = shift @ARGV;
246     $tagname = shift @ARGV;
247     my $delibs = shift @ARGV;
248     foreach my $delib (split /\,/, $delibs) {
249         $deliberately{$delib} = 1;
250     }
251 }
252
253 sub deliberately ($) { return $deliberately{"--deliberately-$_[0]"}; }
254
255 sub action_push () {
256     getpackage();
257     getpushinfo();
258
259     return 0 unless $pkg_exists;
260     return 0 unless $pkg_secret;
261
262     # we suppose that NEW has a version which is already in our
263     # history, as otherwise the repo would have been blown away
264
265     if (deliberately('not-fast-forward')) {
266         add_taint(server_ref($suite),
267                   "rewound suite $suite; --deliberately-not-fast-forward".
268                   " specified in signed tag $tagname for upload of".
269                   " version $version");
270         return NOFFCHECK|FRESHREPO;
271     }
272     if (deliberately('include-questionable-history')) {
273         return 0;
274     }
275     die "Package is in NEW and has not been accepted or rejected yet;".
276         " use a --deliberately option to specify whether you are".
277         " keeping or discarding the previously pushed history. ".
278         " Please RTFM dgit(1).\n";
279 }
280
281 sub action_push_confirm () {
282     getpackage();
283     getpushinfo();
284     die unless @ARGV >= 1;
285     my $freshrepo = shift @ARGV;
286
287     my $initq = $poldbh->prepare(<<END);
288         SELECT taint_id, gitobjid FROM taints t
289             WHERE (package = ? OR package = '')
290 END
291     $initq->execute($pkg);
292
293     my @objscatcmd = qw(git);
294     push @objscatcmd, qw(--git-dir), $freshrepo if length $freshrepo;
295     push @objscatcmd, qw(cat-file --batch);
296     debugcmd '|',@objscatcmd if $debuglevel>=2;
297
298     my @taintids;
299     my $chkinput = tempfile();
300     while (my $taint = $initq->fetchrow_hashref()) {
301         push @taintids, $taint->{taint_id};
302         print $chkinput $taint->{gitobjid}, "\n" or die $!;
303         printdebug '|> ', $taint->{gitobjid}, "\n" if $debuglevel>=2;
304     }
305     flush $chkinput or die $!;
306     seek $chkinput,0,0 or die $!;
307
308     my $checkpid = open CHKOUT, "-|" // die $!;
309     if (!$checkpid) {
310         open STDIN, "<&", $chkinput or die $!;
311         exec @objscatcmd or die $!;
312     }
313
314     my ($taintinfoq,$overridesanyq,$untaintq,$overridesq);
315
316     my $overridesstmt = <<END;
317         SELECT deliberately FROM taintoverrides WHERE (
318             1=0
319 END
320     my @overridesv = sort keys %deliberately;
321     $overridesstmt .= <<END foreach @overridesv;
322             OR deliberately = ?
323 END
324     $overridesstmt .= <<END;
325         ) AND taint_id = ?
326         ORDER BY deliberately ASC
327 END
328
329     my $mustreject=0;
330
331     while (my $taintid = shift @taintids) {
332         # git cat-file prints a spurious newline after it gets EOF
333         # This is not documented.  I guess it might go away.  So we
334         # just read what we expect and then let it get SIGPIPE.
335         $!=0; $_ = <CHKOUT>;
336         die "$? $!" unless defined $_;
337         printdebug "|< ", $_ if $debuglevel>=2;
338
339         next if m/^\w+ missing$/;
340         die unless m/^(\w+) (\w+) (\d+)\s/;
341         my ($objid,$objtype,$nbytes) = ($1,$2,$3);
342
343         my $drop;
344         (read CHKOUT, $drop, $nbytes) == $nbytes or die;
345
346         $taintinfoq ||= $poldbh->prepare(<<END);
347             SELECT package, time, comment FROM taints WHERE taint_id =  ?
348 END
349         $taintinfoq->execute($taintid);
350
351         my $ti = $taintinfoq->fetchrow_hashref();
352         die unless $ti;
353
354         my $timeshow = defined $ti->{time}
355             ? " at time ".strftime("%Y-%m-%d %H:%M:%S Z", gmtime $ti->{time})
356             : "";
357         my $pkgshow = length $ti->{package}
358             ? "package $ti->{package}"
359             : "any package";
360
361         $stderr .= <<END;
362
363 History contains tainted $objtype $objid
364 Taint recorded$timeshow for $pkgshow
365 Reason: $ti->{comment}
366 END
367
368         printdebug "SQL overrides: @overridesv $taintid /\n$overridesstmt\n";
369
370         $overridesq ||= $poldbh->prepare($overridesstmt);
371         $overridesq->execute(@overridesv, $taintid);
372         my ($ovwhy) = $overridesq->fetchrow_array();
373         if (!defined $ovwhy) {
374             $overridesanyq ||= $poldbh->prepare(<<END);
375                 SELECT 1 FROM taintoverrides WHERE taint_id = ? LIMIT 1
376 END
377             $overridesanyq->execute($taintid);
378             my ($ovany) = $overridesanyq->fetchrow_array();
379             $stderr .= $ovany ? <<END : <<END;
380 Could be forced using --deliberately.  Consult documentation.
381 END
382 Uncorrectable error.  If confused, consult administrator.
383 END
384             $mustreject = 1;
385         } else {
386             $stderr .= <<END;
387 Forcing due to --deliberately-$ovwhy
388 END
389             $untaintq ||= $poldbh->prepare(<<END);
390                 DELETE FROM taints WHERE taint_id = ?
391 END
392             $untaintq->execute($taintid);
393         }
394     }
395     close CHKOUT;
396
397     if ($mustreject) {
398         $stderr .= <<END;
399
400 Rejecting push due to questionable history.
401 END
402         return 1;
403     }
404
405     if (length $freshrepo) {
406         if (!good_suite_has_vsn_in_our_history()) {
407             stat $freshrepo or die "$freshrepo $!";
408             my $oldmode = ((stat _)[2]);
409             my $oldwrites = $oldmode & 0222;
410             # remove r and x bits which have corresponding w bits clear
411             my $newmode = $oldmode &
412                 (~0555 | ($oldwrites << 1) | ($oldwrites >> 1));
413             printdebug sprintf "chmod %#o (was %#o) %s\n",
414                 $newmode, $oldmode, $freshrepo;
415             chmod $newmode, $freshrepo or die $!;
416             utime undef, undef, $freshrepo or die $!;
417         }
418     }
419
420     return 0;
421 }
422
423 sub action_check_list () {
424     opendir L, "$repos" or die "$repos $!";
425     while (defined (my $dent = readdir L)) {
426         next unless $dent =~ m/^($package_re)\.git$/;
427         $pkg = $1;
428         statpackage();
429         next unless $pkg_exists;
430         next unless $pkg_secret;
431         print "$pkg\n" or die $!;
432     }
433     closedir L or die $!;
434     close STDOUT or die $!;
435     return 0;
436 }
437
438 $action =~ y/-/_/;
439 my $fn = ${*::}{"action_$action"};
440 if (!$fn) {
441     printdebug "dgit-repos-policy-debian: unknown action $action\n";
442     exit 0;
443 }
444
445 my $sleepy=0;
446 my $rcode;
447
448 for (;;) {
449     poldb_setup(poldb_path($repos));
450     $stderr = '';
451
452     $rcode = $fn->();
453     die unless defined $rcode;
454
455     eval { $poldbh->commit; };
456     last unless length $@;
457
458     die if $sleepy >= 20;
459     print STDERR "[policy database busy, retrying]\n";
460     sleep ++$sleepy;
461
462     $poldbh->rollback;
463 }
464
465 print STDERR $stderr or die $!;
466 flush STDERR or die $!;
467 _exit $rcode;