first commit
This commit is contained in:
54
services/filestore/.gitignore
vendored
Normal file
54
services/filestore/.gitignore
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
compileFolder
|
||||
|
||||
Compiled source #
|
||||
###################
|
||||
*.com
|
||||
*.class
|
||||
*.dll
|
||||
*.exe
|
||||
*.o
|
||||
*.so
|
||||
|
||||
# Packages #
|
||||
############
|
||||
# it's better to unpack these files and commit the raw source
|
||||
# git has its own built in compression methods
|
||||
*.7z
|
||||
*.dmg
|
||||
*.gz
|
||||
*.iso
|
||||
*.jar
|
||||
*.rar
|
||||
*.tar
|
||||
*.zip
|
||||
|
||||
# Logs and databases #
|
||||
######################
|
||||
*.log
|
||||
*.sql
|
||||
*.sqlite
|
||||
|
||||
# OS generated files #
|
||||
######################
|
||||
.DS_Store?
|
||||
ehthumbs.db
|
||||
Icon?
|
||||
Thumbs.db
|
||||
|
||||
/node_modules/*
|
||||
data/*/*
|
||||
|
||||
**/*.map
|
||||
cookies.txt
|
||||
uploads/*
|
||||
|
||||
user_files/*
|
||||
template_files/*
|
||||
|
||||
**.swp
|
||||
|
||||
/log.json
|
||||
hash_folder
|
||||
|
||||
# managed by dev-environment$ bin/update_build_scripts
|
||||
.npmrc
|
3
services/filestore/.mocharc.json
Normal file
3
services/filestore/.mocharc.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"require": "test/setup.js"
|
||||
}
|
1
services/filestore/.nvmrc
Normal file
1
services/filestore/.nvmrc
Normal file
@@ -0,0 +1 @@
|
||||
20.18.2
|
1
services/filestore/.prettierignore
Normal file
1
services/filestore/.prettierignore
Normal file
@@ -0,0 +1 @@
|
||||
node_modules
|
31
services/filestore/Dockerfile
Normal file
31
services/filestore/Dockerfile
Normal file
@@ -0,0 +1,31 @@
|
||||
# This file was auto-generated, do not edit it directly.
|
||||
# Instead run bin/update_build_scripts from
|
||||
# https://github.com/overleaf/internal/
|
||||
|
||||
FROM node:20.18.2 AS base
|
||||
|
||||
WORKDIR /overleaf/services/filestore
|
||||
COPY services/filestore/install_deps.sh /overleaf/services/filestore/
|
||||
RUN chmod 0755 ./install_deps.sh && ./install_deps.sh
|
||||
|
||||
# Google Cloud Storage needs a writable $HOME/.config for resumable uploads
|
||||
# (see https://googleapis.dev/nodejs/storage/latest/File.html#createWriteStream)
|
||||
RUN mkdir /home/node/.config && chown node:node /home/node/.config
|
||||
|
||||
FROM base AS app
|
||||
|
||||
COPY package.json package-lock.json /overleaf/
|
||||
COPY services/filestore/package.json /overleaf/services/filestore/
|
||||
COPY libraries/ /overleaf/libraries/
|
||||
COPY patches/ /overleaf/patches/
|
||||
|
||||
RUN cd /overleaf && npm ci --quiet
|
||||
|
||||
COPY services/filestore/ /overleaf/services/filestore/
|
||||
|
||||
FROM app
|
||||
RUN mkdir -p uploads user_files template_files \
|
||||
&& chown node:node uploads user_files template_files
|
||||
USER node
|
||||
|
||||
CMD ["node", "--expose-gc", "app.js"]
|
662
services/filestore/LICENSE
Normal file
662
services/filestore/LICENSE
Normal file
@@ -0,0 +1,662 @@
|
||||
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
156
services/filestore/Makefile
Normal file
156
services/filestore/Makefile
Normal file
@@ -0,0 +1,156 @@
|
||||
# This file was auto-generated, do not edit it directly.
|
||||
# Instead run bin/update_build_scripts from
|
||||
# https://github.com/overleaf/internal/
|
||||
|
||||
BUILD_NUMBER ?= local
|
||||
BRANCH_NAME ?= $(shell git rev-parse --abbrev-ref HEAD)
|
||||
PROJECT_NAME = filestore
|
||||
BUILD_DIR_NAME = $(shell pwd | xargs basename | tr -cd '[a-zA-Z0-9_.\-]')
|
||||
|
||||
DOCKER_COMPOSE_FLAGS ?= -f docker-compose.yml
|
||||
DOCKER_COMPOSE := BUILD_NUMBER=$(BUILD_NUMBER) \
|
||||
BRANCH_NAME=$(BRANCH_NAME) \
|
||||
PROJECT_NAME=$(PROJECT_NAME) \
|
||||
MOCHA_GREP=${MOCHA_GREP} \
|
||||
docker compose ${DOCKER_COMPOSE_FLAGS}
|
||||
|
||||
COMPOSE_PROJECT_NAME_TEST_ACCEPTANCE ?= test_acceptance_$(BUILD_DIR_NAME)
|
||||
DOCKER_COMPOSE_TEST_ACCEPTANCE = \
|
||||
COMPOSE_PROJECT_NAME=$(COMPOSE_PROJECT_NAME_TEST_ACCEPTANCE) $(DOCKER_COMPOSE)
|
||||
|
||||
COMPOSE_PROJECT_NAME_TEST_UNIT ?= test_unit_$(BUILD_DIR_NAME)
|
||||
DOCKER_COMPOSE_TEST_UNIT = \
|
||||
COMPOSE_PROJECT_NAME=$(COMPOSE_PROJECT_NAME_TEST_UNIT) $(DOCKER_COMPOSE)
|
||||
|
||||
clean:
|
||||
-docker rmi ci/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER)
|
||||
-docker rmi us-east1-docker.pkg.dev/overleaf-ops/ol-docker/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER)
|
||||
-$(DOCKER_COMPOSE_TEST_UNIT) down --rmi local
|
||||
-$(DOCKER_COMPOSE_TEST_ACCEPTANCE) down --rmi local
|
||||
|
||||
HERE=$(shell pwd)
|
||||
MONOREPO=$(shell cd ../../ && pwd)
|
||||
# Run the linting commands in the scope of the monorepo.
|
||||
# Eslint and prettier (plus some configs) are on the root.
|
||||
RUN_LINTING = docker run --rm -v $(MONOREPO):$(MONOREPO) -w $(HERE) node:20.18.2 npm run --silent
|
||||
|
||||
RUN_LINTING_CI = docker run --rm --volume $(MONOREPO)/.editorconfig:/overleaf/.editorconfig --volume $(MONOREPO)/.eslintignore:/overleaf/.eslintignore --volume $(MONOREPO)/.eslintrc:/overleaf/.eslintrc --volume $(MONOREPO)/.prettierignore:/overleaf/.prettierignore --volume $(MONOREPO)/.prettierrc:/overleaf/.prettierrc --volume $(MONOREPO)/tsconfig.backend.json:/overleaf/tsconfig.backend.json ci/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER) npm run --silent
|
||||
|
||||
# Same but from the top of the monorepo
|
||||
RUN_LINTING_MONOREPO = docker run --rm -v $(MONOREPO):$(MONOREPO) -w $(MONOREPO) node:20.18.2 npm run --silent
|
||||
|
||||
SHELLCHECK_OPTS = \
|
||||
--shell=bash \
|
||||
--external-sources
|
||||
SHELLCHECK_COLOR := $(if $(CI),--color=never,--color)
|
||||
SHELLCHECK_FILES := { git ls-files "*.sh" -z; git grep -Plz "\A\#\!.*bash"; } | sort -zu
|
||||
|
||||
shellcheck:
|
||||
@$(SHELLCHECK_FILES) | xargs -0 -r docker run --rm -v $(HERE):/mnt -w /mnt \
|
||||
koalaman/shellcheck:stable $(SHELLCHECK_OPTS) $(SHELLCHECK_COLOR)
|
||||
|
||||
shellcheck_fix:
|
||||
@$(SHELLCHECK_FILES) | while IFS= read -r -d '' file; do \
|
||||
diff=$$(docker run --rm -v $(HERE):/mnt -w /mnt koalaman/shellcheck:stable $(SHELLCHECK_OPTS) --format=diff "$$file" 2>/dev/null); \
|
||||
if [ -n "$$diff" ] && ! echo "$$diff" | patch -p1 >/dev/null 2>&1; then echo "\033[31m$$file\033[0m"; \
|
||||
elif [ -n "$$diff" ]; then echo "$$file"; \
|
||||
else echo "\033[2m$$file\033[0m"; fi \
|
||||
done
|
||||
|
||||
format:
|
||||
$(RUN_LINTING) format
|
||||
|
||||
format_ci:
|
||||
$(RUN_LINTING_CI) format
|
||||
|
||||
format_fix:
|
||||
$(RUN_LINTING) format:fix
|
||||
|
||||
lint:
|
||||
$(RUN_LINTING) lint
|
||||
|
||||
lint_ci:
|
||||
$(RUN_LINTING_CI) lint
|
||||
|
||||
lint_fix:
|
||||
$(RUN_LINTING) lint:fix
|
||||
|
||||
typecheck:
|
||||
$(RUN_LINTING) types:check
|
||||
|
||||
typecheck_ci:
|
||||
$(RUN_LINTING_CI) types:check
|
||||
|
||||
test: format lint typecheck shellcheck test_unit test_acceptance
|
||||
|
||||
test_unit:
|
||||
ifneq (,$(wildcard test/unit))
|
||||
$(DOCKER_COMPOSE_TEST_UNIT) run --rm test_unit
|
||||
$(MAKE) test_unit_clean
|
||||
endif
|
||||
|
||||
test_clean: test_unit_clean
|
||||
test_unit_clean:
|
||||
ifneq (,$(wildcard test/unit))
|
||||
$(DOCKER_COMPOSE_TEST_UNIT) down -v -t 0
|
||||
endif
|
||||
|
||||
test_acceptance: test_acceptance_clean test_acceptance_pre_run test_acceptance_run
|
||||
$(MAKE) test_acceptance_clean
|
||||
|
||||
test_acceptance_debug: test_acceptance_clean test_acceptance_pre_run test_acceptance_run_debug
|
||||
$(MAKE) test_acceptance_clean
|
||||
|
||||
test_acceptance_run:
|
||||
ifneq (,$(wildcard test/acceptance))
|
||||
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) run --rm test_acceptance
|
||||
endif
|
||||
|
||||
test_acceptance_run_debug:
|
||||
ifneq (,$(wildcard test/acceptance))
|
||||
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) run -p 127.0.0.9:19999:19999 --rm test_acceptance npm run test:acceptance -- --inspect=0.0.0.0:19999 --inspect-brk
|
||||
endif
|
||||
|
||||
test_clean: test_acceptance_clean
|
||||
test_acceptance_clean:
|
||||
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) down -v -t 0
|
||||
|
||||
test_acceptance_pre_run:
|
||||
ifneq (,$(wildcard test/acceptance/js/scripts/pre-run))
|
||||
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) run --rm test_acceptance test/acceptance/js/scripts/pre-run
|
||||
endif
|
||||
|
||||
benchmarks:
|
||||
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) run --rm test_acceptance npm run benchmarks
|
||||
|
||||
build:
|
||||
docker build \
|
||||
--pull \
|
||||
--build-arg BUILDKIT_INLINE_CACHE=1 \
|
||||
--tag ci/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER) \
|
||||
--tag us-east1-docker.pkg.dev/overleaf-ops/ol-docker/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER) \
|
||||
--tag us-east1-docker.pkg.dev/overleaf-ops/ol-docker/$(PROJECT_NAME):$(BRANCH_NAME) \
|
||||
--cache-from us-east1-docker.pkg.dev/overleaf-ops/ol-docker/$(PROJECT_NAME):$(BRANCH_NAME) \
|
||||
--cache-from us-east1-docker.pkg.dev/overleaf-ops/ol-docker/$(PROJECT_NAME):main \
|
||||
--file Dockerfile \
|
||||
../..
|
||||
|
||||
tar:
|
||||
$(DOCKER_COMPOSE) up tar
|
||||
|
||||
publish:
|
||||
|
||||
docker push $(DOCKER_REPO)/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER)
|
||||
|
||||
|
||||
.PHONY: clean \
|
||||
format format_fix \
|
||||
lint lint_fix \
|
||||
build_types typecheck \
|
||||
lint_ci format_ci typecheck_ci \
|
||||
shellcheck shellcheck_fix \
|
||||
test test_clean test_unit test_unit_clean \
|
||||
test_acceptance test_acceptance_debug test_acceptance_pre_run \
|
||||
test_acceptance_run test_acceptance_run_debug test_acceptance_clean \
|
||||
benchmarks \
|
||||
build tar publish \
|
22
services/filestore/README.md
Normal file
22
services/filestore/README.md
Normal file
@@ -0,0 +1,22 @@
|
||||
overleaf/filestore
|
||||
====================
|
||||
|
||||
An API for CRUD operations on binary files stored in S3
|
||||
|
||||
filestore acts as a proxy between the CLSIs and (currently) Amazon S3 storage, presenting a RESTful HTTP interface to the CLSIs on port 3009 by default. Urls are mapped to node functions in https://github.com/overleaf/filestore/blob/master/app.coffee . URLs are of the form:
|
||||
|
||||
* `/project/:project_id/file/:file_id`
|
||||
* `/template/:template_id/v/:version/:format`
|
||||
* `/project/:project_id/public/:public_file_id`
|
||||
* `/project/:project_id/size`
|
||||
* `/bucket/:bucket/key/*`
|
||||
* `/shutdown`
|
||||
* `/status` - returns HTTP 200 `filestore is up` or HTTP 503 when shutting down
|
||||
* `/health_check`
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
The code in this repository is released under the GNU AFFERO GENERAL PUBLIC LICENSE, version 3. A copy can be found in the `LICENSE` file.
|
||||
|
||||
Copyright (c) Overleaf, 2014-2019.
|
189
services/filestore/app.js
Normal file
189
services/filestore/app.js
Normal file
@@ -0,0 +1,189 @@
|
||||
// Metrics must be initialized before importing anything else
|
||||
require('@overleaf/metrics/initialize')
|
||||
|
||||
const Events = require('node:events')
|
||||
const Metrics = require('@overleaf/metrics')
|
||||
|
||||
const logger = require('@overleaf/logger')
|
||||
logger.initialize(process.env.METRICS_APP_NAME || 'filestore')
|
||||
|
||||
const settings = require('@overleaf/settings')
|
||||
const express = require('express')
|
||||
const bodyParser = require('body-parser')
|
||||
|
||||
const fileController = require('./app/js/FileController')
|
||||
const keyBuilder = require('./app/js/KeyBuilder')
|
||||
const healthCheckController = require('./app/js/HealthCheckController')
|
||||
|
||||
const RequestLogger = require('./app/js/RequestLogger')
|
||||
|
||||
Events.setMaxListeners(20)
|
||||
|
||||
const app = express()
|
||||
|
||||
app.use(RequestLogger.middleware)
|
||||
|
||||
Metrics.open_sockets.monitor(true)
|
||||
Metrics.memory.monitor(logger)
|
||||
if (Metrics.event_loop) {
|
||||
Metrics.event_loop.monitor(logger)
|
||||
}
|
||||
Metrics.leaked_sockets.monitor(logger)
|
||||
|
||||
app.use(function (req, res, next) {
|
||||
Metrics.inc('http-request')
|
||||
next()
|
||||
})
|
||||
|
||||
// Handle requests that come in after we've started shutting down
|
||||
app.use((req, res, next) => {
|
||||
if (settings.shuttingDown) {
|
||||
logger.warn(
|
||||
{ req, timeSinceShutdown: Date.now() - settings.shutDownTime },
|
||||
'request received after shutting down'
|
||||
)
|
||||
// We don't want keep-alive connections to be kept open when the server is shutting down.
|
||||
res.set('Connection', 'close')
|
||||
}
|
||||
next()
|
||||
})
|
||||
|
||||
Metrics.injectMetricsRoute(app)
|
||||
|
||||
if (settings.filestore.stores.user_files) {
|
||||
app.head(
|
||||
'/project/:project_id/file/:file_id',
|
||||
keyBuilder.userFileKeyMiddleware,
|
||||
fileController.getFileHead
|
||||
)
|
||||
app.get(
|
||||
'/project/:project_id/file/:file_id',
|
||||
keyBuilder.userFileKeyMiddleware,
|
||||
fileController.getFile
|
||||
)
|
||||
app.post(
|
||||
'/project/:project_id/file/:file_id',
|
||||
keyBuilder.userFileKeyMiddleware,
|
||||
fileController.insertFile
|
||||
)
|
||||
app.put(
|
||||
'/project/:project_id/file/:file_id',
|
||||
keyBuilder.userFileKeyMiddleware,
|
||||
bodyParser.json(),
|
||||
fileController.copyFile
|
||||
)
|
||||
app.delete(
|
||||
'/project/:project_id/file/:file_id',
|
||||
keyBuilder.userFileKeyMiddleware,
|
||||
fileController.deleteFile
|
||||
)
|
||||
app.delete(
|
||||
'/project/:project_id',
|
||||
keyBuilder.userProjectKeyMiddleware,
|
||||
fileController.deleteProject
|
||||
)
|
||||
|
||||
app.get(
|
||||
'/project/:project_id/size',
|
||||
keyBuilder.userProjectKeyMiddleware,
|
||||
fileController.directorySize
|
||||
)
|
||||
}
|
||||
|
||||
if (settings.filestore.stores.template_files) {
|
||||
app.head(
|
||||
'/template/:template_id/v/:version/:format',
|
||||
keyBuilder.templateFileKeyMiddleware,
|
||||
fileController.getFileHead
|
||||
)
|
||||
app.get(
|
||||
'/template/:template_id/v/:version/:format',
|
||||
keyBuilder.templateFileKeyMiddleware,
|
||||
fileController.getFile
|
||||
)
|
||||
app.get(
|
||||
'/template/:template_id/v/:version/:format/:sub_type',
|
||||
keyBuilder.templateFileKeyMiddleware,
|
||||
fileController.getFile
|
||||
)
|
||||
app.post(
|
||||
'/template/:template_id/v/:version/:format',
|
||||
keyBuilder.templateFileKeyMiddleware,
|
||||
fileController.insertFile
|
||||
)
|
||||
}
|
||||
|
||||
app.get(
|
||||
'/bucket/:bucket/key/*',
|
||||
keyBuilder.bucketFileKeyMiddleware,
|
||||
fileController.getFile
|
||||
)
|
||||
|
||||
app.get('/status', function (req, res) {
|
||||
if (settings.shuttingDown) {
|
||||
res.sendStatus(503) // Service unavailable
|
||||
} else {
|
||||
res.send('filestore is up')
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/health_check', healthCheckController.check)
|
||||
|
||||
app.use(RequestLogger.errorHandler)
|
||||
|
||||
const port = settings.internal.filestore.port || 3009
|
||||
const host = settings.internal.filestore.host || '0.0.0.0'
|
||||
|
||||
let server = null
|
||||
if (!module.parent) {
|
||||
// Called directly
|
||||
server = app.listen(port, host, error => {
|
||||
if (error) {
|
||||
logger.error({ err: error }, 'Error starting Filestore')
|
||||
throw error
|
||||
}
|
||||
logger.debug(`Filestore starting up, listening on ${host}:${port}`)
|
||||
})
|
||||
}
|
||||
|
||||
process
|
||||
.on('unhandledRejection', (reason, p) => {
|
||||
logger.err(reason, 'Unhandled Rejection at Promise', p)
|
||||
})
|
||||
.on('uncaughtException', err => {
|
||||
logger.err(err, 'Uncaught Exception thrown')
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
function handleShutdownSignal(signal) {
|
||||
logger.info({ signal }, 'received interrupt, cleaning up')
|
||||
if (settings.shuttingDown) {
|
||||
logger.warn({ signal }, 'already shutting down, ignoring interrupt')
|
||||
return
|
||||
}
|
||||
settings.shuttingDown = true
|
||||
settings.shutDownTime = Date.now()
|
||||
// stop accepting new connections, the callback is called when existing connections have finished
|
||||
server.close(() => {
|
||||
logger.info({ signal }, 'server closed')
|
||||
// exit after a short delay so logs can be flushed
|
||||
setTimeout(() => {
|
||||
process.exit()
|
||||
}, 100)
|
||||
})
|
||||
// close idle http keep-alive connections
|
||||
server.closeIdleConnections()
|
||||
setTimeout(() => {
|
||||
logger.info({ signal }, 'shutdown timed out, exiting')
|
||||
// close all connections immediately
|
||||
server.closeAllConnections()
|
||||
// exit after a short delay to allow for cleanup
|
||||
setTimeout(() => {
|
||||
process.exit()
|
||||
}, 100)
|
||||
}, settings.gracefulShutdownDelayInMs)
|
||||
}
|
||||
|
||||
process.on('SIGTERM', handleShutdownSignal)
|
||||
|
||||
module.exports = app
|
30
services/filestore/app/js/Errors.js
Normal file
30
services/filestore/app/js/Errors.js
Normal file
@@ -0,0 +1,30 @@
|
||||
const OError = require('@overleaf/o-error')
|
||||
const { Errors } = require('@overleaf/object-persistor')
|
||||
|
||||
class HealthCheckError extends OError {}
|
||||
class ConversionsDisabledError extends OError {}
|
||||
class ConversionError extends OError {}
|
||||
class TimeoutError extends OError {}
|
||||
class InvalidParametersError extends OError {}
|
||||
|
||||
class FailedCommandError extends OError {
|
||||
constructor(command, code, stdout, stderr) {
|
||||
super('command failed with error exit code', {
|
||||
command,
|
||||
code,
|
||||
})
|
||||
this.stdout = stdout
|
||||
this.stderr = stderr
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
FailedCommandError,
|
||||
ConversionsDisabledError,
|
||||
ConversionError,
|
||||
HealthCheckError,
|
||||
TimeoutError,
|
||||
InvalidParametersError,
|
||||
...Errors,
|
||||
}
|
214
services/filestore/app/js/FileController.js
Normal file
214
services/filestore/app/js/FileController.js
Normal file
@@ -0,0 +1,214 @@
|
||||
const FileHandler = require('./FileHandler')
|
||||
const metrics = require('@overleaf/metrics')
|
||||
const parseRange = require('range-parser')
|
||||
const Errors = require('./Errors')
|
||||
const { pipeline } = require('node:stream')
|
||||
|
||||
const maxSizeInBytes = 1024 * 1024 * 1024 // 1GB
|
||||
|
||||
module.exports = {
|
||||
getFile,
|
||||
getFileHead,
|
||||
insertFile,
|
||||
copyFile,
|
||||
deleteFile,
|
||||
deleteProject,
|
||||
directorySize,
|
||||
}
|
||||
|
||||
function getFile(req, res, next) {
|
||||
const { key, bucket } = req
|
||||
const { format, style } = req.query
|
||||
const options = {
|
||||
key,
|
||||
bucket,
|
||||
format,
|
||||
style,
|
||||
}
|
||||
|
||||
metrics.inc('getFile')
|
||||
req.requestLogger.setMessage('getting file')
|
||||
req.requestLogger.addFields({
|
||||
key,
|
||||
bucket,
|
||||
format,
|
||||
style,
|
||||
cacheWarm: req.query.cacheWarm,
|
||||
})
|
||||
|
||||
if (req.headers.range) {
|
||||
const range = _getRange(req.headers.range)
|
||||
if (range) {
|
||||
options.start = range.start
|
||||
options.end = range.end
|
||||
req.requestLogger.addFields({ range })
|
||||
}
|
||||
}
|
||||
|
||||
FileHandler.getRedirectUrl(bucket, key, options, function (err, redirectUrl) {
|
||||
if (err) {
|
||||
metrics.inc('file_redirect_error')
|
||||
}
|
||||
|
||||
if (redirectUrl) {
|
||||
metrics.inc('file_redirect')
|
||||
return res.redirect(redirectUrl)
|
||||
}
|
||||
|
||||
FileHandler.getFile(bucket, key, options, function (err, fileStream) {
|
||||
if (err) {
|
||||
if (err instanceof Errors.NotFoundError) {
|
||||
res.sendStatus(404)
|
||||
} else {
|
||||
next(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (req.query.cacheWarm) {
|
||||
fileStream.destroy()
|
||||
return res.sendStatus(200).end()
|
||||
}
|
||||
|
||||
pipeline(fileStream, res, err => {
|
||||
if (err && err.code === 'ERR_STREAM_PREMATURE_CLOSE') {
|
||||
res.end()
|
||||
} else if (err) {
|
||||
next(
|
||||
new Errors.ReadError(
|
||||
'error transferring stream',
|
||||
{ bucket, key, format, style },
|
||||
err
|
||||
)
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function getFileHead(req, res, next) {
|
||||
const { key, bucket } = req
|
||||
|
||||
metrics.inc('getFileSize')
|
||||
req.requestLogger.setMessage('getting file size')
|
||||
req.requestLogger.addFields({ key, bucket })
|
||||
|
||||
FileHandler.getFileSize(bucket, key, function (err, fileSize) {
|
||||
if (err) {
|
||||
if (err instanceof Errors.NotFoundError) {
|
||||
res.sendStatus(404)
|
||||
} else {
|
||||
next(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
res.set('Content-Length', fileSize)
|
||||
res.status(200).end()
|
||||
})
|
||||
}
|
||||
|
||||
function insertFile(req, res, next) {
|
||||
metrics.inc('insertFile')
|
||||
const { key, bucket } = req
|
||||
|
||||
req.requestLogger.setMessage('inserting file')
|
||||
req.requestLogger.addFields({ key, bucket })
|
||||
|
||||
FileHandler.insertFile(bucket, key, req, function (err) {
|
||||
if (err) {
|
||||
next(err)
|
||||
} else {
|
||||
res.sendStatus(200)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function copyFile(req, res, next) {
|
||||
metrics.inc('copyFile')
|
||||
const { key, bucket } = req
|
||||
const oldProjectId = req.body.source.project_id
|
||||
const oldFileId = req.body.source.file_id
|
||||
|
||||
req.requestLogger.addFields({
|
||||
key,
|
||||
bucket,
|
||||
oldProject_id: oldProjectId,
|
||||
oldFile_id: oldFileId,
|
||||
})
|
||||
req.requestLogger.setMessage('copying file')
|
||||
|
||||
FileHandler.copyObject(bucket, `${oldProjectId}/${oldFileId}`, key, err => {
|
||||
if (err) {
|
||||
if (err instanceof Errors.NotFoundError) {
|
||||
res.sendStatus(404)
|
||||
} else {
|
||||
next(err)
|
||||
}
|
||||
} else {
|
||||
res.sendStatus(200)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function deleteFile(req, res, next) {
|
||||
metrics.inc('deleteFile')
|
||||
const { key, bucket } = req
|
||||
|
||||
req.requestLogger.addFields({ key, bucket })
|
||||
req.requestLogger.setMessage('deleting file')
|
||||
|
||||
FileHandler.deleteFile(bucket, key, function (err) {
|
||||
if (err) {
|
||||
next(err)
|
||||
} else {
|
||||
res.sendStatus(204)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function deleteProject(req, res, next) {
|
||||
metrics.inc('deleteProject')
|
||||
const { key, bucket } = req
|
||||
|
||||
req.requestLogger.setMessage('deleting project')
|
||||
req.requestLogger.addFields({ key, bucket })
|
||||
|
||||
FileHandler.deleteProject(bucket, key, function (err) {
|
||||
if (err) {
|
||||
if (err instanceof Errors.InvalidParametersError) {
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
next(err)
|
||||
} else {
|
||||
res.sendStatus(204)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function directorySize(req, res, next) {
|
||||
metrics.inc('projectSize')
|
||||
const { project_id: projectId, bucket } = req
|
||||
|
||||
req.requestLogger.setMessage('getting project size')
|
||||
req.requestLogger.addFields({ projectId, bucket })
|
||||
|
||||
FileHandler.getDirectorySize(bucket, projectId, function (err, size) {
|
||||
if (err) {
|
||||
return next(err)
|
||||
}
|
||||
|
||||
res.json({ 'total bytes': size })
|
||||
req.requestLogger.addFields({ size })
|
||||
})
|
||||
}
|
||||
|
||||
function _getRange(header) {
|
||||
const parsed = parseRange(maxSizeInBytes, header)
|
||||
if (parsed === -1 || parsed === -2 || parsed.type !== 'bytes') {
|
||||
return null
|
||||
} else {
|
||||
const range = parsed[0]
|
||||
return { start: range.start, end: range.end }
|
||||
}
|
||||
}
|
98
services/filestore/app/js/FileConverter.js
Normal file
98
services/filestore/app/js/FileConverter.js
Normal file
@@ -0,0 +1,98 @@
|
||||
const metrics = require('@overleaf/metrics')
|
||||
const Settings = require('@overleaf/settings')
|
||||
const { callbackify } = require('node:util')
|
||||
|
||||
const safeExec = require('./SafeExec').promises
|
||||
const { ConversionError } = require('./Errors')
|
||||
|
||||
const APPROVED_FORMATS = ['png']
|
||||
const FOURTY_SECONDS = 40 * 1000
|
||||
const KILL_SIGNAL = 'SIGTERM'
|
||||
|
||||
module.exports = {
|
||||
convert: callbackify(convert),
|
||||
thumbnail: callbackify(thumbnail),
|
||||
preview: callbackify(preview),
|
||||
promises: {
|
||||
convert,
|
||||
thumbnail,
|
||||
preview,
|
||||
},
|
||||
}
|
||||
|
||||
async function convert(sourcePath, requestedFormat) {
|
||||
const width = '600x'
|
||||
return await _convert(sourcePath, requestedFormat, [
|
||||
'convert',
|
||||
'-define',
|
||||
`pdf:fit-page=${width}`,
|
||||
'-flatten',
|
||||
'-density',
|
||||
'300',
|
||||
`${sourcePath}[0]`,
|
||||
])
|
||||
}
|
||||
|
||||
async function thumbnail(sourcePath) {
|
||||
const width = '260x'
|
||||
return await convert(sourcePath, 'png', [
|
||||
'convert',
|
||||
'-flatten',
|
||||
'-background',
|
||||
'white',
|
||||
'-density',
|
||||
'300',
|
||||
'-define',
|
||||
`pdf:fit-page=${width}`,
|
||||
`${sourcePath}[0]`,
|
||||
'-resize',
|
||||
width,
|
||||
])
|
||||
}
|
||||
|
||||
async function preview(sourcePath) {
|
||||
const width = '548x'
|
||||
return await convert(sourcePath, 'png', [
|
||||
'convert',
|
||||
'-flatten',
|
||||
'-background',
|
||||
'white',
|
||||
'-density',
|
||||
'300',
|
||||
'-define',
|
||||
`pdf:fit-page=${width}`,
|
||||
`${sourcePath}[0]`,
|
||||
'-resize',
|
||||
width,
|
||||
])
|
||||
}
|
||||
|
||||
async function _convert(sourcePath, requestedFormat, command) {
|
||||
if (!APPROVED_FORMATS.includes(requestedFormat)) {
|
||||
throw new ConversionError('invalid format requested', {
|
||||
format: requestedFormat,
|
||||
})
|
||||
}
|
||||
|
||||
const timer = new metrics.Timer('imageConvert')
|
||||
const destPath = `${sourcePath}.${requestedFormat}`
|
||||
|
||||
command.push(destPath)
|
||||
command = Settings.commands.convertCommandPrefix.concat(command)
|
||||
|
||||
try {
|
||||
await safeExec(command, {
|
||||
killSignal: KILL_SIGNAL,
|
||||
timeout: FOURTY_SECONDS,
|
||||
})
|
||||
} catch (err) {
|
||||
throw new ConversionError(
|
||||
'something went wrong converting file',
|
||||
{ stderr: err.stderr, sourcePath, requestedFormat, destPath },
|
||||
err
|
||||
)
|
||||
}
|
||||
|
||||
timer.done()
|
||||
return destPath
|
||||
}
|
228
services/filestore/app/js/FileHandler.js
Normal file
228
services/filestore/app/js/FileHandler.js
Normal file
@@ -0,0 +1,228 @@
|
||||
const Settings = require('@overleaf/settings')
|
||||
const { callbackify } = require('node:util')
|
||||
const fs = require('node:fs')
|
||||
let PersistorManager = require('./PersistorManager')
|
||||
const LocalFileWriter = require('./LocalFileWriter')
|
||||
const FileConverter = require('./FileConverter')
|
||||
const KeyBuilder = require('./KeyBuilder')
|
||||
const ImageOptimiser = require('./ImageOptimiser')
|
||||
const { ConversionError, InvalidParametersError } = require('./Errors')
|
||||
const metrics = require('@overleaf/metrics')
|
||||
|
||||
module.exports = {
|
||||
copyObject: callbackify(copyObject),
|
||||
insertFile: callbackify(insertFile),
|
||||
deleteFile: callbackify(deleteFile),
|
||||
deleteProject: callbackify(deleteProject),
|
||||
getFile: callbackify(getFile),
|
||||
getRedirectUrl: callbackify(getRedirectUrl),
|
||||
getFileSize: callbackify(getFileSize),
|
||||
getDirectorySize: callbackify(getDirectorySize),
|
||||
promises: {
|
||||
copyObject,
|
||||
getFile,
|
||||
getRedirectUrl,
|
||||
insertFile,
|
||||
deleteFile,
|
||||
deleteProject,
|
||||
getFileSize,
|
||||
getDirectorySize,
|
||||
},
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV === 'test') {
|
||||
module.exports._TESTONLYSwapPersistorManager = _PersistorManager => {
|
||||
PersistorManager = _PersistorManager
|
||||
}
|
||||
}
|
||||
|
||||
async function copyObject(bucket, sourceKey, destinationKey) {
|
||||
await PersistorManager.copyObject(bucket, sourceKey, destinationKey)
|
||||
}
|
||||
|
||||
async function insertFile(bucket, key, stream) {
|
||||
const convertedKey = KeyBuilder.getConvertedFolderKey(key)
|
||||
if (!convertedKey.match(/^[0-9a-f]{24}\/([0-9a-f]{24}|v\/[0-9]+\/[a-z]+)/i)) {
|
||||
throw new InvalidParametersError('key does not match validation regex', {
|
||||
bucket,
|
||||
key,
|
||||
convertedKey,
|
||||
})
|
||||
}
|
||||
await PersistorManager.sendStream(bucket, key, stream)
|
||||
}
|
||||
|
||||
async function deleteFile(bucket, key) {
|
||||
const convertedKey = KeyBuilder.getConvertedFolderKey(key)
|
||||
if (!convertedKey.match(/^[0-9a-f]{24}\/([0-9a-f]{24}|v\/[0-9]+\/[a-z]+)/i)) {
|
||||
throw new InvalidParametersError('key does not match validation regex', {
|
||||
bucket,
|
||||
key,
|
||||
convertedKey,
|
||||
})
|
||||
}
|
||||
const jobs = [PersistorManager.deleteObject(bucket, key)]
|
||||
if (
|
||||
Settings.enableConversions &&
|
||||
bucket === Settings.filestore.stores.template_files
|
||||
) {
|
||||
jobs.push(PersistorManager.deleteDirectory(bucket, convertedKey))
|
||||
}
|
||||
await Promise.all(jobs)
|
||||
}
|
||||
|
||||
async function deleteProject(bucket, key) {
|
||||
if (!key.match(/^[0-9a-f]{24}\//i)) {
|
||||
throw new InvalidParametersError('key does not match validation regex', {
|
||||
bucket,
|
||||
key,
|
||||
})
|
||||
}
|
||||
await PersistorManager.deleteDirectory(bucket, key)
|
||||
}
|
||||
|
||||
async function getFile(bucket, key, opts) {
|
||||
opts = opts || {}
|
||||
if (!opts.format && !opts.style) {
|
||||
return await PersistorManager.getObjectStream(bucket, key, opts)
|
||||
} else {
|
||||
return await _getConvertedFile(bucket, key, opts)
|
||||
}
|
||||
}
|
||||
|
||||
let ACTIVE_SIGNED_URL_CALLS = 0
|
||||
|
||||
async function getRedirectUrl(bucket, key, opts) {
|
||||
// if we're doing anything unusual with options, or the request isn't for
|
||||
// one of the default buckets, return null so that we proxy the file
|
||||
opts = opts || {}
|
||||
if (
|
||||
!opts.start &&
|
||||
!opts.end &&
|
||||
!opts.format &&
|
||||
!opts.style &&
|
||||
Object.values(Settings.filestore.stores).includes(bucket) &&
|
||||
Settings.filestore.allowRedirects
|
||||
) {
|
||||
// record the number of in-flight calls to generate signed URLs
|
||||
metrics.gauge('active_signed_url_calls', ++ACTIVE_SIGNED_URL_CALLS, {
|
||||
path: bucket,
|
||||
})
|
||||
try {
|
||||
const timer = new metrics.Timer('signed_url_call_time', {
|
||||
path: bucket,
|
||||
})
|
||||
const redirectUrl = await PersistorManager.getRedirectUrl(bucket, key)
|
||||
timer.done()
|
||||
return redirectUrl
|
||||
} finally {
|
||||
metrics.gauge('active_signed_url_calls', --ACTIVE_SIGNED_URL_CALLS, {
|
||||
path: bucket,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
async function getFileSize(bucket, key) {
|
||||
return await PersistorManager.getObjectSize(bucket, key)
|
||||
}
|
||||
|
||||
async function getDirectorySize(bucket, projectId) {
|
||||
return await PersistorManager.directorySize(bucket, projectId)
|
||||
}
|
||||
|
||||
async function _getConvertedFile(bucket, key, opts) {
|
||||
const convertedKey = KeyBuilder.addCachingToKey(key, opts)
|
||||
const exists = await PersistorManager.checkIfObjectExists(
|
||||
bucket,
|
||||
convertedKey
|
||||
)
|
||||
if (exists) {
|
||||
return await PersistorManager.getObjectStream(bucket, convertedKey, opts)
|
||||
} else {
|
||||
return await _getConvertedFileAndCache(bucket, key, convertedKey, opts)
|
||||
}
|
||||
}
|
||||
|
||||
async function _getConvertedFileAndCache(bucket, key, convertedKey, opts) {
|
||||
let convertedFsPath
|
||||
try {
|
||||
convertedFsPath = await _convertFile(bucket, key, opts)
|
||||
await ImageOptimiser.promises.compressPng(convertedFsPath)
|
||||
await PersistorManager.sendFile(bucket, convertedKey, convertedFsPath)
|
||||
} catch (err) {
|
||||
LocalFileWriter.deleteFile(convertedFsPath, () => {})
|
||||
throw new ConversionError(
|
||||
'failed to convert file',
|
||||
{ opts, bucket, key, convertedKey },
|
||||
err
|
||||
)
|
||||
}
|
||||
// Send back the converted file from the local copy to avoid problems
|
||||
// with the file not being present in S3 yet. As described in the
|
||||
// documentation below, we have already made a 'HEAD' request in
|
||||
// checkIfFileExists so we only have "eventual consistency" if we try
|
||||
// to stream it from S3 here. This was a cause of many 403 errors.
|
||||
//
|
||||
// "Amazon S3 provides read-after-write consistency for PUTS of new
|
||||
// objects in your S3 bucket in all regions with one caveat. The
|
||||
// caveat is that if you make a HEAD or GET request to the key name
|
||||
// (to find if the object exists) before creating the object, Amazon
|
||||
// S3 provides eventual consistency for read-after-write.""
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html#ConsistencyModel
|
||||
const readStream = fs.createReadStream(convertedFsPath)
|
||||
readStream.on('error', function () {
|
||||
LocalFileWriter.deleteFile(convertedFsPath, function () {})
|
||||
})
|
||||
readStream.on('end', function () {
|
||||
LocalFileWriter.deleteFile(convertedFsPath, function () {})
|
||||
})
|
||||
return readStream
|
||||
}
|
||||
|
||||
async function _convertFile(bucket, originalKey, opts) {
|
||||
let originalFsPath
|
||||
try {
|
||||
originalFsPath = await _writeFileToDisk(bucket, originalKey, opts)
|
||||
} catch (err) {
|
||||
throw new ConversionError(
|
||||
'unable to write file to disk',
|
||||
{ bucket, originalKey, opts },
|
||||
err
|
||||
)
|
||||
}
|
||||
|
||||
let promise
|
||||
if (opts.format) {
|
||||
promise = FileConverter.promises.convert(originalFsPath, opts.format)
|
||||
} else if (opts.style === 'thumbnail') {
|
||||
promise = FileConverter.promises.thumbnail(originalFsPath)
|
||||
} else if (opts.style === 'preview') {
|
||||
promise = FileConverter.promises.preview(originalFsPath)
|
||||
} else {
|
||||
throw new ConversionError('invalid file conversion options', {
|
||||
bucket,
|
||||
originalKey,
|
||||
opts,
|
||||
})
|
||||
}
|
||||
let destPath
|
||||
try {
|
||||
destPath = await promise
|
||||
} catch (err) {
|
||||
throw new ConversionError(
|
||||
'error converting file',
|
||||
{ bucket, originalKey, opts },
|
||||
err
|
||||
)
|
||||
}
|
||||
LocalFileWriter.deleteFile(originalFsPath, function () {})
|
||||
return destPath
|
||||
}
|
||||
|
||||
async function _writeFileToDisk(bucket, key, opts) {
|
||||
const fileStream = await PersistorManager.getObjectStream(bucket, key, opts)
|
||||
return await LocalFileWriter.promises.writeStream(fileStream, key)
|
||||
}
|
67
services/filestore/app/js/HealthCheckController.js
Normal file
67
services/filestore/app/js/HealthCheckController.js
Normal file
@@ -0,0 +1,67 @@
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const Settings = require('@overleaf/settings')
|
||||
const { WritableBuffer } = require('@overleaf/stream-utils')
|
||||
const { promisify } = require('node:util')
|
||||
const Stream = require('node:stream')
|
||||
|
||||
const pipeline = promisify(Stream.pipeline)
|
||||
const fsCopy = promisify(fs.copyFile)
|
||||
const fsUnlink = promisify(fs.unlink)
|
||||
|
||||
const { HealthCheckError } = require('./Errors')
|
||||
const FileConverter = require('./FileConverter').promises
|
||||
const FileHandler = require('./FileHandler').promises
|
||||
|
||||
async function checkCanGetFiles() {
|
||||
if (!Settings.health_check) {
|
||||
return
|
||||
}
|
||||
|
||||
const projectId = Settings.health_check.project_id
|
||||
const fileId = Settings.health_check.file_id
|
||||
const key = `${projectId}/${fileId}`
|
||||
const bucket = Settings.filestore.stores.user_files
|
||||
|
||||
const buffer = new WritableBuffer({ initialSize: 100 })
|
||||
|
||||
const sourceStream = await FileHandler.getFile(bucket, key, {})
|
||||
try {
|
||||
await pipeline(sourceStream, buffer)
|
||||
} catch (err) {
|
||||
throw new HealthCheckError('failed to get health-check file', {}, err)
|
||||
}
|
||||
|
||||
if (!buffer.size()) {
|
||||
throw new HealthCheckError('no bytes written to download stream')
|
||||
}
|
||||
}
|
||||
|
||||
async function checkFileConvert() {
|
||||
if (!Settings.enableConversions) {
|
||||
return
|
||||
}
|
||||
|
||||
const imgPath = path.join(Settings.path.uploadFolder, '/tiny.pdf')
|
||||
|
||||
let resultPath
|
||||
try {
|
||||
await fsCopy('./tiny.pdf', imgPath)
|
||||
resultPath = await FileConverter.thumbnail(imgPath)
|
||||
} finally {
|
||||
if (resultPath) {
|
||||
await fsUnlink(resultPath)
|
||||
}
|
||||
await fsUnlink(imgPath)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
check(req, res, next) {
|
||||
Promise.all([checkCanGetFiles(), checkFileConvert()])
|
||||
.then(() => res.sendStatus(200))
|
||||
.catch(err => {
|
||||
next(err)
|
||||
})
|
||||
},
|
||||
}
|
34
services/filestore/app/js/ImageOptimiser.js
Normal file
34
services/filestore/app/js/ImageOptimiser.js
Normal file
@@ -0,0 +1,34 @@
|
||||
const logger = require('@overleaf/logger')
|
||||
const metrics = require('@overleaf/metrics')
|
||||
const { callbackify } = require('node:util')
|
||||
const safeExec = require('./SafeExec').promises
|
||||
|
||||
module.exports = {
|
||||
compressPng: callbackify(compressPng),
|
||||
promises: {
|
||||
compressPng,
|
||||
},
|
||||
}
|
||||
|
||||
async function compressPng(localPath, callback) {
|
||||
const timer = new metrics.Timer('compressPng')
|
||||
const args = ['optipng', localPath]
|
||||
const opts = {
|
||||
timeout: 30 * 1000,
|
||||
killSignal: 'SIGKILL',
|
||||
}
|
||||
|
||||
try {
|
||||
await safeExec(args, opts)
|
||||
timer.done()
|
||||
} catch (err) {
|
||||
if (err.code === 'SIGKILL') {
|
||||
logger.warn(
|
||||
{ err, stderr: err.stderr, localPath },
|
||||
'optimiser timeout reached'
|
||||
)
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
71
services/filestore/app/js/KeyBuilder.js
Normal file
71
services/filestore/app/js/KeyBuilder.js
Normal file
@@ -0,0 +1,71 @@
|
||||
const settings = require('@overleaf/settings')
|
||||
|
||||
module.exports = {
|
||||
getConvertedFolderKey,
|
||||
addCachingToKey,
|
||||
userFileKeyMiddleware,
|
||||
userProjectKeyMiddleware,
|
||||
bucketFileKeyMiddleware,
|
||||
templateFileKeyMiddleware,
|
||||
}
|
||||
|
||||
function getConvertedFolderKey(key) {
|
||||
return `${key}-converted-cache/`
|
||||
}
|
||||
|
||||
function addCachingToKey(key, opts) {
|
||||
key = this.getConvertedFolderKey(key)
|
||||
|
||||
if (opts.format && !opts.style) {
|
||||
key = `${key}format-${opts.format}`
|
||||
}
|
||||
if (opts.style && !opts.format) {
|
||||
key = `${key}style-${opts.style}`
|
||||
}
|
||||
if (opts.style && opts.format) {
|
||||
key = `${key}format-${opts.format}-style-${opts.style}`
|
||||
}
|
||||
|
||||
return key
|
||||
}
|
||||
|
||||
function userFileKeyMiddleware(req, res, next) {
|
||||
const { project_id: projectId, file_id: fileId } = req.params
|
||||
req.key = `${projectId}/${fileId}`
|
||||
req.bucket = settings.filestore.stores.user_files
|
||||
next()
|
||||
}
|
||||
|
||||
function userProjectKeyMiddleware(req, res, next) {
|
||||
const { project_id: projectId } = req.params
|
||||
req.project_id = projectId
|
||||
req.key = `${projectId}/`
|
||||
req.bucket = settings.filestore.stores.user_files
|
||||
next()
|
||||
}
|
||||
|
||||
function bucketFileKeyMiddleware(req, res, next) {
|
||||
req.bucket = req.params.bucket
|
||||
req.key = req.params[0]
|
||||
next()
|
||||
}
|
||||
|
||||
function templateFileKeyMiddleware(req, res, next) {
|
||||
const {
|
||||
template_id: templateId,
|
||||
format,
|
||||
version,
|
||||
sub_type: subType,
|
||||
} = req.params
|
||||
|
||||
req.key = `${templateId}/v/${version}/${format}`
|
||||
|
||||
if (subType) {
|
||||
req.key = `${req.key}/${subType}`
|
||||
}
|
||||
|
||||
req.bucket = settings.filestore.stores.template_files
|
||||
req.version = version
|
||||
|
||||
next()
|
||||
}
|
56
services/filestore/app/js/LocalFileWriter.js
Normal file
56
services/filestore/app/js/LocalFileWriter.js
Normal file
@@ -0,0 +1,56 @@
|
||||
const fs = require('node:fs')
|
||||
const crypto = require('node:crypto')
|
||||
const path = require('node:path')
|
||||
const Stream = require('node:stream')
|
||||
const { callbackify, promisify } = require('node:util')
|
||||
const metrics = require('@overleaf/metrics')
|
||||
const Settings = require('@overleaf/settings')
|
||||
const { WriteError } = require('./Errors')
|
||||
|
||||
module.exports = {
|
||||
promises: {
|
||||
writeStream,
|
||||
deleteFile,
|
||||
},
|
||||
writeStream: callbackify(writeStream),
|
||||
deleteFile: callbackify(deleteFile),
|
||||
}
|
||||
|
||||
const pipeline = promisify(Stream.pipeline)
|
||||
|
||||
async function writeStream(stream, key) {
|
||||
const timer = new metrics.Timer('writingFile')
|
||||
const fsPath = _getPath(key)
|
||||
|
||||
const writeStream = fs.createWriteStream(fsPath)
|
||||
try {
|
||||
await pipeline(stream, writeStream)
|
||||
timer.done()
|
||||
return fsPath
|
||||
} catch (err) {
|
||||
await deleteFile(fsPath)
|
||||
|
||||
throw new WriteError('problem writing file locally', { fsPath }, err)
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteFile(fsPath) {
|
||||
if (!fsPath) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await promisify(fs.unlink)(fsPath)
|
||||
} catch (err) {
|
||||
if (err.code !== 'ENOENT') {
|
||||
throw new WriteError('failed to delete file', { fsPath }, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function _getPath(key) {
|
||||
if (key == null) {
|
||||
key = crypto.randomUUID()
|
||||
}
|
||||
key = key.replace(/\//g, '-')
|
||||
return path.join(Settings.path.uploadFolder, key)
|
||||
}
|
9
services/filestore/app/js/PersistorManager.js
Normal file
9
services/filestore/app/js/PersistorManager.js
Normal file
@@ -0,0 +1,9 @@
|
||||
const settings = require('@overleaf/settings')
|
||||
|
||||
const persistorSettings = settings.filestore
|
||||
persistorSettings.paths = settings.path
|
||||
|
||||
const ObjectPersistor = require('@overleaf/object-persistor')
|
||||
const persistor = ObjectPersistor(persistorSettings)
|
||||
|
||||
module.exports = persistor
|
61
services/filestore/app/js/RequestLogger.js
Normal file
61
services/filestore/app/js/RequestLogger.js
Normal file
@@ -0,0 +1,61 @@
|
||||
const logger = require('@overleaf/logger')
|
||||
const metrics = require('@overleaf/metrics')
|
||||
|
||||
class RequestLogger {
|
||||
constructor() {
|
||||
this._logInfo = {}
|
||||
this._logMessage = 'http request'
|
||||
}
|
||||
|
||||
addFields(fields) {
|
||||
Object.assign(this._logInfo, fields)
|
||||
}
|
||||
|
||||
setMessage(message) {
|
||||
this._logMessage = message
|
||||
}
|
||||
|
||||
static errorHandler(err, req, res, next) {
|
||||
req.requestLogger.addFields({ error: err })
|
||||
res.status(500).send(err.message)
|
||||
}
|
||||
|
||||
static middleware(req, res, next) {
|
||||
const startTime = new Date()
|
||||
req.requestLogger = new RequestLogger()
|
||||
|
||||
// override the 'end' method to log and record metrics
|
||||
const end = res.end
|
||||
res.end = function () {
|
||||
// apply the standard request 'end' method before logging and metrics
|
||||
end.apply(this, arguments)
|
||||
|
||||
const responseTime = new Date() - startTime
|
||||
|
||||
const routePath = req.route && req.route.path.toString()
|
||||
|
||||
if (routePath) {
|
||||
metrics.timing('http_request', responseTime, null, {
|
||||
method: req.method,
|
||||
status_code: res.statusCode,
|
||||
path: routePath.replace(/\//g, '_').replace(/:/g, '').slice(1),
|
||||
})
|
||||
}
|
||||
|
||||
const level = res.statusCode >= 500 ? 'err' : 'debug'
|
||||
logger[level](
|
||||
{
|
||||
req,
|
||||
res,
|
||||
responseTimeMs: responseTime,
|
||||
info: req.requestLogger._logInfo,
|
||||
},
|
||||
req.requestLogger._logMessage
|
||||
)
|
||||
}
|
||||
|
||||
next()
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = RequestLogger
|
85
services/filestore/app/js/SafeExec.js
Normal file
85
services/filestore/app/js/SafeExec.js
Normal file
@@ -0,0 +1,85 @@
|
||||
const lodashOnce = require('lodash.once')
|
||||
const childProcess = require('node:child_process')
|
||||
const Settings = require('@overleaf/settings')
|
||||
const { ConversionsDisabledError, FailedCommandError } = require('./Errors')
|
||||
|
||||
// execute a command in the same way as 'exec' but with a timeout that
|
||||
// kills all child processes
|
||||
//
|
||||
// we spawn the command with 'detached:true' to make a new process
|
||||
// group, then we can kill everything in that process group.
|
||||
|
||||
module.exports = safeExec
|
||||
module.exports.promises = safeExecPromise
|
||||
|
||||
// options are {timeout: number-of-milliseconds, killSignal: signal-name}
|
||||
function safeExec(command, options, callback) {
|
||||
if (!Settings.enableConversions) {
|
||||
return callback(
|
||||
new ConversionsDisabledError('image conversions are disabled')
|
||||
)
|
||||
}
|
||||
|
||||
const [cmd, ...args] = command
|
||||
|
||||
const child = childProcess.spawn(cmd, args, { detached: true })
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
|
||||
let killTimer
|
||||
|
||||
const cleanup = lodashOnce(function (err) {
|
||||
if (killTimer) {
|
||||
clearTimeout(killTimer)
|
||||
}
|
||||
callback(err, stdout, stderr)
|
||||
})
|
||||
|
||||
if (options.timeout) {
|
||||
killTimer = setTimeout(function () {
|
||||
try {
|
||||
// use negative process id to kill process group
|
||||
process.kill(-child.pid, options.killSignal || 'SIGTERM')
|
||||
} catch (error) {
|
||||
cleanup(
|
||||
new FailedCommandError('failed to kill process after timeout', {
|
||||
command,
|
||||
options,
|
||||
pid: child.pid,
|
||||
})
|
||||
)
|
||||
}
|
||||
}, options.timeout)
|
||||
}
|
||||
|
||||
child.on('close', function (code, signal) {
|
||||
if (code || signal) {
|
||||
return cleanup(
|
||||
new FailedCommandError(command, code || signal, stdout, stderr)
|
||||
)
|
||||
}
|
||||
|
||||
cleanup()
|
||||
})
|
||||
|
||||
child.on('error', err => {
|
||||
cleanup(err)
|
||||
})
|
||||
child.stdout.on('data', chunk => {
|
||||
stdout += chunk
|
||||
})
|
||||
child.stderr.on('data', chunk => {
|
||||
stderr += chunk
|
||||
})
|
||||
}
|
||||
|
||||
function safeExecPromise(command, options) {
|
||||
return new Promise((resolve, reject) => {
|
||||
safeExec(command, options, (err, stdout, stderr) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
}
|
||||
resolve({ stdout, stderr })
|
||||
})
|
||||
})
|
||||
}
|
12
services/filestore/buildscript.txt
Normal file
12
services/filestore/buildscript.txt
Normal file
@@ -0,0 +1,12 @@
|
||||
filestore
|
||||
--data-dirs=uploads,user_files,template_files
|
||||
--dependencies=s3,gcs
|
||||
--docker-repos=us-east1-docker.pkg.dev/overleaf-ops/ol-docker
|
||||
--env-add=ENABLE_CONVERSIONS="true",USE_PROM_METRICS="true",AWS_S3_USER_FILES_STORAGE_CLASS=REDUCED_REDUNDANCY,AWS_S3_USER_FILES_BUCKET_NAME=fake-user-files,AWS_S3_USER_FILES_DEK_BUCKET_NAME=fake-user-files-dek,AWS_S3_TEMPLATE_FILES_BUCKET_NAME=fake-template-files,GCS_USER_FILES_BUCKET_NAME=fake-gcs-user-files,GCS_TEMPLATE_FILES_BUCKET_NAME=fake-gcs-template-files
|
||||
--env-pass-through=
|
||||
--esmock-loader=False
|
||||
--node-version=20.18.2
|
||||
--public-repo=True
|
||||
--script-version=4.7.0
|
||||
--test-acceptance-shards=SHARD_01_,SHARD_02_,SHARD_03_
|
||||
--use-large-ci-runner=True
|
120
services/filestore/config/settings.defaults.js
Normal file
120
services/filestore/config/settings.defaults.js
Normal file
@@ -0,0 +1,120 @@
|
||||
const Path = require('node:path')
|
||||
|
||||
// environment variables renamed for consistency
|
||||
// use AWS_ACCESS_KEY_ID-style going forward
|
||||
if (process.env.AWS_KEY && !process.env.AWS_ACCESS_KEY_ID) {
|
||||
process.env.AWS_ACCESS_KEY_ID = process.env.AWS_KEY
|
||||
}
|
||||
if (process.env.AWS_SECRET && !process.env.AWS_SECRET_ACCESS_KEY) {
|
||||
process.env.AWS_SECRET_ACCESS_KEY = process.env.AWS_SECRET
|
||||
}
|
||||
|
||||
// pre-backend setting, fall back to old behaviour
|
||||
if (process.env.BACKEND == null) {
|
||||
if (process.env.AWS_ACCESS_KEY_ID || process.env.S3_BUCKET_CREDENTIALS) {
|
||||
process.env.BACKEND = 's3'
|
||||
process.env.USER_FILES_BUCKET_NAME =
|
||||
process.env.AWS_S3_USER_FILES_BUCKET_NAME
|
||||
process.env.TEMPLATE_FILES_BUCKET_NAME =
|
||||
process.env.AWS_S3_TEMPLATE_FILES_BUCKET_NAME
|
||||
} else {
|
||||
process.env.BACKEND = 'fs'
|
||||
process.env.USER_FILES_BUCKET_NAME = Path.join(__dirname, '../user_files')
|
||||
process.env.TEMPLATE_FILES_BUCKET_NAME = Path.join(
|
||||
__dirname,
|
||||
'../template_files'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const settings = {
|
||||
internal: {
|
||||
filestore: {
|
||||
port: 3009,
|
||||
host: process.env.LISTEN_ADDRESS || '127.0.0.1',
|
||||
},
|
||||
},
|
||||
|
||||
filestore: {
|
||||
// Which backend persistor to use.
|
||||
// Choices are
|
||||
// s3 - Amazon S3
|
||||
// fs - local filesystem
|
||||
// gcs - Google Cloud Storage
|
||||
backend: process.env.BACKEND,
|
||||
|
||||
gcs: {
|
||||
endpoint: process.env.GCS_API_ENDPOINT
|
||||
? {
|
||||
apiEndpoint: process.env.GCS_API_ENDPOINT,
|
||||
projectId: process.env.GCS_PROJECT_ID,
|
||||
}
|
||||
: undefined,
|
||||
unlockBeforeDelete: process.env.GCS_UNLOCK_BEFORE_DELETE === 'true', // unlock an event-based hold before deleting. default false
|
||||
deletedBucketSuffix: process.env.GCS_DELETED_BUCKET_SUFFIX, // if present, copy file to another bucket on delete. default null
|
||||
deleteConcurrency: parseInt(process.env.GCS_DELETE_CONCURRENCY) || 50,
|
||||
signedUrlExpiryInMs: parseInt(process.env.LINK_EXPIRY_TIMEOUT || 60000),
|
||||
},
|
||||
|
||||
s3: {
|
||||
key: process.env.AWS_ACCESS_KEY_ID,
|
||||
secret: process.env.AWS_SECRET_ACCESS_KEY,
|
||||
endpoint: process.env.AWS_S3_ENDPOINT,
|
||||
pathStyle: process.env.AWS_S3_PATH_STYLE,
|
||||
partSize: process.env.AWS_S3_PARTSIZE || 100 * 1024 * 1024,
|
||||
bucketCreds: process.env.S3_BUCKET_CREDENTIALS
|
||||
? JSON.parse(process.env.S3_BUCKET_CREDENTIALS)
|
||||
: undefined,
|
||||
},
|
||||
|
||||
// GCS should be configured by the service account on the kubernetes pod. See GOOGLE_APPLICATION_CREDENTIALS,
|
||||
// which will be picked up automatically.
|
||||
|
||||
stores: {
|
||||
user_files: process.env.USER_FILES_BUCKET_NAME,
|
||||
template_files: process.env.TEMPLATE_FILES_BUCKET_NAME,
|
||||
|
||||
// allow signed links to be generated for these buckets
|
||||
project_blobs: process.env.OVERLEAF_EDITOR_PROJECT_BLOBS_BUCKET,
|
||||
global_blobs: process.env.OVERLEAF_EDITOR_BLOBS_BUCKET,
|
||||
},
|
||||
|
||||
fallback: process.env.FALLBACK_BACKEND
|
||||
? {
|
||||
backend: process.env.FALLBACK_BACKEND,
|
||||
// mapping of bucket names on the fallback, to bucket names on the primary.
|
||||
// e.g. { myS3UserFilesBucketName: 'myGoogleUserFilesBucketName' }
|
||||
buckets: JSON.parse(process.env.FALLBACK_BUCKET_MAPPING || '{}'),
|
||||
copyOnMiss: process.env.COPY_ON_MISS === 'true',
|
||||
}
|
||||
: undefined,
|
||||
|
||||
allowRedirects: process.env.ALLOW_REDIRECTS === 'true',
|
||||
},
|
||||
|
||||
path: {
|
||||
uploadFolder: Path.join(__dirname, '../uploads'),
|
||||
},
|
||||
|
||||
commands: {
|
||||
// Any commands to wrap the convert utility in, for example ["nice"], or ["firejail", "--profile=/etc/firejail/convert.profile"]
|
||||
convertCommandPrefix: [],
|
||||
},
|
||||
|
||||
enableConversions: process.env.ENABLE_CONVERSIONS === 'true',
|
||||
|
||||
gracefulShutdownDelayInMs:
|
||||
parseInt(process.env.GRACEFUL_SHUTDOWN_DELAY_SECONDS ?? '30', 10) * 1000,
|
||||
}
|
||||
|
||||
// Filestore health check
|
||||
// ----------------------
|
||||
// Project and file details to check in persistor when calling /health_check
|
||||
if (process.env.HEALTH_CHECK_PROJECT_ID && process.env.HEALTH_CHECK_FILE_ID) {
|
||||
settings.health_check = {
|
||||
project_id: process.env.HEALTH_CHECK_PROJECT_ID,
|
||||
file_id: process.env.HEALTH_CHECK_FILE_ID,
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = settings
|
203
services/filestore/docker-compose.ci.yml
Normal file
203
services/filestore/docker-compose.ci.yml
Normal file
@@ -0,0 +1,203 @@
|
||||
# This file was auto-generated, do not edit it directly.
|
||||
# Instead run bin/update_build_scripts from
|
||||
# https://github.com/overleaf/internal/
|
||||
|
||||
version: "2.3"
|
||||
|
||||
services:
|
||||
test_unit:
|
||||
image: ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER
|
||||
user: node
|
||||
command: npm run test:unit:_run
|
||||
environment:
|
||||
NODE_ENV: test
|
||||
NODE_OPTIONS: "--unhandled-rejections=strict"
|
||||
|
||||
|
||||
test_acceptance:
|
||||
build: .
|
||||
image: ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER
|
||||
environment:
|
||||
ELASTIC_SEARCH_DSN: es:9200
|
||||
MONGO_HOST: mongo
|
||||
POSTGRES_HOST: postgres
|
||||
AWS_S3_ENDPOINT: https://minio:9000
|
||||
AWS_S3_PATH_STYLE: 'true'
|
||||
AWS_ACCESS_KEY_ID: OVERLEAF_FILESTORE_S3_ACCESS_KEY_ID
|
||||
AWS_SECRET_ACCESS_KEY: OVERLEAF_FILESTORE_S3_SECRET_ACCESS_KEY
|
||||
MINIO_ROOT_USER: MINIO_ROOT_USER
|
||||
MINIO_ROOT_PASSWORD: MINIO_ROOT_PASSWORD
|
||||
GCS_API_ENDPOINT: http://gcs:9090
|
||||
GCS_PROJECT_ID: fake
|
||||
STORAGE_EMULATOR_HOST: http://gcs:9090/storage/v1
|
||||
MOCHA_GREP: ${MOCHA_GREP}
|
||||
NODE_ENV: test
|
||||
NODE_OPTIONS: "--unhandled-rejections=strict"
|
||||
ENABLE_CONVERSIONS: "true"
|
||||
USE_PROM_METRICS: "true"
|
||||
AWS_S3_USER_FILES_STORAGE_CLASS: REDUCED_REDUNDANCY
|
||||
AWS_S3_USER_FILES_BUCKET_NAME: fake-user-files
|
||||
AWS_S3_USER_FILES_DEK_BUCKET_NAME: fake-user-files-dek
|
||||
AWS_S3_TEMPLATE_FILES_BUCKET_NAME: fake-template-files
|
||||
GCS_USER_FILES_BUCKET_NAME: fake-gcs-user-files
|
||||
GCS_TEMPLATE_FILES_BUCKET_NAME: fake-gcs-template-files
|
||||
volumes:
|
||||
- ./test/acceptance/certs:/certs
|
||||
depends_on:
|
||||
certs:
|
||||
condition: service_completed_successfully
|
||||
minio:
|
||||
condition: service_started
|
||||
minio_setup:
|
||||
condition: service_completed_successfully
|
||||
gcs:
|
||||
condition: service_healthy
|
||||
user: node
|
||||
command: npm run test:acceptance
|
||||
|
||||
|
||||
tar:
|
||||
build: .
|
||||
image: ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER
|
||||
volumes:
|
||||
- ./:/tmp/build/
|
||||
command: tar -czf /tmp/build/build.tar.gz --exclude=build.tar.gz --exclude-vcs .
|
||||
user: root
|
||||
certs:
|
||||
image: node:20.18.2
|
||||
volumes:
|
||||
- ./test/acceptance/certs:/certs
|
||||
working_dir: /certs
|
||||
entrypoint: sh
|
||||
command:
|
||||
- '-cex'
|
||||
- |
|
||||
if [ ! -f ./certgen ]; then
|
||||
wget -O ./certgen "https://github.com/minio/certgen/releases/download/v1.3.0/certgen-linux-$(dpkg --print-architecture)"
|
||||
chmod +x ./certgen
|
||||
fi
|
||||
if [ ! -f private.key ] || [ ! -f public.crt ]; then
|
||||
./certgen -host minio
|
||||
fi
|
||||
|
||||
minio:
|
||||
image: minio/minio:RELEASE.2024-10-13T13-34-11Z
|
||||
command: server /data
|
||||
volumes:
|
||||
- ./test/acceptance/certs:/root/.minio/certs
|
||||
environment:
|
||||
MINIO_ROOT_USER: MINIO_ROOT_USER
|
||||
MINIO_ROOT_PASSWORD: MINIO_ROOT_PASSWORD
|
||||
depends_on:
|
||||
certs:
|
||||
condition: service_completed_successfully
|
||||
|
||||
minio_setup:
|
||||
depends_on:
|
||||
certs:
|
||||
condition: service_completed_successfully
|
||||
minio:
|
||||
condition: service_started
|
||||
image: minio/mc:RELEASE.2024-10-08T09-37-26Z
|
||||
volumes:
|
||||
- ./test/acceptance/certs:/root/.mc/certs/CAs
|
||||
entrypoint: sh
|
||||
command:
|
||||
- '-cex'
|
||||
- |
|
||||
sleep 1
|
||||
mc alias set s3 https://minio:9000 MINIO_ROOT_USER MINIO_ROOT_PASSWORD \
|
||||
|| sleep 3 && \
|
||||
mc alias set s3 https://minio:9000 MINIO_ROOT_USER MINIO_ROOT_PASSWORD \
|
||||
|| sleep 3 && \
|
||||
mc alias set s3 https://minio:9000 MINIO_ROOT_USER MINIO_ROOT_PASSWORD \
|
||||
|| sleep 3 && \
|
||||
mc alias set s3 https://minio:9000 MINIO_ROOT_USER MINIO_ROOT_PASSWORD
|
||||
mc mb --ignore-existing s3/fake-user-files
|
||||
mc mb --ignore-existing s3/fake-user-files-dek
|
||||
mc mb --ignore-existing s3/fake-template-files
|
||||
mc admin user add s3 \
|
||||
OVERLEAF_FILESTORE_S3_ACCESS_KEY_ID \
|
||||
OVERLEAF_FILESTORE_S3_SECRET_ACCESS_KEY
|
||||
|
||||
echo '
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:ListBucket"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::fake-user-files"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutObject",
|
||||
"s3:GetObject",
|
||||
"s3:DeleteObject"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::fake-user-files/*"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:ListBucket"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::fake-user-files-dek"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutObject",
|
||||
"s3:GetObject",
|
||||
"s3:DeleteObject"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::fake-user-files-dek/*"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:ListBucket"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::fake-template-files"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutObject",
|
||||
"s3:GetObject",
|
||||
"s3:DeleteObject"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::fake-template-files/*"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:ListBucket"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::random-bucket-*"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutObject",
|
||||
"s3:GetObject",
|
||||
"s3:DeleteObject"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::random-bucket-*"
|
||||
}
|
||||
]
|
||||
}' > policy-filestore.json
|
||||
|
||||
mc admin policy create s3 overleaf-filestore policy-filestore.json
|
||||
mc admin policy attach s3 overleaf-filestore \
|
||||
--user=OVERLEAF_FILESTORE_S3_ACCESS_KEY_ID
|
||||
gcs:
|
||||
image: fsouza/fake-gcs-server:1.45.2
|
||||
command: ["--port=9090", "--scheme=http"]
|
||||
healthcheck:
|
||||
test: wget --quiet --output-document=/dev/null http://localhost:9090/storage/v1/b
|
||||
interval: 1s
|
||||
retries: 20
|
211
services/filestore/docker-compose.yml
Normal file
211
services/filestore/docker-compose.yml
Normal file
@@ -0,0 +1,211 @@
|
||||
# This file was auto-generated, do not edit it directly.
|
||||
# Instead run bin/update_build_scripts from
|
||||
# https://github.com/overleaf/internal/
|
||||
|
||||
version: "2.3"
|
||||
|
||||
services:
|
||||
test_unit:
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: services/filestore/Dockerfile
|
||||
target: base
|
||||
volumes:
|
||||
- .:/overleaf/services/filestore
|
||||
- ../../node_modules:/overleaf/node_modules
|
||||
- ../../libraries:/overleaf/libraries
|
||||
working_dir: /overleaf/services/filestore
|
||||
environment:
|
||||
MOCHA_GREP: ${MOCHA_GREP}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-}
|
||||
NODE_ENV: test
|
||||
NODE_OPTIONS: "--unhandled-rejections=strict"
|
||||
command: npm run --silent test:unit
|
||||
user: node
|
||||
|
||||
test_acceptance:
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: services/filestore/Dockerfile
|
||||
target: base
|
||||
volumes:
|
||||
- .:/overleaf/services/filestore
|
||||
- ../../node_modules:/overleaf/node_modules
|
||||
- ../../libraries:/overleaf/libraries
|
||||
- ./test/acceptance/certs:/certs
|
||||
working_dir: /overleaf/services/filestore
|
||||
environment:
|
||||
ELASTIC_SEARCH_DSN: es:9200
|
||||
MONGO_HOST: mongo
|
||||
POSTGRES_HOST: postgres
|
||||
AWS_S3_ENDPOINT: https://minio:9000
|
||||
AWS_S3_PATH_STYLE: 'true'
|
||||
AWS_ACCESS_KEY_ID: OVERLEAF_FILESTORE_S3_ACCESS_KEY_ID
|
||||
AWS_SECRET_ACCESS_KEY: OVERLEAF_FILESTORE_S3_SECRET_ACCESS_KEY
|
||||
MINIO_ROOT_USER: MINIO_ROOT_USER
|
||||
MINIO_ROOT_PASSWORD: MINIO_ROOT_PASSWORD
|
||||
GCS_API_ENDPOINT: http://gcs:9090
|
||||
GCS_PROJECT_ID: fake
|
||||
STORAGE_EMULATOR_HOST: http://gcs:9090/storage/v1
|
||||
MOCHA_GREP: ${MOCHA_GREP}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-}
|
||||
NODE_ENV: test
|
||||
NODE_OPTIONS: "--unhandled-rejections=strict"
|
||||
ENABLE_CONVERSIONS: "true"
|
||||
USE_PROM_METRICS: "true"
|
||||
AWS_S3_USER_FILES_STORAGE_CLASS: REDUCED_REDUNDANCY
|
||||
AWS_S3_USER_FILES_BUCKET_NAME: fake-user-files
|
||||
AWS_S3_USER_FILES_DEK_BUCKET_NAME: fake-user-files-dek
|
||||
AWS_S3_TEMPLATE_FILES_BUCKET_NAME: fake-template-files
|
||||
GCS_USER_FILES_BUCKET_NAME: fake-gcs-user-files
|
||||
GCS_TEMPLATE_FILES_BUCKET_NAME: fake-gcs-template-files
|
||||
user: node
|
||||
depends_on:
|
||||
certs:
|
||||
condition: service_completed_successfully
|
||||
minio:
|
||||
condition: service_started
|
||||
minio_setup:
|
||||
condition: service_completed_successfully
|
||||
gcs:
|
||||
condition: service_healthy
|
||||
command: npm run --silent test:acceptance
|
||||
|
||||
certs:
|
||||
image: node:20.18.2
|
||||
volumes:
|
||||
- ./test/acceptance/certs:/certs
|
||||
working_dir: /certs
|
||||
entrypoint: sh
|
||||
command:
|
||||
- '-cex'
|
||||
- |
|
||||
if [ ! -f ./certgen ]; then
|
||||
wget -O ./certgen "https://github.com/minio/certgen/releases/download/v1.3.0/certgen-linux-$(dpkg --print-architecture)"
|
||||
chmod +x ./certgen
|
||||
fi
|
||||
if [ ! -f private.key ] || [ ! -f public.crt ]; then
|
||||
./certgen -host minio
|
||||
fi
|
||||
|
||||
minio:
|
||||
image: minio/minio:RELEASE.2024-10-13T13-34-11Z
|
||||
command: server /data
|
||||
volumes:
|
||||
- ./test/acceptance/certs:/root/.minio/certs
|
||||
environment:
|
||||
MINIO_ROOT_USER: MINIO_ROOT_USER
|
||||
MINIO_ROOT_PASSWORD: MINIO_ROOT_PASSWORD
|
||||
depends_on:
|
||||
certs:
|
||||
condition: service_completed_successfully
|
||||
|
||||
minio_setup:
|
||||
depends_on:
|
||||
certs:
|
||||
condition: service_completed_successfully
|
||||
minio:
|
||||
condition: service_started
|
||||
image: minio/mc:RELEASE.2024-10-08T09-37-26Z
|
||||
volumes:
|
||||
- ./test/acceptance/certs:/root/.mc/certs/CAs
|
||||
entrypoint: sh
|
||||
command:
|
||||
- '-cex'
|
||||
- |
|
||||
sleep 1
|
||||
mc alias set s3 https://minio:9000 MINIO_ROOT_USER MINIO_ROOT_PASSWORD \
|
||||
|| sleep 3 && \
|
||||
mc alias set s3 https://minio:9000 MINIO_ROOT_USER MINIO_ROOT_PASSWORD \
|
||||
|| sleep 3 && \
|
||||
mc alias set s3 https://minio:9000 MINIO_ROOT_USER MINIO_ROOT_PASSWORD \
|
||||
|| sleep 3 && \
|
||||
mc alias set s3 https://minio:9000 MINIO_ROOT_USER MINIO_ROOT_PASSWORD
|
||||
mc mb --ignore-existing s3/fake-user-files
|
||||
mc mb --ignore-existing s3/fake-user-files-dek
|
||||
mc mb --ignore-existing s3/fake-template-files
|
||||
mc admin user add s3 \
|
||||
OVERLEAF_FILESTORE_S3_ACCESS_KEY_ID \
|
||||
OVERLEAF_FILESTORE_S3_SECRET_ACCESS_KEY
|
||||
|
||||
echo '
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:ListBucket"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::fake-user-files"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutObject",
|
||||
"s3:GetObject",
|
||||
"s3:DeleteObject"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::fake-user-files/*"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:ListBucket"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::fake-user-files-dek"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutObject",
|
||||
"s3:GetObject",
|
||||
"s3:DeleteObject"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::fake-user-files-dek/*"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:ListBucket"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::fake-template-files"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutObject",
|
||||
"s3:GetObject",
|
||||
"s3:DeleteObject"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::fake-template-files/*"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:ListBucket"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::random-bucket-*"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutObject",
|
||||
"s3:GetObject",
|
||||
"s3:DeleteObject"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::random-bucket-*"
|
||||
}
|
||||
]
|
||||
}' > policy-filestore.json
|
||||
|
||||
mc admin policy create s3 overleaf-filestore policy-filestore.json
|
||||
mc admin policy attach s3 overleaf-filestore \
|
||||
--user=OVERLEAF_FILESTORE_S3_ACCESS_KEY_ID
|
||||
gcs:
|
||||
image: fsouza/fake-gcs-server:1.45.2
|
||||
command: ["--port=9090", "--scheme=http"]
|
||||
healthcheck:
|
||||
test: wget --quiet --output-document=/dev/null http://localhost:9090/storage/v1/b
|
||||
interval: 1s
|
||||
retries: 20
|
40
services/filestore/firejail/convert.profile
Normal file
40
services/filestore/firejail/convert.profile
Normal file
@@ -0,0 +1,40 @@
|
||||
# Convert (ImageMagick profile)
|
||||
|
||||
include /etc/firejail/disable-common.inc
|
||||
include /etc/firejail/disable-devel.inc
|
||||
# include /etc/firejail/disable-mgmt.inc ## removed in firejail 0.9.40
|
||||
# include /etc/firejail/disable-secret.inc ## removed in firejail 0.9.40
|
||||
|
||||
read-only /bin
|
||||
blacklist /boot
|
||||
blacklist /dev
|
||||
read-only /etc
|
||||
read-only /home
|
||||
read-only /lib
|
||||
read-only /lib64
|
||||
blacklist /media
|
||||
blacklist /mnt
|
||||
blacklist /opt
|
||||
blacklist /root
|
||||
read-only /run
|
||||
blacklist /sbin
|
||||
blacklist /selinux
|
||||
blacklist /src
|
||||
blacklist /sys
|
||||
read-only /usr
|
||||
blacklist /var
|
||||
|
||||
caps.drop all
|
||||
noroot
|
||||
nogroups
|
||||
protocol unix
|
||||
net none
|
||||
private-tmp
|
||||
private-dev
|
||||
shell none
|
||||
|
||||
seccomp.keep accept,accept4,access,alarm,arch_prctl,bind,brk,capget,capset,chdir,chmod,chown,chroot,clock_getres,clock_gettime,clock_nanosleep,clone,close,connect,creat,dup,dup2,dup3,epoll_create,epoll_create1,epoll_ctl,epoll_ctl_old,epoll_pwait,epoll_wait,epoll_wait_old,eventfd,eventfd2,execve,execveat,exit,exit_group,faccessat,fadvise64,fallocate,fanotify_init,fanotify_mark,fchdir,fchmod,fchmodat,fchown,fchownat,fcntl,fdatasync,fgetxattr,flistxattr,flock,fork,fremovexattr,fsetxattr,fstat,fstatfs,fsync,ftruncate,futex,futimesat,get_robust_list,get_thread_area,getcpu,getcwd,getdents,getdents64,getegid,geteuid,getgid,getgroups,getitimer,getpeername,getpgid,getpgrp,getpid,getppid,getpriority,getrandom,getresgid,getresuid,getrlimit,getrusage,getsid,getsockname,getsockopt,gettid,gettimeofday,getuid,getxattr,inotify_add_watch,inotify_init,inotify_init1,inotify_rm_watch,io_cancel,io_destroy,io_getevents,io_setup,io_submit,ioctl,ioprio_get,ioprio_set,kill,lchown,lgetxattr,link,linkat,listen,listxattr,llistxattr,lremovexattr,lseek,lsetxattr,lstat,madvise,memfd_create,mincore,mkdir,mkdirat,mknod,mknodat,mlock,mlockall,mmap,modify_ldt,mprotect,mq_getsetattr,mq_notify,mq_open,mq_timedreceive,mq_timedsend,mq_unlink,mremap,msgctl,msgget,msgrcv,msgsnd,msync,munlock,munlockall,munmap,nanosleep,newfstatat,open,openat,pause,personality,pipe,pipe2,poll,ppoll,prctl,pread64,preadv,prlimit64,pselect6,pwrite64,pwritev,read,readahead,readlink,readlinkat,readv,recvfrom,recvmmsg,recvmsg,remap_file_pages,removexattr,rename,renameat,renameat2,restart_syscall,rmdir,rt_sigaction,rt_sigpending,rt_sigprocmask,rt_sigqueueinfo,rt_sigreturn,rt_sigsuspend,rt_sigtimedwait,rt_tgsigqueueinfo,sched_get_priority_max,sched_get_priority_min,sched_getaffinity,sched_getattr,sched_getparam,sched_getscheduler,sched_rr_get_interval,sched_setaffinity,sched_setattr,sched_setparam,sched_setscheduler,sched_yield,seccomp,select,semctl,semget,semop,semtimedop,sendfile,sendmmsg,sendmsg,sendto,set_robust_list,set_thread_area,set_tid_address,setdomainname,setfsgid,setfsuid,setgid,setgroups,sethostname,setitimer,setpgid,setpriority,setregid,setresgid,setresuid,setreuid,setrlimit,setsid,setsockopt,setuid,setxattr,shmat,shmctl,shmdt,shmget,shutdown,sigaltstack,signalfd,signalfd4,socket,socketpair,splice,stat,statfs,symlink,symlinkat,sync,sync_file_range,syncfs,sysinfo,syslog,tee,tgkill,time,timer_create,timer_delete,timer_getoverrun,timer_gettime,timer_settime,timerfd_create,timerfd_gettime,timerfd_settime,times,tkill,truncate,umask,uname,unlink,unlinkat,utime,utimensat,utimes,vfork,vhangup,vmsplice,wait4,waitid,write,writev,unshare
|
||||
|
||||
rlimit-fsize 524288000 #500Mb
|
||||
rlimit-nproc 600 #if too low this can cause error: Error fork:sandbox(774): Resource temporarily unavailable
|
||||
rlimit-nofile 100
|
23
services/filestore/install_deps.sh
Executable file
23
services/filestore/install_deps.sh
Executable file
@@ -0,0 +1,23 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -ex
|
||||
|
||||
apt-get update
|
||||
|
||||
apt-get install ghostscript imagemagick optipng iproute2 --yes
|
||||
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Allow ImageMagick to process PDF files. Filestore does pdf to image
|
||||
# conversion for the templates service.
|
||||
patch /etc/ImageMagick-6/policy.xml <<EOF
|
||||
--- old.xml 2022-03-23 09:16:03.985433900 -0400
|
||||
+++ new.xml 2022-03-23 09:16:18.625471992 -0400
|
||||
@@ -91,6 +91,5 @@
|
||||
<policy domain="coder" rights="none" pattern="PS2" />
|
||||
<policy domain="coder" rights="none" pattern="PS3" />
|
||||
<policy domain="coder" rights="none" pattern="EPS" />
|
||||
- <policy domain="coder" rights="none" pattern="PDF" />
|
||||
<policy domain="coder" rights="none" pattern="XPS" />
|
||||
</policymap>
|
||||
EOF
|
49
services/filestore/package.json
Normal file
49
services/filestore/package.json
Normal file
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"name": "@overleaf/filestore",
|
||||
"description": "An API for CRUD operations on binary files stored in S3",
|
||||
"private": true,
|
||||
"main": "app.js",
|
||||
"scripts": {
|
||||
"test:acceptance:run": "mocha --recursive --reporter spec --timeout 15000 $@ test/acceptance/js",
|
||||
"test:acceptance": "npm run test:acceptance:_run -- --grep=$MOCHA_GREP",
|
||||
"test:unit:run": "mocha --recursive --reporter spec $@ test/unit/js",
|
||||
"test:unit": "npm run test:unit:_run -- --grep=$MOCHA_GREP",
|
||||
"start": "node app.js",
|
||||
"nodemon": "node --watch app.js",
|
||||
"lint": "eslint --max-warnings 0 --format unix .",
|
||||
"format": "prettier --list-different $PWD/'**/*.*js'",
|
||||
"format:fix": "prettier --write $PWD/'**/*.*js'",
|
||||
"test:acceptance:_run": "mocha --recursive --reporter spec --timeout 15000 --exit $@ test/acceptance/js",
|
||||
"test:unit:_run": "mocha --recursive --reporter spec $@ test/unit/js",
|
||||
"lint:fix": "eslint --fix .",
|
||||
"types:check": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@overleaf/logger": "*",
|
||||
"@overleaf/metrics": "*",
|
||||
"@overleaf/o-error": "*",
|
||||
"@overleaf/object-persistor": "*",
|
||||
"@overleaf/settings": "*",
|
||||
"@overleaf/stream-utils": "^0.1.0",
|
||||
"body-parser": "^1.20.3",
|
||||
"bunyan": "^1.8.15",
|
||||
"express": "^4.21.2",
|
||||
"glob": "^7.1.6",
|
||||
"lodash.once": "^4.1.1",
|
||||
"node-fetch": "^2.7.0",
|
||||
"range-parser": "^1.2.1",
|
||||
"tiny-async-pool": "^1.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@google-cloud/storage": "^6.10.1",
|
||||
"chai": "^4.3.6",
|
||||
"chai-as-promised": "^7.1.1",
|
||||
"mocha": "^11.1.0",
|
||||
"mongodb": "6.12.0",
|
||||
"sandboxed-module": "2.0.4",
|
||||
"sinon": "9.0.2",
|
||||
"sinon-chai": "^3.7.0",
|
||||
"streamifier": "^0.1.1",
|
||||
"typescript": "^5.0.4"
|
||||
}
|
||||
}
|
2
services/filestore/test/acceptance/certs/.gitignore
vendored
Normal file
2
services/filestore/test/acceptance/certs/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
*
|
||||
!.gitignore
|
@@ -0,0 +1,5 @@
|
||||
FROM fsouza/fake-gcs-server:1.20
|
||||
RUN apk add --update --no-cache curl
|
||||
COPY healthcheck.sh /healthcheck.sh
|
||||
HEALTHCHECK --interval=1s --timeout=1s --retries=30 CMD /healthcheck.sh http://127.0.0.1:9090
|
||||
CMD ["--port=9090", "--scheme=http"]
|
@@ -0,0 +1,4 @@
|
||||
FROM adobe/s3mock:2.4.14
|
||||
RUN apk add --update --no-cache curl
|
||||
COPY healthcheck.sh /healthcheck.sh
|
||||
HEALTHCHECK --interval=1s --timeout=1s --retries=30 CMD /healthcheck.sh http://127.0.0.1:9090
|
9
services/filestore/test/acceptance/deps/healthcheck.sh
Executable file
9
services/filestore/test/acceptance/deps/healthcheck.sh
Executable file
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
|
||||
# health check to allow 404 status code as valid
|
||||
STATUSCODE=$(curl --silent --output /dev/null --write-out "%{http_code}" "$1")
|
||||
# will be 000 on non-http error (e.g. connection failure)
|
||||
if test "$STATUSCODE" -ge 500 || test "$STATUSCODE" -lt 200; then
|
||||
exit 1
|
||||
fi
|
||||
exit 0
|
42
services/filestore/test/acceptance/js/FilestoreApp.js
Normal file
42
services/filestore/test/acceptance/js/FilestoreApp.js
Normal file
@@ -0,0 +1,42 @@
|
||||
const ObjectPersistor = require('@overleaf/object-persistor')
|
||||
const Settings = require('@overleaf/settings')
|
||||
const { promisify } = require('node:util')
|
||||
const App = require('../../../app')
|
||||
const FileHandler = require('../../../app/js/FileHandler')
|
||||
|
||||
class FilestoreApp {
|
||||
async runServer() {
|
||||
if (!this.server) {
|
||||
await new Promise((resolve, reject) => {
|
||||
this.server = App.listen(
|
||||
Settings.internal.filestore.port,
|
||||
'127.0.0.1',
|
||||
err => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
this.persistor = ObjectPersistor({
|
||||
...Settings.filestore,
|
||||
paths: Settings.path,
|
||||
})
|
||||
FileHandler._TESTONLYSwapPersistorManager(this.persistor)
|
||||
}
|
||||
|
||||
async stop() {
|
||||
if (!this.server) return
|
||||
const closeServer = promisify(this.server.close).bind(this.server)
|
||||
try {
|
||||
await closeServer()
|
||||
} finally {
|
||||
delete this.server
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = FilestoreApp
|
1564
services/filestore/test/acceptance/js/FilestoreTests.js
Normal file
1564
services/filestore/test/acceptance/js/FilestoreTests.js
Normal file
File diff suppressed because it is too large
Load Diff
192
services/filestore/test/acceptance/js/TestConfig.js
Normal file
192
services/filestore/test/acceptance/js/TestConfig.js
Normal file
@@ -0,0 +1,192 @@
|
||||
const fs = require('node:fs')
|
||||
const Path = require('node:path')
|
||||
const crypto = require('node:crypto')
|
||||
const {
|
||||
RootKeyEncryptionKey,
|
||||
} = require('@overleaf/object-persistor/src/PerProjectEncryptedS3Persistor')
|
||||
|
||||
const AWS_S3_USER_FILES_STORAGE_CLASS =
|
||||
process.env.AWS_S3_USER_FILES_STORAGE_CLASS
|
||||
|
||||
// use functions to get a fresh copy, not a reference, each time
|
||||
function s3BaseConfig() {
|
||||
return {
|
||||
endpoint: process.env.AWS_S3_ENDPOINT,
|
||||
pathStyle: true,
|
||||
partSize: 100 * 1024 * 1024,
|
||||
ca: [fs.readFileSync('/certs/public.crt')],
|
||||
}
|
||||
}
|
||||
|
||||
function s3Config() {
|
||||
return {
|
||||
key: process.env.AWS_ACCESS_KEY_ID,
|
||||
secret: process.env.AWS_SECRET_ACCESS_KEY,
|
||||
...s3BaseConfig(),
|
||||
}
|
||||
}
|
||||
|
||||
const S3SSECKeys = [
|
||||
new RootKeyEncryptionKey(
|
||||
crypto.generateKeySync('aes', { length: 256 }).export(),
|
||||
Buffer.alloc(32)
|
||||
),
|
||||
]
|
||||
|
||||
function s3SSECConfig() {
|
||||
return {
|
||||
...s3Config(),
|
||||
ignoreErrorsFromDEKReEncryption: false,
|
||||
automaticallyRotateDEKEncryption: true,
|
||||
dataEncryptionKeyBucketName: process.env.AWS_S3_USER_FILES_DEK_BUCKET_NAME,
|
||||
pathToProjectFolder(_bucketName, path) {
|
||||
const match = path.match(/^[a-f0-9]{24}\//)
|
||||
if (!match) throw new Error('not a project-folder')
|
||||
const [projectFolder] = match
|
||||
return projectFolder
|
||||
},
|
||||
async getRootKeyEncryptionKeys() {
|
||||
return S3SSECKeys
|
||||
},
|
||||
storageClass: {
|
||||
[process.env.AWS_S3_USER_FILES_BUCKET_NAME]:
|
||||
AWS_S3_USER_FILES_STORAGE_CLASS,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function s3ConfigDefaultProviderCredentials() {
|
||||
return {
|
||||
...s3BaseConfig(),
|
||||
}
|
||||
}
|
||||
|
||||
function s3Stores() {
|
||||
return {
|
||||
user_files: process.env.AWS_S3_USER_FILES_BUCKET_NAME,
|
||||
template_files: process.env.AWS_S3_TEMPLATE_FILES_BUCKET_NAME,
|
||||
}
|
||||
}
|
||||
|
||||
function gcsConfig() {
|
||||
return {
|
||||
endpoint: {
|
||||
apiEndpoint: process.env.GCS_API_ENDPOINT,
|
||||
projectId: 'fake',
|
||||
},
|
||||
directoryKeyRegex: /^[0-9a-fA-F]{24}\/[0-9a-fA-F]{24}/,
|
||||
unlockBeforeDelete: false, // fake-gcs does not support this
|
||||
deletedBucketSuffix: '-deleted',
|
||||
}
|
||||
}
|
||||
|
||||
function gcsStores() {
|
||||
return {
|
||||
user_files: process.env.GCS_USER_FILES_BUCKET_NAME,
|
||||
template_files: process.env.GCS_TEMPLATE_FILES_BUCKET_NAME,
|
||||
}
|
||||
}
|
||||
|
||||
function fsStores() {
|
||||
return {
|
||||
user_files: Path.resolve(__dirname, '../../../user_files'),
|
||||
template_files: Path.resolve(__dirname, '../../../template_files'),
|
||||
}
|
||||
}
|
||||
|
||||
function fallbackStores(primaryConfig, fallbackConfig) {
|
||||
return {
|
||||
[primaryConfig.user_files]: fallbackConfig.user_files,
|
||||
[primaryConfig.template_files]: fallbackConfig.template_files,
|
||||
}
|
||||
}
|
||||
|
||||
const BackendSettings = {
|
||||
SHARD_01_FSPersistor: {
|
||||
backend: 'fs',
|
||||
stores: fsStores(),
|
||||
},
|
||||
SHARD_01_S3Persistor: {
|
||||
backend: 's3',
|
||||
s3: s3Config(),
|
||||
stores: s3Stores(),
|
||||
},
|
||||
SHARD_01_S3PersistorDefaultProviderCredentials: {
|
||||
backend: 's3',
|
||||
s3: s3ConfigDefaultProviderCredentials(),
|
||||
stores: s3Stores(),
|
||||
},
|
||||
SHARD_01_GcsPersistor: {
|
||||
backend: 'gcs',
|
||||
gcs: gcsConfig(),
|
||||
stores: gcsStores(),
|
||||
},
|
||||
SHARD_01_PerProjectEncryptedS3Persistor: {
|
||||
backend: 's3SSEC',
|
||||
s3SSEC: s3SSECConfig(),
|
||||
stores: s3Stores(),
|
||||
},
|
||||
SHARD_02_FallbackS3ToFSPersistor: {
|
||||
backend: 's3',
|
||||
s3: s3Config(),
|
||||
stores: s3Stores(),
|
||||
fallback: {
|
||||
backend: 'fs',
|
||||
buckets: fallbackStores(s3Stores(), fsStores()),
|
||||
},
|
||||
},
|
||||
SHARD_02_FallbackFSToS3Persistor: {
|
||||
backend: 'fs',
|
||||
s3: s3Config(),
|
||||
stores: fsStores(),
|
||||
fallback: {
|
||||
backend: 's3',
|
||||
buckets: fallbackStores(fsStores(), s3Stores()),
|
||||
},
|
||||
},
|
||||
SHARD_03_FallbackGcsToS3Persistor: {
|
||||
backend: 'gcs',
|
||||
gcs: gcsConfig(),
|
||||
stores: gcsStores(),
|
||||
s3: s3Config(),
|
||||
fallback: {
|
||||
backend: 's3',
|
||||
buckets: fallbackStores(gcsStores(), s3Stores()),
|
||||
},
|
||||
},
|
||||
SHARD_03_FallbackS3ToGcsPersistor: {
|
||||
backend: 's3',
|
||||
// can use the same bucket names for gcs and s3 (in tests)
|
||||
stores: s3Stores(),
|
||||
s3: s3Config(),
|
||||
gcs: gcsConfig(),
|
||||
fallback: {
|
||||
backend: 'gcs',
|
||||
buckets: fallbackStores(s3Stores(), gcsStores()),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
function checkForUnexpectedTestFile() {
|
||||
const awareOfSharding = [
|
||||
'FilestoreApp.js',
|
||||
'FilestoreTests.js',
|
||||
'TestConfig.js',
|
||||
'TestHelper.js',
|
||||
]
|
||||
for (const file of fs.readdirSync(__dirname).sort()) {
|
||||
if (!awareOfSharding.includes(file)) {
|
||||
throw new Error(
|
||||
`Found new test file ${file}: All tests must be aware of the SHARD_ prefix.`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
checkForUnexpectedTestFile()
|
||||
|
||||
module.exports = {
|
||||
AWS_S3_USER_FILES_STORAGE_CLASS,
|
||||
BackendSettings,
|
||||
s3Config,
|
||||
s3SSECConfig,
|
||||
}
|
78
services/filestore/test/acceptance/js/TestHelper.js
Normal file
78
services/filestore/test/acceptance/js/TestHelper.js
Normal file
@@ -0,0 +1,78 @@
|
||||
const streamifier = require('streamifier')
|
||||
const fetch = require('node-fetch')
|
||||
const ObjectPersistor = require('@overleaf/object-persistor')
|
||||
|
||||
const { expect } = require('chai')
|
||||
|
||||
module.exports = {
|
||||
uploadStringToPersistor,
|
||||
getStringFromPersistor,
|
||||
expectPersistorToHaveFile,
|
||||
expectPersistorToHaveSomeFile,
|
||||
expectPersistorNotToHaveFile,
|
||||
streamToString,
|
||||
getMetric,
|
||||
}
|
||||
|
||||
async function getMetric(filestoreUrl, metric) {
|
||||
const res = await fetch(`${filestoreUrl}/metrics`)
|
||||
expect(res.status).to.equal(200)
|
||||
const metricRegex = new RegExp(`^${metric}{[^}]+} ([0-9]+)$`, 'gm')
|
||||
const body = await res.text()
|
||||
let v = 0
|
||||
// Sum up size="lt-128KiB" and size="gte-128KiB"
|
||||
for (const [, found] of body.matchAll(metricRegex)) {
|
||||
v += parseInt(found, 10) || 0
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
function streamToString(stream) {
|
||||
const chunks = []
|
||||
return new Promise((resolve, reject) => {
|
||||
stream.on('data', chunk => chunks.push(chunk))
|
||||
stream.on('error', reject)
|
||||
stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
|
||||
stream.resume()
|
||||
})
|
||||
}
|
||||
|
||||
async function uploadStringToPersistor(persistor, bucket, key, content) {
|
||||
const fileStream = streamifier.createReadStream(content)
|
||||
await persistor.sendStream(bucket, key, fileStream)
|
||||
}
|
||||
|
||||
async function getStringFromPersistor(persistor, bucket, key) {
|
||||
const stream = await persistor.getObjectStream(bucket, key, {})
|
||||
return await streamToString(stream)
|
||||
}
|
||||
|
||||
async function expectPersistorToHaveFile(persistor, bucket, key, content) {
|
||||
const foundContent = await getStringFromPersistor(persistor, bucket, key)
|
||||
expect(foundContent).to.equal(content)
|
||||
}
|
||||
|
||||
async function expectPersistorToHaveSomeFile(persistor, bucket, keys, content) {
|
||||
let foundContent
|
||||
for (const key of keys) {
|
||||
try {
|
||||
foundContent = await getStringFromPersistor(persistor, bucket, key)
|
||||
break
|
||||
} catch (err) {
|
||||
if (err instanceof ObjectPersistor.Errors.NotFoundError) {
|
||||
continue
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
if (foundContent === undefined) {
|
||||
expect.fail(`Could not find any of the specified keys: ${keys}`)
|
||||
}
|
||||
expect(foundContent).to.equal(content)
|
||||
}
|
||||
|
||||
async function expectPersistorNotToHaveFile(persistor, bucket, key) {
|
||||
await expect(
|
||||
getStringFromPersistor(persistor, bucket, key)
|
||||
).to.eventually.have.been.rejected.with.property('name', 'NotFoundError')
|
||||
}
|
BIN
services/filestore/test/fixtures/test.pdf
vendored
Normal file
BIN
services/filestore/test/fixtures/test.pdf
vendored
Normal file
Binary file not shown.
39
services/filestore/test/setup.js
Normal file
39
services/filestore/test/setup.js
Normal file
@@ -0,0 +1,39 @@
|
||||
const sinon = require('sinon')
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
|
||||
// ensure every ObjectId has the id string as a property for correct comparisons
|
||||
require('mongodb').ObjectId.cacheHexString = true
|
||||
|
||||
const sandbox = sinon.createSandbox()
|
||||
const stubs = {
|
||||
logger: {
|
||||
debug: sandbox.stub(),
|
||||
log: sandbox.stub(),
|
||||
info: sandbox.stub(),
|
||||
warn: sandbox.stub(),
|
||||
err: sandbox.stub(),
|
||||
error: sandbox.stub(),
|
||||
fatal: sandbox.stub(),
|
||||
},
|
||||
}
|
||||
|
||||
SandboxedModule.configure({
|
||||
requires: {
|
||||
'@overleaf/logger': stubs.logger,
|
||||
},
|
||||
sourceTransformers: {
|
||||
removeNodePrefix: function (source) {
|
||||
return source.replace(/require\(['"]node:/g, "require('")
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
exports.mochaHooks = {
|
||||
beforeEach() {
|
||||
this.logger = stubs.logger
|
||||
},
|
||||
|
||||
afterEach() {
|
||||
sandbox.reset()
|
||||
},
|
||||
}
|
336
services/filestore/test/unit/js/FileControllerTests.js
Normal file
336
services/filestore/test/unit/js/FileControllerTests.js
Normal file
@@ -0,0 +1,336 @@
|
||||
const sinon = require('sinon')
|
||||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
const Errors = require('../../../app/js/Errors')
|
||||
const modulePath = '../../../app/js/FileController.js'
|
||||
|
||||
describe('FileController', function () {
|
||||
let FileHandler, LocalFileWriter, FileController, req, res, next, stream
|
||||
const settings = {
|
||||
s3: {
|
||||
buckets: {
|
||||
user_files: 'user_files',
|
||||
},
|
||||
},
|
||||
}
|
||||
const fileSize = 1234
|
||||
const fileStream = {
|
||||
destroy() {},
|
||||
}
|
||||
const projectId = 'projectId'
|
||||
const fileId = 'file_id'
|
||||
const bucket = 'user_files'
|
||||
const key = `${projectId}/${fileId}`
|
||||
const error = new Error('incorrect utensil')
|
||||
|
||||
beforeEach(function () {
|
||||
FileHandler = {
|
||||
copyObject: sinon.stub().yields(),
|
||||
getFile: sinon.stub().yields(null, fileStream),
|
||||
getFileSize: sinon.stub().yields(null, fileSize),
|
||||
deleteFile: sinon.stub().yields(),
|
||||
deleteProject: sinon.stub().yields(),
|
||||
insertFile: sinon.stub().yields(),
|
||||
getDirectorySize: sinon.stub().yields(null, fileSize),
|
||||
getRedirectUrl: sinon.stub().yields(null, null),
|
||||
}
|
||||
|
||||
LocalFileWriter = {}
|
||||
stream = {
|
||||
pipeline: sinon.stub(),
|
||||
}
|
||||
|
||||
FileController = SandboxedModule.require(modulePath, {
|
||||
requires: {
|
||||
'./LocalFileWriter': LocalFileWriter,
|
||||
'./FileHandler': FileHandler,
|
||||
'./Errors': Errors,
|
||||
stream,
|
||||
'@overleaf/settings': settings,
|
||||
'@overleaf/metrics': {
|
||||
inc() {},
|
||||
},
|
||||
},
|
||||
globals: { console },
|
||||
})
|
||||
|
||||
req = {
|
||||
key,
|
||||
bucket,
|
||||
project_id: projectId,
|
||||
query: {},
|
||||
params: {
|
||||
project_id: projectId,
|
||||
file_id: fileId,
|
||||
},
|
||||
headers: {},
|
||||
requestLogger: {
|
||||
setMessage: sinon.stub(),
|
||||
addFields: sinon.stub(),
|
||||
},
|
||||
}
|
||||
|
||||
res = {
|
||||
set: sinon.stub().returnsThis(),
|
||||
sendStatus: sinon.stub().returnsThis(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
}
|
||||
|
||||
next = sinon.stub()
|
||||
})
|
||||
|
||||
describe('getFile', function () {
|
||||
it('should try and get a redirect url first', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(FileHandler.getRedirectUrl).to.have.been.calledWith(bucket, key)
|
||||
})
|
||||
|
||||
it('should pipe the stream', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(stream.pipeline).to.have.been.calledWith(fileStream, res)
|
||||
})
|
||||
|
||||
it('should send a 200 if the cacheWarm param is true', function (done) {
|
||||
req.query.cacheWarm = true
|
||||
res.sendStatus = statusCode => {
|
||||
statusCode.should.equal(200)
|
||||
done()
|
||||
}
|
||||
FileController.getFile(req, res, next)
|
||||
})
|
||||
|
||||
it('should send an error if there is a problem', function () {
|
||||
FileHandler.getFile.yields(error)
|
||||
FileController.getFile(req, res, next)
|
||||
expect(next).to.have.been.calledWith(error)
|
||||
})
|
||||
|
||||
describe('with a redirect url', function () {
|
||||
const redirectUrl = 'https://wombat.potato/giraffe'
|
||||
|
||||
beforeEach(function () {
|
||||
FileHandler.getRedirectUrl.yields(null, redirectUrl)
|
||||
res.redirect = sinon.stub()
|
||||
})
|
||||
|
||||
it('should redirect', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(res.redirect).to.have.been.calledWith(redirectUrl)
|
||||
})
|
||||
|
||||
it('should not get a file stream', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(FileHandler.getFile).not.to.have.been.called
|
||||
})
|
||||
|
||||
describe('when there is an error getting the redirect url', function () {
|
||||
beforeEach(function () {
|
||||
FileHandler.getRedirectUrl.yields(new Error('wombat herding error'))
|
||||
})
|
||||
|
||||
it('should not redirect', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(res.redirect).not.to.have.been.called
|
||||
})
|
||||
|
||||
it('should not return an error', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(next).not.to.have.been.called
|
||||
})
|
||||
|
||||
it('should proxy the file', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(FileHandler.getFile).to.have.been.calledWith(bucket, key)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('with a range header', function () {
|
||||
let expectedOptions
|
||||
|
||||
beforeEach(function () {
|
||||
expectedOptions = {
|
||||
bucket,
|
||||
key,
|
||||
format: undefined,
|
||||
style: undefined,
|
||||
}
|
||||
})
|
||||
|
||||
it('should pass range options to FileHandler', function () {
|
||||
req.headers.range = 'bytes=0-8'
|
||||
expectedOptions.start = 0
|
||||
expectedOptions.end = 8
|
||||
|
||||
FileController.getFile(req, res, next)
|
||||
expect(FileHandler.getFile).to.have.been.calledWith(
|
||||
bucket,
|
||||
key,
|
||||
expectedOptions
|
||||
)
|
||||
})
|
||||
|
||||
it('should ignore an invalid range header', function () {
|
||||
req.headers.range = 'potato'
|
||||
FileController.getFile(req, res, next)
|
||||
expect(FileHandler.getFile).to.have.been.calledWith(
|
||||
bucket,
|
||||
key,
|
||||
expectedOptions
|
||||
)
|
||||
})
|
||||
|
||||
it("should ignore any type other than 'bytes'", function () {
|
||||
req.headers.range = 'wombats=0-8'
|
||||
FileController.getFile(req, res, next)
|
||||
expect(FileHandler.getFile).to.have.been.calledWith(
|
||||
bucket,
|
||||
key,
|
||||
expectedOptions
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFileHead', function () {
|
||||
it('should return the file size in a Content-Length header', function (done) {
|
||||
res.end = () => {
|
||||
expect(res.status).to.have.been.calledWith(200)
|
||||
expect(res.set).to.have.been.calledWith('Content-Length', fileSize)
|
||||
done()
|
||||
}
|
||||
|
||||
FileController.getFileHead(req, res, next)
|
||||
})
|
||||
|
||||
it('should return a 404 is the file is not found', function (done) {
|
||||
FileHandler.getFileSize.yields(
|
||||
new Errors.NotFoundError({ message: 'not found', info: {} })
|
||||
)
|
||||
|
||||
res.sendStatus = code => {
|
||||
expect(code).to.equal(404)
|
||||
done()
|
||||
}
|
||||
|
||||
FileController.getFileHead(req, res, next)
|
||||
})
|
||||
|
||||
it('should send an error on internal errors', function () {
|
||||
FileHandler.getFileSize.yields(error)
|
||||
|
||||
FileController.getFileHead(req, res, next)
|
||||
expect(next).to.have.been.calledWith(error)
|
||||
})
|
||||
})
|
||||
|
||||
describe('insertFile', function () {
|
||||
it('should send bucket name key and res to FileHandler', function (done) {
|
||||
res.sendStatus = code => {
|
||||
expect(FileHandler.insertFile).to.have.been.calledWith(bucket, key, req)
|
||||
expect(code).to.equal(200)
|
||||
done()
|
||||
}
|
||||
FileController.insertFile(req, res, next)
|
||||
})
|
||||
})
|
||||
|
||||
describe('copyFile', function () {
|
||||
const oldFileId = 'oldFileId'
|
||||
const oldProjectId = 'oldProjectid'
|
||||
const oldKey = `${oldProjectId}/${oldFileId}`
|
||||
|
||||
beforeEach(function () {
|
||||
req.body = {
|
||||
source: {
|
||||
project_id: oldProjectId,
|
||||
file_id: oldFileId,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
it('should send bucket name and both keys to FileHandler', function (done) {
|
||||
res.sendStatus = code => {
|
||||
code.should.equal(200)
|
||||
expect(FileHandler.copyObject).to.have.been.calledWith(
|
||||
bucket,
|
||||
oldKey,
|
||||
key
|
||||
)
|
||||
done()
|
||||
}
|
||||
FileController.copyFile(req, res, next)
|
||||
})
|
||||
|
||||
it('should send a 404 if the original file was not found', function (done) {
|
||||
FileHandler.copyObject.yields(
|
||||
new Errors.NotFoundError({ message: 'not found', info: {} })
|
||||
)
|
||||
res.sendStatus = code => {
|
||||
code.should.equal(404)
|
||||
done()
|
||||
}
|
||||
FileController.copyFile(req, res, next)
|
||||
})
|
||||
|
||||
it('should send an error if there was an error', function (done) {
|
||||
FileHandler.copyObject.yields(error)
|
||||
FileController.copyFile(req, res, err => {
|
||||
expect(err).to.equal(error)
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('delete file', function () {
|
||||
it('should tell the file handler', function (done) {
|
||||
res.sendStatus = code => {
|
||||
code.should.equal(204)
|
||||
expect(FileHandler.deleteFile).to.have.been.calledWith(bucket, key)
|
||||
done()
|
||||
}
|
||||
FileController.deleteFile(req, res, next)
|
||||
})
|
||||
|
||||
it('should send a 500 if there was an error', function () {
|
||||
FileHandler.deleteFile.yields(error)
|
||||
FileController.deleteFile(req, res, next)
|
||||
expect(next).to.have.been.calledWith(error)
|
||||
})
|
||||
})
|
||||
|
||||
describe('delete project', function () {
|
||||
it('should tell the file handler', function (done) {
|
||||
res.sendStatus = code => {
|
||||
code.should.equal(204)
|
||||
expect(FileHandler.deleteProject).to.have.been.calledWith(bucket, key)
|
||||
done()
|
||||
}
|
||||
FileController.deleteProject(req, res, next)
|
||||
})
|
||||
|
||||
it('should send a 500 if there was an error', function () {
|
||||
FileHandler.deleteProject.yields(error)
|
||||
FileController.deleteProject(req, res, next)
|
||||
expect(next).to.have.been.calledWith(error)
|
||||
})
|
||||
})
|
||||
|
||||
describe('directorySize', function () {
|
||||
it('should return total directory size bytes', function (done) {
|
||||
FileController.directorySize(req, {
|
||||
json: result => {
|
||||
expect(result['total bytes']).to.equal(fileSize)
|
||||
done()
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should send a 500 if there was an error', function () {
|
||||
FileHandler.getDirectorySize.yields(error)
|
||||
FileController.directorySize(req, res, next)
|
||||
expect(next).to.have.been.calledWith(error)
|
||||
})
|
||||
})
|
||||
})
|
107
services/filestore/test/unit/js/FileConverterTests.js
Normal file
107
services/filestore/test/unit/js/FileConverterTests.js
Normal file
@@ -0,0 +1,107 @@
|
||||
const sinon = require('sinon')
|
||||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
const { Errors } = require('@overleaf/object-persistor')
|
||||
|
||||
const modulePath = '../../../app/js/FileConverter.js'
|
||||
|
||||
describe('FileConverter', function () {
|
||||
let SafeExec, FileConverter
|
||||
const sourcePath = '/data/wombat.eps'
|
||||
const destPath = '/tmp/dest.png'
|
||||
const format = 'png'
|
||||
const errorMessage = 'guru meditation error'
|
||||
const Settings = {
|
||||
commands: {
|
||||
convertCommandPrefix: [],
|
||||
},
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
SafeExec = {
|
||||
promises: sinon.stub().resolves(destPath),
|
||||
}
|
||||
|
||||
const ObjectPersistor = { Errors }
|
||||
|
||||
FileConverter = SandboxedModule.require(modulePath, {
|
||||
requires: {
|
||||
'./SafeExec': SafeExec,
|
||||
'@overleaf/metrics': {
|
||||
inc: sinon.stub(),
|
||||
Timer: sinon.stub().returns({ done: sinon.stub() }),
|
||||
},
|
||||
'@overleaf/settings': Settings,
|
||||
'@overleaf/object-persistor': ObjectPersistor,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
describe('convert', function () {
|
||||
it('should convert the source to the requested format', async function () {
|
||||
await FileConverter.promises.convert(sourcePath, format)
|
||||
const args = SafeExec.promises.args[0][0]
|
||||
expect(args).to.include(`${sourcePath}[0]`)
|
||||
expect(args).to.include(`${sourcePath}.${format}`)
|
||||
})
|
||||
|
||||
it('should return the dest path', async function () {
|
||||
const destPath = await FileConverter.promises.convert(sourcePath, format)
|
||||
destPath.should.equal(`${sourcePath}.${format}`)
|
||||
})
|
||||
|
||||
it('should wrap the error from convert', async function () {
|
||||
SafeExec.promises.rejects(errorMessage)
|
||||
try {
|
||||
await FileConverter.promises.convert(sourcePath, format)
|
||||
expect('error should have been thrown').not.to.exist
|
||||
} catch (err) {
|
||||
expect(err.name).to.equal('ConversionError')
|
||||
expect(err.cause.toString()).to.equal(errorMessage)
|
||||
}
|
||||
})
|
||||
|
||||
it('should not accept an non approved format', async function () {
|
||||
try {
|
||||
await FileConverter.promises.convert(sourcePath, 'potato')
|
||||
expect('error should have been thrown').not.to.exist
|
||||
} catch (err) {
|
||||
expect(err.name).to.equal('ConversionError')
|
||||
}
|
||||
})
|
||||
|
||||
it('should prefix the command with Settings.commands.convertCommandPrefix', async function () {
|
||||
Settings.commands.convertCommandPrefix = ['nice']
|
||||
await FileConverter.promises.convert(sourcePath, format)
|
||||
})
|
||||
|
||||
it('should convert the file when called as a callback', function (done) {
|
||||
FileConverter.convert(sourcePath, format, (err, destPath) => {
|
||||
expect(err).not.to.exist
|
||||
destPath.should.equal(`${sourcePath}.${format}`)
|
||||
|
||||
const args = SafeExec.promises.args[0][0]
|
||||
expect(args).to.include(`${sourcePath}[0]`)
|
||||
expect(args).to.include(`${sourcePath}.${format}`)
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('thumbnail', function () {
|
||||
it('should call converter resize with args', async function () {
|
||||
await FileConverter.promises.thumbnail(sourcePath)
|
||||
const args = SafeExec.promises.args[0][0]
|
||||
expect(args).to.include(`${sourcePath}[0]`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('preview', function () {
|
||||
it('should call converter resize with args', async function () {
|
||||
await FileConverter.promises.preview(sourcePath)
|
||||
const args = SafeExec.promises.args[0][0]
|
||||
expect(args).to.include(`${sourcePath}[0]`)
|
||||
})
|
||||
})
|
||||
})
|
405
services/filestore/test/unit/js/FileHandlerTests.js
Normal file
405
services/filestore/test/unit/js/FileHandlerTests.js
Normal file
@@ -0,0 +1,405 @@
|
||||
const sinon = require('sinon')
|
||||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const modulePath = '../../../app/js/FileHandler.js'
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
const { ObjectId } = require('mongodb')
|
||||
const { Errors } = require('@overleaf/object-persistor')
|
||||
|
||||
chai.use(require('sinon-chai'))
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('FileHandler', function () {
|
||||
let PersistorManager,
|
||||
LocalFileWriter,
|
||||
FileConverter,
|
||||
KeyBuilder,
|
||||
ImageOptimiser,
|
||||
FileHandler,
|
||||
Settings,
|
||||
fs
|
||||
|
||||
const bucket = 'my_bucket'
|
||||
const key = `${new ObjectId()}/${new ObjectId()}`
|
||||
const convertedFolderKey = `${new ObjectId()}/${new ObjectId()}`
|
||||
const projectKey = `${new ObjectId()}/`
|
||||
const sourceStream = 'sourceStream'
|
||||
const convertedKey = 'convertedKey'
|
||||
const redirectUrl = 'https://wombat.potato/giraffe'
|
||||
const readStream = {
|
||||
stream: 'readStream',
|
||||
on: sinon.stub(),
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
PersistorManager = {
|
||||
getObjectStream: sinon.stub().resolves(sourceStream),
|
||||
getRedirectUrl: sinon.stub().resolves(redirectUrl),
|
||||
checkIfObjectExists: sinon.stub().resolves(),
|
||||
deleteObject: sinon.stub().resolves(),
|
||||
deleteDirectory: sinon.stub().resolves(),
|
||||
sendStream: sinon.stub().resolves(),
|
||||
insertFile: sinon.stub().resolves(),
|
||||
sendFile: sinon.stub().resolves(),
|
||||
directorySize: sinon.stub().resolves(),
|
||||
}
|
||||
LocalFileWriter = {
|
||||
// the callback style is used for detached cleanup calls
|
||||
deleteFile: sinon.stub().yields(),
|
||||
promises: {
|
||||
writeStream: sinon.stub().resolves(),
|
||||
deleteFile: sinon.stub().resolves(),
|
||||
},
|
||||
}
|
||||
FileConverter = {
|
||||
promises: {
|
||||
convert: sinon.stub().resolves(),
|
||||
thumbnail: sinon.stub().resolves(),
|
||||
preview: sinon.stub().resolves(),
|
||||
},
|
||||
}
|
||||
KeyBuilder = {
|
||||
addCachingToKey: sinon.stub().returns(convertedKey),
|
||||
getConvertedFolderKey: sinon.stub().returns(convertedFolderKey),
|
||||
}
|
||||
ImageOptimiser = {
|
||||
promises: {
|
||||
compressPng: sinon.stub().resolves(),
|
||||
},
|
||||
}
|
||||
Settings = {
|
||||
filestore: {
|
||||
stores: { template_files: 'template_files', user_files: 'user_files' },
|
||||
},
|
||||
}
|
||||
fs = {
|
||||
createReadStream: sinon.stub().returns(readStream),
|
||||
}
|
||||
|
||||
const ObjectPersistor = { Errors }
|
||||
|
||||
FileHandler = SandboxedModule.require(modulePath, {
|
||||
requires: {
|
||||
'./PersistorManager': PersistorManager,
|
||||
'./LocalFileWriter': LocalFileWriter,
|
||||
'./FileConverter': FileConverter,
|
||||
'./KeyBuilder': KeyBuilder,
|
||||
'./ImageOptimiser': ImageOptimiser,
|
||||
'@overleaf/settings': Settings,
|
||||
'@overleaf/object-persistor': ObjectPersistor,
|
||||
'@overleaf/metrics': {
|
||||
gauge: sinon.stub(),
|
||||
Timer: sinon.stub().returns({ done: sinon.stub() }),
|
||||
},
|
||||
fs,
|
||||
},
|
||||
globals: { console, process },
|
||||
})
|
||||
})
|
||||
|
||||
describe('insertFile', function () {
|
||||
const stream = 'stream'
|
||||
|
||||
it('should send file to the filestore', function (done) {
|
||||
FileHandler.insertFile(bucket, key, stream, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.sendStream).to.have.been.calledWith(
|
||||
bucket,
|
||||
key,
|
||||
stream
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should not make a delete request for the convertedKey folder', function (done) {
|
||||
FileHandler.insertFile(bucket, key, stream, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.deleteDirectory).not.to.have.been.called
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should accept templates-api key format', function (done) {
|
||||
KeyBuilder.getConvertedFolderKey.returns(
|
||||
'5ecba29f1a294e007d0bccb4/v/0/pdf'
|
||||
)
|
||||
FileHandler.insertFile(bucket, key, stream, err => {
|
||||
expect(err).not.to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw an error when the key is in the wrong format', function (done) {
|
||||
KeyBuilder.getConvertedFolderKey.returns('wombat')
|
||||
FileHandler.insertFile(bucket, key, stream, err => {
|
||||
expect(err).to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('deleteFile', function () {
|
||||
it('should tell the filestore manager to delete the file', function (done) {
|
||||
FileHandler.deleteFile(bucket, key, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.deleteObject).to.have.been.calledWith(
|
||||
bucket,
|
||||
key
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should not tell the filestore manager to delete the cached folder', function (done) {
|
||||
FileHandler.deleteFile(bucket, key, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.deleteDirectory).not.to.have.been.called
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should accept templates-api key format', function (done) {
|
||||
KeyBuilder.getConvertedFolderKey.returns(
|
||||
'5ecba29f1a294e007d0bccb4/v/0/pdf'
|
||||
)
|
||||
FileHandler.deleteFile(bucket, key, err => {
|
||||
expect(err).not.to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw an error when the key is in the wrong format', function (done) {
|
||||
KeyBuilder.getConvertedFolderKey.returns('wombat')
|
||||
FileHandler.deleteFile(bucket, key, err => {
|
||||
expect(err).to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
describe('when conversions are enabled', function () {
|
||||
beforeEach(function () {
|
||||
Settings.enableConversions = true
|
||||
})
|
||||
|
||||
it('should delete the convertedKey folder for template files', function (done) {
|
||||
FileHandler.deleteFile(
|
||||
Settings.filestore.stores.template_files,
|
||||
key,
|
||||
err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.deleteDirectory).to.have.been.calledWith(
|
||||
Settings.filestore.stores.template_files,
|
||||
convertedFolderKey
|
||||
)
|
||||
done()
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
it('should not delete the convertedKey folder for user files', function (done) {
|
||||
FileHandler.deleteFile(
|
||||
Settings.filestore.stores.user_files,
|
||||
key,
|
||||
err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.deleteDirectory).to.not.have.been.called
|
||||
done()
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('deleteProject', function () {
|
||||
it('should tell the filestore manager to delete the folder', function (done) {
|
||||
FileHandler.deleteProject(bucket, projectKey, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.deleteDirectory).to.have.been.calledWith(
|
||||
bucket,
|
||||
projectKey
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw an error when the key is in the wrong format', function (done) {
|
||||
FileHandler.deleteProject(bucket, 'wombat', err => {
|
||||
expect(err).to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFile', function () {
|
||||
it('should return the source stream no format or style are defined', function (done) {
|
||||
FileHandler.getFile(bucket, key, null, (err, stream) => {
|
||||
expect(err).not.to.exist
|
||||
expect(stream).to.equal(sourceStream)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should pass options through to PersistorManager', function (done) {
|
||||
const options = { start: 0, end: 8 }
|
||||
FileHandler.getFile(bucket, key, options, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.getObjectStream).to.have.been.calledWith(
|
||||
bucket,
|
||||
key,
|
||||
options
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
describe('when a format is defined', function () {
|
||||
let result
|
||||
|
||||
describe('when the file is not cached', function () {
|
||||
beforeEach(function (done) {
|
||||
FileHandler.getFile(bucket, key, { format: 'png' }, (err, stream) => {
|
||||
result = { err, stream }
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should convert the file', function () {
|
||||
expect(FileConverter.promises.convert).to.have.been.called
|
||||
})
|
||||
|
||||
it('should compress the converted file', function () {
|
||||
expect(ImageOptimiser.promises.compressPng).to.have.been.called
|
||||
})
|
||||
|
||||
it('should return the the converted stream', function () {
|
||||
expect(result.err).not.to.exist
|
||||
expect(result.stream).to.equal(readStream)
|
||||
expect(PersistorManager.getObjectStream).to.have.been.calledWith(
|
||||
bucket,
|
||||
key
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('when the file is cached', function () {
|
||||
beforeEach(function (done) {
|
||||
PersistorManager.checkIfObjectExists = sinon.stub().resolves(true)
|
||||
FileHandler.getFile(bucket, key, { format: 'png' }, (err, stream) => {
|
||||
result = { err, stream }
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should not convert the file', function () {
|
||||
expect(FileConverter.promises.convert).not.to.have.been.called
|
||||
})
|
||||
|
||||
it('should not compress the converted file again', function () {
|
||||
expect(ImageOptimiser.promises.compressPng).not.to.have.been.called
|
||||
})
|
||||
|
||||
it('should return the cached stream', function () {
|
||||
expect(result.err).not.to.exist
|
||||
expect(result.stream).to.equal(sourceStream)
|
||||
expect(PersistorManager.getObjectStream).to.have.been.calledWith(
|
||||
bucket,
|
||||
convertedKey
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('when a style is defined', function () {
|
||||
it('generates a thumbnail when requested', function (done) {
|
||||
FileHandler.getFile(bucket, key, { style: 'thumbnail' }, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(FileConverter.promises.thumbnail).to.have.been.called
|
||||
expect(FileConverter.promises.preview).not.to.have.been.called
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('generates a preview when requested', function (done) {
|
||||
FileHandler.getFile(bucket, key, { style: 'preview' }, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(FileConverter.promises.thumbnail).not.to.have.been.called
|
||||
expect(FileConverter.promises.preview).to.have.been.called
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getRedirectUrl', function () {
|
||||
beforeEach(function () {
|
||||
Settings.filestore = {
|
||||
allowRedirects: true,
|
||||
stores: {
|
||||
userFiles: bucket,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
it('should return a redirect url', function (done) {
|
||||
FileHandler.getRedirectUrl(bucket, key, (err, url) => {
|
||||
expect(err).not.to.exist
|
||||
expect(url).to.equal(redirectUrl)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should call the persistor to get a redirect url', function (done) {
|
||||
FileHandler.getRedirectUrl(bucket, key, () => {
|
||||
expect(PersistorManager.getRedirectUrl).to.have.been.calledWith(
|
||||
bucket,
|
||||
key
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should return null if options are supplied', function (done) {
|
||||
FileHandler.getRedirectUrl(
|
||||
bucket,
|
||||
key,
|
||||
{ start: 100, end: 200 },
|
||||
(err, url) => {
|
||||
expect(err).not.to.exist
|
||||
expect(url).to.be.null
|
||||
done()
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
it('should return null if the bucket is not one of the defined ones', function (done) {
|
||||
FileHandler.getRedirectUrl('a_different_bucket', key, (err, url) => {
|
||||
expect(err).not.to.exist
|
||||
expect(url).to.be.null
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should return null if redirects are not enabled', function (done) {
|
||||
Settings.filestore.allowRedirects = false
|
||||
FileHandler.getRedirectUrl(bucket, key, (err, url) => {
|
||||
expect(err).not.to.exist
|
||||
expect(url).to.be.null
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getDirectorySize', function () {
|
||||
it('should call the filestore manager to get directory size', function (done) {
|
||||
FileHandler.getDirectorySize(bucket, key, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.directorySize).to.have.been.calledWith(
|
||||
bucket,
|
||||
key
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
67
services/filestore/test/unit/js/ImageOptimiserTests.js
Normal file
67
services/filestore/test/unit/js/ImageOptimiserTests.js
Normal file
@@ -0,0 +1,67 @@
|
||||
const sinon = require('sinon')
|
||||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const modulePath = '../../../app/js/ImageOptimiser.js'
|
||||
const { FailedCommandError } = require('../../../app/js/Errors')
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
|
||||
describe('ImageOptimiser', function () {
|
||||
let ImageOptimiser, SafeExec
|
||||
const sourcePath = '/wombat/potato.eps'
|
||||
|
||||
beforeEach(function () {
|
||||
SafeExec = {
|
||||
promises: sinon.stub().resolves(),
|
||||
}
|
||||
ImageOptimiser = SandboxedModule.require(modulePath, {
|
||||
requires: {
|
||||
'./SafeExec': SafeExec,
|
||||
'@overleaf/metrics': {
|
||||
Timer: sinon.stub().returns({ done: sinon.stub() }),
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
describe('compressPng', function () {
|
||||
it('should convert the file', function (done) {
|
||||
ImageOptimiser.compressPng(sourcePath, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(SafeExec.promises).to.have.been.calledWith([
|
||||
'optipng',
|
||||
sourcePath,
|
||||
])
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should return the error', function (done) {
|
||||
SafeExec.promises.rejects('wombat herding failure')
|
||||
ImageOptimiser.compressPng(sourcePath, err => {
|
||||
expect(err.toString()).to.equal('wombat herding failure')
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('when optimiser is sigkilled', function () {
|
||||
const expectedError = new FailedCommandError('', 'SIGKILL', '', '')
|
||||
let error
|
||||
|
||||
beforeEach(function (done) {
|
||||
SafeExec.promises.rejects(expectedError)
|
||||
ImageOptimiser.compressPng(sourcePath, err => {
|
||||
error = err
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should not produce an error', function () {
|
||||
expect(error).not.to.exist
|
||||
})
|
||||
|
||||
it('should log a warning', function () {
|
||||
expect(this.logger.warn).to.have.been.calledOnce
|
||||
})
|
||||
})
|
||||
})
|
37
services/filestore/test/unit/js/KeybuilderTests.js
Normal file
37
services/filestore/test/unit/js/KeybuilderTests.js
Normal file
@@ -0,0 +1,37 @@
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
|
||||
const modulePath = '../../../app/js/KeyBuilder.js'
|
||||
|
||||
describe('KeybuilderTests', function () {
|
||||
let KeyBuilder
|
||||
const key = 'wombat/potato'
|
||||
|
||||
beforeEach(function () {
|
||||
KeyBuilder = SandboxedModule.require(modulePath, {
|
||||
requires: { '@overleaf/settings': {} },
|
||||
})
|
||||
})
|
||||
|
||||
describe('cachedKey', function () {
|
||||
it('should add the format to the key', function () {
|
||||
const opts = { format: 'png' }
|
||||
const newKey = KeyBuilder.addCachingToKey(key, opts)
|
||||
newKey.should.equal(`${key}-converted-cache/format-png`)
|
||||
})
|
||||
|
||||
it('should add the style to the key', function () {
|
||||
const opts = { style: 'thumbnail' }
|
||||
const newKey = KeyBuilder.addCachingToKey(key, opts)
|
||||
newKey.should.equal(`${key}-converted-cache/style-thumbnail`)
|
||||
})
|
||||
|
||||
it('should add format first, then style', function () {
|
||||
const opts = {
|
||||
style: 'thumbnail',
|
||||
format: 'png',
|
||||
}
|
||||
const newKey = KeyBuilder.addCachingToKey(key, opts)
|
||||
newKey.should.equal(`${key}-converted-cache/format-png-style-thumbnail`)
|
||||
})
|
||||
})
|
||||
})
|
111
services/filestore/test/unit/js/LocalFileWriterTests.js
Normal file
111
services/filestore/test/unit/js/LocalFileWriterTests.js
Normal file
@@ -0,0 +1,111 @@
|
||||
const sinon = require('sinon')
|
||||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const modulePath = '../../../app/js/LocalFileWriter.js'
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
const { Errors } = require('@overleaf/object-persistor')
|
||||
chai.use(require('sinon-chai'))
|
||||
|
||||
describe('LocalFileWriter', function () {
|
||||
const writeStream = 'writeStream'
|
||||
const readStream = 'readStream'
|
||||
const settings = { path: { uploadFolder: '/uploads' } }
|
||||
const fsPath = '/uploads/wombat'
|
||||
const filename = 'wombat'
|
||||
let stream, fs, LocalFileWriter
|
||||
|
||||
beforeEach(function () {
|
||||
fs = {
|
||||
createWriteStream: sinon.stub().returns(writeStream),
|
||||
unlink: sinon.stub().yields(),
|
||||
}
|
||||
stream = {
|
||||
pipeline: sinon.stub().yields(),
|
||||
}
|
||||
|
||||
const ObjectPersistor = { Errors }
|
||||
|
||||
LocalFileWriter = SandboxedModule.require(modulePath, {
|
||||
requires: {
|
||||
fs,
|
||||
stream,
|
||||
'@overleaf/settings': settings,
|
||||
'@overleaf/metrics': {
|
||||
inc: sinon.stub(),
|
||||
Timer: sinon.stub().returns({ done: sinon.stub() }),
|
||||
},
|
||||
'@overleaf/object-persistor': ObjectPersistor,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
describe('writeStream', function () {
|
||||
it('writes the stream to the upload folder', function (done) {
|
||||
LocalFileWriter.writeStream(readStream, filename, (err, path) => {
|
||||
expect(err).not.to.exist
|
||||
expect(fs.createWriteStream).to.have.been.calledWith(fsPath)
|
||||
expect(stream.pipeline).to.have.been.calledWith(readStream, writeStream)
|
||||
expect(path).to.equal(fsPath)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
describe('when there is an error', function () {
|
||||
const error = new Error('not enough ketchup')
|
||||
beforeEach(function () {
|
||||
stream.pipeline.yields(error)
|
||||
})
|
||||
|
||||
it('should wrap the error', function () {
|
||||
LocalFileWriter.writeStream(readStream, filename, err => {
|
||||
expect(err).to.exist
|
||||
expect(err.cause).to.equal(error)
|
||||
})
|
||||
})
|
||||
|
||||
it('should delete the temporary file', function () {
|
||||
LocalFileWriter.writeStream(readStream, filename, () => {
|
||||
expect(fs.unlink).to.have.been.calledWith(fsPath)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('deleteFile', function () {
|
||||
it('should unlink the file', function (done) {
|
||||
LocalFileWriter.deleteFile(fsPath, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(fs.unlink).to.have.been.calledWith(fsPath)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should not call unlink with an empty path', function (done) {
|
||||
LocalFileWriter.deleteFile('', err => {
|
||||
expect(err).not.to.exist
|
||||
expect(fs.unlink).not.to.have.been.called
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should not throw a error if the file does not exist', function (done) {
|
||||
const error = new Error('file not found')
|
||||
error.code = 'ENOENT'
|
||||
fs.unlink = sinon.stub().yields(error)
|
||||
LocalFileWriter.deleteFile(fsPath, err => {
|
||||
expect(err).not.to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should wrap the error', function (done) {
|
||||
const error = new Error('failed to reticulate splines')
|
||||
fs.unlink = sinon.stub().yields(error)
|
||||
LocalFileWriter.deleteFile(fsPath, err => {
|
||||
expect(err).to.exist
|
||||
expect(err.cause).to.equal(error)
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
110
services/filestore/test/unit/js/SafeExecTests.js
Normal file
110
services/filestore/test/unit/js/SafeExecTests.js
Normal file
@@ -0,0 +1,110 @@
|
||||
const chai = require('chai')
|
||||
const should = chai.should()
|
||||
const { expect } = chai
|
||||
const modulePath = '../../../app/js/SafeExec'
|
||||
const { Errors } = require('@overleaf/object-persistor')
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
|
||||
describe('SafeExec', function () {
|
||||
let settings, options, safeExec
|
||||
|
||||
beforeEach(function () {
|
||||
settings = { enableConversions: true }
|
||||
options = { timeout: 10 * 1000, killSignal: 'SIGTERM' }
|
||||
|
||||
const ObjectPersistor = { Errors }
|
||||
|
||||
safeExec = SandboxedModule.require(modulePath, {
|
||||
globals: { process },
|
||||
requires: {
|
||||
'@overleaf/settings': settings,
|
||||
'@overleaf/object-persistor': ObjectPersistor,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
describe('safeExec', function () {
|
||||
it('should execute a valid command', function (done) {
|
||||
safeExec(['/bin/echo', 'hello'], options, (err, stdout, stderr) => {
|
||||
stdout.should.equal('hello\n')
|
||||
stderr.should.equal('')
|
||||
should.not.exist(err)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should error when conversions are disabled', function (done) {
|
||||
settings.enableConversions = false
|
||||
safeExec(['/bin/echo', 'hello'], options, err => {
|
||||
expect(err).to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should execute a command with non-zero exit status', function (done) {
|
||||
safeExec(['/usr/bin/env', 'false'], options, err => {
|
||||
expect(err).to.exist
|
||||
expect(err.name).to.equal('FailedCommandError')
|
||||
expect(err.code).to.equal(1)
|
||||
expect(err.stdout).to.equal('')
|
||||
expect(err.stderr).to.equal('')
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle an invalid command', function (done) {
|
||||
safeExec(['/bin/foobar'], options, err => {
|
||||
err.code.should.equal('ENOENT')
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle a command that runs too long', function (done) {
|
||||
safeExec(
|
||||
['/bin/sleep', '10'],
|
||||
{ timeout: 500, killSignal: 'SIGTERM' },
|
||||
err => {
|
||||
expect(err).to.exist
|
||||
expect(err.name).to.equal('FailedCommandError')
|
||||
expect(err.code).to.equal('SIGTERM')
|
||||
done()
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('as a promise', function () {
|
||||
beforeEach(function () {
|
||||
safeExec = safeExec.promises
|
||||
})
|
||||
|
||||
it('should execute a valid command', async function () {
|
||||
const { stdout, stderr } = await safeExec(['/bin/echo', 'hello'], options)
|
||||
|
||||
stdout.should.equal('hello\n')
|
||||
stderr.should.equal('')
|
||||
})
|
||||
|
||||
it('should throw a ConversionsDisabledError when appropriate', async function () {
|
||||
settings.enableConversions = false
|
||||
try {
|
||||
await safeExec(['/bin/echo', 'hello'], options)
|
||||
} catch (err) {
|
||||
expect(err.name).to.equal('ConversionsDisabledError')
|
||||
return
|
||||
}
|
||||
expect('method did not throw an error').not.to.exist
|
||||
})
|
||||
|
||||
it('should throw a FailedCommandError when appropriate', async function () {
|
||||
try {
|
||||
await safeExec(['/usr/bin/env', 'false'], options)
|
||||
} catch (err) {
|
||||
expect(err.name).to.equal('FailedCommandError')
|
||||
expect(err.code).to.equal(1)
|
||||
return
|
||||
}
|
||||
expect('method did not throw an error').not.to.exist
|
||||
})
|
||||
})
|
||||
})
|
21
services/filestore/test/unit/js/SettingsTests.js
Normal file
21
services/filestore/test/unit/js/SettingsTests.js
Normal file
@@ -0,0 +1,21 @@
|
||||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
|
||||
describe('Settings', function () {
|
||||
describe('s3', function () {
|
||||
it('should use JSONified env var if present', function () {
|
||||
const s3Settings = {
|
||||
bucket1: {
|
||||
auth_key: 'bucket1_key',
|
||||
auth_secret: 'bucket1_secret',
|
||||
},
|
||||
}
|
||||
process.env.S3_BUCKET_CREDENTIALS = JSON.stringify(s3Settings)
|
||||
const settings = SandboxedModule.require('@overleaf/settings', {
|
||||
globals: { console, process },
|
||||
})
|
||||
expect(settings.filestore.s3.bucketCreds).to.deep.equal(s3Settings)
|
||||
})
|
||||
})
|
||||
})
|
58
services/filestore/tiny.pdf
Normal file
58
services/filestore/tiny.pdf
Normal file
@@ -0,0 +1,58 @@
|
||||
%PDF-1.1
|
||||
%¥±ë
|
||||
|
||||
1 0 obj
|
||||
<< /Type /Catalog
|
||||
/Pages 2 0 R
|
||||
>>
|
||||
endobj
|
||||
|
||||
2 0 obj
|
||||
<< /Type /Pages
|
||||
/Kids [3 0 R]
|
||||
/Count 1
|
||||
/MediaBox [0 0 300 144]
|
||||
>>
|
||||
endobj
|
||||
|
||||
3 0 obj
|
||||
<< /Type /Page
|
||||
/Parent 2 0 R
|
||||
/Resources
|
||||
<< /Font
|
||||
<< /F1
|
||||
<< /Type /Font
|
||||
/Subtype /Type1
|
||||
/BaseFont /Times-Roman
|
||||
>>
|
||||
>>
|
||||
>>
|
||||
/Contents 4 0 R
|
||||
>>
|
||||
endobj
|
||||
|
||||
4 0 obj
|
||||
<< /Length 55 >>
|
||||
stream
|
||||
BT
|
||||
/F1 18 Tf
|
||||
0 0 Td
|
||||
(Hello World) Tj
|
||||
ET
|
||||
endstream
|
||||
endobj
|
||||
|
||||
xref
|
||||
0 5
|
||||
0000000000 65535 f
|
||||
0000000018 00000 n
|
||||
0000000077 00000 n
|
||||
0000000178 00000 n
|
||||
0000000457 00000 n
|
||||
trailer
|
||||
<< /Root 1 0 R
|
||||
/Size 5
|
||||
>>
|
||||
startxref
|
||||
565
|
||||
%%EOF
|
12
services/filestore/tsconfig.json
Normal file
12
services/filestore/tsconfig.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"extends": "../../tsconfig.backend.json",
|
||||
"include": [
|
||||
"app.js",
|
||||
"app/js/**/*",
|
||||
"benchmarks/**/*",
|
||||
"config/**/*",
|
||||
"scripts/**/*",
|
||||
"test/**/*",
|
||||
"types"
|
||||
]
|
||||
}
|
Reference in New Issue
Block a user