From 53c773d681a5ecfbdce61e91b06c8120787e3b0a Mon Sep 17 00:00:00 2001 From: David Lawrence Date: Wed, 2 Dec 2026 21:38:51 -0500 Subject: [PATCH 1/4] Bug 2100601 - Add a button to download all of a bug's attachments as a ZIP file --- Bugzilla/Attachment/Zip.pm | 107 ++++++ Bugzilla/Config/Attachment.pm | 6 + attachment.cgi | 35 ++ .../default/bug_modal/attachments.html.tmpl | 5 + t/bmo/attachment-zip.t | 331 ++++++++++++++++++ .../default/admin/params/attachment.html.tmpl | 5 + .../en/default/global/code-error.html.tmpl | 5 + .../en/default/global/user-error.html.tmpl | 11 + 8 files changed, 505 insertions(+) create mode 100644 Bugzilla/Attachment/Zip.pm create mode 100644 t/bmo/attachment-zip.t diff --git a/Bugzilla/Attachment/Zip.pm b/Bugzilla/Attachment/Zip.pm new file mode 100644 index 0000000000..5ccf09d5f1 --- /dev/null +++ b/Bugzilla/Attachment/Zip.pm @@ -0,0 +1,107 @@ +# 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); + +# 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 $attachments + = Bugzilla::Attachment->get_attachments_by_bug($bug, {exclude_obsolete => 1}); + return [grep { $_->datasize } @$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'); + + my $max_size = Bugzilla->params->{attachment_zip_max_size} * 1024; + my $total_size = sum0(map { $_->datasize } @$attachments); + 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. +sub build { + my ($class, $attachments) = @_; + my $output = ''; + my $zip; + + foreach my $attachment (@$attachments) { + + # 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($attachment->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, drive letters and +# control characters become "_", so no name can make an extractor write +# outside its target directory. +sub member_name { + my ($class, $attachment) = @_; + my $filename = $attachment->filename // ''; + $filename =~ s/[\x00-\x1f\x7f\/\\:]/_/g; + $filename = 'attachment' if $filename =~ /^\.*$/; + return $attachment->id . '-' . $filename; +} + +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..e4157d9a56 100644 --- a/extensions/BugModal/template/en/default/bug_modal/attachments.html.tmpl +++ b/extensions/BugModal/template/en/default/bug_modal/attachments.html.tmpl @@ -105,6 +105,11 @@ [% END %] + [% IF user.id && active_attachments %] + + + + [% END %] [% IF external_attachments_total %] [% END %] diff --git a/t/bmo/attachment-zip.t b/t/bmo/attachment-zip.t new file mode 100644 index 0000000000..fa45c660c4 --- /dev/null +++ b/t/bmo/attachment-zip.t @@ -0,0 +1,331 @@ +#!/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); +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' +); + +# 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' + ); +} + +############################################################################### +# 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 $members = unzip_members(Bugzilla::Attachment::Zip->build( + Bugzilla::Attachment::Zip->attachments_for_bug($dupes) + )); + + 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' + ); +} + +############################################################################### +# 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', + ); + 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.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'); +} + +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..b05759db37 100644 --- a/template/en/default/global/code-error.html.tmpl +++ b/template/en/default/global/code-error.html.tmpl @@ -50,6 +50,11 @@ [% 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 == "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 ae54fee884..543c2f6a6e 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. From 2a939b87fa05b5cc5c22ca160f443212eee64792 Mon Sep 17 00:00:00 2001 From: David Lawrence Date: Thu, 3 Dec 2026 17:34:40 -0500 Subject: [PATCH 2/4] Bug 2100601 - Address review feedback on the attachment ZIP download - Read attachment data through the storage while building the ZIP, so each attachment's data is not cached in memory alongside the archive. - Replace characters Windows does not allow in member names, and trim names to 255 UTF-8 bytes, keeping the id prefix and extension. - Show the "Download All (ZIP)" button only when at least one active attachment still has data, matching what the endpoint serves. - Use a single button instead of a link wrapping a button, so the control has one tab stop. --- Bugzilla/Attachment/Zip.pm | 24 +++++++++--- .../default/bug_modal/attachments.html.tmpl | 10 +++-- .../en/default/bug_modal/edit.html.tmpl | 7 ++++ extensions/BugModal/web/bug_modal.js | 5 +++ t/bmo/attachment-zip.t | 37 +++++++++++++++++-- 5 files changed, 70 insertions(+), 13 deletions(-) diff --git a/Bugzilla/Attachment/Zip.pm b/Bugzilla/Attachment/Zip.pm index 5ccf09d5f1..a1f9fc25ef 100644 --- a/Bugzilla/Attachment/Zip.pm +++ b/Bugzilla/Attachment/Zip.pm @@ -19,6 +19,9 @@ 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 @@ -70,7 +73,10 @@ sub build { = $zip ? $zip->newStream(%member) : ($zip = IO::Compress::Zip->new(\$output, %member)); - $ok && $zip->print($attachment->data) + + # Read through the storage, not $attachment->data, which would keep every + # attachment's data cached in memory alongside the ZIP until the request ends. + $ok && $zip->print($attachment->current_storage->get_data) or ThrowCodeError('attachment_zip_failed', {zip_error => $ZipError}); } $zip && $zip->close() @@ -79,15 +85,21 @@ sub build { return \$output; } -# The name of $attachment inside the ZIP. Path separators, drive letters and -# control characters become "_", so no name can make an extractor write -# outside its target directory. +# 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. 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/[\x00-\x1f\x7f<>:"\/\\|?*]/_/g; $filename = 'attachment' if $filename =~ /^\.*$/; - return $attachment->id . '-' . $filename; + + my ($stem, $extension) + = ($attachment->id . '-' . $filename) =~ /^(.*?)((?:\.[^.]{1,16})?)$/s; + chop $stem while length(encode('UTF-8', $stem . $extension)) > MAX_NAME_BYTES; + return $stem . $extension; } 1; 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 e4157d9a56..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,10 +107,10 @@ [% END %] - [% IF user.id && active_attachments %] - - - + [% IF user.id && downloadable_attachments %] + [%# A plain button, not a form: this template sits inside #changeform. %] + [% END %] [% IF external_attachments_total %] 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 index fa45c660c4..e1da7e0a82 100644 --- a/t/bmo/attachment-zip.t +++ b/t/bmo/attachment-zip.t @@ -224,9 +224,8 @@ is_deeply( my $unicode = attach($dupes, $admin, 'résumé.txt', "unicode\n"); my $binary = attach($dupes, $admin, 'blob.bin', "\x00\xff\x01\xfe"); - my $members = unzip_members(Bugzilla::Attachment::Zip->build( - Bugzilla::Attachment::Zip->attachments_for_bug($dupes) - )); + my $attachments = Bugzilla::Attachment::Zip->attachments_for_bug($dupes); + my $members = unzip_members(Bugzilla::Attachment::Zip->build($attachments)); is_deeply( $members, @@ -238,6 +237,8 @@ is_deeply( }, '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'); } ############################################################################### @@ -253,6 +254,7 @@ is_deeply( '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', ); foreach my $filename (sort keys %cases) { my $label = $filename =~ s/([^ -~])/sprintf('\\x%02x', ord $1)/ger; @@ -261,6 +263,16 @@ is_deeply( 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'); } ############################################################################### @@ -326,6 +338,25 @@ SKIP: { $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; From 04a7352305ec3bd0a76d6da251b2866af4bf8ac6 Mon Sep 17 00:00:00 2001 From: David Lawrence Date: Thu, 3 Dec 2026 18:24:44 -0500 Subject: [PATCH 3/4] Bug 2100601 - Address further review feedback on the attachment ZIP download - Recheck attachment privacy on the loaded rows, closing the window between get_attachments_by_bug's id query and its row load. - Hold the bytes actually read from storage to attachment_zip_max_size, since datasize can count characters rather than bytes. - Throw attachment_zip_missing_data when an attachment's data is gone during the build, instead of writing an empty member. - Strip trailing periods and spaces from member names, again after truncation. --- Bugzilla/Attachment/Zip.pm | 58 +++++++++++++++---- t/bmo/attachment-zip.t | 48 +++++++++++++++ .../en/default/global/code-error.html.tmpl | 5 ++ 3 files changed, 100 insertions(+), 11 deletions(-) diff --git a/Bugzilla/Attachment/Zip.pm b/Bugzilla/Attachment/Zip.pm index a1f9fc25ef..9cf2a3ce20 100644 --- a/Bugzilla/Attachment/Zip.pm +++ b/Bugzilla/Attachment/Zip.pm @@ -28,9 +28,19 @@ use constant MAX_NAME_BYTES => 255; # (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}); - return [grep { $_->datasize } @$attachments]; + + # get_attachments_by_bug checks privacy on the ids and then loads the rows + # in a second query, so check it again on the rows as loaded, as the bug + # page does. + return [ + grep { + $_->datasize + && (!$_->isprivate || $user->is_insider || $_->attacher->id == $user->id) + } @$attachments + ]; } # Throws a user error unless there is something to download and its total @@ -41,8 +51,15 @@ sub check_size { my ($class, $attachments) = @_; @$attachments || ThrowUserError('attachment_zip_empty'); - my $max_size = Bugzilla->params->{attachment_zip_max_size} * 1024; - my $total_size = sum0(map { $_->datasize } @$attachments); + $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}); @@ -53,13 +70,29 @@ sub check_size { # 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 $output = ''; + 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)), @@ -74,9 +107,7 @@ sub build { ? $zip->newStream(%member) : ($zip = IO::Compress::Zip->new(\$output, %member)); - # Read through the storage, not $attachment->data, which would keep every - # attachment's data cached in memory alongside the ZIP until the request ends. - $ok && $zip->print($attachment->current_storage->get_data) + $ok && $zip->print($data) or ThrowCodeError('attachment_zip_failed', {zip_error => $ZipError}); } $zip && $zip->close() @@ -88,18 +119,23 @@ sub build { # 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. Names too long for a filesystem lose the -# end of their stem, keeping the extension. +# 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 = 'attachment' if $filename =~ /^\.*$/; + $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; - return $stem . $extension; + + # Cutting the stem short can leave a period or space at the end again. + (my $name = $stem . $extension) =~ s/[. ]+$//; + return $name; } 1; diff --git a/t/bmo/attachment-zip.t b/t/bmo/attachment-zip.t index e1da7e0a82..469ceaa27e 100644 --- a/t/bmo/attachment-zip.t +++ b/t/bmo/attachment-zip.t @@ -171,6 +171,16 @@ is_deeply( 'non-insider also gets private attachments they attached' ); +# Privacy is checked again on the loaded rows, so an attachment made private +# 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]) }; + is_deeply(zip_ids_for($outsider, $bug), + [$public_id], 'private 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. { @@ -211,6 +221,31 @@ is_deeply( 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' + ); } ############################################################################### @@ -255,6 +290,9 @@ is_deeply( '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; @@ -273,6 +311,16 @@ is_deeply( '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' + ); } ############################################################################### diff --git a/template/en/default/global/code-error.html.tmpl b/template/en/default/global/code-error.html.tmpl index b05759db37..e69087ee3c 100644 --- a/template/en/default/global/code-error.html.tmpl +++ b/template/en/default/global/code-error.html.tmpl @@ -55,6 +55,11 @@ 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. From 22a58975c5b69db38b5fc3a26099c1f212739a80 Mon Sep 17 00:00:00 2001 From: David Lawrence Date: Fri, 4 Dec 2026 11:10:04 -0500 Subject: [PATCH 4/4] Bug 2100601 - Recheck obsolescence on loaded attachments in the ZIP download get_attachments_by_bug applies exclude_obsolete to its id query and loads the rows in a second query, so an attachment made obsolete in between was still added to the ZIP. Check isobsolete again on the loaded rows, as is already done for privacy. --- Bugzilla/Attachment/Zip.pm | 9 +++++---- t/bmo/attachment-zip.t | 17 ++++++++++------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/Bugzilla/Attachment/Zip.pm b/Bugzilla/Attachment/Zip.pm index 9cf2a3ce20..259b01a3ae 100644 --- a/Bugzilla/Attachment/Zip.pm +++ b/Bugzilla/Attachment/Zip.pm @@ -32,12 +32,13 @@ sub attachments_for_bug { my $attachments = Bugzilla::Attachment->get_attachments_by_bug($bug, {exclude_obsolete => 1}); - # get_attachments_by_bug checks privacy on the ids and then loads the rows - # in a second query, so check it again on the rows as loaded, as the bug - # page does. + # 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 + $_->datasize + && !$_->isobsolete && (!$_->isprivate || $user->is_insider || $_->attacher->id == $user->id) } @$attachments ]; diff --git a/t/bmo/attachment-zip.t b/t/bmo/attachment-zip.t index 469ceaa27e..4ff7fd62f7 100644 --- a/t/bmo/attachment-zip.t +++ b/t/bmo/attachment-zip.t @@ -152,8 +152,8 @@ 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); -attach($bug, $admin, 'obsolete.txt', "old\n", obsolete => 1); -attach($bug, $admin, 'deleted.txt', "gone\n", deleted => 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"); @@ -171,14 +171,17 @@ is_deeply( 'non-insider also gets private attachments they attached' ); -# Privacy is checked again on the loaded rows, so an attachment made private -# after get_attachments_by_bug picked its ids is still left out. +# 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]) }; + 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 rows are dropped even when the id query let them in'); + [$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