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