diff --git a/Bugzilla/Attachment/Zip.pm b/Bugzilla/Attachment/Zip.pm new file mode 100644 index 0000000000..259b01a3ae --- /dev/null +++ b/Bugzilla/Attachment/Zip.pm @@ -0,0 +1,156 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This Source Code Form is "Incompatible With Secondary Licenses", as +# defined by the Mozilla Public License, v. 2.0. + +package Bugzilla::Attachment::Zip; + +use 5.10.1; +use strict; +use warnings; + +use Bugzilla::Attachment; +use Bugzilla::Error; +use Bugzilla::Util qw(datetime_from); + +use Encode qw(encode); +use IO::Compress::Zip qw($ZipError); +use List::Util qw(sum0); + +# Most filesystems cap one file name at 255 bytes. +use constant MAX_NAME_BYTES => 255; + +# Returns the attachments of $bug the current user may download as a ZIP: +# those get_attachments_by_bug lets them see, minus obsolete and deleted +# ones. The caller must already have checked that the user can see $bug +# (Bugzilla::Bug->check does). +sub attachments_for_bug { + my ($class, $bug) = @_; + my $user = Bugzilla->user; + my $attachments + = Bugzilla::Attachment->get_attachments_by_bug($bug, {exclude_obsolete => 1}); + + # get_attachments_by_bug checks privacy and obsolescence on the ids and then + # loads the rows in a second query, so check both again on the rows as + # loaded, as the bug page does. + return [ + grep { + $_->datasize + && !$_->isobsolete + && (!$_->isprivate || $user->is_insider || $_->attacher->id == $user->id) + } @$attachments + ]; +} + +# Throws a user error unless there is something to download and its total +# size is within the attachment_zip_max_size param (in kilobytes). Runs on +# datasize alone, so no attachment data is fetched from storage for a +# request that will be refused. +sub check_size { + my ($class, $attachments) = @_; + @$attachments || ThrowUserError('attachment_zip_empty'); + + $class->_check_limit(sum0(map { $_->datasize } @$attachments)); + return; +} + +# Throws a user error if $total_size bytes is over the attachment_zip_max_size +# param (in kilobytes). +sub _check_limit { + my ($class, $total_size) = @_; + my $max_size = Bugzilla->params->{attachment_zip_max_size} * 1024; + if ($total_size > $max_size) { + ThrowUserError('attachment_zip_too_large', + {total_size => $total_size, max_size => $max_size}); + } + return; +} + +# Returns the bytes of a ZIP file holding $attachments. Each member is named +# "-", so two attachments with the same filename do not +# overwrite each other when the archive is extracted. +# +# check_size works from datasize, which can differ from the bytes in storage +# (it counts characters for pasted text), so the bytes actually read are +# held to the same limit here. +sub build { + my ($class, $attachments) = @_; + my $read_size = 0; + my $output = ''; + my $zip; + + foreach my $attachment (@$attachments) { + + # Read through the storage, not $attachment->data, which would keep every + # attachment's data cached in memory alongside the ZIP until the request + # ends. Database and filesystem storage return undef for data that has + # gone since the attachment was loaded, such as one deleted meanwhile. + my $data = $attachment->current_storage->get_data; + if (!defined $data) { + ThrowCodeError('attachment_zip_missing_data', {attach_id => $attachment->id}); + } + + $class->_check_limit($read_size += length $data); + + # Efs marks the name as UTF-8 but does not encode it, so encode it here. + my %member = ( + Name => encode('UTF-8', $class->member_name($attachment)), + Time => datetime_from($attachment->attached)->epoch, + Efs => 1, + ); + + # IO::Compress::Zip takes the first member's header from new() and each + # later one from newStream(). + my $ok + = $zip + ? $zip->newStream(%member) + : ($zip = IO::Compress::Zip->new(\$output, %member)); + + $ok && $zip->print($data) + or ThrowCodeError('attachment_zip_failed', {zip_error => $ZipError}); + } + $zip && $zip->close() + or ThrowCodeError('attachment_zip_failed', {zip_error => $ZipError}); + + return \$output; +} + +# The name of $attachment inside the ZIP. Path separators and drive letters +# become "_", so no name can make an extractor write outside its target +# directory, and so do control characters and the other characters Windows +# does not allow in a file name. Trailing periods and spaces, which Windows +# drops or refuses, are removed. Names too long for a filesystem lose the end +# of their stem, keeping the extension. +sub member_name { + my ($class, $attachment) = @_; + my $filename = $attachment->filename // ''; + $filename =~ s/[\x00-\x1f\x7f<>:"\/\\|?*]/_/g; + $filename =~ s/[. ]+$//; + $filename = 'attachment' if $filename eq ''; + + my ($stem, $extension) + = ($attachment->id . '-' . $filename) =~ /^(.*?)((?:\.[^.]{1,16})?)$/s; + chop $stem while length(encode('UTF-8', $stem . $extension)) > MAX_NAME_BYTES; + + # Cutting the stem short can leave a period or space at the end again. + (my $name = $stem . $extension) =~ s/[. ]+$//; + return $name; +} + +1; + +__END__ + +=head1 NAME + +Bugzilla::Attachment::Zip - Download all of a bug's attachments as a ZIP + +=head1 SYNOPSIS + + my $bug = Bugzilla::Bug->check({id => $bug_id}); + my $attachments = Bugzilla::Attachment::Zip->attachments_for_bug($bug); + Bugzilla::Attachment::Zip->check_size($attachments); + my $zip_ref = Bugzilla::Attachment::Zip->build($attachments); + diff --git a/Bugzilla/Config/Attachment.pm b/Bugzilla/Config/Attachment.pm index c55b9e58cb..b76ef83c3d 100644 --- a/Bugzilla/Config/Attachment.pm +++ b/Bugzilla/Config/Attachment.pm @@ -26,6 +26,12 @@ sub get_param_list { default => '1000', checker => \&check_maxattachmentsize }, + { + name => 'attachment_zip_max_size', + type => 't', + default => '51200', + checker => \&check_numeric + }, { name => 'attachment_storage', type => 's', diff --git a/attachment.cgi b/attachment.cgi index 0c26500efb..ec5e2c0910 100755 --- a/attachment.cgi +++ b/attachment.cgi @@ -24,6 +24,7 @@ use Bugzilla::Bug; use Bugzilla::Field; use Bugzilla::Attachment; use Bugzilla::Attachment::PatchReader; +use Bugzilla::Attachment::Zip; use Bugzilla::Token; use Bugzilla::Keyword; use Bugzilla::Hook; @@ -92,6 +93,12 @@ elsif ($action eq "diff") { elsif ($action eq "viewall") { viewall(); } +elsif ($action eq "zip") { + + # Building a ZIP of every attachment is costly, so anonymous users may not. + Bugzilla->login(LOGIN_REQUIRED); + zip_all(); +} elsif ($action eq "enter") { Bugzilla->login(LOGIN_REQUIRED); enter(); @@ -496,6 +503,34 @@ sub viewall { || ThrowTemplateError($template->error()); } +# Download every attachment of a bug the user can access, except obsolete +# ones, as a single ZIP file. The ZIP is served as a download, never inline, +# so it does not need the attachment_base host. +sub zip_all { + my $bug = Bugzilla::Bug->check({id => scalar $cgi->param('bugid'), cache => 1}); + + my $attachments = Bugzilla::Attachment::Zip->attachments_for_bug($bug); + Bugzilla::Attachment::Zip->check_size($attachments); + my $zip_ref = Bugzilla::Attachment::Zip->build($attachments); + + foreach my $attachment (@$attachments) { + Bugzilla->log_user_request($bug->id, $attachment->id, 'attachment-get'); + } + + # A ZIP is binary: send no charset, as view() does. + $cgi->charset(''); + my $filename = 'bug-' . $bug->id . '-attachments.zip'; + print $cgi->header( + -type => 'application/zip', + -content_disposition => qq{attachment; filename="$filename"}, + -content_length => length($$zip_ref), + -Cache_Control => 'no-store, private', + -X_Content_Type_Options => 'nosniff', + ); + disable_utf8(); + print $$zip_ref; +} + # Display a form for entering a new attachment. sub enter { diff --git a/extensions/BugModal/template/en/default/bug_modal/attachments.html.tmpl b/extensions/BugModal/template/en/default/bug_modal/attachments.html.tmpl index 62768ddd0c..24460e21c2 100644 --- a/extensions/BugModal/template/en/default/bug_modal/attachments.html.tmpl +++ b/extensions/BugModal/template/en/default/bug_modal/attachments.html.tmpl @@ -12,6 +12,8 @@ # obsolete_attachments: count of obsolete attachment objects # external_attachments: count of non-obsolete external attachments # external_attachments_total: count of all external attachments (incl. obsolete) + # downloadable_attachments: count of active attachments with data, i.e. the + # ones the "Download All (ZIP)" button gets # attachment_hide_types: hash of content types hidden behind "Show External" #%] @@ -105,6 +107,11 @@ [% END %] + [% IF user.id && downloadable_attachments %] + [%# A plain button, not a form: this template sits inside #changeform. %] + + [% END %] [% IF external_attachments_total %] [% END %] diff --git a/extensions/BugModal/template/en/default/bug_modal/edit.html.tmpl b/extensions/BugModal/template/en/default/bug_modal/edit.html.tmpl index b15faae4c6..5004f55b0f 100644 --- a/extensions/BugModal/template/en/default/bug_modal/edit.html.tmpl +++ b/extensions/BugModal/template/en/default/bug_modal/edit.html.tmpl @@ -56,6 +56,9 @@ # External" button is still rendered (and the rows remain reachable) when # every external attachment happens to be obsolete. external_attachments_total = 0; + # downloadable_attachments matches what attachment.cgi?action=zip serves: + # active attachments whose data has not been deleted. + downloadable_attachments = 0; attachment_hide_types = {}; IF Param('attachment_hide_content_types'); @@ -74,6 +77,9 @@ obsolete_attachments = obsolete_attachments + 1; ELSE; active_attachments = active_attachments + 1; + IF attachment.datasize; + downloadable_attachments = downloadable_attachments + 1; + END; IF is_external; external_attachments = external_attachments + 1; END; @@ -1442,6 +1448,7 @@ obsolete_attachments = obsolete_attachments external_attachments = external_attachments external_attachments_total = external_attachments_total + downloadable_attachments = downloadable_attachments attachment_hide_types = attachment_hide_types %] [% END %] diff --git a/extensions/BugModal/web/bug_modal.js b/extensions/BugModal/web/bug_modal.js index 02b8af324f..32ae2dd18a 100644 --- a/extensions/BugModal/web/bug_modal.js +++ b/extensions/BugModal/web/bug_modal.js @@ -352,6 +352,11 @@ $(function() { updateAttachmentRows(); } + $('#attachments-zip-btn').click(function(event) { + event.preventDefault(); + window.location.href = this.dataset.href; + }); + // top btn $('#top-btn') .click(function(event) { diff --git a/t/bmo/attachment-zip.t b/t/bmo/attachment-zip.t new file mode 100644 index 0000000000..4ff7fd62f7 --- /dev/null +++ b/t/bmo/attachment-zip.t @@ -0,0 +1,413 @@ +#!/usr/bin/env perl +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This Source Code Form is "Incompatible With Secondary Licenses", as +# defined by the Mozilla Public License, v. 2.0. + +# Downloading all of a bug's attachments as one ZIP (attachment.cgi +# action=zip, Bugzilla::Attachment::Zip): which attachments each user gets, +# the attachment_zip_max_size cap, and what the ZIP holds. + +use 5.10.1; +use strict; +use warnings; +use utf8; +use lib qw(. lib local/lib/perl5); +use Test::More; + +use Bugzilla; +use Bugzilla::Attachment; +use Bugzilla::Attachment::Zip; +use Bugzilla::Bug; +use Bugzilla::Constants; +use Bugzilla::Group; +use Bugzilla::Test::Util qw(create_bug create_group create_user); +use Encode qw(decode); +use IO::Uncompress::Unzip qw($UnzipError); +use Mojo::UserAgent; +BEGIN { Bugzilla->extensions } + +Bugzilla->usage_mode(USAGE_MODE_TEST); +Bugzilla->error_mode(ERROR_MODE_DIE); + +my $dbh = Bugzilla->dbh; +my $admin = Bugzilla::User->check({id => 1}); +Bugzilla->set_user($admin); + +# Real passwords, so the HTTP tests at the end can log in as these users. +my $PASSWORD = 'attachzip.correct.horse.BATTERY'; +my $insider = create_user('attachzip-insider@mozilla.example', $PASSWORD); +my $attacher = create_user('attachzip-attacher@mozilla.example', $PASSWORD); +my $outsider = create_user('attachzip-outsider@mozilla.example', $PASSWORD); + +# The insider group is the site's own, so the web server the HTTP tests at +# the end talk to agrees on who is an insider. +my $insiders = Bugzilla::Group->new({name => Bugzilla->params->{insidergroup}}); +plan skip_all => 'insidergroup param must name a group' unless $insiders; +$dbh->do('INSERT IGNORE INTO user_group_map (user_id, group_id) VALUES (?, ?)', + undef, $insider->id, $insiders->id); +my $secure = group_with('attachzip-secure', $insider, $attacher); + +############################################################################### +# Helpers +############################################################################### + +# A bug group of our own with the given members. Reused on a rerun against +# the same DB. The members are fresh users, so their group membership isn't +# read before it is set. +sub group_with { + my ($name, @members) = @_; + my $group = Bugzilla::Group->new({name => $name}); + return $group if $group; + $group = create_group($name, isbuggroup => 1); + $dbh->do('INSERT INTO user_group_map (user_id, group_id) VALUES (?, ?)', + undef, $_->id, $group->id) + for @members; + return $group; +} + +# A public bug, or one in $group when given. The group is set straight in the +# DB, since a group of our own has no group controls on the product. +sub new_bug { + my ($group) = @_; + my $bug = create_bug( + short_desc => 'Attachment ZIP test', + bug_type => 'defect', + comment => 'Attachment ZIP test', + assigned_to => 'nobody@mozilla.org', + ); + if ($group) { + $dbh->do('INSERT INTO bug_group_map (bug_id, group_id) VALUES (?, ?)', + undef, $bug->id, $group->id); + } + return Bugzilla::Bug->new($bug->id); +} + +# Attaches $data to $bug as $submitter. isprivate, isobsolete and a deleted +# (zero) size are set straight in the DB: the point here is reading them, +# not the rules for setting them. +sub attach { + my ($bug, $submitter, $filename, $data, %flags) = @_; + Bugzilla->set_user($submitter); + my $attachment = Bugzilla::Attachment->create({ + bug => $bug, + data => $data, + description => $filename, + filename => $filename, + ispatch => 0, + isprivate => 0, + mimetype => 'application/octet-stream', + }); + Bugzilla->set_user($admin); + my %set = ( + private => 'isprivate = 1', + obsolete => 'isobsolete = 1', + deleted => 'attach_size = 0', + ); + $dbh->do("UPDATE attachments SET $set{$_} WHERE attach_id = ?", + undef, $attachment->id) + for grep { $flags{$_} } sort keys %set; + return $attachment->id; +} + +# The ids of the attachments $user would get in the ZIP of $bug. +sub zip_ids_for { + my ($user, $bug) = @_; + Bugzilla->set_user(Bugzilla::User->new($user->id)); + my $ids + = [map { $_->id } @{Bugzilla::Attachment::Zip->attachments_for_bug($bug)}]; + Bugzilla->set_user($admin); + return [sort { $a <=> $b } @$ids]; +} + +# name => data of every member of the ZIP in $zip_ref. +sub unzip_members { + my ($zip_ref) = @_; + my $unzip = IO::Uncompress::Unzip->new($zip_ref) or die "unzip: $UnzipError"; + my %members; + my $status = 1; + while ($status > 0) { + my $name = decode('UTF-8', $unzip->getHeaderInfo->{Name}); + local $/; + $members{$name} = <$unzip> // ''; + $status = $unzip->nextStream; + } + die "unzip: $UnzipError" if $status < 0; + return \%members; +} + +# The error $code dies with, or undef if it doesn't. +sub error_of { + my ($code) = @_; + return eval { $code->(); 1 } ? undef : $@; +} + +############################################################################### +# Which attachments each user gets +############################################################################### + +my $bug = new_bug(); +my $public_id = attach($bug, $admin, 'public.txt', "public\n"); +my $private_id = attach($bug, $admin, 'private.txt', "private\n", private => 1); +my $own_id = attach($bug, $attacher, 'own.txt', "own\n", private => 1); +my $obsolete_id = attach($bug, $admin, 'obsolete.txt', "old\n", obsolete => 1); +attach($bug, $admin, 'deleted.txt', "gone\n", deleted => 1); + +my $secure_bug = new_bug($secure); +my $secret_id = attach($secure_bug, $admin, 'secret.txt', "secret\n"); + +is_deeply( + zip_ids_for($insider, $bug), + [$public_id, $private_id, $own_id], + 'insider gets public and private attachments, not obsolete or deleted ones' +); +is_deeply(zip_ids_for($outsider, $bug), + [$public_id], 'non-insider gets public attachments only'); +is_deeply( + zip_ids_for($attacher, $bug), + [$public_id, $own_id], + 'non-insider also gets private attachments they attached' +); + +# Privacy and obsolescence are checked again on the loaded rows, so an +# attachment made private or obsolete after get_attachments_by_bug picked its +# ids is still left out. +{ + no warnings 'redefine'; + local *Bugzilla::Attachment::get_attachments_by_bug = sub { + Bugzilla::Attachment->new_from_list([$public_id, $private_id, $obsolete_id]); + }; + is_deeply(zip_ids_for($outsider, $bug), + [$public_id], + 'private and obsolete rows are dropped even when the id query let them in'); +} + +# attachment.cgi checks the bug with Bugzilla::Bug->check before asking for +# its attachments; a user who cannot see the bug gets nothing. +{ + Bugzilla->set_user(Bugzilla::User->new($outsider->id)); + ok( + !eval { Bugzilla::Bug->check({id => $secure_bug->id}); 1 }, + 'user outside the bug group cannot load the bug' + ); + Bugzilla->set_user(Bugzilla::User->new($attacher->id)); + ok(eval { Bugzilla::Bug->check({id => $secure_bug->id}); 1 }, + 'user in the bug group can'); + Bugzilla->set_user($admin); +} + +############################################################################### +# Size cap +############################################################################### + +{ + my $check_size_of = sub { + my ($bug) = @_; + return error_of(sub { + Bugzilla::Attachment::Zip->check_size( + Bugzilla::Attachment::Zip->attachments_for_bug($bug)); + }); + }; + local Bugzilla->params->{attachment_zip_max_size} = 1; + + is($check_size_of->($bug), undef, 'within the cap: no error'); + + my $big = new_bug(); + attach($big, $admin, 'big.bin', 'x' x 2048); + like($check_size_of->($big), + qr/2\.00 KB/, 'over the cap: attachment_zip_too_large'); + + like( + $check_size_of->(new_bug()), + qr/no attachments you can download/, + 'no attachments: attachment_zip_empty' + ); + + # datasize can be smaller than the bytes in storage, so build holds the + # bytes it reads to the cap too. + my $understated = new_bug(); + my $understated_id = attach($understated, $admin, 'big.bin', 'x' x 2048); + $dbh->do('UPDATE attachments SET attach_size = 10 WHERE attach_id = ?', + undef, $understated_id); + my $attachments = Bugzilla::Attachment::Zip->attachments_for_bug($understated); + is($check_size_of->($understated), undef, 'understated size passes check_size'); + like(error_of(sub { Bugzilla::Attachment::Zip->build($attachments) }), + qr/2\.00 KB/, 'but build stops once the bytes read pass the cap'); +} + +# Data that is gone by the time the ZIP is built is an error, not an empty +# member. +{ + my $vanished = new_bug(); + my $vanished_id = attach($vanished, $admin, 'vanished.txt', "here\n"); + my $attachments = Bugzilla::Attachment::Zip->attachments_for_bug($vanished); + $attachments->[0]->current_storage->remove_data; + like( + error_of(sub { Bugzilla::Attachment::Zip->build($attachments) }), + qr/attachment $vanished_id could not be read/, + 'missing data: attachment_zip_missing_data' + ); +} + +############################################################################### +# ZIP contents +############################################################################### + +{ + my $dupes = new_bug(); + my $first = attach($dupes, $admin, 'poc.html', "

