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