Compare commits
1 Commits
refactor/e
...
18a048a69e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18a048a69e |
@@ -1,8 +1,7 @@
|
|||||||
.git
|
.git
|
||||||
.gitignore
|
.gitignore
|
||||||
.DS_Store
|
*.md
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
.env*
|
.env*
|
||||||
.claude
|
.claude
|
||||||
node_modules
|
|
||||||
bin/
|
|
||||||
data/
|
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
root = true
|
|
||||||
|
|
||||||
[*]
|
|
||||||
indent_style = space
|
|
||||||
indent_size = 4
|
|
||||||
end_of_line = lf
|
|
||||||
charset = utf-8
|
|
||||||
trim_trailing_whitespace = true
|
|
||||||
insert_final_newline = true
|
|
||||||
|
|
||||||
[Makefile]
|
|
||||||
indent_style = tab
|
|
||||||
|
|
||||||
[*.go]
|
|
||||||
indent_style = tab
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
name: check
|
|
||||||
on: [push]
|
|
||||||
jobs:
|
|
||||||
check:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
# actions/checkout v4.2.2, 2026-02-22
|
|
||||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
|
||||||
- run: docker build .
|
|
||||||
33
.gitignore
vendored
33
.gitignore
vendored
@@ -1,35 +1,20 @@
|
|||||||
# OS
|
|
||||||
.DS_Store
|
|
||||||
Thumbs.db
|
|
||||||
|
|
||||||
# Editors
|
|
||||||
*.swp
|
|
||||||
*.swo
|
|
||||||
*~
|
|
||||||
*.bak
|
|
||||||
.idea/
|
|
||||||
.vscode/
|
|
||||||
*.sublime-*
|
|
||||||
|
|
||||||
# Environment / secrets
|
|
||||||
.env
|
|
||||||
.env.*
|
|
||||||
*.pem
|
|
||||||
*.key
|
|
||||||
|
|
||||||
# Dependencies
|
# Dependencies
|
||||||
vendor/
|
vendor/
|
||||||
node_modules/
|
|
||||||
|
|
||||||
# Build output
|
# Build output
|
||||||
/bin/
|
/bin/
|
||||||
/pixad
|
/pixad
|
||||||
/cmd/pixad/pixad
|
/cmd/pixad/pixad
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
# Data
|
# Data
|
||||||
/data/
|
/data/
|
||||||
*.sqlite3
|
*.sqlite3
|
||||||
|
|
||||||
# Local dev configs
|
|
||||||
config.yaml
|
|
||||||
config.dev.yml
|
|
||||||
|
|||||||
31
Dockerfile
31
Dockerfile
@@ -1,28 +1,5 @@
|
|||||||
# Lint stage
|
|
||||||
# golangci/golangci-lint:v2.10.1-alpine, 2026-02-17
|
|
||||||
FROM golangci/golangci-lint:v2.10.1-alpine@sha256:33bc6b6156d4c7da87175f187090019769903d04dd408833b83083ed214b0ddf AS lint
|
|
||||||
|
|
||||||
RUN apk add --no-cache make build-base vips-dev libheif-dev pkgconfig
|
|
||||||
|
|
||||||
WORKDIR /src
|
|
||||||
|
|
||||||
# Copy go mod files first for better layer caching
|
|
||||||
COPY go.mod go.sum ./
|
|
||||||
RUN go mod download
|
|
||||||
|
|
||||||
# Copy source code
|
|
||||||
COPY . .
|
|
||||||
|
|
||||||
# Run formatting check and linter
|
|
||||||
RUN make fmt-check
|
|
||||||
RUN make lint
|
|
||||||
|
|
||||||
# Build stage
|
# Build stage
|
||||||
# golang:1.25.4-alpine, 2026-02-25
|
FROM golang:1.24-alpine AS builder
|
||||||
FROM golang:1.25.4-alpine@sha256:d3f0cf7723f3429e3f9ed846243970b20a2de7bae6a5b66fc5914e228d831bbb AS builder
|
|
||||||
|
|
||||||
# Depend on lint stage passing
|
|
||||||
COPY --from=lint /src/go.sum /dev/null
|
|
||||||
|
|
||||||
ARG VERSION=dev
|
ARG VERSION=dev
|
||||||
|
|
||||||
@@ -42,15 +19,11 @@ RUN GOTOOLCHAIN=auto go mod download
|
|||||||
# Copy source code
|
# Copy source code
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Run tests
|
|
||||||
RUN make test
|
|
||||||
|
|
||||||
# Build with CGO enabled
|
# Build with CGO enabled
|
||||||
RUN CGO_ENABLED=1 GOTOOLCHAIN=auto go build -ldflags "-X main.Version=${VERSION}" -o /pixad ./cmd/pixad
|
RUN CGO_ENABLED=1 GOTOOLCHAIN=auto go build -ldflags "-X main.Version=${VERSION}" -o /pixad ./cmd/pixad
|
||||||
|
|
||||||
# Runtime stage
|
# Runtime stage
|
||||||
# alpine:3.21, 2026-02-25
|
FROM alpine:3.21
|
||||||
FROM alpine:3.21@sha256:c3f8e73fdb79deaebaa2037150150191b9dcbfba68b4a46d70103204c53f4709
|
|
||||||
|
|
||||||
# Install runtime dependencies only
|
# Install runtime dependencies only
|
||||||
RUN apk add --no-cache \
|
RUN apk add --no-cache \
|
||||||
|
|||||||
674
LICENSE
674
LICENSE
@@ -1,674 +0,0 @@
|
|||||||
GNU GENERAL PUBLIC LICENSE
|
|
||||||
Version 3, 29 June 2007
|
|
||||||
|
|
||||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
|
||||||
Everyone is permitted to copy and distribute verbatim copies
|
|
||||||
of this license document, but changing it is not allowed.
|
|
||||||
|
|
||||||
Preamble
|
|
||||||
|
|
||||||
The GNU General Public License is a free, copyleft license for
|
|
||||||
software and other kinds of works.
|
|
||||||
|
|
||||||
The licenses for most software and other practical works are designed
|
|
||||||
to take away your freedom to share and change the works. By contrast,
|
|
||||||
the GNU General Public License is 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. We, the Free Software Foundation, use the
|
|
||||||
GNU General Public License for most of our software; it applies also to
|
|
||||||
any other work released this way by its authors. You can apply it to
|
|
||||||
your programs, too.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
To protect your rights, we need to prevent others from denying you
|
|
||||||
these rights or asking you to surrender the rights. Therefore, you have
|
|
||||||
certain responsibilities if you distribute copies of the software, or if
|
|
||||||
you modify it: responsibilities to respect the freedom of others.
|
|
||||||
|
|
||||||
For example, if you distribute copies of such a program, whether
|
|
||||||
gratis or for a fee, you must pass on to the recipients the same
|
|
||||||
freedoms that you received. You must make sure that they, too, receive
|
|
||||||
or can get the source code. And you must show them these terms so they
|
|
||||||
know their rights.
|
|
||||||
|
|
||||||
Developers that use the GNU GPL protect your rights with two steps:
|
|
||||||
(1) assert copyright on the software, and (2) offer you this License
|
|
||||||
giving you legal permission to copy, distribute and/or modify it.
|
|
||||||
|
|
||||||
For the developers' and authors' protection, the GPL clearly explains
|
|
||||||
that there is no warranty for this free software. For both users' and
|
|
||||||
authors' sake, the GPL requires that modified versions be marked as
|
|
||||||
changed, so that their problems will not be attributed erroneously to
|
|
||||||
authors of previous versions.
|
|
||||||
|
|
||||||
Some devices are designed to deny users access to install or run
|
|
||||||
modified versions of the software inside them, although the manufacturer
|
|
||||||
can do so. This is fundamentally incompatible with the aim of
|
|
||||||
protecting users' freedom to change the software. The systematic
|
|
||||||
pattern of such abuse occurs in the area of products for individuals to
|
|
||||||
use, which is precisely where it is most unacceptable. Therefore, we
|
|
||||||
have designed this version of the GPL to prohibit the practice for those
|
|
||||||
products. If such problems arise substantially in other domains, we
|
|
||||||
stand ready to extend this provision to those domains in future versions
|
|
||||||
of the GPL, as needed to protect the freedom of users.
|
|
||||||
|
|
||||||
Finally, every program is threatened constantly by software patents.
|
|
||||||
States should not allow patents to restrict development and use of
|
|
||||||
software on general-purpose computers, but in those that do, we wish to
|
|
||||||
avoid the special danger that patents applied to a free program could
|
|
||||||
make it effectively proprietary. To prevent this, the GPL assures that
|
|
||||||
patents cannot be used to render the program non-free.
|
|
||||||
|
|
||||||
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 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. Use with the GNU Affero General Public License.
|
|
||||||
|
|
||||||
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 Affero 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 special requirements of the GNU Affero General Public License,
|
|
||||||
section 13, concerning interaction through a network will apply to the
|
|
||||||
combination as such.
|
|
||||||
|
|
||||||
14. Revised Versions of this License.
|
|
||||||
|
|
||||||
The Free Software Foundation may publish revised and/or new versions of
|
|
||||||
the GNU 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 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 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 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 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 General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU General Public License
|
|
||||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
Also add information on how to contact you by electronic and paper mail.
|
|
||||||
|
|
||||||
If the program does terminal interaction, make it output a short
|
|
||||||
notice like this when it starts in an interactive mode:
|
|
||||||
|
|
||||||
<program> Copyright (C) <year> <name of author>
|
|
||||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
|
||||||
This is free software, and you are welcome to redistribute it
|
|
||||||
under certain conditions; type `show c' for details.
|
|
||||||
|
|
||||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
|
||||||
parts of the General Public License. Of course, your program's commands
|
|
||||||
might be different; for a GUI interface, you would use an "about box".
|
|
||||||
|
|
||||||
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 GPL, see
|
|
||||||
<https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
The GNU General Public License does not permit incorporating your program
|
|
||||||
into proprietary programs. If your program is a subroutine library, you
|
|
||||||
may consider it more useful to permit linking proprietary applications with
|
|
||||||
the library. If this is what you want to do, use the GNU Lesser General
|
|
||||||
Public License instead of this License. But first, please read
|
|
||||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
|
||||||
31
Makefile
31
Makefile
@@ -1,19 +1,8 @@
|
|||||||
.PHONY: check lint test fmt fmt-check build clean docker docker-test devserver devserver-stop hooks
|
.PHONY: check lint test fmt build clean docker docker-test devserver devserver-stop
|
||||||
|
|
||||||
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
|
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
|
||||||
LDFLAGS := -X main.Version=$(VERSION)
|
LDFLAGS := -X main.Version=$(VERSION)
|
||||||
|
|
||||||
# Use nix-shell to provide CGO dependencies unless they are already available
|
|
||||||
# (e.g. inside a Docker build or an existing nix-shell).
|
|
||||||
HAS_PKGCONFIG := $(shell command -v pkg-config 2>/dev/null)
|
|
||||||
ifdef HAS_PKGCONFIG
|
|
||||||
NIX_RUN_PREFIX =
|
|
||||||
NIX_RUN_SUFFIX =
|
|
||||||
else
|
|
||||||
NIX_RUN_PREFIX = nix-shell -p pkg-config vips libheif golangci-lint git --run '
|
|
||||||
NIX_RUN_SUFFIX = '
|
|
||||||
endif
|
|
||||||
|
|
||||||
# Default target: run all checks
|
# Default target: run all checks
|
||||||
check: fmt-check lint test
|
check: fmt-check lint test
|
||||||
|
|
||||||
@@ -30,17 +19,19 @@ fmt:
|
|||||||
# Run linter
|
# Run linter
|
||||||
lint:
|
lint:
|
||||||
@echo "Running linter..."
|
@echo "Running linter..."
|
||||||
$(NIX_RUN_PREFIX)golangci-lint run$(NIX_RUN_SUFFIX)
|
golangci-lint run
|
||||||
|
|
||||||
# Run tests (30-second timeout)
|
# Run tests
|
||||||
test:
|
test:
|
||||||
@echo "Running tests..."
|
@echo "Running tests..."
|
||||||
$(NIX_RUN_PREFIX)CGO_ENABLED=1 go test -timeout 30s -v ./...$(NIX_RUN_SUFFIX)
|
go test -v ./...
|
||||||
|
|
||||||
# Build the binary
|
# Build the binary
|
||||||
build:
|
build: ./bin/pixad
|
||||||
|
|
||||||
|
./bin/pixad: ./internal/*/*.go ./cmd/pixad/*.go ./internal/static/* ./internal/templates/*
|
||||||
@echo "Building pixad..."
|
@echo "Building pixad..."
|
||||||
$(NIX_RUN_PREFIX)CGO_ENABLED=1 go build -ldflags "$(LDFLAGS)" -o ./bin/pixad ./cmd/pixad$(NIX_RUN_SUFFIX)
|
go build -ldflags "$(LDFLAGS)" -o $@ ./cmd/pixad
|
||||||
|
|
||||||
# Clean build artifacts
|
# Clean build artifacts
|
||||||
clean:
|
clean:
|
||||||
@@ -67,9 +58,3 @@ devserver: docker devserver-stop
|
|||||||
devserver-stop:
|
devserver-stop:
|
||||||
-docker stop pixad-dev 2>/dev/null
|
-docker stop pixad-dev 2>/dev/null
|
||||||
-docker rm pixad-dev 2>/dev/null
|
-docker rm pixad-dev 2>/dev/null
|
||||||
|
|
||||||
# Install pre-commit hook
|
|
||||||
hooks:
|
|
||||||
@printf '#!/bin/sh\nset -e\n' > .git/hooks/pre-commit
|
|
||||||
@printf 'make check\n' >> .git/hooks/pre-commit
|
|
||||||
@chmod +x .git/hooks/pre-commit
|
|
||||||
|
|||||||
379
README.md
379
README.md
@@ -1,141 +1,324 @@
|
|||||||
# pixa
|
# pixa caching image reverse proxy server
|
||||||
|
|
||||||
pixa is a GPL-3.0-licensed Go web server by
|
This is a web service written in go that is designed to proxy images from
|
||||||
[@sneak](https://sneak.berlin) that proxies images from upstream
|
source URLs, optionally resizing or transforming them, and serving the
|
||||||
sources, optionally resizing or transforming them, and serves the
|
results. Both the source images as well as the transformed images are
|
||||||
results. Both source and transformed images are cached to disk so that
|
cached. The images served to the client are cached a configurable interval
|
||||||
subsequent requests are served without origin fetches or additional
|
so that subsequent requests to the same path on the pixa server are served
|
||||||
processing.
|
from disk without origin server requests or additional processing.
|
||||||
|
|
||||||
## Getting Started
|
# storage
|
||||||
|
|
||||||
```bash
|
* unaltered source file straight from upstream:
|
||||||
# clone and build
|
* `<statedir>/cache/src-content/<ab>/<cd>/<abcdef0123... sha256 of source content>`
|
||||||
git clone https://git.eeqj.de/sneak/pixa.git
|
* source path metadata
|
||||||
cd pixa
|
* `<statedir>/cache/src-metadata/<hostname>/<sha256 of path component>.json`
|
||||||
make build
|
* fetch time
|
||||||
|
* all original resp headers
|
||||||
|
* original request
|
||||||
|
* sha256 hash
|
||||||
|
|
||||||
# run with a config file
|
Note that multiple source paths may reference the same content blob. We
|
||||||
./bin/pixad --config config.example.yml
|
won't do refcounting here, we'll use the state database for that.
|
||||||
|
|
||||||
# or build and run via Docker
|
* database:
|
||||||
make docker
|
* `<statedir>/state.sqlite3`
|
||||||
docker run -p 8080:8080 pixad:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
## Rationale
|
* output documents:
|
||||||
|
* `<statedir>/cache/dst-content/<ab>/<cd>/<abcd... sha256 of output content>`
|
||||||
|
|
||||||
Image-heavy web applications need a fast, caching reverse proxy that
|
While the database is the long-term authority on what we have in the output
|
||||||
can resize and transcode images on the fly. pixa fills that role as a
|
cache, we must aggressively cache in-process the mapping between requests
|
||||||
single, self-contained binary with no external runtime dependencies
|
and output content hashes so as to serve as a maximally efficient caching
|
||||||
beyond libvips. It supports HMAC-SHA256 signed URLs with expiration to
|
proxy for extremely popular/hot request paths. The goal is the ability to
|
||||||
prevent abuse, and whitelisted source hosts for open access.
|
easily support 1-5k r/s.
|
||||||
|
|
||||||
## Design
|
# Routes
|
||||||
|
|
||||||
### Storage
|
/img/<size>/<orig host>/<orig path>?signature=<sig>&format=<format>
|
||||||
|
|
||||||
- **Source content**:
|
Images are only fetched from origins using TLS. Origin certificates must be
|
||||||
`<statedir>/cache/src-content/<ab>/<cd>/<sha256 of source content>`
|
valid at time of fetch.
|
||||||
- **Source metadata**:
|
|
||||||
`<statedir>/cache/src-metadata/<hostname>/<sha256 of path>.json`
|
|
||||||
(fetch time, original headers, request, content hash)
|
|
||||||
- **Database**: `<statedir>/state.sqlite3` (SQLite)
|
|
||||||
- **Output documents**:
|
|
||||||
`<statedir>/cache/dst-content/<ab>/<cd>/<sha256 of output content>`
|
|
||||||
|
|
||||||
Multiple source paths may reference the same content blob; the
|
<format> is one of 'orig', 'png', 'jpeg', 'webp'
|
||||||
database tracks references rather than using filesystem refcounting.
|
|
||||||
In-process caching of request-to-output mappings targets 1-5k r/s.
|
|
||||||
|
|
||||||
### Routes
|
<size> is one of 'orig' or '<x resolution>x<y resolution>'
|
||||||
|
|
||||||
```
|
# Source Hosts
|
||||||
/v1/image/<host>/<path>/<size>.<format>?sig=<signature>&exp=<expiration>
|
|
||||||
```
|
|
||||||
|
|
||||||
Images are only fetched from origins using TLS with valid certificates.
|
Source hosts may be whitelisted in the pixa configuration. If not in the
|
||||||
|
explicit whitelist, a signature using a shared secret must be appended.
|
||||||
|
|
||||||
- `<format>`: one of `orig`, `png`, `jpeg`, `webp`
|
## Signature Specification
|
||||||
- `<size>`: `orig` or `<width>x<height>` (e.g. `800x600`)
|
|
||||||
|
|
||||||
### Source Hosts
|
Signatures use HMAC-SHA256 and include an expiration timestamp to prevent replay attacks.
|
||||||
|
|
||||||
Source hosts may be whitelisted in the configuration. Non-whitelisted
|
### Signed Data Format
|
||||||
hosts require an HMAC-SHA256 signature.
|
|
||||||
|
|
||||||
#### Signature Specification
|
The signature is computed over a colon-separated string:
|
||||||
|
|
||||||
Signatures use HMAC-SHA256 and include an expiration timestamp to
|
|
||||||
prevent replay attacks. Signatures are **exact match only**: every
|
|
||||||
component (host, path, query, dimensions, format, expiration) must
|
|
||||||
match exactly what was signed. No suffix matching, wildcard matching,
|
|
||||||
or partial matching is supported.
|
|
||||||
|
|
||||||
**Signed data format** (colon-separated):
|
|
||||||
|
|
||||||
```
|
```
|
||||||
HMAC-SHA256(secret, "host:path:query:width:height:format:expiration")
|
HMAC-SHA256(secret, "host:path:query:width:height:format:expiration")
|
||||||
```
|
```
|
||||||
|
|
||||||
Where:
|
Where:
|
||||||
|
- `host` - Source origin hostname (e.g., `cdn.example.com`)
|
||||||
|
- `path` - Source path (e.g., `/photos/cat.jpg`)
|
||||||
|
- `query` - Source query string, empty string if none
|
||||||
|
- `width` - Requested width in pixels, `0` for original
|
||||||
|
- `height` - Requested height in pixels, `0` for original
|
||||||
|
- `format` - Output format (jpeg, png, webp, avif, gif, orig)
|
||||||
|
- `expiration` - Unix timestamp when signature expires
|
||||||
|
|
||||||
- `host` — source origin hostname (e.g. `cdn.example.com`)
|
### URL Format with Signature
|
||||||
- `path` — source path (e.g. `/photos/cat.jpg`)
|
|
||||||
- `query` — source query string, empty string if none
|
|
||||||
- `width` — requested width in pixels, `0` for original
|
|
||||||
- `height` — requested height in pixels, `0` for original
|
|
||||||
- `format` — output format (jpeg, png, webp, avif, gif, orig)
|
|
||||||
- `expiration` — Unix timestamp when signature expires
|
|
||||||
|
|
||||||
**Example:** resize
|
```
|
||||||
`https://cdn.example.com/photos/cat.jpg` to 800x600 WebP with
|
/v1/image/<host>/<path>/<size>.<format>?sig=<signature>&exp=<expiration>
|
||||||
expiration 1704067200:
|
```
|
||||||
|
|
||||||
|
### Example
|
||||||
|
|
||||||
|
For a request to resize `https://cdn.example.com/photos/cat.jpg` to 800x600 WebP
|
||||||
|
with expiration at Unix timestamp 1704067200:
|
||||||
|
|
||||||
|
1. Build the signature input:
|
||||||
|
```
|
||||||
|
cdn.example.com:/photos/cat.jpg::800:600:webp:1704067200
|
||||||
|
```
|
||||||
|
|
||||||
1. Build input:
|
|
||||||
`cdn.example.com:/photos/cat.jpg::800:600:webp:1704067200`
|
|
||||||
2. Compute HMAC-SHA256 with your secret key
|
2. Compute HMAC-SHA256 with your secret key
|
||||||
|
|
||||||
3. Base64URL-encode the result
|
3. Base64URL-encode the result
|
||||||
4. URL:
|
|
||||||
`/v1/image/cdn.example.com/photos/cat.jpg/800x600.webp?sig=<base64url>&exp=1704067200`
|
|
||||||
|
|
||||||
**Whitelist patterns:**
|
4. Final URL:
|
||||||
|
```
|
||||||
|
/v1/image/cdn.example.com/photos/cat.jpg/800x600.webp?sig=<base64url>&exp=1704067200
|
||||||
|
```
|
||||||
|
|
||||||
- **Exact match**: `cdn.example.com` — matches only that host
|
### Whitelist Patterns
|
||||||
- **Suffix match**: `.example.com` — matches `cdn.example.com`,
|
|
||||||
`images.example.com`, and `example.com`
|
|
||||||
|
|
||||||
### Configuration
|
The whitelist supports two pattern types:
|
||||||
|
- **Exact match**: `cdn.example.com` - matches only that host
|
||||||
|
- **Suffix match**: `.example.com` - matches `cdn.example.com`, `images.example.com`, and `example.com`
|
||||||
|
|
||||||
Configured via YAML file (`--config`). Key settings:
|
# configuration
|
||||||
|
|
||||||
- `access_control_allow_origin` — CORS origin
|
* access-control-allow-origin config
|
||||||
- `source_host_whitelist` — list of allowed upstream hosts
|
* source host whitelist
|
||||||
- `upstream_fetch_timeout` — timeout for origin requests
|
* upstream fetch timeout
|
||||||
- `upstream_max_response_size` — max origin response size
|
* upstream max response size
|
||||||
- `downstream_timeout` — client response timeout
|
* downstream timeout
|
||||||
- `signing_key` — HMAC secret for URL signatures
|
* downstream max request size
|
||||||
|
* downstream max response size
|
||||||
|
* internal processing timeout
|
||||||
|
* referer blacklist
|
||||||
|
|
||||||
See `config.example.yml` for all options with defaults.
|
# Design Review & Recommendations
|
||||||
|
|
||||||
### Architecture
|
## Security Concerns
|
||||||
|
|
||||||
- **Dependency injection**: Uber fx
|
### Critical
|
||||||
- **HTTP router**: go-chi
|
- **HMAC signature scheme is undefined** - The "FIXME" for signature
|
||||||
- **Image processing**: govips (CGO wrapper for libvips)
|
construction is a blocker. Recommend HMAC-SHA256 over the full path:
|
||||||
- **Database**: SQLite via modernc.org/sqlite
|
`HMAC-SHA256(secret, "/<size>/<host>/<path>?format=<format>")`
|
||||||
- **Static assets**: embedded via `//go:embed`
|
- **No signature expiration** - Signatures should include a timestamp to
|
||||||
- **Metrics**: Prometheus
|
prevent indefinite replay. Add `&expires=<unix_ts>` and include it in the
|
||||||
- **Logging**: stdlib slog
|
HMAC input
|
||||||
|
- **Path traversal risk** - Ensure `<orig path>` cannot contain `..`
|
||||||
|
sequences or be used to access unintended resources on origin
|
||||||
|
- **SSRF potential** - Even with TLS requirement, internal/private IPs
|
||||||
|
(10.x, 172.16.x, 192.168.x, 127.x, ::1, link-local) must be blocked to
|
||||||
|
prevent server-side request forgery
|
||||||
|
- **Open redirect via Host header** - Validate that requests cannot be
|
||||||
|
manipulated to cache content under incorrect keys
|
||||||
|
|
||||||
## TODO
|
### Important
|
||||||
|
- **No authentication for cache purge** - If cache invalidation is needed, it requires auth
|
||||||
|
- **Response header sanitization** - Strip sensitive headers from upstream before forwarding (X-Powered-By, Server, etc.)
|
||||||
|
- **Content-Type validation** - Verify upstream Content-Type matches expected image types before processing
|
||||||
|
- **Maximum image dimensions** - Limit output dimensions to prevent resource exhaustion (e.g., max 4096x4096)
|
||||||
|
|
||||||
See [TODO.md](TODO.md) for the full prioritized task list.
|
## URL Route Improvements
|
||||||
|
|
||||||
## License
|
Current: `/img/<size>/<orig host>/<orig path>?signature=<sig>&format=<format>`
|
||||||
|
|
||||||
GPL-3.0. See [LICENSE](LICENSE).
|
### Recommended Scheme
|
||||||
|
```
|
||||||
|
/v1/image/<host>/<path>/<width>x<height>.<format>?sig=<sig>&exp=<expires>
|
||||||
|
```
|
||||||
|
|
||||||
## Author
|
The size+format segment (e.g., `800x600.webp`) is appended to the source path and stripped when constructing the upstream request. This pattern is unambiguous (regex: `(\d+x\d+|orig)\.(webp|jpg|jpeg|png|avif)$`) and won't collide with real paths.
|
||||||
|
|
||||||
[@sneak](https://sneak.berlin)
|
**Size options:**
|
||||||
|
- `800x600.<format>` - resize to 800x600
|
||||||
|
- `0x0.<format>` - original size, format conversion only
|
||||||
|
- `orig.<format>` - original size, format conversion only (human-friendly alias)
|
||||||
|
|
||||||
|
**Benefits:**
|
||||||
|
- API versioning (`/v1/`) allows breaking changes later
|
||||||
|
- Human-readable URLs that can be manually constructed for whitelisted domains
|
||||||
|
- Format as extension is intuitive and CDN-friendly
|
||||||
|
|
||||||
|
### Examples
|
||||||
|
|
||||||
|
**Basic resize and convert:**
|
||||||
|
```
|
||||||
|
/v1/image/cdn.example.com/photos/cat.jpg/800x600.webp?sig=abc123&exp=1704067200
|
||||||
|
```
|
||||||
|
Fetches `https://cdn.example.com/photos/cat.jpg`, resizes to 800x600, converts to webp.
|
||||||
|
|
||||||
|
**Source URL with query parameters:**
|
||||||
|
```
|
||||||
|
/v1/image/cdn.example.com/photos/cat.jpg%3Farg1=val1%26arg2=val2/800x600.webp?sig=abc123&exp=1704067200
|
||||||
|
```
|
||||||
|
Fetches `https://cdn.example.com/photos/cat.jpg?arg1=val1&arg2=val2`, resizes to 800x600, converts to webp.
|
||||||
|
|
||||||
|
Note: The source query string must be URL-encoded (`?` → `%3F`, `&` → `%26`) to avoid ambiguity with pixa's own query parameters.
|
||||||
|
|
||||||
|
**Original size, format conversion only:**
|
||||||
|
```
|
||||||
|
/v1/image/cdn.example.com/photos/cat.jpg/orig.webp?sig=abc123&exp=1704067200
|
||||||
|
/v1/image/cdn.example.com/photos/cat.jpg/0x0.webp?sig=abc123&exp=1704067200
|
||||||
|
```
|
||||||
|
Both fetch the original image and convert to webp without resizing.
|
||||||
|
|
||||||
|
## Additional Formats
|
||||||
|
|
||||||
|
### Output Formats to Support
|
||||||
|
- `avif` - Superior compression, growing browser support
|
||||||
|
- `gif` - For animated image passthrough (with frame limit)
|
||||||
|
- `svg` - Passthrough only, no resizing (vector)
|
||||||
|
|
||||||
|
### Input Format Whitelist (MIME types to accept)
|
||||||
|
- `image/jpeg`
|
||||||
|
- `image/png`
|
||||||
|
- `image/webp`
|
||||||
|
- `image/gif`
|
||||||
|
- `image/avif`
|
||||||
|
- `image/svg+xml` (passthrough or rasterize)
|
||||||
|
- **Reject all others** - Especially `image/x-*`, `application/*`
|
||||||
|
|
||||||
|
### Input Validation
|
||||||
|
- Verify magic bytes match declared Content-Type
|
||||||
|
- Maximum input file size (e.g., 50MB)
|
||||||
|
- Maximum input dimensions (e.g., 16384x16384)
|
||||||
|
- Reject files with embedded scripts (SVG sanitization)
|
||||||
|
|
||||||
|
## Rate Limiting
|
||||||
|
|
||||||
|
### Per-IP Limits
|
||||||
|
- Requests per second (e.g., 10 req/s burst, 100 req/min sustained)
|
||||||
|
- Concurrent connections (e.g., 50 per IP)
|
||||||
|
|
||||||
|
### Global Limits
|
||||||
|
- Total concurrent upstream fetches (prevent origin overwhelm)
|
||||||
|
- Per-origin fetch rate limiting (be a good citizen)
|
||||||
|
- Cache miss rate limiting (prevent cache-busting attacks)
|
||||||
|
|
||||||
|
### Response
|
||||||
|
- Return `429 Too Many Requests` with `Retry-After` header
|
||||||
|
- Consider `X-RateLimit-*` headers for transparency
|
||||||
|
|
||||||
|
## Additional Features for 1.0
|
||||||
|
|
||||||
|
### Must Have
|
||||||
|
- **Health check endpoint** - `/health` or `/healthz` for load balancers
|
||||||
|
- **Metrics endpoint** - `/metrics` (Prometheus format) for observability
|
||||||
|
- **Graceful shutdown** - Drain connections on SIGTERM
|
||||||
|
- **Request ID/tracing** - `X-Request-ID` header propagation
|
||||||
|
- **Cache-Control headers** - Proper `Cache-Control`, `ETag`, `Last-Modified` on responses
|
||||||
|
- **Vary header** - `Vary: Accept` if doing content negotiation
|
||||||
|
|
||||||
|
### Should Have
|
||||||
|
- **Auto-format selection** - If `format=auto`, pick best format based on `Accept` header
|
||||||
|
- **Quality parameter** - `&q=85` for lossy format quality control
|
||||||
|
- **Fit modes** - `fit=cover|contain|fill|inside|outside` for resize behavior
|
||||||
|
- **Background color** - For transparent-to-JPEG conversion
|
||||||
|
- **Blur/sharpen** - Common post-resize operations
|
||||||
|
- **Watermarking** - Optional overlay support
|
||||||
|
|
||||||
|
### Nice to Have
|
||||||
|
- **Cache warming API** - Pre-populate cache for known images
|
||||||
|
- **Cache stats API** - Hit/miss rates, storage usage
|
||||||
|
- **Admin UI** - Simple dashboard for monitoring
|
||||||
|
|
||||||
|
## Configuration Additions
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
server:
|
||||||
|
listen: ":8080"
|
||||||
|
read_timeout: 30s
|
||||||
|
write_timeout: 60s
|
||||||
|
max_header_bytes: 8192
|
||||||
|
|
||||||
|
cache:
|
||||||
|
directory: "/var/cache/pixa"
|
||||||
|
max_size_gb: 100
|
||||||
|
ttl: 168h # 7 days
|
||||||
|
negative_ttl: 5m # Cache 404s briefly
|
||||||
|
|
||||||
|
upstream:
|
||||||
|
timeout: 30s
|
||||||
|
max_response_size: 52428800 # 50MB
|
||||||
|
max_concurrent: 100
|
||||||
|
user_agent: "Pixa/1.0"
|
||||||
|
|
||||||
|
processing:
|
||||||
|
max_input_pixels: 268435456 # 16384x16384
|
||||||
|
max_output_dimension: 4096
|
||||||
|
default_quality: 85
|
||||||
|
strip_metadata: true # Remove EXIF etc.
|
||||||
|
|
||||||
|
security:
|
||||||
|
hmac_secret: "${PIXA_HMAC_SECRET}" # From env
|
||||||
|
signature_ttl: 3600 # 1 hour
|
||||||
|
blocked_networks:
|
||||||
|
- "10.0.0.0/8"
|
||||||
|
- "172.16.0.0/12"
|
||||||
|
- "192.168.0.0/16"
|
||||||
|
- "127.0.0.0/8"
|
||||||
|
- "::1/128"
|
||||||
|
- "fc00::/7"
|
||||||
|
|
||||||
|
rate_limit:
|
||||||
|
per_ip_rps: 10
|
||||||
|
per_ip_burst: 50
|
||||||
|
per_origin_rps: 100
|
||||||
|
|
||||||
|
cors:
|
||||||
|
allowed_origins: ["*"] # Or specific list
|
||||||
|
allowed_methods: ["GET", "HEAD", "OPTIONS"]
|
||||||
|
max_age: 86400
|
||||||
|
```
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
### HTTP Status Codes
|
||||||
|
- `400` - Bad request (invalid parameters, malformed URL)
|
||||||
|
- `403` - Forbidden (invalid/expired signature, blocked origin)
|
||||||
|
- `404` - Origin returned 404 (cache negative response briefly)
|
||||||
|
- `413` - Payload too large (origin image exceeds limits)
|
||||||
|
- `415` - Unsupported media type (origin returned non-image)
|
||||||
|
- `422` - Unprocessable (valid image but cannot transform as requested)
|
||||||
|
- `429` - Rate limited
|
||||||
|
- `500` - Internal error
|
||||||
|
- `502` - Bad gateway (origin connection failed)
|
||||||
|
- `503` - Service unavailable (overloaded)
|
||||||
|
- `504` - Gateway timeout (origin timeout)
|
||||||
|
|
||||||
|
### Error Response Format
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"error": "invalid_signature",
|
||||||
|
"message": "Signature has expired",
|
||||||
|
"request_id": "abc123"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Wins
|
||||||
|
|
||||||
|
1. **Conditional requests** - Support `If-None-Match` / `If-Modified-Since` to return `304 Not Modified`
|
||||||
|
2. **HEAD support** - Allow clients to check image metadata without downloading
|
||||||
|
3. **Canonical URLs** - Redirect non-canonical requests to prevent cache fragmentation
|
||||||
|
4. **Debug header** - `X-Pixa-Cache: HIT|MISS|STALE` for debugging
|
||||||
|
5. **Robots.txt** - Serve a robots.txt to prevent search engine crawling of proxy URLs
|
||||||
|
|||||||
182
REPO_POLICIES.md
182
REPO_POLICIES.md
@@ -1,182 +0,0 @@
|
|||||||
---
|
|
||||||
title: Repository Policies
|
|
||||||
last_modified: 2026-02-22
|
|
||||||
---
|
|
||||||
|
|
||||||
This document covers repository structure, tooling, and workflow standards. Code
|
|
||||||
style conventions are in separate documents:
|
|
||||||
|
|
||||||
- [Code Styleguide](https://git.eeqj.de/sneak/prompts/raw/branch/main/prompts/CODE_STYLEGUIDE.md)
|
|
||||||
(general, bash, Docker)
|
|
||||||
- [Go](https://git.eeqj.de/sneak/prompts/raw/branch/main/prompts/CODE_STYLEGUIDE_GO.md)
|
|
||||||
- [JavaScript](https://git.eeqj.de/sneak/prompts/raw/branch/main/prompts/CODE_STYLEGUIDE_JS.md)
|
|
||||||
- [Python](https://git.eeqj.de/sneak/prompts/raw/branch/main/prompts/CODE_STYLEGUIDE_PYTHON.md)
|
|
||||||
- [Go HTTP Server Conventions](https://git.eeqj.de/sneak/prompts/raw/branch/main/prompts/GO_HTTP_SERVER_CONVENTIONS.md)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
- Cross-project documentation (such as this file) must include
|
|
||||||
`last_modified: YYYY-MM-DD` in the YAML front matter so it can be kept in sync
|
|
||||||
with the authoritative source as policies evolve.
|
|
||||||
|
|
||||||
- **ALL external references must be pinned by cryptographic hash.** This
|
|
||||||
includes Docker base images, Go modules, npm packages, GitHub Actions, and
|
|
||||||
anything else fetched from a remote source. Version tags (`@v4`, `@latest`,
|
|
||||||
`:3.21`, etc.) are server-mutable and therefore remote code execution
|
|
||||||
vulnerabilities. The ONLY acceptable way to reference an external dependency
|
|
||||||
is by its content hash (Docker `@sha256:...`, Go module hash in `go.sum`, npm
|
|
||||||
integrity hash in lockfile, GitHub Actions `@<commit-sha>`). No exceptions.
|
|
||||||
This also means never `curl | bash` to install tools like pyenv, nvm, rustup,
|
|
||||||
etc. Instead, download a specific release archive from GitHub, verify its hash
|
|
||||||
(hardcoded in the Dockerfile or script), and only then install. Unverified
|
|
||||||
install scripts are arbitrary remote code execution. This is the single most
|
|
||||||
important rule in this document. Double-check every external reference in
|
|
||||||
every file before committing. There are zero exceptions to this rule.
|
|
||||||
|
|
||||||
- Every repo with software must have a root `Makefile` with these targets:
|
|
||||||
`make test`, `make lint`, `make fmt` (writes), `make fmt-check` (read-only),
|
|
||||||
`make check` (prereqs: `test`, `lint`, `fmt-check`), `make docker`, and
|
|
||||||
`make hooks` (installs pre-commit hook). A model Makefile is at
|
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/Makefile`.
|
|
||||||
|
|
||||||
- Always use Makefile targets (`make fmt`, `make test`, `make lint`, etc.)
|
|
||||||
instead of invoking the underlying tools directly. The Makefile is the single
|
|
||||||
source of truth for how these operations are run.
|
|
||||||
|
|
||||||
- The Makefile is authoritative documentation for how the repo is used. Beyond
|
|
||||||
the required targets above, it should have targets for every common operation:
|
|
||||||
running a local development server (`make run`, `make dev`), re-initializing
|
|
||||||
or migrating the database (`make db-reset`, `make migrate`), building
|
|
||||||
artifacts (`make build`), generating code, seeding data, or anything else a
|
|
||||||
developer would do regularly. If someone checks out the repo and types
|
|
||||||
`make<tab>`, they should see every meaningful operation available. A new
|
|
||||||
contributor should be able to understand the entire development workflow by
|
|
||||||
reading the Makefile.
|
|
||||||
|
|
||||||
- Every repo should have a `Dockerfile`. All Dockerfiles must run `make check`
|
|
||||||
as a build step so the build fails if the branch is not green. For non-server
|
|
||||||
repos, the Dockerfile should bring up a development environment and run
|
|
||||||
`make check`. For server repos, `make check` should run as an early build
|
|
||||||
stage before the final image is assembled.
|
|
||||||
|
|
||||||
- Every repo should have a Gitea Actions workflow (`.gitea/workflows/`) that
|
|
||||||
runs `docker build .` on push. Since the Dockerfile already runs `make check`,
|
|
||||||
a successful build implies all checks pass.
|
|
||||||
|
|
||||||
- Use platform-standard formatters: `black` for Python, `prettier` for
|
|
||||||
JS/CSS/Markdown/HTML, `go fmt` for Go. Always use default configuration with
|
|
||||||
two exceptions: four-space indents (except Go), and `proseWrap: always` for
|
|
||||||
Markdown (hard-wrap at 80 columns). Documentation and writing repos (Markdown,
|
|
||||||
HTML, CSS) should also have `.prettierrc` and `.prettierignore`.
|
|
||||||
|
|
||||||
- Pre-commit hook: `make check` if local testing is possible, otherwise
|
|
||||||
`make lint && make fmt-check`. The Makefile should provide a `make hooks`
|
|
||||||
target to install the pre-commit hook.
|
|
||||||
|
|
||||||
- All repos with software must have tests that run via the platform-standard
|
|
||||||
test framework (`go test`, `pytest`, `jest`/`vitest`, etc.). If no meaningful
|
|
||||||
tests exist yet, add the most minimal test possible — e.g. importing the
|
|
||||||
module under test to verify it compiles/parses. There is no excuse for
|
|
||||||
`make test` to be a no-op.
|
|
||||||
|
|
||||||
- `make test` must complete in under 20 seconds. Add a 30-second timeout in the
|
|
||||||
Makefile.
|
|
||||||
|
|
||||||
- Docker builds must complete in under 5 minutes.
|
|
||||||
|
|
||||||
- `make check` must not modify any files in the repo. Tests may use temporary
|
|
||||||
directories.
|
|
||||||
|
|
||||||
- `main` must always pass `make check`, no exceptions.
|
|
||||||
|
|
||||||
- Never commit secrets. `.env` files, credentials, API keys, and private keys
|
|
||||||
must be in `.gitignore`. No exceptions.
|
|
||||||
|
|
||||||
- `.gitignore` should be comprehensive from the start: OS files (`.DS_Store`),
|
|
||||||
editor files (`.swp`, `*~`), language build artifacts, and `node_modules/`.
|
|
||||||
Fetch the standard `.gitignore` from
|
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when setting up
|
|
||||||
a new repo.
|
|
||||||
|
|
||||||
- Never use `git add -A` or `git add .`. Always stage files explicitly by name.
|
|
||||||
|
|
||||||
- Never force-push to `main`.
|
|
||||||
|
|
||||||
- Make all changes on a feature branch. You can do whatever you want on a
|
|
||||||
feature branch.
|
|
||||||
|
|
||||||
- `.golangci.yml` is standardized and must _NEVER_ be modified by an agent, only
|
|
||||||
manually by the user. Fetch from
|
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.golangci.yml`.
|
|
||||||
|
|
||||||
- When pinning images or packages by hash, add a comment above the reference
|
|
||||||
with the version and date (YYYY-MM-DD).
|
|
||||||
|
|
||||||
- Use `yarn`, not `npm`.
|
|
||||||
|
|
||||||
- Write all dates as YYYY-MM-DD (ISO 8601).
|
|
||||||
|
|
||||||
- Simple projects should be configured with environment variables.
|
|
||||||
|
|
||||||
- Dockerized web services listen on port 8080 by default, overridable with
|
|
||||||
`PORT`.
|
|
||||||
|
|
||||||
- `README.md` is the primary documentation. Required sections:
|
|
||||||
- **Description**: First line must include the project name, purpose,
|
|
||||||
category (web server, SPA, CLI tool, etc.), license, and author. Example:
|
|
||||||
"µPaaS is an MIT-licensed Go web application by @sneak that receives
|
|
||||||
git-frontend webhooks and deploys applications via Docker in realtime."
|
|
||||||
- **Getting Started**: Copy-pasteable install/usage code block.
|
|
||||||
- **Rationale**: Why does this exist?
|
|
||||||
- **Design**: How is the program structured?
|
|
||||||
- **TODO**: Update meticulously, even between commits. When planning, put
|
|
||||||
the todo list in the README so a new agent can pick up where the last one
|
|
||||||
left off.
|
|
||||||
- **License**: MIT, GPL, or WTFPL. Ask the user for new projects. Include a
|
|
||||||
`LICENSE` file in the repo root and a License section in the README.
|
|
||||||
- **Author**: [@sneak](https://sneak.berlin).
|
|
||||||
|
|
||||||
- First commit of a new repo should contain only `README.md`.
|
|
||||||
|
|
||||||
- Go module root: `sneak.berlin/go/<name>`. Always run `go mod tidy` before
|
|
||||||
committing.
|
|
||||||
|
|
||||||
- Use SemVer.
|
|
||||||
|
|
||||||
- Database migrations live in `internal/db/migrations/` and must be embedded in
|
|
||||||
the binary. Pre-1.0.0: modify existing migrations (no installed base assumed).
|
|
||||||
Post-1.0.0: add new migration files.
|
|
||||||
|
|
||||||
- All repos should have an `.editorconfig` enforcing the project's indentation
|
|
||||||
settings.
|
|
||||||
|
|
||||||
- Avoid putting files in the repo root unless necessary. Root should contain
|
|
||||||
only project-level config files (`README.md`, `Makefile`, `Dockerfile`,
|
|
||||||
`LICENSE`, `.gitignore`, `.editorconfig`, `REPO_POLICIES.md`, and
|
|
||||||
language-specific config). Everything else goes in a subdirectory. Canonical
|
|
||||||
subdirectory names:
|
|
||||||
- `bin/` — executable scripts and tools
|
|
||||||
- `cmd/` — Go command entrypoints
|
|
||||||
- `configs/` — configuration templates and examples
|
|
||||||
- `deploy/` — deployment manifests (k8s, compose, terraform)
|
|
||||||
- `docs/` — documentation and markdown (README.md stays in root)
|
|
||||||
- `internal/` — Go internal packages
|
|
||||||
- `internal/db/migrations/` — database migrations
|
|
||||||
- `pkg/` — Go library packages
|
|
||||||
- `share/` — systemd units, data files
|
|
||||||
- `static/` — static assets (images, fonts, etc.)
|
|
||||||
- `web/` — web frontend source
|
|
||||||
|
|
||||||
- When setting up a new repo, files from the `prompts` repo may be used as
|
|
||||||
templates. Fetch them from
|
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/<path>`.
|
|
||||||
|
|
||||||
- New repos must contain at minimum:
|
|
||||||
- `README.md`, `.git`, `.gitignore`, `.editorconfig`
|
|
||||||
- `LICENSE`, `REPO_POLICIES.md` (copy from the `prompts` repo)
|
|
||||||
- `Makefile`
|
|
||||||
- `Dockerfile`, `.dockerignore`
|
|
||||||
- `.gitea/workflows/check.yml`
|
|
||||||
- Go: `go.mod`, `go.sum`, `.golangci.yml`
|
|
||||||
- JS: `package.json`, `yarn.lock`, `.prettierrc`, `.prettierignore`
|
|
||||||
- Python: `pyproject.toml`
|
|
||||||
2
TODO.md
2
TODO.md
@@ -6,7 +6,7 @@ Remaining tasks sorted by priority for a working 1.0 release.
|
|||||||
|
|
||||||
### Image Processing
|
### Image Processing
|
||||||
- [x] Add WebP encoding support (currently returns error)
|
- [x] Add WebP encoding support (currently returns error)
|
||||||
- [x] Add AVIF encoding support (implemented via govips)
|
- [ ] Add AVIF encoding support (currently returns error)
|
||||||
|
|
||||||
### Manual Testing (verify auth/encrypted URLs work)
|
### Manual Testing (verify auth/encrypted URLs work)
|
||||||
- [ ] Manual test: visit `/`, see login form
|
- [ ] Manual test: visit `/`, see login form
|
||||||
|
|||||||
@@ -17,7 +17,10 @@ import (
|
|||||||
"sneak.berlin/go/pixa/internal/server"
|
"sneak.berlin/go/pixa/internal/server"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Version string //nolint:gochecknoglobals // set by ldflags
|
var (
|
||||||
|
Appname = "pixad" //nolint:gochecknoglobals // set by ldflags
|
||||||
|
Version string //nolint:gochecknoglobals // set by ldflags
|
||||||
|
)
|
||||||
|
|
||||||
var configPath string //nolint:gochecknoglobals // cobra flag
|
var configPath string //nolint:gochecknoglobals // cobra flag
|
||||||
|
|
||||||
@@ -37,6 +40,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func run(_ *cobra.Command, _ []string) {
|
func run(_ *cobra.Command, _ []string) {
|
||||||
|
globals.Appname = Appname
|
||||||
globals.Version = Version
|
globals.Version = Version
|
||||||
|
|
||||||
// Set config path in environment if specified via flag
|
// Set config path in environment if specified via flag
|
||||||
|
|||||||
11
config.dev.yml
Normal file
11
config.dev.yml
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
# Development config for local Docker testing
|
||||||
|
signing_key: "dev-signing-key-minimum-32-chars!"
|
||||||
|
debug: true
|
||||||
|
allow_http: true
|
||||||
|
whitelist_hosts:
|
||||||
|
- localhost
|
||||||
|
- s3.sneak.cloud
|
||||||
|
- static.sneak.cloud
|
||||||
|
- sneak.berlin
|
||||||
|
- github.com
|
||||||
|
- user-images.githubusercontent.com
|
||||||
@@ -1,37 +1,13 @@
|
|||||||
# Pixa Example Configuration
|
# Pixa configuration
|
||||||
|
#
|
||||||
# Server settings
|
# REQUIRED: Set signing_key before starting the server.
|
||||||
port: 8080
|
|
||||||
debug: false
|
|
||||||
maintenance_mode: false
|
|
||||||
|
|
||||||
# Data directory for SQLite database and cache files
|
|
||||||
state_dir: ./data
|
|
||||||
|
|
||||||
# Image proxy settings
|
|
||||||
# HMAC signing key for URL signatures (leave empty to require whitelist for all requests)
|
|
||||||
# Generate with: openssl rand -base64 32
|
# Generate with: openssl rand -base64 32
|
||||||
|
|
||||||
signing_key: "CHANGE_ME_generate_with_openssl_rand_base64_32"
|
signing_key: "CHANGE_ME_generate_with_openssl_rand_base64_32"
|
||||||
|
|
||||||
# Hosts that don't require signatures
|
|
||||||
# Use "." prefix for wildcard subdomain matching (e.g., ".example.com" matches "cdn.example.com")
|
|
||||||
whitelist_hosts:
|
whitelist_hosts:
|
||||||
- s3.sneak.cloud
|
- s3.sneak.cloud
|
||||||
- static.sneak.cloud
|
- static.sneak.cloud
|
||||||
- sneak.berlin
|
- sneak.berlin
|
||||||
- github.com
|
- github.com
|
||||||
- user-images.githubusercontent.com
|
- user-images.githubusercontent.com
|
||||||
|
|
||||||
# Allow HTTP upstream (only for testing, always use HTTPS in production)
|
|
||||||
allow_http: false
|
|
||||||
|
|
||||||
# Maximum concurrent connections per upstream host (default: 20)
|
|
||||||
upstream_connections_per_host: 20
|
|
||||||
|
|
||||||
# Sentry error reporting (optional)
|
|
||||||
sentry_dsn: ""
|
|
||||||
|
|
||||||
# Metrics endpoint authentication (optional)
|
|
||||||
# metrics:
|
|
||||||
# username: "admin"
|
|
||||||
# password: "secret"
|
|
||||||
|
|||||||
10
config.yaml
Normal file
10
config.yaml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
debug: true
|
||||||
|
port: 8080
|
||||||
|
state_dir: ./data
|
||||||
|
signing_key: "test-signing-key-for-development-only"
|
||||||
|
whitelist_hosts:
|
||||||
|
- "*.example.com"
|
||||||
|
- "images.unsplash.com"
|
||||||
|
- "picsum.photos"
|
||||||
|
- "s3.sneak.cloud"
|
||||||
|
allow_http: false
|
||||||
34
example-config.yml
Normal file
34
example-config.yml
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
# Pixa Example Configuration
|
||||||
|
|
||||||
|
# Server settings
|
||||||
|
port: 8080
|
||||||
|
debug: false
|
||||||
|
maintenance_mode: false
|
||||||
|
|
||||||
|
# Data directory for SQLite database and cache files
|
||||||
|
state_dir: ./data
|
||||||
|
|
||||||
|
# Image proxy settings
|
||||||
|
# HMAC signing key for URL signatures (leave empty to require whitelist for all requests)
|
||||||
|
signing_key: "change-me-to-a-secure-random-string"
|
||||||
|
|
||||||
|
# Hosts that don't require signatures
|
||||||
|
# Use "." prefix for wildcard subdomain matching (e.g., ".example.com" matches "cdn.example.com")
|
||||||
|
whitelist_hosts:
|
||||||
|
- static.sneak.cloud
|
||||||
|
- sneak.berlin
|
||||||
|
- s3.sneak.cloud
|
||||||
|
|
||||||
|
# Allow HTTP upstream (only for testing, always use HTTPS in production)
|
||||||
|
allow_http: false
|
||||||
|
|
||||||
|
# Maximum concurrent connections per upstream host (default: 20)
|
||||||
|
upstream_connections_per_host: 20
|
||||||
|
|
||||||
|
# Sentry error reporting (optional)
|
||||||
|
sentry_dsn: ""
|
||||||
|
|
||||||
|
# Metrics endpoint authentication (optional)
|
||||||
|
# metrics:
|
||||||
|
# username: "admin"
|
||||||
|
# password: "secret"
|
||||||
@@ -132,9 +132,7 @@ func loadConfigFile(log *slog.Logger, appName string) (*smartconfig.Config, erro
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, path := range configPaths {
|
for _, path := range configPaths {
|
||||||
cleanPath := filepath.Clean(path)
|
if _, statErr := os.Stat(path); statErr == nil {
|
||||||
//nolint:gosec // G703: paths are hardcoded config locations
|
|
||||||
if _, statErr := os.Stat(cleanPath); statErr == nil {
|
|
||||||
sc, err := smartconfig.NewFromConfigPath(path)
|
sc, err := smartconfig.NewFromConfigPath(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warn("failed to parse config file", "path", path, "error", err)
|
log.Warn("failed to parse config file", "path", path, "error", err)
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"go.uber.org/fx"
|
"go.uber.org/fx"
|
||||||
@@ -22,10 +21,6 @@ import (
|
|||||||
//go:embed schema/*.sql
|
//go:embed schema/*.sql
|
||||||
var schemaFS embed.FS
|
var schemaFS embed.FS
|
||||||
|
|
||||||
// bootstrapVersion is the migration that creates the schema_migrations
|
|
||||||
// table itself. It is applied before the normal migration loop.
|
|
||||||
const bootstrapVersion = 0
|
|
||||||
|
|
||||||
// Params defines dependencies for Database.
|
// Params defines dependencies for Database.
|
||||||
type Params struct {
|
type Params struct {
|
||||||
fx.In
|
fx.In
|
||||||
@@ -40,46 +35,6 @@ type Database struct {
|
|||||||
config *config.Config
|
config *config.Config
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseMigrationVersion extracts the numeric version prefix from a migration
|
|
||||||
// filename. Filenames must follow the pattern "<version>.sql" or
|
|
||||||
// "<version>_<description>.sql", where version is a zero-padded numeric
|
|
||||||
// string (e.g. "001", "002"). Returns the version as an integer and an
|
|
||||||
// error if the filename does not match the expected pattern.
|
|
||||||
func ParseMigrationVersion(filename string) (int, error) {
|
|
||||||
name := strings.TrimSuffix(filename, filepath.Ext(filename))
|
|
||||||
if name == "" {
|
|
||||||
return 0, fmt.Errorf("invalid migration filename %q: empty name", filename)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Split on underscore to separate version from description.
|
|
||||||
// If there's no underscore, the entire stem is the version.
|
|
||||||
versionStr := name
|
|
||||||
if idx := strings.IndexByte(name, '_'); idx >= 0 {
|
|
||||||
versionStr = name[:idx]
|
|
||||||
}
|
|
||||||
|
|
||||||
if versionStr == "" {
|
|
||||||
return 0, fmt.Errorf("invalid migration filename %q: empty version prefix", filename)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate the version is purely numeric.
|
|
||||||
for _, ch := range versionStr {
|
|
||||||
if ch < '0' || ch > '9' {
|
|
||||||
return 0, fmt.Errorf(
|
|
||||||
"invalid migration filename %q: version %q contains non-numeric character %q",
|
|
||||||
filename, versionStr, string(ch),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
version, err := strconv.Atoi(versionStr)
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf("invalid migration filename %q: %w", filename, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return version, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// New creates a new Database instance.
|
// New creates a new Database instance.
|
||||||
func New(lc fx.Lifecycle, params Params) (*Database, error) {
|
func New(lc fx.Lifecycle, params Params) (*Database, error) {
|
||||||
s := &Database{
|
s := &Database{
|
||||||
@@ -129,87 +84,43 @@ func (s *Database) connect(ctx context.Context) error {
|
|||||||
s.db = db
|
s.db = db
|
||||||
s.log.Info("database connected")
|
s.log.Info("database connected")
|
||||||
|
|
||||||
return ApplyMigrations(ctx, s.db, s.log)
|
return s.runMigrations(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
// collectMigrations reads the embedded schema directory and returns
|
func (s *Database) runMigrations(ctx context.Context) error {
|
||||||
// migration filenames sorted lexicographically.
|
// Create migrations tracking table
|
||||||
func collectMigrations() ([]string, error) {
|
_, err := s.db.ExecContext(ctx, `
|
||||||
entries, err := schemaFS.ReadDir("schema")
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
version TEXT PRIMARY KEY,
|
||||||
|
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
`)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to read schema directory: %w", err)
|
return fmt.Errorf("failed to create migrations table: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var migrations []string
|
// Get list of migration files
|
||||||
|
entries, err := schemaFS.ReadDir("schema")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to read schema directory: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort migration files by name (001.sql, 002.sql, etc.)
|
||||||
|
var migrations []string
|
||||||
for _, entry := range entries {
|
for _, entry := range entries {
|
||||||
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".sql") {
|
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".sql") {
|
||||||
migrations = append(migrations, entry.Name())
|
migrations = append(migrations, entry.Name())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sort.Strings(migrations)
|
sort.Strings(migrations)
|
||||||
|
|
||||||
return migrations, nil
|
// Apply each migration that hasn't been applied yet
|
||||||
}
|
|
||||||
|
|
||||||
// bootstrapMigrationsTable ensures the schema_migrations table exists
|
|
||||||
// by applying 000.sql if the table is missing.
|
|
||||||
func bootstrapMigrationsTable(ctx context.Context, db *sql.DB, log *slog.Logger) error {
|
|
||||||
var tableExists int
|
|
||||||
|
|
||||||
err := db.QueryRowContext(ctx,
|
|
||||||
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='schema_migrations'",
|
|
||||||
).Scan(&tableExists)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to check for migrations table: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if tableExists > 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
content, err := schemaFS.ReadFile("schema/000.sql")
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to read bootstrap migration 000.sql: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if log != nil {
|
|
||||||
log.Info("applying bootstrap migration", "version", bootstrapVersion)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = db.ExecContext(ctx, string(content))
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to apply bootstrap migration: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ApplyMigrations applies all pending migrations to db. An optional logger
|
|
||||||
// may be provided for informational output; pass nil for silent operation.
|
|
||||||
// This is exported so tests can apply the real schema without the full fx
|
|
||||||
// lifecycle.
|
|
||||||
func ApplyMigrations(ctx context.Context, db *sql.DB, log *slog.Logger) error {
|
|
||||||
if err := bootstrapMigrationsTable(ctx, db, log); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
migrations, err := collectMigrations()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, migration := range migrations {
|
for _, migration := range migrations {
|
||||||
version, parseErr := ParseMigrationVersion(migration)
|
version := strings.TrimSuffix(migration, filepath.Ext(migration))
|
||||||
if parseErr != nil {
|
|
||||||
return parseErr
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if already applied.
|
// Check if already applied
|
||||||
var count int
|
var count int
|
||||||
|
err := s.db.QueryRowContext(ctx,
|
||||||
err := db.QueryRowContext(ctx,
|
|
||||||
"SELECT COUNT(*) FROM schema_migrations WHERE version = ?",
|
"SELECT COUNT(*) FROM schema_migrations WHERE version = ?",
|
||||||
version,
|
version,
|
||||||
).Scan(&count)
|
).Scan(&count)
|
||||||
@@ -218,40 +129,34 @@ func ApplyMigrations(ctx context.Context, db *sql.DB, log *slog.Logger) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if count > 0 {
|
if count > 0 {
|
||||||
if log != nil {
|
s.log.Debug("migration already applied", "version", version)
|
||||||
log.Debug("migration already applied", "version", version)
|
|
||||||
}
|
|
||||||
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read and apply migration.
|
// Read and apply migration
|
||||||
content, readErr := schemaFS.ReadFile(filepath.Join("schema", migration))
|
content, err := schemaFS.ReadFile(filepath.Join("schema", migration))
|
||||||
if readErr != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to read migration %s: %w", migration, readErr)
|
return fmt.Errorf("failed to read migration %s: %w", migration, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if log != nil {
|
s.log.Info("applying migration", "version", version)
|
||||||
log.Info("applying migration", "version", version)
|
|
||||||
|
_, err = s.db.ExecContext(ctx, string(content))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to apply migration %s: %w", migration, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
_, execErr := db.ExecContext(ctx, string(content))
|
// Record migration as applied
|
||||||
if execErr != nil {
|
_, err = s.db.ExecContext(ctx,
|
||||||
return fmt.Errorf("failed to apply migration %s: %w", migration, execErr)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Record migration as applied.
|
|
||||||
_, recErr := db.ExecContext(ctx,
|
|
||||||
"INSERT INTO schema_migrations (version) VALUES (?)",
|
"INSERT INTO schema_migrations (version) VALUES (?)",
|
||||||
version,
|
version,
|
||||||
)
|
)
|
||||||
if recErr != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to record migration %s: %w", migration, recErr)
|
return fmt.Errorf("failed to record migration %s: %w", migration, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if log != nil {
|
s.log.Info("migration applied successfully", "version", version)
|
||||||
log.Info("migration applied successfully", "version", version)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -261,3 +166,77 @@ func ApplyMigrations(ctx context.Context, db *sql.DB, log *slog.Logger) error {
|
|||||||
func (s *Database) DB() *sql.DB {
|
func (s *Database) DB() *sql.DB {
|
||||||
return s.db
|
return s.db
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ApplyMigrations applies all migrations to the given database.
|
||||||
|
// This is useful for testing where you want to use the real schema
|
||||||
|
// without the full fx lifecycle.
|
||||||
|
func ApplyMigrations(db *sql.DB) error {
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// Create migrations tracking table
|
||||||
|
_, err := db.ExecContext(ctx, `
|
||||||
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
version TEXT PRIMARY KEY,
|
||||||
|
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to create migrations table: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get list of migration files
|
||||||
|
entries, err := schemaFS.ReadDir("schema")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to read schema directory: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort migration files by name (001.sql, 002.sql, etc.)
|
||||||
|
var migrations []string
|
||||||
|
for _, entry := range entries {
|
||||||
|
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".sql") {
|
||||||
|
migrations = append(migrations, entry.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(migrations)
|
||||||
|
|
||||||
|
// Apply each migration that hasn't been applied yet
|
||||||
|
for _, migration := range migrations {
|
||||||
|
version := strings.TrimSuffix(migration, filepath.Ext(migration))
|
||||||
|
|
||||||
|
// Check if already applied
|
||||||
|
var count int
|
||||||
|
err := db.QueryRowContext(ctx,
|
||||||
|
"SELECT COUNT(*) FROM schema_migrations WHERE version = ?",
|
||||||
|
version,
|
||||||
|
).Scan(&count)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to check migration status: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if count > 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read and apply migration
|
||||||
|
content, err := schemaFS.ReadFile(filepath.Join("schema", migration))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to read migration %s: %w", migration, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = db.ExecContext(ctx, string(content))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to apply migration %s: %w", migration, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record migration as applied
|
||||||
|
_, err = db.ExecContext(ctx,
|
||||||
|
"INSERT INTO schema_migrations (version) VALUES (?)",
|
||||||
|
version,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to record migration %s: %w", migration, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,224 +0,0 @@
|
|||||||
package database
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"database/sql"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
_ "modernc.org/sqlite" // SQLite driver registration
|
|
||||||
)
|
|
||||||
|
|
||||||
// openTestDB returns a fresh in-memory SQLite database.
|
|
||||||
func openTestDB(t *testing.T) *sql.DB {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
db, err := sql.Open("sqlite", ":memory:")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to open test db: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Cleanup(func() { db.Close() })
|
|
||||||
|
|
||||||
return db
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestParseMigrationVersion(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
filename string
|
|
||||||
want int
|
|
||||||
wantErr bool
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "version only",
|
|
||||||
filename: "001.sql",
|
|
||||||
want: 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "version with description",
|
|
||||||
filename: "001_initial_schema.sql",
|
|
||||||
want: 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "multi-digit version",
|
|
||||||
filename: "042_add_indexes.sql",
|
|
||||||
want: 42,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "long version number",
|
|
||||||
filename: "00001_long_prefix.sql",
|
|
||||||
want: 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "description with multiple underscores",
|
|
||||||
filename: "003_add_user_auth_tables.sql",
|
|
||||||
want: 3,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "empty filename",
|
|
||||||
filename: ".sql",
|
|
||||||
wantErr: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "leading underscore",
|
|
||||||
filename: "_description.sql",
|
|
||||||
wantErr: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "non-numeric version",
|
|
||||||
filename: "abc_migration.sql",
|
|
||||||
wantErr: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "mixed alphanumeric version",
|
|
||||||
filename: "001a_migration.sql",
|
|
||||||
wantErr: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
got, err := ParseMigrationVersion(tt.filename)
|
|
||||||
if tt.wantErr {
|
|
||||||
if err == nil {
|
|
||||||
t.Errorf("ParseMigrationVersion(%q) expected error, got %d", tt.filename, got)
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("ParseMigrationVersion(%q) unexpected error: %v", tt.filename, err)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if got != tt.want {
|
|
||||||
t.Errorf("ParseMigrationVersion(%q) = %d, want %d", tt.filename, got, tt.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestApplyMigrations_CreatesSchemaAndTables(t *testing.T) {
|
|
||||||
db := openTestDB(t)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if err := ApplyMigrations(ctx, db, nil); err != nil {
|
|
||||||
t.Fatalf("ApplyMigrations failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The schema_migrations table must exist and contain at least
|
|
||||||
// version 0 (the bootstrap) and 1 (the initial schema).
|
|
||||||
rows, err := db.Query("SELECT version FROM schema_migrations ORDER BY version")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to query schema_migrations: %v", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var versions []int
|
|
||||||
for rows.Next() {
|
|
||||||
var v int
|
|
||||||
if err := rows.Scan(&v); err != nil {
|
|
||||||
t.Fatalf("failed to scan version: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
versions = append(versions, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
t.Fatalf("row iteration error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(versions) < 2 {
|
|
||||||
t.Fatalf("expected at least 2 migrations recorded, got %d: %v", len(versions), versions)
|
|
||||||
}
|
|
||||||
|
|
||||||
if versions[0] != 0 {
|
|
||||||
t.Errorf("first recorded migration = %d, want %d", versions[0], 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
if versions[1] != 1 {
|
|
||||||
t.Errorf("second recorded migration = %d, want %d", versions[1], 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify that the application tables created by 001.sql exist.
|
|
||||||
for _, table := range []string{"source_content", "source_metadata", "output_content", "request_cache", "negative_cache", "cache_stats"} {
|
|
||||||
var count int
|
|
||||||
|
|
||||||
err := db.QueryRow(
|
|
||||||
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?",
|
|
||||||
table,
|
|
||||||
).Scan(&count)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to check for table %s: %v", table, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if count != 1 {
|
|
||||||
t.Errorf("table %s does not exist after migrations", table)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestApplyMigrations_Idempotent(t *testing.T) {
|
|
||||||
db := openTestDB(t)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if err := ApplyMigrations(ctx, db, nil); err != nil {
|
|
||||||
t.Fatalf("first ApplyMigrations failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Running a second time must succeed without errors.
|
|
||||||
if err := ApplyMigrations(ctx, db, nil); err != nil {
|
|
||||||
t.Fatalf("second ApplyMigrations failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify no duplicate rows in schema_migrations.
|
|
||||||
var count int
|
|
||||||
|
|
||||||
err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations WHERE version = 0").Scan(&count)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to count version 0 rows: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if count != 1 {
|
|
||||||
t.Errorf("expected exactly 1 row for version 0, got %d", count)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBootstrapMigrationsTable_FreshDatabase(t *testing.T) {
|
|
||||||
db := openTestDB(t)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if err := bootstrapMigrationsTable(ctx, db, nil); err != nil {
|
|
||||||
t.Fatalf("bootstrapMigrationsTable failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// schema_migrations table must exist.
|
|
||||||
var tableCount int
|
|
||||||
|
|
||||||
err := db.QueryRow(
|
|
||||||
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='schema_migrations'",
|
|
||||||
).Scan(&tableCount)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to check for table: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if tableCount != 1 {
|
|
||||||
t.Fatalf("schema_migrations table not created")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Version 0 must be recorded.
|
|
||||||
var recorded int
|
|
||||||
|
|
||||||
err = db.QueryRow(
|
|
||||||
"SELECT COUNT(*) FROM schema_migrations WHERE version = 0",
|
|
||||||
).Scan(&recorded)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to check version: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if recorded != 1 {
|
|
||||||
t.Errorf("expected version 0 to be recorded, got count %d", recorded)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
-- Migration 000: Schema migrations tracking table
|
|
||||||
-- Applied as a bootstrap step before the normal migration loop.
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
||||||
version INTEGER PRIMARY KEY,
|
|
||||||
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
||||||
);
|
|
||||||
|
|
||||||
INSERT OR IGNORE INTO schema_migrations (version) VALUES (0);
|
|
||||||
@@ -5,10 +5,11 @@ import (
|
|||||||
"go.uber.org/fx"
|
"go.uber.org/fx"
|
||||||
)
|
)
|
||||||
|
|
||||||
const appname = "pixad"
|
// Build-time variables populated from main() via ldflags.
|
||||||
|
var (
|
||||||
// Version is populated from main() via ldflags.
|
Appname string //nolint:gochecknoglobals // set from main
|
||||||
var Version string //nolint:gochecknoglobals // set from main
|
Version string //nolint:gochecknoglobals // set from main
|
||||||
|
)
|
||||||
|
|
||||||
// Globals holds application-wide constants.
|
// Globals holds application-wide constants.
|
||||||
type Globals struct {
|
type Globals struct {
|
||||||
@@ -19,7 +20,7 @@ type Globals struct {
|
|||||||
// New creates a new Globals instance from build-time variables.
|
// New creates a new Globals instance from build-time variables.
|
||||||
func New(_ fx.Lifecycle) (*Globals, error) {
|
func New(_ fx.Lifecycle) (*Globals, error) {
|
||||||
return &Globals{
|
return &Globals{
|
||||||
Appname: appname,
|
Appname: Appname,
|
||||||
Version: Version,
|
Version: Version,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ func setupTestDB(t *testing.T) *sql.DB {
|
|||||||
t.Fatalf("failed to open test db: %v", err)
|
t.Fatalf("failed to open test db: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := database.ApplyMigrations(context.Background(), db, nil); err != nil {
|
if err := database.ApplyMigrations(db); err != nil {
|
||||||
t.Fatalf("failed to apply migrations: %v", err)
|
t.Fatalf("failed to apply migrations: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
BIN
internal/imageprocessor/testdata/red.avif
vendored
BIN
internal/imageprocessor/testdata/red.avif
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 281 B |
@@ -8,6 +8,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -42,7 +43,8 @@ type Cache struct {
|
|||||||
config CacheConfig
|
config CacheConfig
|
||||||
|
|
||||||
// In-memory cache of variant metadata (content type, size) to avoid reading .meta files
|
// In-memory cache of variant metadata (content type, size) to avoid reading .meta files
|
||||||
metaCache map[VariantKey]variantMeta
|
metaCache map[VariantKey]variantMeta
|
||||||
|
metaCacheMu sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCache creates a new cache instance.
|
// NewCache creates a new cache instance.
|
||||||
@@ -175,7 +177,6 @@ func (c *Cache) StoreSource(
|
|||||||
// StoreVariant stores a processed variant by its cache key.
|
// StoreVariant stores a processed variant by its cache key.
|
||||||
func (c *Cache) StoreVariant(cacheKey VariantKey, content io.Reader, contentType string) error {
|
func (c *Cache) StoreVariant(cacheKey VariantKey, content io.Reader, contentType string) error {
|
||||||
_, err := c.variants.Store(cacheKey, content, contentType)
|
_, err := c.variants.Store(cacheKey, content, contentType)
|
||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptrace"
|
"net/http/httptrace"
|
||||||
neturl "net/url"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -159,18 +158,11 @@ func (f *HTTPFetcher) Fetch(ctx context.Context, url string) (*FetchResult, erro
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
parsedURL, err := neturl.Parse(url)
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to parse URL: %w", err)
|
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
req := &http.Request{
|
|
||||||
Method: http.MethodGet,
|
|
||||||
URL: parsedURL,
|
|
||||||
Header: make(http.Header),
|
|
||||||
}
|
|
||||||
req = req.WithContext(ctx)
|
|
||||||
|
|
||||||
req.Header.Set("User-Agent", f.config.UserAgent)
|
req.Header.Set("User-Agent", f.config.UserAgent)
|
||||||
req.Header.Set("Accept", strings.Join(f.config.AllowedContentTypes, ", "))
|
req.Header.Set("Accept", strings.Join(f.config.AllowedContentTypes, ", "))
|
||||||
|
|
||||||
@@ -188,7 +180,6 @@ func (f *HTTPFetcher) Fetch(ctx context.Context, url string) (*FetchResult, erro
|
|||||||
|
|
||||||
startTime := time.Now()
|
startTime := time.Now()
|
||||||
|
|
||||||
//nolint:gosec // G704: URL validated by validateURL() above
|
|
||||||
resp, err := f.client.Do(req)
|
resp, err := f.client.Do(req)
|
||||||
|
|
||||||
fetchDuration := time.Since(startTime)
|
fetchDuration := time.Since(startTime)
|
||||||
|
|||||||
@@ -199,6 +199,36 @@ type FetchResult struct {
|
|||||||
TLSCipherSuite string
|
TLSCipherSuite string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Processor handles image transformation (resize, format conversion)
|
||||||
|
type Processor interface {
|
||||||
|
// Process transforms an image according to the request
|
||||||
|
Process(ctx context.Context, input io.Reader, req *ImageRequest) (*ProcessResult, error)
|
||||||
|
// SupportedInputFormats returns MIME types this processor can read
|
||||||
|
SupportedInputFormats() []string
|
||||||
|
// SupportedOutputFormats returns formats this processor can write
|
||||||
|
SupportedOutputFormats() []ImageFormat
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProcessResult contains the result of image processing
|
||||||
|
type ProcessResult struct {
|
||||||
|
// Content is the processed image data
|
||||||
|
Content io.ReadCloser
|
||||||
|
// ContentLength is the size in bytes
|
||||||
|
ContentLength int64
|
||||||
|
// ContentType is the MIME type of the output
|
||||||
|
ContentType string
|
||||||
|
// Width is the output image width
|
||||||
|
Width int
|
||||||
|
// Height is the output image height
|
||||||
|
Height int
|
||||||
|
// InputWidth is the original image width before processing
|
||||||
|
InputWidth int
|
||||||
|
// InputHeight is the original image height before processing
|
||||||
|
InputHeight int
|
||||||
|
// InputFormat is the detected input format (e.g., "jpeg", "png")
|
||||||
|
InputFormat string
|
||||||
|
}
|
||||||
|
|
||||||
// Storage handles persistent storage of cached content
|
// Storage handles persistent storage of cached content
|
||||||
type Storage interface {
|
type Storage interface {
|
||||||
// Store saves content and returns its hash
|
// Store saves content and returns its hash
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
// Package magic detects image formats from magic bytes and validates
|
package imgcache
|
||||||
// content against declared MIME types.
|
|
||||||
package magic
|
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
@@ -29,20 +27,6 @@ const (
|
|||||||
MIMETypeSVG = MIMEType("image/svg+xml")
|
MIMETypeSVG = MIMEType("image/svg+xml")
|
||||||
)
|
)
|
||||||
|
|
||||||
// ImageFormat represents supported output image formats.
|
|
||||||
// This mirrors the type in imgcache to avoid circular imports.
|
|
||||||
type ImageFormat string
|
|
||||||
|
|
||||||
// Supported image output formats.
|
|
||||||
const (
|
|
||||||
FormatOriginal ImageFormat = "orig"
|
|
||||||
FormatJPEG ImageFormat = "jpeg"
|
|
||||||
FormatPNG ImageFormat = "png"
|
|
||||||
FormatWebP ImageFormat = "webp"
|
|
||||||
FormatAVIF ImageFormat = "avif"
|
|
||||||
FormatGIF ImageFormat = "gif"
|
|
||||||
)
|
|
||||||
|
|
||||||
// MinMagicBytes is the minimum number of bytes needed to detect format.
|
// MinMagicBytes is the minimum number of bytes needed to detect format.
|
||||||
const MinMagicBytes = 12
|
const MinMagicBytes = 12
|
||||||
|
|
||||||
@@ -205,7 +189,7 @@ func PeekAndValidate(r io.Reader, declaredType string) (io.Reader, error) {
|
|||||||
return io.MultiReader(bytes.NewReader(buf), r), nil
|
return io.MultiReader(bytes.NewReader(buf), r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// MIMEToImageFormat converts a MIME type to an ImageFormat.
|
// MIMEToImageFormat converts a MIME type to our ImageFormat type.
|
||||||
func MIMEToImageFormat(mimeType string) (ImageFormat, bool) {
|
func MIMEToImageFormat(mimeType string) (ImageFormat, bool) {
|
||||||
normalized := normalizeMIMEType(mimeType)
|
normalized := normalizeMIMEType(mimeType)
|
||||||
switch MIMEType(normalized) {
|
switch MIMEType(normalized) {
|
||||||
@@ -224,7 +208,7 @@ func MIMEToImageFormat(mimeType string) (ImageFormat, bool) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ImageFormatToMIME converts an ImageFormat to a MIME type string.
|
// ImageFormatToMIME converts our ImageFormat to a MIME type string.
|
||||||
func ImageFormatToMIME(format ImageFormat) string {
|
func ImageFormatToMIME(format ImageFormat) string {
|
||||||
switch format {
|
switch format {
|
||||||
case FormatJPEG:
|
case FormatJPEG:
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package magic
|
package imgcache
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
// Package imageprocessor provides image format conversion and resizing using libvips.
|
package imgcache
|
||||||
package imageprocessor
|
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
@@ -13,7 +12,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// vipsOnce ensures vips is initialized exactly once.
|
// vipsOnce ensures vips is initialized exactly once.
|
||||||
var vipsOnce sync.Once //nolint:gochecknoglobals // package-level sync.Once for one-time vips init
|
var vipsOnce sync.Once
|
||||||
|
|
||||||
// initVips initializes libvips with quiet logging.
|
// initVips initializes libvips with quiet logging.
|
||||||
func initVips() {
|
func initVips() {
|
||||||
@@ -23,133 +22,37 @@ func initVips() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Format represents supported output image formats.
|
|
||||||
type Format string
|
|
||||||
|
|
||||||
// Supported image output formats.
|
|
||||||
const (
|
|
||||||
FormatOriginal Format = "orig"
|
|
||||||
FormatJPEG Format = "jpeg"
|
|
||||||
FormatPNG Format = "png"
|
|
||||||
FormatWebP Format = "webp"
|
|
||||||
FormatAVIF Format = "avif"
|
|
||||||
FormatGIF Format = "gif"
|
|
||||||
)
|
|
||||||
|
|
||||||
// FitMode represents how to fit an image into requested dimensions.
|
|
||||||
type FitMode string
|
|
||||||
|
|
||||||
// Supported image fit modes.
|
|
||||||
const (
|
|
||||||
FitCover FitMode = "cover"
|
|
||||||
FitContain FitMode = "contain"
|
|
||||||
FitFill FitMode = "fill"
|
|
||||||
FitInside FitMode = "inside"
|
|
||||||
FitOutside FitMode = "outside"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ErrInvalidFitMode is returned when an invalid fit mode is provided.
|
|
||||||
var ErrInvalidFitMode = errors.New("invalid fit mode")
|
|
||||||
|
|
||||||
// Size represents requested image dimensions.
|
|
||||||
type Size struct {
|
|
||||||
Width int
|
|
||||||
Height int
|
|
||||||
}
|
|
||||||
|
|
||||||
// Request holds the parameters for image processing.
|
|
||||||
type Request struct {
|
|
||||||
Size Size
|
|
||||||
Format Format
|
|
||||||
Quality int
|
|
||||||
FitMode FitMode
|
|
||||||
}
|
|
||||||
|
|
||||||
// Result contains the output of image processing.
|
|
||||||
type Result struct {
|
|
||||||
// Content is the processed image data.
|
|
||||||
Content io.ReadCloser
|
|
||||||
// ContentLength is the size in bytes.
|
|
||||||
ContentLength int64
|
|
||||||
// ContentType is the MIME type of the output.
|
|
||||||
ContentType string
|
|
||||||
// Width is the output image width.
|
|
||||||
Width int
|
|
||||||
// Height is the output image height.
|
|
||||||
Height int
|
|
||||||
// InputWidth is the original image width before processing.
|
|
||||||
InputWidth int
|
|
||||||
// InputHeight is the original image height before processing.
|
|
||||||
InputHeight int
|
|
||||||
// InputFormat is the detected input format (e.g., "jpeg", "png").
|
|
||||||
InputFormat string
|
|
||||||
}
|
|
||||||
|
|
||||||
// MaxInputDimension is the maximum allowed width or height for input images.
|
// MaxInputDimension is the maximum allowed width or height for input images.
|
||||||
// Images larger than this are rejected to prevent DoS via decompression bombs.
|
// Images larger than this are rejected to prevent DoS via decompression bombs.
|
||||||
const MaxInputDimension = 8192
|
const MaxInputDimension = 8192
|
||||||
|
|
||||||
// DefaultMaxInputBytes is the default maximum input size in bytes (50 MiB).
|
|
||||||
// This matches the default upstream fetcher limit.
|
|
||||||
const DefaultMaxInputBytes = 50 << 20
|
|
||||||
|
|
||||||
// ErrInputTooLarge is returned when input image dimensions exceed MaxInputDimension.
|
// ErrInputTooLarge is returned when input image dimensions exceed MaxInputDimension.
|
||||||
var ErrInputTooLarge = errors.New("input image dimensions exceed maximum")
|
var ErrInputTooLarge = errors.New("input image dimensions exceed maximum")
|
||||||
|
|
||||||
// ErrInputDataTooLarge is returned when the raw input data exceeds the configured byte limit.
|
|
||||||
var ErrInputDataTooLarge = errors.New("input data exceeds maximum allowed size")
|
|
||||||
|
|
||||||
// ErrUnsupportedOutputFormat is returned when the requested output format is not supported.
|
// ErrUnsupportedOutputFormat is returned when the requested output format is not supported.
|
||||||
var ErrUnsupportedOutputFormat = errors.New("unsupported output format")
|
var ErrUnsupportedOutputFormat = errors.New("unsupported output format")
|
||||||
|
|
||||||
// ImageProcessor implements image transformation using libvips via govips.
|
// ImageProcessor implements the Processor interface using libvips via govips.
|
||||||
type ImageProcessor struct {
|
type ImageProcessor struct{}
|
||||||
maxInputBytes int64
|
|
||||||
}
|
|
||||||
|
|
||||||
// Params holds configuration for creating an ImageProcessor.
|
// NewImageProcessor creates a new image processor.
|
||||||
// Zero values use sensible defaults (MaxInputBytes defaults to DefaultMaxInputBytes).
|
func NewImageProcessor() *ImageProcessor {
|
||||||
type Params struct {
|
|
||||||
// MaxInputBytes is the maximum allowed input size in bytes.
|
|
||||||
// If <= 0, DefaultMaxInputBytes is used.
|
|
||||||
MaxInputBytes int64
|
|
||||||
}
|
|
||||||
|
|
||||||
// New creates a new image processor with the given parameters.
|
|
||||||
// A zero-value Params{} uses sensible defaults.
|
|
||||||
func New(params Params) *ImageProcessor {
|
|
||||||
initVips()
|
initVips()
|
||||||
|
return &ImageProcessor{}
|
||||||
maxInputBytes := params.MaxInputBytes
|
|
||||||
if maxInputBytes <= 0 {
|
|
||||||
maxInputBytes = DefaultMaxInputBytes
|
|
||||||
}
|
|
||||||
|
|
||||||
return &ImageProcessor{
|
|
||||||
maxInputBytes: maxInputBytes,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Process transforms an image according to the request.
|
// Process transforms an image according to the request.
|
||||||
func (p *ImageProcessor) Process(
|
func (p *ImageProcessor) Process(
|
||||||
_ context.Context,
|
_ context.Context,
|
||||||
input io.Reader,
|
input io.Reader,
|
||||||
req *Request,
|
req *ImageRequest,
|
||||||
) (*Result, error) {
|
) (*ProcessResult, error) {
|
||||||
// Read input with a size limit to prevent unbounded memory consumption.
|
// Read input
|
||||||
// We read at most maxInputBytes+1 so we can detect if the input exceeds
|
data, err := io.ReadAll(input)
|
||||||
// the limit without consuming additional memory.
|
|
||||||
limited := io.LimitReader(input, p.maxInputBytes+1)
|
|
||||||
|
|
||||||
data, err := io.ReadAll(limited)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to read input: %w", err)
|
return nil, fmt.Errorf("failed to read input: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if int64(len(data)) > p.maxInputBytes {
|
|
||||||
return nil, ErrInputDataTooLarge
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decode image
|
// Decode image
|
||||||
img, err := vips.NewImageFromBuffer(data)
|
img, err := vips.NewImageFromBuffer(data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -205,10 +108,10 @@ func (p *ImageProcessor) Process(
|
|||||||
return nil, fmt.Errorf("failed to encode: %w", err)
|
return nil, fmt.Errorf("failed to encode: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Result{
|
return &ProcessResult{
|
||||||
Content: io.NopCloser(bytes.NewReader(output)),
|
Content: io.NopCloser(bytes.NewReader(output)),
|
||||||
ContentLength: int64(len(output)),
|
ContentLength: int64(len(output)),
|
||||||
ContentType: FormatToMIME(outputFormat),
|
ContentType: ImageFormatToMIME(outputFormat),
|
||||||
Width: img.Width(),
|
Width: img.Width(),
|
||||||
Height: img.Height(),
|
Height: img.Height(),
|
||||||
InputWidth: origWidth,
|
InputWidth: origWidth,
|
||||||
@@ -220,17 +123,17 @@ func (p *ImageProcessor) Process(
|
|||||||
// SupportedInputFormats returns MIME types this processor can read.
|
// SupportedInputFormats returns MIME types this processor can read.
|
||||||
func (p *ImageProcessor) SupportedInputFormats() []string {
|
func (p *ImageProcessor) SupportedInputFormats() []string {
|
||||||
return []string{
|
return []string{
|
||||||
"image/jpeg",
|
string(MIMETypeJPEG),
|
||||||
"image/png",
|
string(MIMETypePNG),
|
||||||
"image/gif",
|
string(MIMETypeGIF),
|
||||||
"image/webp",
|
string(MIMETypeWebP),
|
||||||
"image/avif",
|
string(MIMETypeAVIF),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportedOutputFormats returns formats this processor can write.
|
// SupportedOutputFormats returns formats this processor can write.
|
||||||
func (p *ImageProcessor) SupportedOutputFormats() []Format {
|
func (p *ImageProcessor) SupportedOutputFormats() []ImageFormat {
|
||||||
return []Format{
|
return []ImageFormat{
|
||||||
FormatJPEG,
|
FormatJPEG,
|
||||||
FormatPNG,
|
FormatPNG,
|
||||||
FormatGIF,
|
FormatGIF,
|
||||||
@@ -239,24 +142,6 @@ func (p *ImageProcessor) SupportedOutputFormats() []Format {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// FormatToMIME converts a Format to its MIME type string.
|
|
||||||
func FormatToMIME(format Format) string {
|
|
||||||
switch format {
|
|
||||||
case FormatJPEG:
|
|
||||||
return "image/jpeg"
|
|
||||||
case FormatPNG:
|
|
||||||
return "image/png"
|
|
||||||
case FormatWebP:
|
|
||||||
return "image/webp"
|
|
||||||
case FormatGIF:
|
|
||||||
return "image/gif"
|
|
||||||
case FormatAVIF:
|
|
||||||
return "image/avif"
|
|
||||||
default:
|
|
||||||
return "application/octet-stream"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// detectFormat returns the format string from a vips image.
|
// detectFormat returns the format string from a vips image.
|
||||||
func (p *ImageProcessor) detectFormat(img *vips.ImageRef) string {
|
func (p *ImageProcessor) detectFormat(img *vips.ImageRef) string {
|
||||||
format := img.Format()
|
format := img.Format()
|
||||||
@@ -285,17 +170,17 @@ func (p *ImageProcessor) resize(img *vips.ImageRef, width, height int, fit FitMo
|
|||||||
|
|
||||||
case FitContain:
|
case FitContain:
|
||||||
// Resize to fit within dimensions, maintaining aspect ratio
|
// Resize to fit within dimensions, maintaining aspect ratio
|
||||||
|
// Calculate target dimensions maintaining aspect ratio
|
||||||
imgW, imgH := img.Width(), img.Height()
|
imgW, imgH := img.Width(), img.Height()
|
||||||
scaleW := float64(width) / float64(imgW)
|
scaleW := float64(width) / float64(imgW)
|
||||||
scaleH := float64(height) / float64(imgH)
|
scaleH := float64(height) / float64(imgH)
|
||||||
scale := min(scaleW, scaleH)
|
scale := min(scaleW, scaleH)
|
||||||
newW := int(float64(imgW) * scale)
|
newW := int(float64(imgW) * scale)
|
||||||
newH := int(float64(imgH) * scale)
|
newH := int(float64(imgH) * scale)
|
||||||
|
|
||||||
return img.Thumbnail(newW, newH, vips.InterestingNone)
|
return img.Thumbnail(newW, newH, vips.InterestingNone)
|
||||||
|
|
||||||
case FitFill:
|
case FitFill:
|
||||||
// Resize to exact dimensions (may distort)
|
// Resize to exact dimensions (may distort) - use ThumbnailWithSize with Force
|
||||||
return img.ThumbnailWithSize(width, height, vips.InterestingNone, vips.SizeForce)
|
return img.ThumbnailWithSize(width, height, vips.InterestingNone, vips.SizeForce)
|
||||||
|
|
||||||
case FitInside:
|
case FitInside:
|
||||||
@@ -309,7 +194,6 @@ func (p *ImageProcessor) resize(img *vips.ImageRef, width, height int, fit FitMo
|
|||||||
scale := min(scaleW, scaleH)
|
scale := min(scaleW, scaleH)
|
||||||
newW := int(float64(imgW) * scale)
|
newW := int(float64(imgW) * scale)
|
||||||
newH := int(float64(imgH) * scale)
|
newH := int(float64(imgH) * scale)
|
||||||
|
|
||||||
return img.Thumbnail(newW, newH, vips.InterestingNone)
|
return img.Thumbnail(newW, newH, vips.InterestingNone)
|
||||||
|
|
||||||
case FitOutside:
|
case FitOutside:
|
||||||
@@ -320,7 +204,6 @@ func (p *ImageProcessor) resize(img *vips.ImageRef, width, height int, fit FitMo
|
|||||||
scale := max(scaleW, scaleH)
|
scale := max(scaleW, scaleH)
|
||||||
newW := int(float64(imgW) * scale)
|
newW := int(float64(imgW) * scale)
|
||||||
newH := int(float64(imgH) * scale)
|
newH := int(float64(imgH) * scale)
|
||||||
|
|
||||||
return img.Thumbnail(newW, newH, vips.InterestingNone)
|
return img.Thumbnail(newW, newH, vips.InterestingNone)
|
||||||
|
|
||||||
default:
|
default:
|
||||||
@@ -331,7 +214,7 @@ func (p *ImageProcessor) resize(img *vips.ImageRef, width, height int, fit FitMo
|
|||||||
const defaultQuality = 85
|
const defaultQuality = 85
|
||||||
|
|
||||||
// encode encodes an image to the specified format.
|
// encode encodes an image to the specified format.
|
||||||
func (p *ImageProcessor) encode(img *vips.ImageRef, format Format, quality int) ([]byte, error) {
|
func (p *ImageProcessor) encode(img *vips.ImageRef, format ImageFormat, quality int) ([]byte, error) {
|
||||||
if quality <= 0 {
|
if quality <= 0 {
|
||||||
quality = defaultQuality
|
quality = defaultQuality
|
||||||
}
|
}
|
||||||
@@ -379,8 +262,8 @@ func (p *ImageProcessor) encode(img *vips.ImageRef, format Format, quality int)
|
|||||||
return output, nil
|
return output, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// formatFromString converts a format string to Format.
|
// formatFromString converts a format string to ImageFormat.
|
||||||
func (p *ImageProcessor) formatFromString(format string) Format {
|
func (p *ImageProcessor) formatFromString(format string) ImageFormat {
|
||||||
switch format {
|
switch format {
|
||||||
case "jpeg":
|
case "jpeg":
|
||||||
return FormatJPEG
|
return FormatJPEG
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package imageprocessor
|
package imgcache
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
@@ -70,36 +70,13 @@ func createTestPNG(t *testing.T, width, height int) []byte {
|
|||||||
return buf.Bytes()
|
return buf.Bytes()
|
||||||
}
|
}
|
||||||
|
|
||||||
// detectMIME is a minimal magic-byte detector for test assertions.
|
|
||||||
func detectMIME(data []byte) string {
|
|
||||||
if len(data) >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF {
|
|
||||||
return "image/jpeg"
|
|
||||||
}
|
|
||||||
if len(data) >= 8 && string(data[:8]) == "\x89PNG\r\n\x1a\n" {
|
|
||||||
return "image/png"
|
|
||||||
}
|
|
||||||
if len(data) >= 4 && string(data[:4]) == "GIF8" {
|
|
||||||
return "image/gif"
|
|
||||||
}
|
|
||||||
if len(data) >= 12 && string(data[:4]) == "RIFF" && string(data[8:12]) == "WEBP" {
|
|
||||||
return "image/webp"
|
|
||||||
}
|
|
||||||
if len(data) >= 12 && string(data[4:8]) == "ftyp" {
|
|
||||||
brand := string(data[8:12])
|
|
||||||
if brand == "avif" || brand == "avis" {
|
|
||||||
return "image/avif"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestImageProcessor_ResizeJPEG(t *testing.T) {
|
func TestImageProcessor_ResizeJPEG(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
input := createTestJPEG(t, 800, 600)
|
input := createTestJPEG(t, 800, 600)
|
||||||
|
|
||||||
req := &Request{
|
req := &ImageRequest{
|
||||||
Size: Size{Width: 400, Height: 300},
|
Size: Size{Width: 400, Height: 300},
|
||||||
Format: FormatJPEG,
|
Format: FormatJPEG,
|
||||||
Quality: 85,
|
Quality: 85,
|
||||||
@@ -130,19 +107,23 @@ func TestImageProcessor_ResizeJPEG(t *testing.T) {
|
|||||||
t.Fatalf("failed to read result: %v", err)
|
t.Fatalf("failed to read result: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
mime := detectMIME(data)
|
mime, err := DetectFormat(data)
|
||||||
if mime != "image/jpeg" {
|
if err != nil {
|
||||||
t.Errorf("Output format = %v, want image/jpeg", mime)
|
t.Fatalf("DetectFormat() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if mime != MIMETypeJPEG {
|
||||||
|
t.Errorf("Output format = %v, want %v", mime, MIMETypeJPEG)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestImageProcessor_ConvertToPNG(t *testing.T) {
|
func TestImageProcessor_ConvertToPNG(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
input := createTestJPEG(t, 200, 150)
|
input := createTestJPEG(t, 200, 150)
|
||||||
|
|
||||||
req := &Request{
|
req := &ImageRequest{
|
||||||
Size: Size{Width: 200, Height: 150},
|
Size: Size{Width: 200, Height: 150},
|
||||||
Format: FormatPNG,
|
Format: FormatPNG,
|
||||||
FitMode: FitCover,
|
FitMode: FitCover,
|
||||||
@@ -159,19 +140,23 @@ func TestImageProcessor_ConvertToPNG(t *testing.T) {
|
|||||||
t.Fatalf("failed to read result: %v", err)
|
t.Fatalf("failed to read result: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
mime := detectMIME(data)
|
mime, err := DetectFormat(data)
|
||||||
if mime != "image/png" {
|
if err != nil {
|
||||||
t.Errorf("Output format = %v, want image/png", mime)
|
t.Fatalf("DetectFormat() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if mime != MIMETypePNG {
|
||||||
|
t.Errorf("Output format = %v, want %v", mime, MIMETypePNG)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestImageProcessor_OriginalSize(t *testing.T) {
|
func TestImageProcessor_OriginalSize(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
input := createTestJPEG(t, 640, 480)
|
input := createTestJPEG(t, 640, 480)
|
||||||
|
|
||||||
req := &Request{
|
req := &ImageRequest{
|
||||||
Size: Size{Width: 0, Height: 0}, // Original size
|
Size: Size{Width: 0, Height: 0}, // Original size
|
||||||
Format: FormatJPEG,
|
Format: FormatJPEG,
|
||||||
Quality: 85,
|
Quality: 85,
|
||||||
@@ -194,14 +179,14 @@ func TestImageProcessor_OriginalSize(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestImageProcessor_FitContain(t *testing.T) {
|
func TestImageProcessor_FitContain(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
// 800x400 image (2:1 aspect) into 400x400 box with contain
|
// 800x400 image (2:1 aspect) into 400x400 box with contain
|
||||||
// Should result in 400x200 (maintaining aspect ratio)
|
// Should result in 400x200 (maintaining aspect ratio)
|
||||||
input := createTestJPEG(t, 800, 400)
|
input := createTestJPEG(t, 800, 400)
|
||||||
|
|
||||||
req := &Request{
|
req := &ImageRequest{
|
||||||
Size: Size{Width: 400, Height: 400},
|
Size: Size{Width: 400, Height: 400},
|
||||||
Format: FormatJPEG,
|
Format: FormatJPEG,
|
||||||
Quality: 85,
|
Quality: 85,
|
||||||
@@ -221,14 +206,14 @@ func TestImageProcessor_FitContain(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestImageProcessor_ProportionalScale_WidthOnly(t *testing.T) {
|
func TestImageProcessor_ProportionalScale_WidthOnly(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
// 800x600 image, request width=400 height=0
|
// 800x600 image, request width=400 height=0
|
||||||
// Should scale proportionally to 400x300
|
// Should scale proportionally to 400x300
|
||||||
input := createTestJPEG(t, 800, 600)
|
input := createTestJPEG(t, 800, 600)
|
||||||
|
|
||||||
req := &Request{
|
req := &ImageRequest{
|
||||||
Size: Size{Width: 400, Height: 0},
|
Size: Size{Width: 400, Height: 0},
|
||||||
Format: FormatJPEG,
|
Format: FormatJPEG,
|
||||||
Quality: 85,
|
Quality: 85,
|
||||||
@@ -251,14 +236,14 @@ func TestImageProcessor_ProportionalScale_WidthOnly(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestImageProcessor_ProportionalScale_HeightOnly(t *testing.T) {
|
func TestImageProcessor_ProportionalScale_HeightOnly(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
// 800x600 image, request width=0 height=300
|
// 800x600 image, request width=0 height=300
|
||||||
// Should scale proportionally to 400x300
|
// Should scale proportionally to 400x300
|
||||||
input := createTestJPEG(t, 800, 600)
|
input := createTestJPEG(t, 800, 600)
|
||||||
|
|
||||||
req := &Request{
|
req := &ImageRequest{
|
||||||
Size: Size{Width: 0, Height: 300},
|
Size: Size{Width: 0, Height: 300},
|
||||||
Format: FormatJPEG,
|
Format: FormatJPEG,
|
||||||
Quality: 85,
|
Quality: 85,
|
||||||
@@ -281,12 +266,12 @@ func TestImageProcessor_ProportionalScale_HeightOnly(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestImageProcessor_ProcessPNG(t *testing.T) {
|
func TestImageProcessor_ProcessPNG(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
input := createTestPNG(t, 400, 300)
|
input := createTestPNG(t, 400, 300)
|
||||||
|
|
||||||
req := &Request{
|
req := &ImageRequest{
|
||||||
Size: Size{Width: 200, Height: 150},
|
Size: Size{Width: 200, Height: 150},
|
||||||
Format: FormatPNG,
|
Format: FormatPNG,
|
||||||
FitMode: FitCover,
|
FitMode: FitCover,
|
||||||
@@ -307,8 +292,13 @@ func TestImageProcessor_ProcessPNG(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestImageProcessor_ImplementsInterface(t *testing.T) {
|
||||||
|
// Verify ImageProcessor implements Processor interface
|
||||||
|
var _ Processor = (*ImageProcessor)(nil)
|
||||||
|
}
|
||||||
|
|
||||||
func TestImageProcessor_SupportedFormats(t *testing.T) {
|
func TestImageProcessor_SupportedFormats(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
|
|
||||||
inputFormats := proc.SupportedInputFormats()
|
inputFormats := proc.SupportedInputFormats()
|
||||||
if len(inputFormats) == 0 {
|
if len(inputFormats) == 0 {
|
||||||
@@ -322,14 +312,14 @@ func TestImageProcessor_SupportedFormats(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestImageProcessor_RejectsOversizedInput(t *testing.T) {
|
func TestImageProcessor_RejectsOversizedInput(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
// Create an image that exceeds MaxInputDimension (e.g., 10000x100)
|
// Create an image that exceeds MaxInputDimension (e.g., 10000x100)
|
||||||
// This should be rejected before processing to prevent DoS
|
// This should be rejected before processing to prevent DoS
|
||||||
input := createTestJPEG(t, 10000, 100)
|
input := createTestJPEG(t, 10000, 100)
|
||||||
|
|
||||||
req := &Request{
|
req := &ImageRequest{
|
||||||
Size: Size{Width: 100, Height: 100},
|
Size: Size{Width: 100, Height: 100},
|
||||||
Format: FormatJPEG,
|
Format: FormatJPEG,
|
||||||
Quality: 85,
|
Quality: 85,
|
||||||
@@ -347,13 +337,13 @@ func TestImageProcessor_RejectsOversizedInput(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestImageProcessor_RejectsOversizedInputHeight(t *testing.T) {
|
func TestImageProcessor_RejectsOversizedInputHeight(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
// Create an image with oversized height
|
// Create an image with oversized height
|
||||||
input := createTestJPEG(t, 100, 10000)
|
input := createTestJPEG(t, 100, 10000)
|
||||||
|
|
||||||
req := &Request{
|
req := &ImageRequest{
|
||||||
Size: Size{Width: 100, Height: 100},
|
Size: Size{Width: 100, Height: 100},
|
||||||
Format: FormatJPEG,
|
Format: FormatJPEG,
|
||||||
Quality: 85,
|
Quality: 85,
|
||||||
@@ -371,13 +361,14 @@ func TestImageProcessor_RejectsOversizedInputHeight(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestImageProcessor_AcceptsMaxDimensionInput(t *testing.T) {
|
func TestImageProcessor_AcceptsMaxDimensionInput(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
// Create an image at exactly MaxInputDimension - should be accepted
|
// Create an image at exactly MaxInputDimension - should be accepted
|
||||||
|
// Using smaller dimensions to keep test fast
|
||||||
input := createTestJPEG(t, MaxInputDimension, 100)
|
input := createTestJPEG(t, MaxInputDimension, 100)
|
||||||
|
|
||||||
req := &Request{
|
req := &ImageRequest{
|
||||||
Size: Size{Width: 100, Height: 100},
|
Size: Size{Width: 100, Height: 100},
|
||||||
Format: FormatJPEG,
|
Format: FormatJPEG,
|
||||||
Quality: 85,
|
Quality: 85,
|
||||||
@@ -392,12 +383,12 @@ func TestImageProcessor_AcceptsMaxDimensionInput(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestImageProcessor_EncodeWebP(t *testing.T) {
|
func TestImageProcessor_EncodeWebP(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
input := createTestJPEG(t, 200, 150)
|
input := createTestJPEG(t, 200, 150)
|
||||||
|
|
||||||
req := &Request{
|
req := &ImageRequest{
|
||||||
Size: Size{Width: 100, Height: 75},
|
Size: Size{Width: 100, Height: 75},
|
||||||
Format: FormatWebP,
|
Format: FormatWebP,
|
||||||
Quality: 80,
|
Quality: 80,
|
||||||
@@ -416,9 +407,13 @@ func TestImageProcessor_EncodeWebP(t *testing.T) {
|
|||||||
t.Fatalf("failed to read result: %v", err)
|
t.Fatalf("failed to read result: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
mime := detectMIME(data)
|
mime, err := DetectFormat(data)
|
||||||
if mime != "image/webp" {
|
if err != nil {
|
||||||
t.Errorf("Output format = %v, want image/webp", mime)
|
t.Fatalf("DetectFormat() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if mime != MIMETypeWebP {
|
||||||
|
t.Errorf("Output format = %v, want %v", mime, MIMETypeWebP)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify dimensions
|
// Verify dimensions
|
||||||
@@ -431,7 +426,7 @@ func TestImageProcessor_EncodeWebP(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestImageProcessor_DecodeAVIF(t *testing.T) {
|
func TestImageProcessor_DecodeAVIF(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
// Load test AVIF file
|
// Load test AVIF file
|
||||||
@@ -441,7 +436,7 @@ func TestImageProcessor_DecodeAVIF(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Request resize and convert to JPEG
|
// Request resize and convert to JPEG
|
||||||
req := &Request{
|
req := &ImageRequest{
|
||||||
Size: Size{Width: 2, Height: 2},
|
Size: Size{Width: 2, Height: 2},
|
||||||
Format: FormatJPEG,
|
Format: FormatJPEG,
|
||||||
Quality: 85,
|
Quality: 85,
|
||||||
@@ -460,84 +455,23 @@ func TestImageProcessor_DecodeAVIF(t *testing.T) {
|
|||||||
t.Fatalf("failed to read result: %v", err)
|
t.Fatalf("failed to read result: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
mime := detectMIME(data)
|
mime, err := DetectFormat(data)
|
||||||
if mime != "image/jpeg" {
|
|
||||||
t.Errorf("Output format = %v, want image/jpeg", mime)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestImageProcessor_RejectsOversizedInputData(t *testing.T) {
|
|
||||||
// Create a processor with a very small byte limit
|
|
||||||
const limit = 1024
|
|
||||||
proc := New(Params{MaxInputBytes: limit})
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
// Create a valid JPEG that exceeds the byte limit
|
|
||||||
input := createTestJPEG(t, 800, 600) // will be well over 1 KiB
|
|
||||||
if int64(len(input)) <= limit {
|
|
||||||
t.Fatalf("test JPEG must exceed %d bytes, got %d", limit, len(input))
|
|
||||||
}
|
|
||||||
|
|
||||||
req := &Request{
|
|
||||||
Size: Size{Width: 100, Height: 75},
|
|
||||||
Format: FormatJPEG,
|
|
||||||
Quality: 85,
|
|
||||||
FitMode: FitCover,
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := proc.Process(ctx, bytes.NewReader(input), req)
|
|
||||||
if err == nil {
|
|
||||||
t.Fatal("Process() should reject input exceeding maxInputBytes")
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != ErrInputDataTooLarge {
|
|
||||||
t.Errorf("Process() error = %v, want ErrInputDataTooLarge", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestImageProcessor_AcceptsInputWithinLimit(t *testing.T) {
|
|
||||||
// Create a small image and set limit well above its size
|
|
||||||
input := createTestJPEG(t, 10, 10)
|
|
||||||
limit := int64(len(input)) * 10 // 10× headroom
|
|
||||||
|
|
||||||
proc := New(Params{MaxInputBytes: limit})
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
req := &Request{
|
|
||||||
Size: Size{Width: 10, Height: 10},
|
|
||||||
Format: FormatJPEG,
|
|
||||||
Quality: 85,
|
|
||||||
FitMode: FitCover,
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := proc.Process(ctx, bytes.NewReader(input), req)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Process() error = %v, want nil", err)
|
t.Fatalf("DetectFormat() error = %v", err)
|
||||||
}
|
|
||||||
defer result.Content.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestImageProcessor_DefaultMaxInputBytes(t *testing.T) {
|
|
||||||
// Passing 0 should use the default
|
|
||||||
proc := New(Params{})
|
|
||||||
if proc.maxInputBytes != DefaultMaxInputBytes {
|
|
||||||
t.Errorf("maxInputBytes = %d, want %d", proc.maxInputBytes, DefaultMaxInputBytes)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Passing negative should also use the default
|
if mime != MIMETypeJPEG {
|
||||||
proc = New(Params{MaxInputBytes: -1})
|
t.Errorf("Output format = %v, want %v", mime, MIMETypeJPEG)
|
||||||
if proc.maxInputBytes != DefaultMaxInputBytes {
|
|
||||||
t.Errorf("maxInputBytes = %d, want %d", proc.maxInputBytes, DefaultMaxInputBytes)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestImageProcessor_EncodeAVIF(t *testing.T) {
|
func TestImageProcessor_EncodeAVIF(t *testing.T) {
|
||||||
proc := New(Params{})
|
proc := NewImageProcessor()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
input := createTestJPEG(t, 200, 150)
|
input := createTestJPEG(t, 200, 150)
|
||||||
|
|
||||||
req := &Request{
|
req := &ImageRequest{
|
||||||
Size: Size{Width: 100, Height: 75},
|
Size: Size{Width: 100, Height: 75},
|
||||||
Format: FormatAVIF,
|
Format: FormatAVIF,
|
||||||
Quality: 85,
|
Quality: 85,
|
||||||
@@ -556,9 +490,13 @@ func TestImageProcessor_EncodeAVIF(t *testing.T) {
|
|||||||
t.Fatalf("failed to read result: %v", err)
|
t.Fatalf("failed to read result: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
mime := detectMIME(data)
|
mime, err := DetectFormat(data)
|
||||||
if mime != "image/avif" {
|
if err != nil {
|
||||||
t.Errorf("Output format = %v, want image/avif", mime)
|
t.Fatalf("DetectFormat() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if mime != MIMETypeAVIF {
|
||||||
|
t.Errorf("Output format = %v, want %v", mime, MIMETypeAVIF)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify dimensions
|
// Verify dimensions
|
||||||
@@ -11,21 +11,17 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/dustin/go-humanize"
|
"github.com/dustin/go-humanize"
|
||||||
"sneak.berlin/go/pixa/internal/allowlist"
|
|
||||||
"sneak.berlin/go/pixa/internal/imageprocessor"
|
|
||||||
"sneak.berlin/go/pixa/internal/magic"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Service implements the ImageCache interface, orchestrating cache, fetcher, and processor.
|
// Service implements the ImageCache interface, orchestrating cache, fetcher, and processor.
|
||||||
type Service struct {
|
type Service struct {
|
||||||
cache *Cache
|
cache *Cache
|
||||||
fetcher Fetcher
|
fetcher Fetcher
|
||||||
processor *imageprocessor.ImageProcessor
|
processor Processor
|
||||||
signer *Signer
|
signer *Signer
|
||||||
allowlist *allowlist.HostAllowList
|
whitelist *HostWhitelist
|
||||||
log *slog.Logger
|
log *slog.Logger
|
||||||
allowHTTP bool
|
allowHTTP bool
|
||||||
maxResponseSize int64
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServiceConfig holds configuration for the image service.
|
// ServiceConfig holds configuration for the image service.
|
||||||
@@ -54,17 +50,15 @@ func NewService(cfg *ServiceConfig) (*Service, error) {
|
|||||||
return nil, errors.New("signing key is required")
|
return nil, errors.New("signing key is required")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resolve fetcher config for defaults
|
|
||||||
fetcherCfg := cfg.FetcherConfig
|
|
||||||
if fetcherCfg == nil {
|
|
||||||
fetcherCfg = DefaultFetcherConfig()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use custom fetcher if provided, otherwise create HTTP fetcher
|
// Use custom fetcher if provided, otherwise create HTTP fetcher
|
||||||
var fetcher Fetcher
|
var fetcher Fetcher
|
||||||
if cfg.Fetcher != nil {
|
if cfg.Fetcher != nil {
|
||||||
fetcher = cfg.Fetcher
|
fetcher = cfg.Fetcher
|
||||||
} else {
|
} else {
|
||||||
|
fetcherCfg := cfg.FetcherConfig
|
||||||
|
if fetcherCfg == nil {
|
||||||
|
fetcherCfg = DefaultFetcherConfig()
|
||||||
|
}
|
||||||
fetcher = NewHTTPFetcher(fetcherCfg)
|
fetcher = NewHTTPFetcher(fetcherCfg)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,17 +74,14 @@ func NewService(cfg *ServiceConfig) (*Service, error) {
|
|||||||
allowHTTP = cfg.FetcherConfig.AllowHTTP
|
allowHTTP = cfg.FetcherConfig.AllowHTTP
|
||||||
}
|
}
|
||||||
|
|
||||||
maxResponseSize := fetcherCfg.MaxResponseSize
|
|
||||||
|
|
||||||
return &Service{
|
return &Service{
|
||||||
cache: cfg.Cache,
|
cache: cfg.Cache,
|
||||||
fetcher: fetcher,
|
fetcher: fetcher,
|
||||||
processor: imageprocessor.New(imageprocessor.Params{MaxInputBytes: maxResponseSize}),
|
processor: NewImageProcessor(),
|
||||||
signer: signer,
|
signer: signer,
|
||||||
allowlist: allowlist.New(cfg.Whitelist),
|
whitelist: NewHostWhitelist(cfg.Whitelist),
|
||||||
log: log,
|
log: log,
|
||||||
allowHTTP: allowHTTP,
|
allowHTTP: allowHTTP,
|
||||||
maxResponseSize: maxResponseSize,
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,7 +103,6 @@ func (s *Service) Get(ctx context.Context, req *ImageRequest) (*ImageResponse, e
|
|||||||
"host", req.SourceHost,
|
"host", req.SourceHost,
|
||||||
"path", req.SourcePath,
|
"path", req.SourcePath,
|
||||||
)
|
)
|
||||||
|
|
||||||
return nil, fmt.Errorf("%w: %w", ErrUpstreamError, ErrNegativeCached)
|
return nil, fmt.Errorf("%w: %w", ErrUpstreamError, ErrNegativeCached)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,40 +145,6 @@ func (s *Service) Get(ctx context.Context, req *ImageRequest) (*ImageResponse, e
|
|||||||
return response, nil
|
return response, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// loadCachedSource attempts to load source content from cache, returning nil
|
|
||||||
// if the cached data is unavailable or exceeds maxResponseSize.
|
|
||||||
func (s *Service) loadCachedSource(contentHash ContentHash) []byte {
|
|
||||||
reader, err := s.cache.GetSourceContent(contentHash)
|
|
||||||
if err != nil {
|
|
||||||
s.log.Warn("failed to load cached source, fetching", "error", err)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bound the read to maxResponseSize to prevent unbounded memory use
|
|
||||||
// from unexpectedly large cached files.
|
|
||||||
limited := io.LimitReader(reader, s.maxResponseSize+1)
|
|
||||||
data, err := io.ReadAll(limited)
|
|
||||||
_ = reader.Close()
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
s.log.Warn("failed to read cached source, fetching", "error", err)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if int64(len(data)) > s.maxResponseSize {
|
|
||||||
s.log.Warn("cached source exceeds max response size, discarding",
|
|
||||||
"hash", contentHash,
|
|
||||||
"max_bytes", s.maxResponseSize,
|
|
||||||
)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return data
|
|
||||||
}
|
|
||||||
|
|
||||||
// processFromSourceOrFetch processes an image, using cached source content if available.
|
// processFromSourceOrFetch processes an image, using cached source content if available.
|
||||||
func (s *Service) processFromSourceOrFetch(
|
func (s *Service) processFromSourceOrFetch(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
@@ -205,8 +161,22 @@ func (s *Service) processFromSourceOrFetch(
|
|||||||
var fetchBytes int64
|
var fetchBytes int64
|
||||||
|
|
||||||
if contentHash != "" {
|
if contentHash != "" {
|
||||||
|
// We have cached source - load it
|
||||||
s.log.Debug("using cached source", "hash", contentHash)
|
s.log.Debug("using cached source", "hash", contentHash)
|
||||||
sourceData = s.loadCachedSource(contentHash)
|
|
||||||
|
reader, err := s.cache.GetSourceContent(contentHash)
|
||||||
|
if err != nil {
|
||||||
|
s.log.Warn("failed to load cached source, fetching", "error", err)
|
||||||
|
// Fall through to fetch
|
||||||
|
} else {
|
||||||
|
sourceData, err = io.ReadAll(reader)
|
||||||
|
_ = reader.Close()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
s.log.Warn("failed to read cached source, fetching", "error", err)
|
||||||
|
// Fall through to fetch
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch from upstream if we don't have source data or it's empty
|
// Fetch from upstream if we don't have source data or it's empty
|
||||||
@@ -278,7 +248,7 @@ func (s *Service) fetchAndProcess(
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Validate magic bytes match content type
|
// Validate magic bytes match content type
|
||||||
if err := magic.ValidateMagicBytes(sourceData, fetchResult.ContentType); err != nil {
|
if err := ValidateMagicBytes(sourceData, fetchResult.ContentType); err != nil {
|
||||||
return nil, fmt.Errorf("content validation failed: %w", err)
|
return nil, fmt.Errorf("content validation failed: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -303,14 +273,7 @@ func (s *Service) processAndStore(
|
|||||||
// Process the image
|
// Process the image
|
||||||
processStart := time.Now()
|
processStart := time.Now()
|
||||||
|
|
||||||
processReq := &imageprocessor.Request{
|
processResult, err := s.processor.Process(ctx, bytes.NewReader(sourceData), req)
|
||||||
Size: imageprocessor.Size{Width: req.Size.Width, Height: req.Size.Height},
|
|
||||||
Format: imageprocessor.Format(req.Format),
|
|
||||||
Quality: req.Quality,
|
|
||||||
FitMode: imageprocessor.FitMode(req.FitMode),
|
|
||||||
}
|
|
||||||
|
|
||||||
processResult, err := s.processor.Process(ctx, bytes.NewReader(sourceData), processReq)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("image processing failed: %w", err)
|
return nil, fmt.Errorf("image processing failed: %w", err)
|
||||||
}
|
}
|
||||||
@@ -383,7 +346,7 @@ func (s *Service) Stats(ctx context.Context) (*CacheStats, error) {
|
|||||||
|
|
||||||
// ValidateRequest validates the request signature if required.
|
// ValidateRequest validates the request signature if required.
|
||||||
func (s *Service) ValidateRequest(req *ImageRequest) error {
|
func (s *Service) ValidateRequest(req *ImageRequest) error {
|
||||||
// Check if host is allowed (no signature required)
|
// Check if host is whitelisted (no signature required)
|
||||||
sourceURL := req.SourceURL()
|
sourceURL := req.SourceURL()
|
||||||
|
|
||||||
parsedURL, err := url.Parse(sourceURL)
|
parsedURL, err := url.Parse(sourceURL)
|
||||||
@@ -391,11 +354,11 @@ func (s *Service) ValidateRequest(req *ImageRequest) error {
|
|||||||
return fmt.Errorf("invalid source URL: %w", err)
|
return fmt.Errorf("invalid source URL: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if s.allowlist.IsAllowed(parsedURL) {
|
if s.whitelist.IsWhitelisted(parsedURL) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Signature required for non-allowed hosts
|
// Signature required for non-whitelisted hosts
|
||||||
return s.signer.Verify(req)
|
return s.signer.Verify(req)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,8 +5,6 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"sneak.berlin/go/pixa/internal/magic"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestService_Get_WhitelistedHost(t *testing.T) {
|
func TestService_Get_WhitelistedHost(t *testing.T) {
|
||||||
@@ -153,74 +151,6 @@ func TestService_Get_NonWhitelistedHost_InvalidSignature(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestService_ValidateRequest_SignatureExactHostMatch verifies that
|
|
||||||
// ValidateRequest enforces exact host matching for signatures. A
|
|
||||||
// signature for one host must not verify for a different host, even
|
|
||||||
// if they share a domain suffix.
|
|
||||||
func TestService_ValidateRequest_SignatureExactHostMatch(t *testing.T) {
|
|
||||||
signingKey := "test-signing-key-must-be-32-chars"
|
|
||||||
svc, _ := SetupTestService(t,
|
|
||||||
WithSigningKey(signingKey),
|
|
||||||
WithNoWhitelist(),
|
|
||||||
)
|
|
||||||
|
|
||||||
signer := NewSigner(signingKey)
|
|
||||||
|
|
||||||
// Sign a request for "cdn.example.com"
|
|
||||||
signedReq := &ImageRequest{
|
|
||||||
SourceHost: "cdn.example.com",
|
|
||||||
SourcePath: "/photos/cat.jpg",
|
|
||||||
Size: Size{Width: 50, Height: 50},
|
|
||||||
Format: FormatJPEG,
|
|
||||||
Quality: 85,
|
|
||||||
FitMode: FitCover,
|
|
||||||
Expires: time.Now().Add(time.Hour),
|
|
||||||
}
|
|
||||||
signedReq.Signature = signer.Sign(signedReq)
|
|
||||||
|
|
||||||
// The original request should pass validation
|
|
||||||
t.Run("exact host passes", func(t *testing.T) {
|
|
||||||
err := svc.ValidateRequest(signedReq)
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("ValidateRequest() exact host failed: %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// Try to reuse the signature with different hosts
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
host string
|
|
||||||
}{
|
|
||||||
{"parent domain", "example.com"},
|
|
||||||
{"sibling subdomain", "images.example.com"},
|
|
||||||
{"deeper subdomain", "a.cdn.example.com"},
|
|
||||||
{"evil suffix domain", "cdn.example.com.evil.com"},
|
|
||||||
{"prefixed host", "evilcdn.example.com"},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name+" rejected", func(t *testing.T) {
|
|
||||||
req := &ImageRequest{
|
|
||||||
SourceHost: tt.host,
|
|
||||||
SourcePath: signedReq.SourcePath,
|
|
||||||
SourceQuery: signedReq.SourceQuery,
|
|
||||||
Size: signedReq.Size,
|
|
||||||
Format: signedReq.Format,
|
|
||||||
Quality: signedReq.Quality,
|
|
||||||
FitMode: signedReq.FitMode,
|
|
||||||
Expires: signedReq.Expires,
|
|
||||||
Signature: signedReq.Signature,
|
|
||||||
}
|
|
||||||
|
|
||||||
err := svc.ValidateRequest(req)
|
|
||||||
if err == nil {
|
|
||||||
t.Errorf("ValidateRequest() should reject signature for host %q (signed for %q)",
|
|
||||||
tt.host, signedReq.SourceHost)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestService_Get_InvalidFile(t *testing.T) {
|
func TestService_Get_InvalidFile(t *testing.T) {
|
||||||
svc, fixtures := SetupTestService(t)
|
svc, fixtures := SetupTestService(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
@@ -317,17 +247,17 @@ func TestService_Get_FormatConversion(t *testing.T) {
|
|||||||
t.Fatalf("failed to read response: %v", err)
|
t.Fatalf("failed to read response: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
detectedMIME, err := magic.DetectFormat(data)
|
detectedMIME, err := DetectFormat(data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("failed to detect format: %v", err)
|
t.Fatalf("failed to detect format: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedFormat, ok := magic.MIMEToImageFormat(tt.wantMIME)
|
expectedFormat, ok := MIMEToImageFormat(tt.wantMIME)
|
||||||
if !ok {
|
if !ok {
|
||||||
t.Fatalf("unknown format for MIME type: %s", tt.wantMIME)
|
t.Fatalf("unknown format for MIME type: %s", tt.wantMIME)
|
||||||
}
|
}
|
||||||
|
|
||||||
detectedFormat, ok := magic.MIMEToImageFormat(string(detectedMIME))
|
detectedFormat, ok := MIMEToImageFormat(string(detectedMIME))
|
||||||
if !ok {
|
if !ok {
|
||||||
t.Fatalf("unknown format for detected MIME type: %s", detectedMIME)
|
t.Fatalf("unknown format for detected MIME type: %s", detectedMIME)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,11 +43,6 @@ func (s *Signer) Sign(req *ImageRequest) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Verify checks if the signature on the request is valid and not expired.
|
// Verify checks if the signature on the request is valid and not expired.
|
||||||
// Signatures are exact-match only: every component of the signed data
|
|
||||||
// (host, path, query, dimensions, format, expiration) must match exactly.
|
|
||||||
// No suffix matching, wildcard matching, or partial matching is supported.
|
|
||||||
// A signature for "cdn.example.com" will NOT verify for "example.com" or
|
|
||||||
// "other.cdn.example.com", and vice versa.
|
|
||||||
func (s *Signer) Verify(req *ImageRequest) error {
|
func (s *Signer) Verify(req *ImageRequest) error {
|
||||||
// Check expiration first
|
// Check expiration first
|
||||||
if req.Expires.IsZero() {
|
if req.Expires.IsZero() {
|
||||||
@@ -71,8 +66,6 @@ func (s *Signer) Verify(req *ImageRequest) error {
|
|||||||
|
|
||||||
// buildSignatureData creates the string to be signed.
|
// buildSignatureData creates the string to be signed.
|
||||||
// Format: "host:path:query:width:height:format:expiration"
|
// Format: "host:path:query:width:height:format:expiration"
|
||||||
// All components are used verbatim (exact match). No normalization,
|
|
||||||
// suffix matching, or wildcard expansion is performed.
|
|
||||||
func (s *Signer) buildSignatureData(req *ImageRequest) string {
|
func (s *Signer) buildSignatureData(req *ImageRequest) string {
|
||||||
return fmt.Sprintf("%s:%s:%s:%d:%d:%s:%d",
|
return fmt.Sprintf("%s:%s:%s:%d:%d:%s:%d",
|
||||||
req.SourceHost,
|
req.SourceHost,
|
||||||
|
|||||||
@@ -152,178 +152,6 @@ func TestSigner_Verify(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSigner_Verify_ExactMatchOnly verifies that signatures enforce exact
|
|
||||||
// matching on every URL component. No suffix matching, wildcard matching,
|
|
||||||
// or partial matching is supported.
|
|
||||||
func TestSigner_Verify_ExactMatchOnly(t *testing.T) {
|
|
||||||
signer := NewSigner("test-secret-key")
|
|
||||||
|
|
||||||
// Base request that we'll sign, then tamper with individual fields.
|
|
||||||
baseReq := func() *ImageRequest {
|
|
||||||
req := &ImageRequest{
|
|
||||||
SourceHost: "cdn.example.com",
|
|
||||||
SourcePath: "/photos/cat.jpg",
|
|
||||||
SourceQuery: "token=abc",
|
|
||||||
Size: Size{Width: 800, Height: 600},
|
|
||||||
Format: FormatWebP,
|
|
||||||
Expires: time.Now().Add(1 * time.Hour),
|
|
||||||
}
|
|
||||||
req.Signature = signer.Sign(req)
|
|
||||||
|
|
||||||
return req
|
|
||||||
}
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
tamper func(req *ImageRequest)
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "parent domain does not match subdomain",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
// Signed for cdn.example.com, try example.com
|
|
||||||
req.SourceHost = "example.com"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "subdomain does not match parent domain",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
// Signed for cdn.example.com, try images.cdn.example.com
|
|
||||||
req.SourceHost = "images.cdn.example.com"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "sibling subdomain does not match",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
// Signed for cdn.example.com, try images.example.com
|
|
||||||
req.SourceHost = "images.example.com"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "host with suffix appended does not match",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
// Signed for cdn.example.com, try cdn.example.com.evil.com
|
|
||||||
req.SourceHost = "cdn.example.com.evil.com"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "host with prefix does not match",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
// Signed for cdn.example.com, try evilcdn.example.com
|
|
||||||
req.SourceHost = "evilcdn.example.com"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "different path does not match",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
req.SourcePath = "/photos/dog.jpg"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "path suffix does not match",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
req.SourcePath = "/photos/cat.jpg/extra"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "path prefix does not match",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
req.SourcePath = "/other/photos/cat.jpg"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "different query does not match",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
req.SourceQuery = "token=xyz"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "added query does not match empty query",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
req.SourceQuery = "extra=1"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "removed query does not match",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
req.SourceQuery = ""
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "different width does not match",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
req.Size.Width = 801
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "different height does not match",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
req.Size.Height = 601
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "different format does not match",
|
|
||||||
tamper: func(req *ImageRequest) {
|
|
||||||
req.Format = FormatPNG
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
req := baseReq()
|
|
||||||
tt.tamper(req)
|
|
||||||
|
|
||||||
err := signer.Verify(req)
|
|
||||||
if err != ErrSignatureInvalid {
|
|
||||||
t.Errorf("Verify() = %v, want %v", err, ErrSignatureInvalid)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify the unmodified base request still passes
|
|
||||||
t.Run("unmodified request passes", func(t *testing.T) {
|
|
||||||
req := baseReq()
|
|
||||||
if err := signer.Verify(req); err != nil {
|
|
||||||
t.Errorf("Verify() unmodified request failed: %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestSigner_Sign_ExactHostInData verifies that Sign uses the exact host
|
|
||||||
// string in the signature data, producing different signatures for
|
|
||||||
// suffix-related hosts.
|
|
||||||
func TestSigner_Sign_ExactHostInData(t *testing.T) {
|
|
||||||
signer := NewSigner("test-secret-key")
|
|
||||||
|
|
||||||
hosts := []string{
|
|
||||||
"cdn.example.com",
|
|
||||||
"example.com",
|
|
||||||
"images.example.com",
|
|
||||||
"images.cdn.example.com",
|
|
||||||
"cdn.example.com.evil.com",
|
|
||||||
}
|
|
||||||
|
|
||||||
sigs := make(map[string]string)
|
|
||||||
|
|
||||||
for _, host := range hosts {
|
|
||||||
req := &ImageRequest{
|
|
||||||
SourceHost: host,
|
|
||||||
SourcePath: "/photos/cat.jpg",
|
|
||||||
SourceQuery: "",
|
|
||||||
Size: Size{Width: 800, Height: 600},
|
|
||||||
Format: FormatWebP,
|
|
||||||
Expires: time.Unix(1704067200, 0),
|
|
||||||
}
|
|
||||||
|
|
||||||
sig := signer.Sign(req)
|
|
||||||
if existing, ok := sigs[sig]; ok {
|
|
||||||
t.Errorf("hosts %q and %q produced the same signature", existing, host)
|
|
||||||
}
|
|
||||||
|
|
||||||
sigs[sig] = host
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSigner_DifferentKeys(t *testing.T) {
|
func TestSigner_DifferentKeys(t *testing.T) {
|
||||||
signer1 := NewSigner("secret-key-1")
|
signer1 := NewSigner("secret-key-1")
|
||||||
signer2 := NewSigner("secret-key-2")
|
signer2 := NewSigner("secret-key-2")
|
||||||
|
|||||||
@@ -18,9 +18,9 @@ func TestImageRequest_SourceURL_DefaultHTTPS(t *testing.T) {
|
|||||||
|
|
||||||
func TestImageRequest_SourceURL_AllowHTTP(t *testing.T) {
|
func TestImageRequest_SourceURL_AllowHTTP(t *testing.T) {
|
||||||
req := &ImageRequest{
|
req := &ImageRequest{
|
||||||
SourceHost: "localhost:8080",
|
SourceHost: "localhost:8080",
|
||||||
SourcePath: "/photos/cat.jpg",
|
SourcePath: "/photos/cat.jpg",
|
||||||
AllowHTTP: true,
|
AllowHTTP: true,
|
||||||
}
|
}
|
||||||
|
|
||||||
got := req.SourceURL()
|
got := req.SourceURL()
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ func setupStatsTestDB(t *testing.T) *sql.DB {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := database.ApplyMigrations(context.Background(), db, nil); err != nil {
|
if err := database.ApplyMigrations(db); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
t.Cleanup(func() { db.Close() })
|
t.Cleanup(func() { db.Close() })
|
||||||
|
|||||||
@@ -16,8 +16,6 @@ import (
|
|||||||
const (
|
const (
|
||||||
// StorageDirPerm is the permission mode for storage directories.
|
// StorageDirPerm is the permission mode for storage directories.
|
||||||
StorageDirPerm = 0750
|
StorageDirPerm = 0750
|
||||||
// StorageFilePerm is the permission mode for storage files.
|
|
||||||
StorageFilePerm = 0600
|
|
||||||
// MinHashLength is the minimum hash length for path splitting.
|
// MinHashLength is the minimum hash length for path splitting.
|
||||||
MinHashLength = 4
|
MinHashLength = 4
|
||||||
)
|
)
|
||||||
@@ -103,8 +101,7 @@ func (s *ContentStorage) Store(r io.Reader) (hash ContentHash, size int64, err e
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Atomic rename
|
// Atomic rename
|
||||||
//nolint:gosec // G703: paths from internal SHA256 hashes
|
if err := os.Rename(tmpPath, path); err != nil {
|
||||||
if err := os.Rename(filepath.Clean(tmpPath), filepath.Clean(path)); err != nil {
|
|
||||||
return "", 0, fmt.Errorf("failed to rename temp file: %w", err)
|
return "", 0, fmt.Errorf("failed to rename temp file: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,10 +171,10 @@ func (s *ContentStorage) Exists(hash ContentHash) bool {
|
|||||||
func (s *ContentStorage) hashToPath(hash ContentHash) string {
|
func (s *ContentStorage) hashToPath(hash ContentHash) string {
|
||||||
h := string(hash)
|
h := string(hash)
|
||||||
if len(h) < MinHashLength {
|
if len(h) < MinHashLength {
|
||||||
return filepath.Clean(filepath.Join(s.baseDir, h))
|
return filepath.Join(s.baseDir, h)
|
||||||
}
|
}
|
||||||
|
|
||||||
return filepath.Clean(filepath.Join(s.baseDir, h[0:2], h[2:4], h))
|
return filepath.Join(s.baseDir, h[0:2], h[2:4], h)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MetadataStorage handles JSON metadata file storage.
|
// MetadataStorage handles JSON metadata file storage.
|
||||||
@@ -253,8 +250,7 @@ func (s *MetadataStorage) Store(host string, pathHash PathHash, meta *SourceMeta
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Atomic rename
|
// Atomic rename
|
||||||
//nolint:gosec // G703: paths from internal SHA256 hashes
|
if err := os.Rename(tmpPath, path); err != nil {
|
||||||
if err := os.Rename(filepath.Clean(tmpPath), filepath.Clean(path)); err != nil {
|
|
||||||
return fmt.Errorf("failed to rename temp file: %w", err)
|
return fmt.Errorf("failed to rename temp file: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -304,7 +300,7 @@ func (s *MetadataStorage) Exists(host string, pathHash PathHash) bool {
|
|||||||
|
|
||||||
// metaPath returns the file path for metadata: <basedir>/<host>/<path_hash>.json
|
// metaPath returns the file path for metadata: <basedir>/<host>/<path_hash>.json
|
||||||
func (s *MetadataStorage) metaPath(host string, pathHash PathHash) string {
|
func (s *MetadataStorage) metaPath(host string, pathHash PathHash) string {
|
||||||
return filepath.Clean(filepath.Join(s.baseDir, host, string(pathHash)+".json"))
|
return filepath.Join(s.baseDir, host, string(pathHash)+".json")
|
||||||
}
|
}
|
||||||
|
|
||||||
// HashPath computes the SHA256 hash of a path string.
|
// HashPath computes the SHA256 hash of a path string.
|
||||||
@@ -397,8 +393,7 @@ func (s *VariantStorage) Store(key VariantKey, r io.Reader, contentType string)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Atomic rename content
|
// Atomic rename content
|
||||||
//nolint:gosec // G703: paths from internal SHA256 hashes
|
if err := os.Rename(tmpPath, path); err != nil {
|
||||||
if err := os.Rename(filepath.Clean(tmpPath), filepath.Clean(path)); err != nil {
|
|
||||||
return 0, fmt.Errorf("failed to rename temp file: %w", err)
|
return 0, fmt.Errorf("failed to rename temp file: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -414,7 +409,7 @@ func (s *VariantStorage) Store(key VariantKey, r io.Reader, contentType string)
|
|||||||
return 0, fmt.Errorf("failed to marshal metadata: %w", err)
|
return 0, fmt.Errorf("failed to marshal metadata: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := os.WriteFile(metaPath, metaData, StorageFilePerm); err != nil {
|
if err := os.WriteFile(metaPath, metaData, 0640); err != nil {
|
||||||
// Non-fatal, content is stored
|
// Non-fatal, content is stored
|
||||||
_ = err
|
_ = err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package imgcache
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"image"
|
"image"
|
||||||
"image/color"
|
"image/color"
|
||||||
@@ -194,7 +193,7 @@ func setupServiceTestDB(t *testing.T) *sql.DB {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Use the real production schema via migrations
|
// Use the real production schema via migrations
|
||||||
if err := database.ApplyMigrations(context.Background(), db, nil); err != nil {
|
if err := database.ApplyMigrations(db); err != nil {
|
||||||
t.Fatalf("failed to apply migrations: %v", err)
|
t.Fatalf("failed to apply migrations: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,26 +1,25 @@
|
|||||||
// Package allowlist provides host-based URL allow-listing for the image proxy.
|
package imgcache
|
||||||
package allowlist
|
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// HostAllowList checks whether source hosts are permitted.
|
// HostWhitelist implements the Whitelist interface for checking allowed source hosts.
|
||||||
type HostAllowList struct {
|
type HostWhitelist struct {
|
||||||
// exactHosts contains hosts that must match exactly (e.g., "cdn.example.com")
|
// exactHosts contains hosts that must match exactly (e.g., "cdn.example.com")
|
||||||
exactHosts map[string]struct{}
|
exactHosts map[string]struct{}
|
||||||
// suffixHosts contains domain suffixes to match (e.g., ".example.com" matches "cdn.example.com")
|
// suffixHosts contains domain suffixes to match (e.g., ".example.com" matches "cdn.example.com")
|
||||||
suffixHosts []string
|
suffixHosts []string
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a HostAllowList from a list of host patterns.
|
// NewHostWhitelist creates a whitelist from a list of host patterns.
|
||||||
// Patterns starting with "." are treated as suffix matches.
|
// Patterns starting with "." are treated as suffix matches.
|
||||||
// Examples:
|
// Examples:
|
||||||
// - "cdn.example.com" - exact match only
|
// - "cdn.example.com" - exact match only
|
||||||
// - ".example.com" - matches cdn.example.com, images.example.com, etc.
|
// - ".example.com" - matches cdn.example.com, images.example.com, etc.
|
||||||
func New(patterns []string) *HostAllowList {
|
func NewHostWhitelist(patterns []string) *HostWhitelist {
|
||||||
w := &HostAllowList{
|
w := &HostWhitelist{
|
||||||
exactHosts: make(map[string]struct{}),
|
exactHosts: make(map[string]struct{}),
|
||||||
suffixHosts: make([]string, 0),
|
suffixHosts: make([]string, 0),
|
||||||
}
|
}
|
||||||
@@ -41,8 +40,8 @@ func New(patterns []string) *HostAllowList {
|
|||||||
return w
|
return w
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsAllowed checks if a URL's host is in the allow list.
|
// IsWhitelisted checks if a URL's host is in the whitelist.
|
||||||
func (w *HostAllowList) IsAllowed(u *url.URL) bool {
|
func (w *HostWhitelist) IsWhitelisted(u *url.URL) bool {
|
||||||
if u == nil {
|
if u == nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -72,12 +71,12 @@ func (w *HostAllowList) IsAllowed(u *url.URL) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsEmpty returns true if the allow list has no entries.
|
// IsEmpty returns true if the whitelist has no entries.
|
||||||
func (w *HostAllowList) IsEmpty() bool {
|
func (w *HostWhitelist) IsEmpty() bool {
|
||||||
return len(w.exactHosts) == 0 && len(w.suffixHosts) == 0
|
return len(w.exactHosts) == 0 && len(w.suffixHosts) == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// Count returns the total number of allow list entries.
|
// Count returns the total number of whitelist entries.
|
||||||
func (w *HostAllowList) Count() int {
|
func (w *HostWhitelist) Count() int {
|
||||||
return len(w.exactHosts) + len(w.suffixHosts)
|
return len(w.exactHosts) + len(w.suffixHosts)
|
||||||
}
|
}
|
||||||
@@ -1,13 +1,11 @@
|
|||||||
package allowlist_test
|
package imgcache
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/url"
|
"net/url"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"sneak.berlin/go/pixa/internal/allowlist"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestHostAllowList_IsAllowed(t *testing.T) {
|
func TestHostWhitelist_IsWhitelisted(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
patterns []string
|
patterns []string
|
||||||
@@ -69,7 +67,7 @@ func TestHostAllowList_IsAllowed(t *testing.T) {
|
|||||||
want: true,
|
want: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "empty allow list",
|
name: "empty whitelist",
|
||||||
patterns: []string{},
|
patterns: []string{},
|
||||||
testURL: "https://cdn.example.com/image.jpg",
|
testURL: "https://cdn.example.com/image.jpg",
|
||||||
want: false,
|
want: false,
|
||||||
@@ -96,7 +94,7 @@ func TestHostAllowList_IsAllowed(t *testing.T) {
|
|||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
w := allowlist.New(tt.patterns)
|
w := NewHostWhitelist(tt.patterns)
|
||||||
|
|
||||||
var u *url.URL
|
var u *url.URL
|
||||||
if tt.testURL != "" {
|
if tt.testURL != "" {
|
||||||
@@ -107,15 +105,15 @@ func TestHostAllowList_IsAllowed(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
got := w.IsAllowed(u)
|
got := w.IsWhitelisted(u)
|
||||||
if got != tt.want {
|
if got != tt.want {
|
||||||
t.Errorf("IsAllowed() = %v, want %v", got, tt.want)
|
t.Errorf("IsWhitelisted() = %v, want %v", got, tt.want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHostAllowList_IsEmpty(t *testing.T) {
|
func TestHostWhitelist_IsEmpty(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
patterns []string
|
patterns []string
|
||||||
@@ -145,7 +143,7 @@ func TestHostAllowList_IsEmpty(t *testing.T) {
|
|||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
w := allowlist.New(tt.patterns)
|
w := NewHostWhitelist(tt.patterns)
|
||||||
if got := w.IsEmpty(); got != tt.want {
|
if got := w.IsEmpty(); got != tt.want {
|
||||||
t.Errorf("IsEmpty() = %v, want %v", got, tt.want)
|
t.Errorf("IsEmpty() = %v, want %v", got, tt.want)
|
||||||
}
|
}
|
||||||
@@ -153,7 +151,7 @@ func TestHostAllowList_IsEmpty(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHostAllowList_Count(t *testing.T) {
|
func TestHostWhitelist_Count(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
patterns []string
|
patterns []string
|
||||||
@@ -183,7 +181,7 @@ func TestHostAllowList_Count(t *testing.T) {
|
|||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
w := allowlist.New(tt.patterns)
|
w := NewHostWhitelist(tt.patterns)
|
||||||
if got := w.Count(); got != tt.want {
|
if got := w.Count(); got != tt.want {
|
||||||
t.Errorf("Count() = %v, want %v", got, tt.want)
|
t.Errorf("Count() = %v, want %v", got, tt.want)
|
||||||
}
|
}
|
||||||
@@ -40,13 +40,12 @@ func New(_ fx.Lifecycle, params Params) (*Logger, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// replaceAttr simplifies the source attribute to "file.go:line"
|
// replaceAttr simplifies the source attribute to "file.go:line"
|
||||||
replaceAttr := func(_ []string, a slog.Attr) slog.Attr {
|
replaceAttr := func(groups []string, a slog.Attr) slog.Attr {
|
||||||
if a.Key == slog.SourceKey {
|
if a.Key == slog.SourceKey {
|
||||||
if src, ok := a.Value.Any().(*slog.Source); ok {
|
if src, ok := a.Value.Any().(*slog.Source); ok {
|
||||||
a.Value = slog.StringValue(fmt.Sprintf("%s:%d", filepath.Base(src.File), src.Line))
|
a.Value = slog.StringValue(fmt.Sprintf("%s:%d", filepath.Base(src.File), src.Line))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ fi
|
|||||||
|
|
||||||
# Test 3: Wrong password shows error
|
# Test 3: Wrong password shows error
|
||||||
echo "--- Test 3: Login with wrong password ---"
|
echo "--- Test 3: Login with wrong password ---"
|
||||||
WRONG_LOGIN=$(curl -sf -X POST "$BASE_URL/" -d "key=wrong-key" -c "$COOKIE_JAR")
|
WRONG_LOGIN=$(curl -sf -X POST "$BASE_URL/" -d "password=wrong-key" -c "$COOKIE_JAR")
|
||||||
if echo "$WRONG_LOGIN" | grep -qi "invalid\|error\|incorrect\|wrong"; then
|
if echo "$WRONG_LOGIN" | grep -qi "invalid\|error\|incorrect\|wrong"; then
|
||||||
pass "Wrong password shows error message"
|
pass "Wrong password shows error message"
|
||||||
else
|
else
|
||||||
@@ -57,7 +57,7 @@ fi
|
|||||||
|
|
||||||
# Test 4: Correct password redirects to generator
|
# Test 4: Correct password redirects to generator
|
||||||
echo "--- Test 4: Login with correct signing key ---"
|
echo "--- Test 4: Login with correct signing key ---"
|
||||||
curl -sf -X POST "$BASE_URL/" -d "key=$SIGNING_KEY" -c "$COOKIE_JAR" -b "$COOKIE_JAR" -L -o /dev/null
|
curl -sf -X POST "$BASE_URL/" -d "password=$SIGNING_KEY" -c "$COOKIE_JAR" -b "$COOKIE_JAR" -L -o /dev/null
|
||||||
GENERATOR_PAGE=$(curl -sf "$BASE_URL/" -b "$COOKIE_JAR")
|
GENERATOR_PAGE=$(curl -sf "$BASE_URL/" -b "$COOKIE_JAR")
|
||||||
if echo "$GENERATOR_PAGE" | grep -qi "generate\|url\|source\|logout"; then
|
if echo "$GENERATOR_PAGE" | grep -qi "generate\|url\|source\|logout"; then
|
||||||
pass "Correct password shows generator page"
|
pass "Correct password shows generator page"
|
||||||
@@ -68,12 +68,12 @@ fi
|
|||||||
# Test 5: Generate encrypted URL
|
# Test 5: Generate encrypted URL
|
||||||
echo "--- Test 5: Generate encrypted URL ---"
|
echo "--- Test 5: Generate encrypted URL ---"
|
||||||
GEN_RESULT=$(curl -sf -X POST "$BASE_URL/generate" -b "$COOKIE_JAR" \
|
GEN_RESULT=$(curl -sf -X POST "$BASE_URL/generate" -b "$COOKIE_JAR" \
|
||||||
-d "url=$TEST_IMAGE_URL" \
|
-d "source_url=$TEST_IMAGE_URL" \
|
||||||
-d "width=800" \
|
-d "width=800" \
|
||||||
-d "height=600" \
|
-d "height=600" \
|
||||||
-d "format=jpeg" \
|
-d "format=jpeg" \
|
||||||
-d "quality=85" \
|
-d "quality=85" \
|
||||||
-d "fit=cover" \
|
-d "fit_mode=cover" \
|
||||||
-d "ttl=3600")
|
-d "ttl=3600")
|
||||||
if echo "$GEN_RESULT" | grep -q "/v1/e/"; then
|
if echo "$GEN_RESULT" | grep -q "/v1/e/"; then
|
||||||
pass "Encrypted URL generated"
|
pass "Encrypted URL generated"
|
||||||
@@ -121,10 +121,10 @@ fi
|
|||||||
# Test 9: Generate short-TTL URL and verify expiration
|
# Test 9: Generate short-TTL URL and verify expiration
|
||||||
echo "--- Test 9: Expired URL returns 410 ---"
|
echo "--- Test 9: Expired URL returns 410 ---"
|
||||||
# Login again
|
# Login again
|
||||||
curl -sf -X POST "$BASE_URL/" -d "key=$SIGNING_KEY" -c "$COOKIE_JAR" -b "$COOKIE_JAR" -L -o /dev/null
|
curl -sf -X POST "$BASE_URL/" -d "password=$SIGNING_KEY" -c "$COOKIE_JAR" -b "$COOKIE_JAR" -L -o /dev/null
|
||||||
# Generate URL with 1 second TTL
|
# Generate URL with 1 second TTL
|
||||||
GEN_RESULT=$(curl -sf -X POST "$BASE_URL/generate" -b "$COOKIE_JAR" \
|
GEN_RESULT=$(curl -sf -X POST "$BASE_URL/generate" -b "$COOKIE_JAR" \
|
||||||
-d "url=$TEST_IMAGE_URL" \
|
-d "source_url=$TEST_IMAGE_URL" \
|
||||||
-d "width=100" \
|
-d "width=100" \
|
||||||
-d "height=100" \
|
-d "height=100" \
|
||||||
-d "format=jpeg" \
|
-d "format=jpeg" \
|
||||||
|
|||||||
Reference in New Issue
Block a user