one

\n"); + my $second = attach($dupes, $admin, 'poc.html', "

two

\n"); + my $unicode = attach($dupes, $admin, 'résumé.txt', "unicode\n"); + my $binary = attach($dupes, $admin, 'blob.bin', "\x00\xff\x01\xfe"); + + my $attachments = Bugzilla::Attachment::Zip->attachments_for_bug($dupes); + my $members = unzip_members(Bugzilla::Attachment::Zip->build($attachments)); + + is_deeply( + $members, + { + "$first-poc.html" => "

one

\n", + "$second-poc.html" => "

two

\n", + "$unicode-résumé.txt" => "unicode\n", + "$binary-blob.bin" => "\x00\xff\x01\xfe", + }, + 'one member per attachment, named by id, with its exact data' + ); + ok(!grep({ defined $_->{data} } @$attachments), + 'building the ZIP leaves no attachment data cached in memory'); +} + +############################################################################### +# Member names cannot escape the extraction directory +############################################################################### + +{ + my %cases = ( + 'evil.txt' => 'evil.txt', + '..' => 'attachment', + '' => 'attachment', + "a\x00b\nc.txt" => 'a_b_c.txt', + 'C:evil.txt' => 'C_evil.txt', + 'dir\\evil.txt' => 'dir_evil.txt', + '../../evil' => '.._.._evil', + 'ac"d|e?f*g' => 'a_b_c_d_e_f_g', + 'report.txt.' => 'report.txt', + 'notes . . ' => 'notes', + '. .' => 'attachment', + ); + foreach my $filename (sort keys %cases) { + my $label = $filename =~ s/([^ -~])/sprintf('\\x%02x', ord $1)/ger; + my $fake = bless {attach_id => 7, filename => $filename}, + 'Bugzilla::Attachment'; + is(Bugzilla::Attachment::Zip->member_name($fake), + "7-$cases{$filename}", "member name for '$label'"); + } + + # Attachment filenames may be 100 characters, which can be 400 UTF-8 bytes. + my $long = bless {attach_id => 7, filename => ('界' x 99) . '.txt'}, + 'Bugzilla::Attachment'; + my $name = Bugzilla::Attachment::Zip->member_name($long); + ok( + length(Encode::encode('UTF-8', $name)) <= 255, + 'a long multibyte name fits in 255 bytes' + ); + like($name, qr/^7-界+\.txt$/, 'and keeps its id and extension'); + + # Cut short exactly at a space, with no extension to keep: 2 bytes of + # "7-", 252 of 界, then the space would end the name. + my $cut = bless {attach_id => 7, filename => ('界' x 84) . ' ' . ('x' x 20)}, + 'Bugzilla::Attachment'; + is( + Bugzilla::Attachment::Zip->member_name($cut), + '7-' . ('界' x 84), + 'shortening does not leave a trailing space' + ); +} + +############################################################################### +# attachment.cgi?action=zip over HTTP, against the server test_bmo starts +############################################################################### + +SKIP: { + skip 'BZ_BASE_URL is not set: no web server to test against', 1 + unless $ENV{BZ_BASE_URL}; + + # A user agent logged in as $user, or anonymous without one. + my $agent_for = sub { + my ($user) = @_; + my $ua = Mojo::UserAgent->new(max_redirects => 0); + return $ua unless $user; + my $form = $ua->get("$ENV{BZ_BASE_URL}index.cgi?GoAheadAndLogIn=1")->result; + my $token = $form->dom->at('input[name="Bugzilla_login_token"]')->attr('value'); + $ua->post( + "$ENV{BZ_BASE_URL}index.cgi" => form => { + Bugzilla_login => $user->login, + Bugzilla_password => $PASSWORD, + Bugzilla_login_token => $token, + GoAheadAndLogIn => 'Log In', + } + ); + return $ua; + }; + my $zip_of = sub { + my ($ua, $bug) = @_; + return $ua->get("$ENV{BZ_BASE_URL}attachment.cgi?action=zip&bugid=" . $bug->id) + ->result; + }; + + my $res = $zip_of->($agent_for->($outsider), $bug); + is($res->code, 200, 'outsider: ZIP of a public bug is served'); + is($res->headers->content_type, 'application/zip', 'as application/zip'); + like( + $res->headers->content_disposition, + qr/^attachment; filename="bug-\d+-attachments\.zip"$/, + 'as a download, never inline' + ); + is($res->headers->header('X-Content-Type-Options'), 'nosniff', 'nosniff'); + is_deeply([sort keys %{unzip_members(\$res->body)}], + ["$public_id-public.txt"], + 'outsider: only the public attachment is in the ZIP'); + + $res = $zip_of->($agent_for->($insider), $bug); + is_deeply( + [sort keys %{unzip_members(\$res->body)}], + [sort "$public_id-public.txt", "$private_id-private.txt", "$own_id-own.txt"], + 'insider: public and private attachments are in the ZIP' + ); + + $res = $zip_of->($agent_for->($outsider), $secure_bug); + isnt($res->headers->content_type // '', + 'application/zip', 'outsider: no ZIP of a bug they cannot see'); + unlike($res->body, qr/secret/, 'and no attachment data leaks'); + + $res = $zip_of->($agent_for->($attacher), $secure_bug); + is_deeply([sort keys %{unzip_members(\$res->body)}], + ["$secret_id-secret.txt"], 'bug group member: ZIP of the bug they can see'); + + $res = $zip_of->($agent_for->(), $bug); + isnt($res->headers->content_type // '', + 'application/zip', 'anonymous: no ZIP, login is required'); + + # The button is shown only when the ZIP would hold something. + my $deleted_only = new_bug(); + attach($deleted_only, $admin, 'gone.txt', "gone\n", deleted => 1); + my $ua = $agent_for->($outsider); + my $zip_button = sub { + my ($bug) = @_; + return $ua->get("$ENV{BZ_BASE_URL}show_bug.cgi?id=" . $bug->id) + ->result->dom->at('#attachments-zip-btn'); + }; + my $button = $zip_button->($bug); + ok($button, 'button shown on a bug with attachments'); + like( + $button ? $button->attr('data-href') : '', + qr{attachment\.cgi\?bugid=@{[$bug->id]}&action=zip$}, + 'and it points at the ZIP of that bug' + ); + ok(!$zip_button->($deleted_only), + 'no button when the only active attachment is deleted'); +} + +done_testing; diff --git a/template/en/default/admin/params/attachment.html.tmpl b/template/en/default/admin/params/attachment.html.tmpl index a905d58cbd..e978dd3a33 100644 --- a/template/en/default/admin/params/attachment.html.tmpl +++ b/template/en/default/admin/params/attachment.html.tmpl @@ -42,6 +42,11 @@ maxattachmentsize => "The maximum size (in kilobytes) of attachments.", + attachment_zip_max_size => + "The maximum total size (in kilobytes) of the attachments a user can " _ + "download from a bug as one ZIP file. The ZIP is built in memory by the " _ + "web server, so this bounds the memory one download can use.", + attachment_storage => "Where attachment data should be stored. If this value is changed you " _ "must use scripts/migrate-attachments to migrate existing " _ diff --git a/template/en/default/global/code-error.html.tmpl b/template/en/default/global/code-error.html.tmpl index 090b24212d..e69087ee3c 100644 --- a/template/en/default/global/code-error.html.tmpl +++ b/template/en/default/global/code-error.html.tmpl @@ -50,6 +50,16 @@ [% END %] It also must not contain any illegal characters. + [% ELSIF error == "attachment_zip_failed" %] + [% title = "ZIP Creation Failed" %] + The attachments could not be packed into a ZIP file: + [% zip_error FILTER html %] + + [% ELSIF error == "attachment_zip_missing_data" %] + [% title = "Attachment Data Missing" %] + The data of attachment [% attach_id FILTER html %] could not be read, + so no ZIP file was made. + [% ELSIF error == "authres_unhandled" %] The result value of [% value FILTER html %] was not handled by the login code. diff --git a/template/en/default/global/user-error.html.tmpl b/template/en/default/global/user-error.html.tmpl index 82acd56839..6fc1cf17f1 100644 --- a/template/en/default/global/user-error.html.tmpl +++ b/template/en/default/global/user-error.html.tmpl @@ -279,6 +279,17 @@ [% title = "Attachment Deletion Disabled" %] Attachment deletion is disabled on this installation. + [% ELSIF error == "attachment_zip_empty" %] + [% title = "No Attachments To Download" %] + This [% terms.bug %] has no attachments you can download. + + [% ELSIF error == "attachment_zip_too_large" %] + [% title = "Attachments Too Large" %] + The attachments on this [% terms.bug %] total + [%+ total_size FILTER unitconvert %], which is more than the + [%+ max_size FILTER unitconvert %] that can be downloaded as one ZIP file. + Please download them individually. + [% ELSIF error == "attachment_removed" %] [% title = "Attachment Removed" %] The attachment you are attempting to access has been removed.