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