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