chiark / gitweb /
DGIT_TEST_DEBUG: Improve plumbing and honour in policy hook. Also honour $dgitlive
[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
13 use Debian::Dgit qw(:DEFAULT :policyflags);
14 use Debian::Dgit::Policy::Debian;
15
16 our $distro = shift @ARGV // die "need DISTRO";
17 our $repos = shift @ARGV // die "need DGIT-REPOS-DIR";
18 our $dgitlive = shift @ARGV // die "need DGIT-LIVE-DIR";
19 our $action = shift @ARGV // die "need ACTION";
20
21 our $publicmode = 02775;
22 our $new_upload_propagation_slop = 3600*4 + 100;
23
24 our $poldbh;
25 our $pkg;
26 our $pkgdir;
27 our ($pkg_exists,$pkg_secret);
28
29 our $stderr;
30
31 our ($version,$suite,$tagname);
32 our %deliberately;
33
34 # We assume that it is not possible for NEW to have a version older
35 # than sid.
36
37 # Whenever pushing, we check for
38 #   source-package-local tainted history
39 #   global tainted history
40 #   can be overridden by --deliberately except for an admin prohib taint
41
42 # ALL of the following apply only if history is secret:
43
44 # if NEW has no version, or a version which is not in our history[1]
45 #   (always)
46 #   check all suites
47 #   if any suite's version is in our history[1], publish our history
48 #   otherwise discard our history,
49 #     tainting --deliberately-include-questionable-history
50
51 # if NEW has a version which is in our history[1]
52 #   (on push only)
53 #   require explicit specification of one of
54 #     --deliberately-include-questionable-history
55 #     --deliberately-not-fast-forward
56 #       (latter will taint old NEW version --d-i-q-h)
57 #   (otherwise)
58 #   leave it be
59
60 # [1] looking for the relevant git tag for the version number and not
61 #    caring what that tag refers to.
62 #
63 # A wrinkle: if we approved a push recently, we treat NEW as having
64 # a version which is in our history.  This is because the package may
65 # still be being uploaded.  (We record this using the timestamp of the
66 # package's git repo directory.)
67
68 # We aim for the following invariants and properties:
69 #
70 # - .dsc of published dgit package will have corresponding publicly
71 #   visible dgit-repo (soon)
72 #
73 # - when a new package is rejected we help maintainer avoid
74 #   accidentally including bad objects in published dgit history
75 #
76 # - .dsc of NEW dgit package has corresponding dgit-repo but not
77 #   publicly readable
78
79 sub apiquery ($) {
80     my ($subpath) = @_;
81     local $/=undef;
82     my $cmd = "$dgitlive/dgit -d $distro ".
83         "\$DGIT_TEST_OPTS \$DGIT_TEST_DEBUG archive-api-query $subpath";
84     $!=0; $?=0; my $json = `$cmd`;
85     defined $json or die "$subpath $! $?";
86     return decode_json $json;
87 }
88
89 sub specific_suite_has_vsn_in_our_history ($) {
90     my ($suite) = @_;
91     my $in_suite = apiquery "/dsc_in_suite/$suite/$pkg";
92     foreach my $entry (@$in_suite) {
93         my $vsn = $entry->{version};
94         die "$pkg ?" unless defined $vsn;
95         my $tag = debiantag $vsn;
96         $?=0; my $r = system qw(git show-ref --verify --quiet), $tag;
97         return 1 if !$r;
98         next if $r==256;
99         die "$pkg tag $tag $? $!";
100     }
101     return 0;
102 }
103
104 sub new_has_vsn_in_our_history () {
105     stat $pkgdir or die "$pkgdir $!";
106     my $mtime = ((stat _)[9]);
107     my $age = time -  $mtime;
108     return 1 if $age < $new_upload_propagation_slop;
109     return specific_suite_has_vsn_in_our_history('new');
110 }
111
112 sub good_suite_has_vsn_in_our_history () {
113     my $suites = apiquery "/suites";
114     foreach my $suitei (@$suites) {
115         my $suite = $suitei->{name};
116         die unless defined $suite;
117         next if $suite =~ m/\bnew$/;
118         return 1 if specific_suite_has_vsn_in_our_history($suite);
119     }
120     return 0;
121 }
122
123 sub getpackage () {
124     die unless @ARGV >= 1;
125     $pkg = shift @ARGV;
126     die unless $pkg =~ m/^$package_re$/;
127
128     $pkgdir = "$repos/$pkg";
129     if (!stat_exists $pkgdir) {
130         $pkg_exists = 0;
131     } else {
132         $pkg_exists = 1;
133         $pkg_secret = !!(~(stat _)[2] & 05);
134     }
135 }
136
137 sub add_taint ($$) {
138     my ($refobj, $reason);
139
140     my $tf = new File::Temp or die $!;
141     print $tf "$refobj^0\n" or die $!;
142
143     my $gcfpid = open GCF, "-|";
144     defined $gcfpid or die $!;
145     if (!$gcfpid) {
146         open STDIN, "<&", $tf or die $!;
147         exec 'git', 'cat-file';
148         die $!;
149     }
150
151     close $tf or die $!;
152     $_ = <GCF>;
153     m/^(\w+) (\w+) (\d+)\n/ or die "$_ ?";
154     my $gitobjid = $1;
155     my $gitobjtype = $2;
156     my $bytes = $3;
157
158     my $gitobjdata;
159     if ($gitobjtype eq 'commit' or $gitobjtype eq 'tag') {
160         $!=0; read GCF, $gitobjdata, $bytes == $bytes
161             or die "$gitobjid $bytes $!";
162     }
163     close GCF;
164
165     $poldbh->do("INSERT INTO taints".
166                 " (package, gitobjid, gitobjtype, gitobjdata, time, comment)",
167                 " VALUES (?,?,?,?,?,?)", {},
168                 $pkg, $gitobjid, $gitobjtype, $gitobjdata, time, $reason);
169
170     my $taint_id = $poldbh->last_insert_id(undef,undef,"taints","taint_id");
171     die unless defined $taint_id;
172
173     $poldbh->do("INSERT INTO taintoverrides".
174                 " (taint_id, deliberately)",
175                 " VALUES (?, 'include-questionable-history')", {},
176                 $taint_id);
177 }
178
179 sub add_taint_by_tag ($$) {
180     my ($tagname,$refobjid) = @_;
181     add_taint($refobjid,
182               "tag $tagname referred to this object in git tree but all".
183               " previously pushed versions were found to have been".
184               " removed from NEW (ie, rejected) (or never arrived)");
185 }
186
187 sub action__check_package () {
188     getpackage();
189     return 0 unless $pkg_exists;
190     return 0 unless $pkg_secret;
191
192     chdir $pkgdir or die "$pkgdir $!";
193     return if new_has_vsn_in_our_history();
194
195     if (good_suite_has_vsn_in_our_history) {
196         chmod $publicmode, "." or die $!;
197         return 0;
198     }
199
200     git_for_each_ref('refs/tags', sub {
201         my ($objid,$objtype,$fullrefname,$tagname) = @_;
202         add_taint_by_tag($tagname,$objid);
203     });
204
205     return FRESHREPO;
206 }
207
208 sub getpushinfo () {
209     die unless @ARGV >= 4;
210     $version = shift @ARGV;
211     $suite = shift @ARGV;
212     $tagname = shift @ARGV;
213     my $delibs = shift @ARGV;
214     foreach my $delib (split /\,/, $delibs) {
215         $deliberately{$delib} = 1;
216     }
217 }
218
219 sub deliberately ($) { return $deliberately{$_[0]}; }
220
221 sub action_push () {
222     getpackage();
223     return 0 unless $pkg_exists;
224     return 0 unless $pkg_secret;
225
226     # we suppose that NEW has a version which is already in our
227     # history, as otherwise the repo would have been blown away
228
229     if (deliberately('not-fast-forward')) {
230         add_taint(server_ref($suite),
231                   "suite $suite when --deliberately-not-fast-forward".
232                   " specified in signed tag $tagname for upload of".
233                   " version $version into suite $suite");
234         return NOFFCHECK|FRESHREPO;
235     }
236     if (deliberately('include-questionable-history')) {
237         return 0;
238     }
239     die "Package is in NEW and has not been accepted or rejected yet;".
240         " use a --deliberately option to specify whether you are".
241         " keeping or discarding the previously pushed history. ".
242         " Please RTFM dgit(1).\n";
243 }
244
245 sub action_push_confirm () {
246     my $initq = $poldbh->prepare(<<END);
247         SELECT taint_id, gitobjid FROM taints t
248             WHERE (package = ? OR package = '')
249 END
250     $initq->execute($pkg);
251
252     my @taintids;
253     my $chkinput = tempfile();
254     while (my $taint = $initq->fetchrow_hashref()) {
255         push @taintids, $taint->{taint_id};
256         print $chkinput $taint->{gitobjid}, "\n" or die $!;
257     }
258     flush $chkinput or die $!;
259     seek $chkinput,0,0 or die $!;
260
261     my $checkpid = open CHKOUT, "-|" // die $!;
262     if (!$checkpid) {
263         open STDIN, "<&", $chkinput or die $!;
264         exec qw(git cat-file --batch) or die $!;
265     }
266
267     my ($taintinfoq,$overridesanyq,$untaintq,$overridesq);
268
269     my $overridesstmt = <<END;
270         SELECT deliberately FROM taintoverrides WHERE ( 1
271 END
272     my @overridesv = sort keys %deliberately;
273     $overridesstmt .= join '', (<<END x @overridesv);
274             OR deliberately = ?
275 END
276     $overridesstmt .= <<END;
277         ) AND taint_id = ?
278         ORDER BY deliberately ASC
279 END
280
281     my $mustreject=0;
282
283     while (my $taintid = shift @taintids) {
284         # git cat-file prints a spurious newline after it gets EOF
285         # This is not documented.  I guess it might go away.  So we
286         # just read what we expect and then let it get SIGPIPE.
287         $!=0; $_ = <CHKOUT>;
288         die "$? $!" unless defined $_;
289
290         next if m/^\w+ missing$/;
291         die unless m/^(\w+) (\w+) (\d+)\s/;
292         my ($objid,$objtype,$nbytes) = ($1,$2,$3);
293
294         my $drop;
295         (read CHKOUT, $drop, $nbytes) == $nbytes or die;
296
297         $taintinfoq ||= $poldbh->prepare(<<END);
298             SELECT package, time, comment FROM taints WHERE taint_id =  ?
299 END
300         $taintinfoq->execute($taintid);
301
302         my $ti = $taintinfoq->fetchrow_hashref();
303         die unless $ti;
304
305         my $timeshow = defined $ti->{time}
306             ? " at time ".strftime("%Y-%m-%d %H:%M:%S Z", gmtime $ti->{time})
307             : "";
308         my $pkgshow = length $ti->{package}
309             ? "package $ti->{package}"
310             : "any package";
311
312         $stderr .= <<END;
313
314 History contains tainted $objtype $objid
315 Taint recorded$timeshow for $pkgshow
316 Reason: $ti->{comment}
317 END
318
319         $overridesq ||= $poldbh->prepare($overridesstmt);
320         $overridesq->execute(@overridesv, $taintid);
321         my ($ovwhy) = $overridesq->fetchrow_array();
322         if (!defined $ovwhy) {
323             $overridesanyq ||= $poldbh->prepare(<<END);
324                 SELECT 1 FROM taintoverrides WHERE taint_id = ? LIMIT 1
325 END
326             $overridesanyq->execute($taintid);
327             my ($ovany) = $overridesanyq->fetchrow_array();
328             $stderr .= $ovany ? <<END : <<END;
329 Could be forced using --deliberately.  Consult documentation.
330 END
331 Uncorrectable error.  If confused, consult administrator.
332 END
333             $mustreject = 1;
334         } else {
335             $stderr .= <<END;
336 Forcing due to --deliberately-$ovwhy
337 END
338             $untaintq ||= $poldbh->prepare(<<END);
339                 DELETE FROM taints WHERE taint_id = ?
340 END
341             $untaintq->execute($taintid);
342         }
343     }
344     close CHKOUT;
345
346     if ($mustreject) {
347         $stderr .= <<END;
348
349 Rejecting push due to questionable history.
350 END
351         return 1;
352     }
353
354     return 0;
355 }
356
357 $action =~ y/-/_/;
358 my $fn = ${*::}{"action_$action"};
359 if (!$fn) {
360     exit 0;
361 }
362
363 my $sleepy=0;
364 our $rcode = 127;
365
366 for (;;) {
367     poldb_setup(poldb_path($repos));
368     $stderr = '';
369
370     $rcode = $fn->();
371     die unless defined $rcode;
372
373     eval { $poldbh->commit; };
374     last unless length $@;
375
376     die if $sleepy >= 20;
377     print STDERR "[policy database busy, retrying]\n";
378     sleep ++$sleepy;
379
380     $poldbh->rollback;
381 }
382
383 print STDERR $stderr;
384 exit $rcode;