docs: migrate to AGPL-3.0-or-later and add COPYRIGHT

- Replace SSPL with GNU AGPLv3 (LICENSE)
- Add COPYRIGHT with attribution
- Update Dockerfile label, README(s), BUILD.md
- Add SPDX headers across repo

refacto: remove redundant descriptive comments; keep only meaningful rationales
- Convert doc-comments to GoDoc style without colons
- Keep only security/algorithm rationales (CSRF state, CSP, chain hash, Bresenham)

tests: harden OAuth handlers tests (state missing/invalid) and fix fakes
- Add VerifyState token checks; ensure CreateAuthURL used
- Clean noisy comments in tests

docs: align docker-compose and scripts headers
This commit is contained in:
Benjamin
2025-09-27 17:35:24 +02:00
parent 4b11f5f638
commit 3aaf1b25f8
53 changed files with 993 additions and 566 deletions

View File

@@ -168,4 +168,4 @@ This is the Community Edition. Contributions are welcome! Please see the main re
## License
Community Edition is released under the Server Side Public License (SSPL).
Community Edition is released under the GNU Affero General Public License v3.0 (AGPLv3).

4
COPYRIGHT Normal file
View File

@@ -0,0 +1,4 @@
Ackify CE — Copyright (C) 2025 Benjamin TOUCHARD.
Licensed under the GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later). See LICENSE.

View File

@@ -34,7 +34,7 @@ LABEL version="${VERSION}"
LABEL description="Ackify - Document signature validation platform"
LABEL org.opencontainers.image.source="https://github.com/btouchard/ackify-ce"
LABEL org.opencontainers.image.description="Professional solution for validating and tracking document reading"
LABEL org.opencontainers.image.licenses="SSPL"
LABEL org.opencontainers.image.licenses="AGPL-3.0-or-later"
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
@@ -50,3 +50,4 @@ ENV ACKIFY_TEMPLATES_DIR=/app/templates
EXPOSE 8080
ENTRYPOINT ["/app/ackify"]
## SPDX-License-Identifier: AGPL-3.0-or-later

717
LICENSE
View File

@@ -1,103 +1,664 @@
Server Side Public License
Version 1, October 16, 2018
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (c) 2025 Benjamin TOUCHARD
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.
The Server Side Public License (the "License") applies to the use, reproduction,
modification and distribution of the Work and any derivatives thereof.
Preamble
The Work is (c) 2025 Benjamin TOUCHARD
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
Parameters
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program—to make sure it remains free
software for all its users.
Licensor: Benjamin TOUCHARD
Licensed Work: Ackify
The Licensed Work is (c) 2025 Benjamin TOUCHARD
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.
Additional Use Grant: You may make use of the Licensed Work, provided that you may not use
the Licensed Work for a Service.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A "Service" is a commercial offering, product, hosted, or managed
service, that allows third parties (other than your own employees
and contractors acting on your behalf) to access and/or use the
Licensed Work or a substantial set of the features or functionality
of the Licensed Work to third parties as a software-as-a-service,
platform-as-a-service, infrastructure-as-a-service or other similar
services that compete with Licensor products or services.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
Change Date: The earlier of the date specified in a Change License, or four
years from the date the Licensed Work is published.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
Change License: Apache License, Version 2.0
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
For information about alternative licensing arrangements for the Licensed Work,
please visit: https://github.com/btouchard/ackify-ce
The precise terms and conditions for copying, distribution and
modification follow.
Notice
TERMS AND CONDITIONS
The Business Source License (this document) is not an Open Source license.
However, the Licensed Work will eventually be made available under an Open Source
License, as stated in this License.
0. Definitions.
License Text
"This License" refers to version 3 of the GNU Affero General Public License.
Terms and Conditions
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
1. License Grant. Subject to the terms and conditions of this License, Licensor
hereby grants to you a non-exclusive, royalty-free, worldwide, non-transferable
license during the term of this License to:
"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.
(a) use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Licensed Work; and
(b) permit persons to whom the Licensed Work is furnished to do so, subject to
the following conditions.
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.
2. Limitations. You may not use the Licensed Work:
A "covered work" means either the unmodified Program or a work based
on the Program.
(a) for a Service, unless you have a separate agreement with Licensor
permitting such use; or
(b) to provide a Service to third parties.
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.
3. Conditions. Your exercise of the rights granted under this License is subject to
the following conditions:
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.
(a) You must give any other recipients of the Licensed Work a copy of this License;
(b) You must cause any modified files to carry prominent notices stating that you
changed the files;
(c) You must retain, in the source form of any derivative works that you distribute,
all copyright, patent, trademark, and attribution notices from the source form
of the Licensed Work, excluding those notices that do not pertain to any part
of the derivative works; and
(d) If the Licensed Work includes a "NOTICE" text file as part of its distribution,
then any derivative works that you distribute must include a readable copy of
the attribution notices contained within such NOTICE file.
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.
4. Termination. This License will terminate automatically upon any breach by you of
the terms of this License. Upon termination, you must stop all use of the Licensed
Work and destroy all copies of the Licensed Work in your possession or control.
1. Source Code.
5. Disclaimer of Warranty. THE LICENSED WORK IS PROVIDED "AS IS" WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE LICENSED WORK OR THE USE OR OTHER DEALINGS
IN THE LICENSED WORK.
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.
6. Limitation of Liability. IN NO EVENT SHALL THE LICENSOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE LICENSED WORK, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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.
7. General. This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be unenforceable,
such provision shall be reformed only to the extent necessary to make it
enforceable. Any use of the Licensed Work in violation of this License will
automatically terminate your rights under this License for the current and all
other versions of the Licensed Work.
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.
For more information on the Server Side Public License, please see:
https://www.mongodb.com/licensing/server-side-public-license
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can
regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same
work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey,
without conditions so long as your license otherwise remains in force.
You may convey covered works to others for the sole purpose of having
them make modifications exclusively for you, or provide you with
facilities for running those works, provided that you comply with the
terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for
you must do so exclusively on your behalf, under your direction and
control, on terms that prohibit them from making any copies of your
copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of
sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does not
survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero
General Public License "or any later version" applies to it, you have
the option of following the terms and conditions either of that
numbered version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number
of the GNU Affero General Public License, you may choose any version
ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions
of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <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 AGPL, see
<https://www.gnu.org/licenses/>.

View File

@@ -1,3 +1,4 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
# Makefile for ackify-ce project
.PHONY: build test test-unit test-integration test-short coverage lint fmt vet clean help

View File

@@ -7,7 +7,7 @@ Secure document reading validation service with cryptographic traceability and i
[![Build](https://img.shields.io/badge/build-passing-brightgreen.svg)](https://github.com/btouchard/ackify-ce)
[![Security](https://img.shields.io/badge/crypto-Ed25519-blue.svg)](https://en.wikipedia.org/wiki/EdDSA)
[![Go](https://img.shields.io/badge/go-1.24.5-blue.svg)](https://golang.org/)
[![License](https://img.shields.io/badge/license-SSPL-blue.svg)](LICENSE)
[![License](https://img.shields.io/badge/License-AGPL_v3-blue.svg)](LICENSE)
> 🇫🇷 [Version française disponible ici](README_FR.md)
@@ -355,9 +355,9 @@ staticcheck ./...
- 🐛 **Issues**: [GitHub Issues](https://github.com/btouchard/ackify-ce/issues)
- 💬 **Discussions**: [GitHub Discussions](https://github.com/btouchard/ackify-ce/discussions)
### SSPL License
Free usage for internal projects. Restriction for competing commercial services.
See [LICENSE](LICENSE) for complete details.
### License (AGPLv3)
Distributed under the GNU Affero General Public License v3.0.
See [LICENSE](LICENSE) for details.
---

View File

@@ -7,7 +7,7 @@ Service sécurisé de validation de lecture avec traçabilité cryptographique e
[![Build](https://img.shields.io/badge/build-passing-brightgreen.svg)](https://github.com/btouchard/ackify-ce)
[![Security](https://img.shields.io/badge/crypto-Ed25519-blue.svg)](https://en.wikipedia.org/wiki/EdDSA)
[![Go](https://img.shields.io/badge/go-1.24.5-blue.svg)](https://golang.org/)
[![License](https://img.shields.io/badge/license-SSPL-blue.svg)](LICENSE)
[![License](https://img.shields.io/badge/License-AGPL_v3-blue.svg)](LICENSE)
> 🌍 [English version available here](README.md)
@@ -359,9 +359,9 @@ docker run -p 8080:8080 --env-file .env ackify:dev
- 🐛 **Issues** : [GitHub Issues](https://github.com/btouchard/ackify-ce/issues)
- 💬 **Discussions** : [GitHub Discussions](https://github.com/btouchard/ackify-ce/discussions)
### Licence SSPL
Usage libre pour projets internes. Restriction pour services commerciaux concurrents.
Voir [LICENSE](LICENSE) pour détails complets.
### Licence AGPLv3
Distribué sous la licence GNU Affero General Public License v3.0.
Voir [LICENSE](LICENSE) pour plus de détails.
---

View File

@@ -1,3 +1,4 @@
## SPDX-License-Identifier: AGPL-3.0-or-later
name: ackify-ce
services:

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
function onOpen() {
DocumentApp.getUi()
.createMenu("Signatures")

View File

@@ -1,3 +1,4 @@
## SPDX-License-Identifier: AGPL-3.0-or-later
name: ackify-ce
services:
@@ -46,4 +47,4 @@ networks:
internal:
volumes:
ackify_data:
ackify_data:

View File

@@ -1,4 +1,5 @@
#!/bin/bash
# SPDX-License-Identifier: AGPL-3.0-or-later
# Ackify Community Edition (CE) Installation Script
# Quick setup for Docker deployment

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package services
import (
@@ -12,15 +13,15 @@ import (
)
type repository interface {
Create(ctx context.Context, signature *models.Signature) error
GetByDocAndUser(ctx context.Context, docID, userSub string) (*models.Signature, error)
GetByDoc(ctx context.Context, docID string) ([]*models.Signature, error)
GetByUser(ctx context.Context, userSub string) ([]*models.Signature, error)
ExistsByDocAndUser(ctx context.Context, docID, userSub string) (bool, error)
CheckUserSignatureStatus(ctx context.Context, docID, userIdentifier string) (bool, error)
GetLastSignature(ctx context.Context) (*models.Signature, error)
GetAllSignaturesOrdered(ctx context.Context) ([]*models.Signature, error)
UpdatePrevHash(ctx context.Context, id int64, prevHash *string) error
Create(ctx context.Context, signature *models.Signature) error
GetByDocAndUser(ctx context.Context, docID, userSub string) (*models.Signature, error)
GetByDoc(ctx context.Context, docID string) ([]*models.Signature, error)
GetByUser(ctx context.Context, userSub string) ([]*models.Signature, error)
ExistsByDocAndUser(ctx context.Context, docID, userSub string) (bool, error)
CheckUserSignatureStatus(ctx context.Context, docID, userIdentifier string) (bool, error)
GetLastSignature(ctx context.Context) (*models.Signature, error)
GetAllSignaturesOrdered(ctx context.Context) ([]*models.Signature, error)
UpdatePrevHash(ctx context.Context, id int64, prevHash *string) error
}
type cryptoSigner interface {
@@ -32,7 +33,6 @@ type SignatureService struct {
signer cryptoSigner
}
// NewSignatureService creates a new signature service
func NewSignatureService(repo repository, signer cryptoSigner) *SignatureService {
return &SignatureService{
repo: repo,
@@ -259,11 +259,11 @@ func (s *SignatureService) RebuildChain(ctx context.Context) error {
logger.Logger.Info("Starting chain rebuild", "totalSignatures", len(signatures))
if signatures[0].PrevHash != nil {
if err := s.repo.UpdatePrevHash(ctx, signatures[0].ID, nil); err != nil {
logger.Logger.Warn("Failed to nullify genesis prev_hash", "id", signatures[0].ID, "error", err)
}
}
if signatures[0].PrevHash != nil {
if err := s.repo.UpdatePrevHash(ctx, signatures[0].ID, nil); err != nil {
logger.Logger.Warn("Failed to nullify genesis prev_hash", "id", signatures[0].ID, "error", err)
}
}
for i := 1; i < len(signatures); i++ {
current := signatures[i]
@@ -271,16 +271,16 @@ func (s *SignatureService) RebuildChain(ctx context.Context) error {
expectedHash := previous.ComputeRecordHash()
if current.PrevHash == nil || *current.PrevHash != expectedHash {
logger.Logger.Info("Chain rebuild: updating prev_hash",
"id", current.ID,
"expectedHash", expectedHash[:16]+"...",
"hadPrevHash", current.PrevHash != nil)
if err := s.repo.UpdatePrevHash(ctx, current.ID, &expectedHash); err != nil {
logger.Logger.Warn("Failed to update prev_hash", "id", current.ID, "error", err)
}
}
}
if current.PrevHash == nil || *current.PrevHash != expectedHash {
logger.Logger.Info("Chain rebuild: updating prev_hash",
"id", current.ID,
"expectedHash", expectedHash[:16]+"...",
"hadPrevHash", current.PrevHash != nil)
if err := s.repo.UpdatePrevHash(ctx, current.ID, &expectedHash); err != nil {
logger.Logger.Warn("Failed to update prev_hash", "id", current.ID, "error", err)
}
}
}
logger.Logger.Info("Chain rebuild completed", "processedSignatures", len(signatures))
return nil

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package services
import (
@@ -9,7 +10,6 @@ import (
"github.com/btouchard/ackify-ce/internal/domain/models"
)
// Mock repository implementation
type fakeRepository struct {
signatures map[string]*models.Signature // key: docID_userSub
allSignatures []*models.Signature
@@ -145,7 +145,6 @@ func (f *fakeRepository) UpdatePrevHash(ctx context.Context, id int64, prevHash
return nil
}
// Mock crypto signer implementation
type fakeCryptoSigner struct {
shouldFail bool
}
@@ -164,7 +163,6 @@ func (f *fakeCryptoSigner) CreateSignature(docID string, user *models.User, time
return payloadHash, signature, nil
}
// Test NewSignatureService
func TestNewSignatureService(t *testing.T) {
repo := newFakeRepository()
signer := newFakeCryptoSigner()
@@ -247,7 +245,6 @@ func TestSignatureService_CreateSignature(t *testing.T) {
},
},
setupRepo: func(r *fakeRepository) {
// Pre-populate with existing signature
r.signatures["existing-doc_existing-user"] = &models.Signature{
ID: 1,
DocID: "existing-doc",
@@ -366,13 +363,12 @@ func TestSignatureService_CreateSignature(t *testing.T) {
return
}
// Verify signature was created
key := tt.request.DocID + "_" + tt.request.User.Sub
signature, exists := repo.signatures[key]
if !exists {
t.Error("Signature should have been created")
return
}
key := tt.request.DocID + "_" + tt.request.User.Sub
signature, exists := repo.signatures[key]
if !exists {
t.Error("Signature should have been created")
return
}
if signature.DocID != tt.request.DocID {
t.Errorf("DocID = %v, expected %v", signature.DocID, tt.request.DocID)
@@ -509,7 +505,6 @@ func TestSignatureService_GetDocumentSignatures(t *testing.T) {
signer := newFakeCryptoSigner()
service := NewSignatureService(repo, signer)
// Setup test data
sig1 := &models.Signature{ID: 1, DocID: "doc1", UserSub: "user1"}
sig2 := &models.Signature{ID: 2, DocID: "doc1", UserSub: "user2"}
sig3 := &models.Signature{ID: 3, DocID: "doc2", UserSub: "user1"}
@@ -543,7 +538,6 @@ func TestSignatureService_GetUserSignatures(t *testing.T) {
signer := newFakeCryptoSigner()
service := NewSignatureService(repo, signer)
// Setup test data
sig1 := &models.Signature{ID: 1, DocID: "doc1", UserSub: "user1"}
sig2 := &models.Signature{ID: 2, DocID: "doc2", UserSub: "user1"}
sig3 := &models.Signature{ID: 3, DocID: "doc1", UserSub: "user2"}
@@ -586,7 +580,6 @@ func TestSignatureService_GetSignatureByDocAndUser(t *testing.T) {
signer := newFakeCryptoSigner()
service := NewSignatureService(repo, signer)
// Setup test data
sig := &models.Signature{ID: 1, DocID: "doc1", UserSub: "user1"}
repo.signatures["doc1_user1"] = sig
@@ -624,7 +617,6 @@ func TestSignatureService_CheckUserSignature(t *testing.T) {
signer := newFakeCryptoSigner()
service := NewSignatureService(repo, signer)
// Setup test data
sig := &models.Signature{ID: 1, DocID: "doc1", UserSub: "user1", UserEmail: "user1@example.com"}
repo.signatures["doc1_user1"] = sig
@@ -838,7 +830,6 @@ func TestSignatureService_RebuildChain(t *testing.T) {
signer := newFakeCryptoSigner()
service := NewSignatureService(repo, signer)
// Setup signatures that need rebuilding
hash := "wrong-hash"
sig1 := &models.Signature{
ID: 1,
@@ -896,7 +887,6 @@ func TestChainIntegrityResult_Structure(t *testing.T) {
}
}
// Helper functions
func stringPtr(s string) *string {
return &s
}

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package models
import "errors"

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package models
import (
@@ -111,24 +112,21 @@ func TestErrorWrapping(t *testing.T) {
originalErr := ErrSignatureNotFound
wrappedErr := errors.Join(originalErr, errors.New("additional context"))
// Test that the original error can be detected in the wrapped error
if !errors.Is(wrappedErr, originalErr) {
t.Error("Original error should be detectable in wrapped error")
}
if !errors.Is(wrappedErr, originalErr) {
t.Error("Original error should be detectable in wrapped error")
}
// Test error message contains both parts
wrappedMsg := wrappedErr.Error()
if !contains(wrappedMsg, "signature not found") {
t.Errorf("Wrapped error should contain original message: %v", wrappedMsg)
}
if !contains(wrappedMsg, "additional context") {
t.Errorf("Wrapped error should contain additional context: %v", wrappedMsg)
}
wrappedMsg := wrappedErr.Error()
if !contains(wrappedMsg, "signature not found") {
t.Errorf("Wrapped error should contain original message: %v", wrappedMsg)
}
if !contains(wrappedMsg, "additional context") {
t.Errorf("Wrapped error should contain additional context: %v", wrappedMsg)
}
}
func TestErrorTypes(t *testing.T) {
// Test that all errors are of type error interface
errors := []error{
errors := []error{
ErrSignatureNotFound,
ErrSignatureAlreadyExists,
ErrInvalidUser,
@@ -144,22 +142,19 @@ func TestErrorTypes(t *testing.T) {
t.Error("Error should not be nil")
}
// Test that error implements error interface
if _, ok := err.(error); !ok {
t.Error("Error should implement error interface")
}
if _, ok := err.(error); !ok {
t.Error("Error should implement error interface")
}
// Test that error message is not empty
if err.Error() == "" {
t.Error("Error message should not be empty")
}
if err.Error() == "" {
t.Error("Error message should not be empty")
}
})
}
}
func TestErrorUniqueness(t *testing.T) {
// Test that all error messages are unique
errors := map[string]error{
errors := map[string]error{
"signature not found": ErrSignatureNotFound,
"signature already exists": ErrSignatureAlreadyExists,
"invalid user": ErrInvalidUser,
@@ -181,16 +176,14 @@ func TestErrorUniqueness(t *testing.T) {
}
}
// Verify we have the expected number of unique errors
expectedCount := 7
expectedCount := 7
if len(messages) != expectedCount {
t.Errorf("Expected %d unique error messages, got %d", expectedCount, len(messages))
}
}
func TestErrorSentinelValues(t *testing.T) {
// Test that errors are sentinel values (same instance when accessed multiple times)
if ErrSignatureNotFound != ErrSignatureNotFound {
if ErrSignatureNotFound != ErrSignatureNotFound {
t.Error("ErrSignatureNotFound should be a sentinel value")
}
if ErrSignatureAlreadyExists != ErrSignatureAlreadyExists {
@@ -213,7 +206,6 @@ func TestErrorSentinelValues(t *testing.T) {
}
}
// Helper function to check if string contains substring
func contains(s, substr string) bool {
return len(s) >= len(substr) && (s == substr || containsAt(s, substr, 0))
}

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package models
import (
@@ -9,7 +10,6 @@ import (
"github.com/btouchard/ackify-ce/pkg/services"
)
// Signature represents a document signature record
type Signature struct {
ID int64 `json:"id" db:"id"`
DocID string `json:"doc_id" db:"doc_id"`
@@ -25,7 +25,6 @@ type Signature struct {
PrevHash *string `json:"prev_hash,omitempty" db:"prev_hash"`
}
// GetServiceInfo returns information about the service that originated this signature
func (s *Signature) GetServiceInfo() *services.ServiceInfo {
if s.Referer == nil {
return nil
@@ -33,14 +32,12 @@ func (s *Signature) GetServiceInfo() *services.ServiceInfo {
return services.DetectServiceFromReferrer(*s.Referer)
}
// SignatureRequest represents a request to create a signature
type SignatureRequest struct {
DocID string
User *User
Referer *string
}
// SignatureStatus represents the status of a signature for a user
type SignatureStatus struct {
DocID string
UserEmail string
@@ -48,7 +45,7 @@ type SignatureStatus struct {
SignedAt *time.Time
}
// ComputeRecordHash computes the SHA-256 hash of a signature record for chaining
// ComputeRecordHash Stable record hash supports tamper-evident chaining and integrity checks across migrations.
func (s *Signature) ComputeRecordHash() string {
data := fmt.Sprintf("%d|%s|%s|%s|%v|%s|%s|%s|%s|%s|%s",
s.ID,

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package models
import (
@@ -29,21 +30,18 @@ func TestSignature_JSONSerialization(t *testing.T) {
PrevHash: &prevHash,
}
// Test serialization
data, err := json.Marshal(signature)
data, err := json.Marshal(signature)
if err != nil {
t.Fatalf("Failed to marshal signature: %v", err)
}
// Test deserialization
var unmarshaled Signature
var unmarshaled Signature
err = json.Unmarshal(data, &unmarshaled)
if err != nil {
t.Fatalf("Failed to unmarshal signature: %v", err)
}
// Verify all fields
if unmarshaled.ID != signature.ID {
if unmarshaled.ID != signature.ID {
t.Errorf("ID mismatch: got %v, expected %v", unmarshaled.ID, signature.ID)
}
if unmarshaled.DocID != signature.DocID {
@@ -109,14 +107,12 @@ func TestSignature_JSONSerializationWithNilFields(t *testing.T) {
PrevHash: nil,
}
// Test serialization
data, err := json.Marshal(signature)
data, err := json.Marshal(signature)
if err != nil {
t.Fatalf("Failed to marshal signature: %v", err)
}
// Verify nil fields are omitted from JSON
jsonStr := string(data)
jsonStr := string(data)
if strings.Contains(jsonStr, "user_name") {
t.Error("user_name should be omitted when nil")
}
@@ -127,15 +123,13 @@ func TestSignature_JSONSerializationWithNilFields(t *testing.T) {
t.Error("prev_hash should be omitted when nil")
}
// Test deserialization
var unmarshaled Signature
var unmarshaled Signature
err = json.Unmarshal(data, &unmarshaled)
if err != nil {
t.Fatalf("Failed to unmarshal signature: %v", err)
}
// Verify nil fields remain nil
if unmarshaled.UserName != nil {
if unmarshaled.UserName != nil {
t.Errorf("UserName should be nil, got %v", unmarshaled.UserName)
}
if unmarshaled.Referer != nil {
@@ -268,23 +262,19 @@ func TestSignature_ComputeRecordHash(t *testing.T) {
hash1 := signature.ComputeRecordHash()
hash2 := signature.ComputeRecordHash()
// Hash should be deterministic
if hash1 != hash2 {
if hash1 != hash2 {
t.Errorf("Hash computation is not deterministic: %v != %v", hash1, hash2)
}
// Hash should not be empty
if hash1 == "" {
if hash1 == "" {
t.Error("Hash should not be empty")
}
// Hash should be base64 encoded
if !isValidBase64(hash1) {
if !isValidBase64(hash1) {
t.Errorf("Hash is not valid base64: %v", hash1)
}
// Changing any field should change the hash
originalID := signature.ID
originalID := signature.ID
signature.ID = 456
hashChanged := signature.ComputeRecordHash()
if hashChanged == hash1 {
@@ -292,15 +282,13 @@ func TestSignature_ComputeRecordHash(t *testing.T) {
}
signature.ID = originalID
// Test with nil UserName
signature.UserName = nil
signature.UserName = nil
hashWithNilName := signature.ComputeRecordHash()
if hashWithNilName == hash1 {
t.Error("Hash should change when UserName becomes nil")
}
// Test with nil Referer
signature.UserName = &userName
signature.UserName = &userName
signature.Referer = nil
hashWithNilReferer := signature.ComputeRecordHash()
if hashWithNilReferer == hash1 {
@@ -452,8 +440,7 @@ func TestSignatureStatus_Creation(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Test JSON serialization
data, err := json.Marshal(tt.status)
data, err := json.Marshal(tt.status)
if err != nil {
t.Fatalf("Failed to marshal status: %v", err)
}
@@ -464,8 +451,7 @@ func TestSignatureStatus_Creation(t *testing.T) {
t.Fatalf("Failed to unmarshal status: %v", err)
}
// Verify fields
if unmarshaled.DocID != tt.status.DocID {
if unmarshaled.DocID != tt.status.DocID {
t.Errorf("DocID mismatch: got %v, expected %v", unmarshaled.DocID, tt.status.DocID)
}
if unmarshaled.UserEmail != tt.status.UserEmail {
@@ -518,31 +504,27 @@ func TestSignature_TimestampValidation(t *testing.T) {
CreatedAt: tt.createdAt,
}
// Business rule: CreatedAt should be after or equal to SignedAtUTC
isValid := !signature.CreatedAt.Before(signature.SignedAtUTC)
isValid := !signature.CreatedAt.Before(signature.SignedAtUTC)
if isValid != tt.expectValid {
t.Errorf("Timestamp validation mismatch: got %v, expected %v", isValid, tt.expectValid)
}
// Verify timestamps are UTC
if signature.SignedAtUTC.Location() != time.UTC {
t.Error("SignedAtUTC should be in UTC timezone")
}
if signature.CreatedAt.Location() != time.UTC {
t.Error("CreatedAt should be in UTC timezone")
}
if signature.SignedAtUTC.Location() != time.UTC {
t.Error("SignedAtUTC should be in UTC timezone")
}
if signature.CreatedAt.Location() != time.UTC {
t.Error("CreatedAt should be in UTC timezone")
}
})
}
}
// Helper functions
func stringPtr(s string) *string {
return &s
return &s
}
func isValidBase64(s string) bool {
// Simple base64 validation - should contain only valid base64 characters
validChars := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
validChars := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
for _, char := range s {
found := false
for _, valid := range validChars {

View File

@@ -1,20 +1,18 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package models
import "strings"
// User represents an authenticated user
type User struct {
Sub string `json:"sub"`
Email string `json:"email"`
Name string `json:"name"`
}
// IsValid checks if the user has valid credentials
func (u *User) IsValid() bool {
return strings.TrimSpace(u.Sub) != "" && strings.TrimSpace(u.Email) != ""
}
// NormalizedEmail returns the email in lowercase
func (u *User) NormalizedEmail() string {
return strings.ToLower(u.Email)
}

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package models
import (
@@ -173,8 +174,7 @@ func TestUser_JSONSerialization(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Test serialization
data, err := json.Marshal(tt.user)
data, err := json.Marshal(tt.user)
if err != nil {
t.Fatalf("Failed to marshal user: %v", err)
}
@@ -183,8 +183,7 @@ func TestUser_JSONSerialization(t *testing.T) {
t.Errorf("JSON serialization mismatch:\ngot: %s\nexpected: %s", string(data), tt.expected)
}
// Test deserialization
var user User
var user User
err = json.Unmarshal(data, &user)
if err != nil {
t.Fatalf("Failed to unmarshal user: %v", err)

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package auth
import (
@@ -20,14 +21,13 @@ import (
const sessionName = "ackapp_session"
type OauthService struct {
oauthConfig *oauth2.Config
sessionStore *sessions.CookieStore
userInfoURL string
allowedDomain string
secureCookies bool
oauthConfig *oauth2.Config
sessionStore *sessions.CookieStore
userInfoURL string
allowedDomain string
secureCookies bool
}
// Config holds OAuth service configuration
type Config struct {
BaseURL string
ClientID string
@@ -41,7 +41,6 @@ type Config struct {
SecureCookies bool
}
// NewOAuthService creates a new OAuth service
func NewOAuthService(config Config) *OauthService {
oauthConfig := &oauth2.Config{
ClientID: config.ClientID,
@@ -114,50 +113,50 @@ func (s *OauthService) Logout(w http.ResponseWriter, r *http.Request) {
}
func (s *OauthService) GetAuthURL(nextURL string) string {
state := base64.RawURLEncoding.EncodeToString(securecookie.GenerateRandomKey(20)) +
":" + base64.RawURLEncoding.EncodeToString([]byte(nextURL))
state := base64.RawURLEncoding.EncodeToString(securecookie.GenerateRandomKey(20)) +
":" + base64.RawURLEncoding.EncodeToString([]byte(nextURL))
return s.oauthConfig.AuthCodeURL(state, oauth2.SetAuthURLParam("prompt", "select_account"))
return s.oauthConfig.AuthCodeURL(state, oauth2.SetAuthURLParam("prompt", "select_account"))
}
// CreateAuthURL generates the OAuth URL and stores the random state token in session for later verification
// CreateAuthURL Persist a CSRF state token server-side to prevent forged OAuth callbacks; encode nextURL to preserve intended redirect.
func (s *OauthService) CreateAuthURL(w http.ResponseWriter, r *http.Request, nextURL string) string {
randPart := securecookie.GenerateRandomKey(20)
token := base64.RawURLEncoding.EncodeToString(randPart)
state := token + ":" + base64.RawURLEncoding.EncodeToString([]byte(nextURL))
randPart := securecookie.GenerateRandomKey(20)
token := base64.RawURLEncoding.EncodeToString(randPart)
state := token + ":" + base64.RawURLEncoding.EncodeToString([]byte(nextURL))
session, _ := s.sessionStore.Get(r, sessionName)
session.Values["oauth_state"] = token
session.Options = &sessions.Options{Path: "/", HttpOnly: true, Secure: s.secureCookies, SameSite: http.SameSiteLaxMode}
_ = session.Save(r, w)
session, _ := s.sessionStore.Get(r, sessionName)
session.Values["oauth_state"] = token
session.Options = &sessions.Options{Path: "/", HttpOnly: true, Secure: s.secureCookies, SameSite: http.SameSiteLaxMode}
_ = session.Save(r, w)
return s.oauthConfig.AuthCodeURL(state, oauth2.SetAuthURLParam("prompt", "select_account"))
return s.oauthConfig.AuthCodeURL(state, oauth2.SetAuthURLParam("prompt", "select_account"))
}
// VerifyState checks the provided state token against the session and clears it on success
// VerifyState Clear single-use state on success to prevent replay; compare in constant time to avoid timing leaks.
func (s *OauthService) VerifyState(w http.ResponseWriter, r *http.Request, stateToken string) bool {
session, _ := s.sessionStore.Get(r, sessionName)
stored, _ := session.Values["oauth_state"].(string)
if stored == "" || stateToken == "" {
return false
}
if subtleConstantTimeCompare(stored, stateToken) {
delete(session.Values, "oauth_state")
_ = session.Save(r, w)
return true
}
return false
session, _ := s.sessionStore.Get(r, sessionName)
stored, _ := session.Values["oauth_state"].(string)
if stored == "" || stateToken == "" {
return false
}
if subtleConstantTimeCompare(stored, stateToken) {
delete(session.Values, "oauth_state")
_ = session.Save(r, w)
return true
}
return false
}
func subtleConstantTimeCompare(a, b string) bool {
if len(a) != len(b) {
return false
}
var v byte
for i := 0; i < len(a); i++ {
v |= a[i] ^ b[i]
}
return v == 0
if len(a) != len(b) {
return false
}
var v byte
for i := 0; i < len(a); i++ {
v |= a[i] ^ b[i]
}
return v == 0
}
func (s *OauthService) HandleCallback(ctx context.Context, code, state string) (*models.User, string, error) {
@@ -212,12 +211,14 @@ func (s *OauthService) parseUserInfo(resp *http.Response) (*models.User, error)
return nil, fmt.Errorf("failed to decode user info: %w", err)
}
// Reduce PII in standard logs; log only keys at debug level
if rawUser != nil {
keys := make([]string, 0, len(rawUser))
for k := range rawUser { keys = append(keys, k) }
logger.Logger.Debug("OAuth user info received", "keys", keys)
}
// Reduce PII in standard logs; log only keys at debug level
if rawUser != nil {
keys := make([]string, 0, len(rawUser))
for k := range rawUser {
keys = append(keys, k)
}
logger.Logger.Debug("OAuth user info received", "keys", keys)
}
user := &models.User{}
@@ -254,10 +255,10 @@ func (s *OauthService) parseUserInfo(resp *http.Response) (*models.User, error)
user.Name = name
logger.Logger.Debug("Extracted OAuth user identifiers",
"sub", user.Sub,
"email_present", user.Email != "",
"name_present", user.Name != "")
logger.Logger.Debug("Extracted OAuth user identifiers",
"sub", user.Sub,
"email_present", user.Email != "",
"name_present", user.Name != "")
if !user.IsValid() {
return nil, fmt.Errorf("invalid user data extracted: sub=%s, email=%s", user.Sub, user.Email)

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package auth
import (

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package config
import (
@@ -9,7 +10,6 @@ import (
"github.com/gorilla/securecookie"
)
// Config holds all application configuration
type Config struct {
App AppConfig
Database DatabaseConfig
@@ -17,19 +17,16 @@ type Config struct {
Server ServerConfig
}
// AppConfig holds general application settings
type AppConfig struct {
BaseURL string
Organisation string
SecureCookies bool
}
// DatabaseConfig holds database connection settings
type DatabaseConfig struct {
DSN string
}
// OAuthConfig holds OAuth authentication settings
type OAuthConfig struct {
ClientID string
ClientSecret string
@@ -41,7 +38,6 @@ type OAuthConfig struct {
CookieSecret []byte
}
// ServerConfig holds server settings
type ServerConfig struct {
ListenAddr string
}
@@ -98,7 +94,6 @@ func Load() (*Config, error) {
return config, nil
}
// mustGetEnv gets an environment variable or panics if not found
func mustGetEnv(key string) string {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
@@ -107,7 +102,6 @@ func mustGetEnv(key string) string {
return value
}
// getEnv gets an environment variable with a default value
func getEnv(key, defaultValue string) string {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
@@ -116,7 +110,6 @@ func getEnv(key, defaultValue string) string {
return value
}
// parseCookieSecret parses the cookie secret from environment
func parseCookieSecret() ([]byte, error) {
raw := os.Getenv("ACKIFY_OAUTH_COOKIE_SECRET")
if raw == "" {

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package config
import (
@@ -504,10 +505,9 @@ func TestLoad_CustomProvider(t *testing.T) {
t.Fatalf("Load() failed: %v", err)
}
// Test custom OAuth config
if config.OAuth.AuthURL != "https://auth.custom.com/oauth/authorize" {
t.Errorf("OAuth.AuthURL = %v, expected custom auth URL", config.OAuth.AuthURL)
}
if config.OAuth.AuthURL != "https://auth.custom.com/oauth/authorize" {
t.Errorf("OAuth.AuthURL = %v, expected custom auth URL", config.OAuth.AuthURL)
}
if config.OAuth.TokenURL != "https://auth.custom.com/oauth/token" {
t.Errorf("OAuth.TokenURL = %v, expected custom token URL", config.OAuth.TokenURL)
}
@@ -531,8 +531,7 @@ func TestLoad_MissingRequiredEnvironmentVariables(t *testing.T) {
for _, missingVar := range requiredVars {
t.Run("missing_"+missingVar, func(t *testing.T) {
// Set all required variables except the one being tested
envVars := map[string]string{
envVars := map[string]string{
"ACKIFY_BASE_URL": "https://ackify.example.com",
"ACKIFY_ORGANISATION": "Test Organisation",
"ACKIFY_DB_DSN": "postgres://user:pass@localhost/test",
@@ -541,24 +540,20 @@ func TestLoad_MissingRequiredEnvironmentVariables(t *testing.T) {
"ACKIFY_OAUTH_PROVIDER": "google",
}
// Remove the variable we're testing
delete(envVars, missingVar)
delete(envVars, missingVar)
// Set environment variables
for key, value := range envVars {
for key, value := range envVars {
os.Setenv(key, value)
defer os.Unsetenv(key)
}
// Ensure the missing variable is not set
os.Unsetenv(missingVar)
os.Unsetenv(missingVar)
// Test that Load() panics
defer func() {
if r := recover(); r == nil {
t.Errorf("Load() should panic when %s is missing", missingVar)
}
}()
defer func() {
if r := recover(); r == nil {
t.Errorf("Load() should panic when %s is missing", missingVar)
}
}()
Load()
})
@@ -574,8 +569,7 @@ func TestLoad_CustomProviderMissingRequiredVars(t *testing.T) {
for _, missingVar := range customRequiredVars {
t.Run("custom_missing_"+missingVar, func(t *testing.T) {
// Set basic required variables
envVars := map[string]string{
envVars := map[string]string{
"ACKIFY_BASE_URL": "https://ackify.example.com",
"ACKIFY_ORGANISATION": "Test Organisation",
"ACKIFY_DB_DSN": "postgres://user:pass@localhost/test",
@@ -586,24 +580,20 @@ func TestLoad_CustomProviderMissingRequiredVars(t *testing.T) {
"ACKIFY_OAUTH_USERINFO_URL": "https://api.custom.com/user",
}
// Remove the variable we're testing
delete(envVars, missingVar)
delete(envVars, missingVar)
// Set environment variables
for key, value := range envVars {
for key, value := range envVars {
os.Setenv(key, value)
defer os.Unsetenv(key)
}
// Ensure the missing variable is not set
os.Unsetenv(missingVar)
os.Unsetenv(missingVar)
// Test that Load() panics for custom provider missing URLs
defer func() {
if r := recover(); r == nil {
t.Errorf("Load() should panic when %s is missing for custom provider", missingVar)
}
}()
defer func() {
if r := recover(); r == nil {
t.Errorf("Load() should panic when %s is missing for custom provider", missingVar)
}
}()
Load()
})
@@ -697,8 +687,7 @@ func TestParseCookieSecret_InvalidBase64(t *testing.T) {
}
func TestParseCookieSecret_ValidBase64WrongLength(t *testing.T) {
// Test valid base64 but wrong length (should fall back to raw string)
wrongLength := base64.StdEncoding.EncodeToString(make([]byte, 16)) // 16 bytes instead of 32/64
wrongLength := base64.StdEncoding.EncodeToString(make([]byte, 16)) // 16 bytes instead of 32/64
os.Setenv("ACKIFY_OAUTH_COOKIE_SECRET", wrongLength)
defer os.Unsetenv("ACKIFY_OAUTH_COOKIE_SECRET")
@@ -707,10 +696,9 @@ func TestParseCookieSecret_ValidBase64WrongLength(t *testing.T) {
t.Errorf("parseCookieSecret() should not fail for wrong length: %v", err)
}
// Should fall back to raw string
if string(result) != wrongLength {
t.Errorf("parseCookieSecret() should fall back to raw string for wrong length")
}
if string(result) != wrongLength {
t.Errorf("parseCookieSecret() should fall back to raw string for wrong length")
}
}
func TestLoad_ErrorInParseCookieSecret(t *testing.T) {
@@ -728,8 +716,7 @@ func TestLoad_ErrorInParseCookieSecret(t *testing.T) {
defer os.Unsetenv(key)
}
// Set a cookie secret that won't cause an error (parseCookieSecret doesn't actually return errors in current implementation)
os.Setenv("ACKIFY_OAUTH_COOKIE_SECRET", "valid-secret")
os.Setenv("ACKIFY_OAUTH_COOKIE_SECRET", "valid-secret")
defer os.Unsetenv("ACKIFY_OAUTH_COOKIE_SECRET")
config, err := Load()
@@ -737,10 +724,9 @@ func TestLoad_ErrorInParseCookieSecret(t *testing.T) {
t.Fatalf("Load() should not fail: %v", err)
}
// Verify the config was loaded successfully
if config == nil {
t.Error("Config should not be nil")
}
if config == nil {
t.Error("Config should not be nil")
}
}
func TestAppConfig_SecureCookiesLogic(t *testing.T) {
@@ -800,7 +786,6 @@ func TestAppConfig_SecureCookiesLogic(t *testing.T) {
}
}
// Helper function to compare slices
func equalSlices(a, b []string) bool {
if len(a) != len(b) {
return false

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package database
import (
@@ -9,10 +10,9 @@ import (
"github.com/btouchard/ackify-ce/internal/infrastructure/config"
)
// DocumentAgg represents a document with signature count
type DocumentAgg struct {
DocID string `json:"doc_id"`
Count int `json:"count"`
DocID string `json:"doc_id"`
Count int `json:"count"`
}
// AdminRepository provides read-only access for admin operations
@@ -20,7 +20,6 @@ type AdminRepository struct {
db *sql.DB
}
// NewAdminRepository creates a new admin repository with its own database connection
func NewAdminRepository(ctx context.Context) (*AdminRepository, error) {
cfg, err := config.Load()
if err != nil {
@@ -35,7 +34,6 @@ func NewAdminRepository(ctx context.Context) (*AdminRepository, error) {
return &AdminRepository{db: db}, nil
}
// NewAdminRepositoryFromDB reuses an existing *sql.DB connection
func NewAdminRepositoryFromDB(db *sql.DB) *AdminRepository {
return &AdminRepository{db: db}
}

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package database
import (
@@ -9,12 +10,10 @@ import (
_ "github.com/lib/pq"
)
// Config holds database configuration
type Config struct {
DSN string
DSN string
}
// InitDB initializes the database connection
func InitDB(ctx context.Context, config Config) (*sql.DB, error) {
db, err := sql.Open("postgres", config.DSN)
if err != nil {

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package database
import (
@@ -13,9 +14,8 @@ type SignatureRepository struct {
db *sql.DB
}
// NewSignatureRepository creates a new PostgresSQL signature repository
func NewSignatureRepository(db *sql.DB) *SignatureRepository {
return &SignatureRepository{db: db}
return &SignatureRepository{db: db}
}
func (r *SignatureRepository) Create(ctx context.Context, signature *models.Signature) error {
@@ -266,7 +266,6 @@ func (r *SignatureRepository) GetAllSignaturesOrdered(ctx context.Context) ([]*m
return signatures, nil
}
// UpdatePrevHash updates the prev_hash field for a signature record by ID
func (r *SignatureRepository) UpdatePrevHash(ctx context.Context, id int64, prevHash *string) error {
query := `UPDATE signatures SET prev_hash = $2 WHERE id = $1`
if _, err := r.db.ExecContext(ctx, query, id, prevHash); err != nil {

View File

@@ -1,5 +1,6 @@
//go:build integration
// SPDX-License-Identifier: AGPL-3.0-or-later
package database
import (
@@ -100,7 +101,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
close(successCount)
close(errorCount)
// Count results
successes := 0
failures := 0
for range successCount {
@@ -110,7 +110,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
failures++
}
// Only one should succeed due to unique constraint
if successes != 1 {
t.Errorf("Expected exactly 1 success, got %d", successes)
}
@@ -118,7 +117,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
t.Errorf("Expected %d failures, got %d", numGoroutines-1, failures)
}
// Verify only one record exists
count := testDB.GetTableCount(t)
if count != 1 {
t.Errorf("Expected 1 signature after concurrent duplicates, got %d", count)
@@ -135,7 +133,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
var wg sync.WaitGroup
// Start writers
for i := 0; i < numWriters; i++ {
wg.Add(1)
go func(writerID int) {
@@ -154,7 +151,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
}(i)
}
// Start readers
readResults := make(chan int, numReaders*10) // Buffer for all results
for i := 0; i < numReaders; i++ {
wg.Add(1)
@@ -176,14 +172,12 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
wg.Wait()
close(readResults)
// Verify reads were consistent (no corruption)
for count := range readResults {
if count < 0 || count > numWriters*numWrites {
t.Errorf("Invalid read result: %d (should be 0-%d)", count, numWriters*numWrites)
}
}
// Verify final count
finalCount := testDB.GetTableCount(t)
expectedCount := numWriters * numWrites
if finalCount != expectedCount {
@@ -199,7 +193,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
var wg sync.WaitGroup
// Start creators
for i := 0; i < numCreators; i++ {
wg.Add(1)
go func(creatorID int) {
@@ -217,7 +210,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
}(i)
}
// Start readers calling GetLastSignature
lastSigResults := make(chan *models.Signature, numReaders*10)
for i := 0; i < numReaders; i++ {
wg.Add(1)
@@ -239,14 +231,11 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
wg.Wait()
close(lastSigResults)
// Verify GetLastSignature results are valid
for sig := range lastSigResults {
if sig != nil {
// Should have valid ID assigned by database
if sig.ID <= 0 {
t.Error("GetLastSignature returned signature with invalid ID")
}
// Should have valid required fields
if sig.DocID == "" || sig.UserSub == "" {
t.Error("GetLastSignature returned signature with empty required fields")
}
@@ -262,7 +251,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
var wg sync.WaitGroup
// Start creators
for i := 0; i < numCreators; i++ {
wg.Add(1)
go func(creatorID int) {
@@ -280,7 +268,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
}(i)
}
// Start readers calling GetAllSignaturesOrdered
orderingErrors := make(chan error, numReaders*5)
for i := 0; i < numReaders; i++ {
wg.Add(1)
@@ -294,7 +281,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
return
}
// Verify ordering (ID should be ascending)
for k := 1; k < len(signatures); k++ {
if signatures[k].ID <= signatures[k-1].ID {
orderingErrors <- err
@@ -310,7 +296,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
wg.Wait()
close(orderingErrors)
// Check for ordering violations
for err := range orderingErrors {
if err != nil {
t.Errorf("Concurrent ordering error: %v", err)
@@ -330,7 +315,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
var wg sync.WaitGroup
operationCounts := make(chan map[string]int, numWorkers)
// Start workers doing mixed operations
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go func(workerID int) {
@@ -351,7 +335,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
operationCounts <- counts
return
default:
// Randomly choose operation
switch workerID % 5 {
case 0: // Create
sig := factory.CreateSignatureWithUser(
@@ -404,7 +387,6 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
wg.Wait()
close(operationCounts)
// Aggregate results
totalOps := 0
totalErrors := 0
for counts := range operationCounts {
@@ -419,12 +401,10 @@ func TestRepository_Concurrency_Integration(t *testing.T) {
t.Logf("Stress test completed: %d operations, %d errors", totalOps, totalErrors)
// Should have completed many operations with minimal errors
if totalOps < 100 {
t.Errorf("Expected at least 100 operations, got %d", totalOps)
}
// Error rate should be reasonable (< 10%)
errorRate := float64(totalErrors) / float64(totalOps+totalErrors) * 100
if errorRate > 10 {
t.Errorf("Error rate too high: %.2f%% (expected < 10%%)", errorRate)
@@ -446,7 +426,6 @@ func TestRepository_DeadlockPrevention_Integration(t *testing.T) {
var wg sync.WaitGroup
deadlockErrors := make(chan error, numWorkers)
// Workers with different access patterns that could cause deadlocks
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go func(workerID int) {
@@ -454,7 +433,6 @@ func TestRepository_DeadlockPrevention_Integration(t *testing.T) {
repo := NewSignatureRepository(testDB.DB)
for j := 0; j < opsPerWorker; j++ {
// Pattern 1: Create then immediately query
if workerID%2 == 0 {
sig := factory.CreateSignatureWithUser(
fmt.Sprintf("pattern1-user-%d-%d", workerID, j),
@@ -466,7 +444,6 @@ func TestRepository_DeadlockPrevention_Integration(t *testing.T) {
_, _ = repo.ExistsByDocAndUser(ctx, sig.DocID, sig.UserSub)
}
} else {
// Pattern 2: Query then create
testDocID := fmt.Sprintf("pattern2-doc-%d", workerID)
testUserSub := fmt.Sprintf("pattern2-user-%d", j)
@@ -481,13 +458,11 @@ func TestRepository_DeadlockPrevention_Integration(t *testing.T) {
_ = repo.Create(ctx, sig)
}
// Small random delay to increase chance of contention
time.Sleep(time.Duration(workerID%3+1) * time.Millisecond)
}
}(i)
}
// Wait with timeout to detect deadlocks
done := make(chan bool)
go func() {
wg.Wait()
@@ -496,14 +471,12 @@ func TestRepository_DeadlockPrevention_Integration(t *testing.T) {
select {
case <-done:
// Success - no deadlocks
case <-time.After(30 * time.Second):
t.Fatal("Test timed out - possible deadlock detected")
}
close(deadlockErrors)
// Check for deadlock-specific errors
for err := range deadlockErrors {
if err != nil {
t.Errorf("Deadlock-related error: %v", err)

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
//go:build integration
package database

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
//go:build integration
package database
@@ -56,7 +57,6 @@ func TestRepository_Create_Integration(t *testing.T) {
t.Fatalf("Unexpected error: %v", err)
}
// Verify signature was created with ID and CreatedAt
if tt.signature.ID <= 0 {
t.Error("Expected ID to be set after create")
}
@@ -65,7 +65,6 @@ func TestRepository_Create_Integration(t *testing.T) {
t.Error("Expected CreatedAt to be set after create")
}
// Verify data in database
count := testDB.GetTableCount(t)
if count != 1 {
t.Errorf("Expected 1 signature in DB, got %d", count)
@@ -80,14 +79,12 @@ func TestRepository_Create_UniqueConstraint_Integration(t *testing.T) {
factory := NewSignatureFactory()
ctx := context.Background()
// Create first signature
sig1 := factory.CreateSignatureWithDocAndUser("doc1", "user1", "user1@example.com")
err := repo.Create(ctx, sig1)
if err != nil {
t.Fatalf("Failed to create first signature: %v", err)
}
// Try to create duplicate (same doc_id and user_sub)
sig2 := factory.CreateSignatureWithDocAndUser("doc1", "user1", "user1@example.com")
err = repo.Create(ctx, sig2)
@@ -95,7 +92,6 @@ func TestRepository_Create_UniqueConstraint_Integration(t *testing.T) {
t.Error("Expected error for duplicate signature but got none")
}
// Should still have only 1 signature
count := testDB.GetTableCount(t)
if count != 1 {
t.Errorf("Expected 1 signature in DB after constraint violation, got %d", count)
@@ -184,7 +180,6 @@ func TestRepository_GetByDocAndUser_Integration(t *testing.T) {
t.Fatal("Expected signature but got nil")
}
// Compare with expected (excluding ID and CreatedAt which are set by DB)
AssertSignatureEqual(t, expected, result)
})
}
@@ -196,7 +191,6 @@ func TestRepository_GetByDoc_Integration(t *testing.T) {
factory := NewSignatureFactory()
ctx := context.Background()
// Setup: Create signatures for multiple docs and users
sig1 := factory.CreateSignatureWithDocAndUser("doc1", "user1", "user1@example.com")
sig2 := factory.CreateSignatureWithDocAndUser("doc1", "user2", "user2@example.com")
sig3 := factory.CreateSignatureWithDocAndUser("doc2", "user1", "user1@example.com")
@@ -245,7 +239,6 @@ func TestRepository_GetByDoc_Integration(t *testing.T) {
t.Errorf("Expected %d signatures, got %d", tt.expectedCount, len(result))
}
// Verify order (should be by created_at DESC)
for i, sig := range result {
if i < len(tt.expectedUsers) && sig.UserSub != tt.expectedUsers[i] {
t.Errorf("Expected user %s at position %d, got %s", tt.expectedUsers[i], i, sig.UserSub)
@@ -265,7 +258,6 @@ func TestRepository_GetByUser_Integration(t *testing.T) {
factory := NewSignatureFactory()
ctx := context.Background()
// Setup: Create signatures for multiple users and docs
sig1 := factory.CreateSignatureWithDocAndUser("doc1", "user1", "user1@example.com")
sig2 := factory.CreateSignatureWithDocAndUser("doc2", "user1", "user1@example.com")
sig3 := factory.CreateSignatureWithDocAndUser("doc1", "user2", "user2@example.com")
@@ -314,7 +306,6 @@ func TestRepository_GetByUser_Integration(t *testing.T) {
t.Errorf("Expected %d signatures, got %d", tt.expectedCount, len(result))
}
// Verify order and data
for i, sig := range result {
if i < len(tt.expectedDocIDs) && sig.DocID != tt.expectedDocIDs[i] {
t.Errorf("Expected DocID %s at position %d, got %s", tt.expectedDocIDs[i], i, sig.DocID)
@@ -334,7 +325,6 @@ func TestRepository_ExistsByDocAndUser_Integration(t *testing.T) {
factory := NewSignatureFactory()
ctx := context.Background()
// Setup: Create a signature
sig := factory.CreateSignatureWithDocAndUser("doc1", "user1", "user1@example.com")
_ = repo.Create(ctx, sig)
@@ -391,7 +381,6 @@ func TestRepository_CheckUserSignatureStatus_Integration(t *testing.T) {
factory := NewSignatureFactory()
ctx := context.Background()
// Setup: Create signatures with different users
sig1 := factory.CreateSignatureWithDocAndUser("doc1", "user-sub-123", "user@EXAMPLE.COM")
sig2 := factory.CreateSignatureWithDocAndUser("doc2", "another-user", "another@example.com")
@@ -499,7 +488,6 @@ func TestRepository_GetLastSignature_Integration(t *testing.T) {
t.Run("multiple signatures", func(t *testing.T) {
testDB.ClearTable(t)
// Create signatures with different content
sig1 := factory.CreateSignatureWithUser("user1", "user1@example.com")
sig2 := factory.CreateSignatureWithUser("user2", "user2@example.com")
sig3 := factory.CreateSignatureWithUser("user3", "user3@example.com")
@@ -520,7 +508,6 @@ func TestRepository_GetLastSignature_Integration(t *testing.T) {
t.Fatal("Expected signature but got nil")
}
// Should return the last created signature (sig3)
if result.UserSub != "user3" {
t.Errorf("Expected last signature to be user3, got %s", result.UserSub)
}
@@ -550,7 +537,6 @@ func TestRepository_GetAllSignaturesOrdered_Integration(t *testing.T) {
t.Run("multiple signatures ordered by ID ASC", func(t *testing.T) {
testDB.ClearTable(t)
// Create signatures
sig1 := factory.CreateSignatureWithUser("user1", "user1@example.com")
sig2 := factory.CreateSignatureWithUser("user2", "user2@example.com")
sig3 := factory.CreateSignatureWithUser("user3", "user3@example.com")
@@ -569,14 +555,12 @@ func TestRepository_GetAllSignaturesOrdered_Integration(t *testing.T) {
t.Errorf("Expected 3 signatures, got %d", len(result))
}
// Verify order by ID ASC
expectedUsers := []string{"user1", "user2", "user3"}
for i, sig := range result {
if sig.UserSub != expectedUsers[i] {
t.Errorf("Expected user %s at position %d, got %s", expectedUsers[i], i, sig.UserSub)
}
// Verify IDs are in ascending order
if i > 0 && result[i].ID <= result[i-1].ID {
t.Errorf("IDs not in ascending order: %d should be > %d", result[i].ID, result[i-1].ID)
}

View File

@@ -1,5 +1,6 @@
//go:build integration
// SPDX-License-Identifier: AGPL-3.0-or-later
package database
import (
@@ -14,14 +15,12 @@ import (
_ "github.com/lib/pq"
)
// TestDB holds test database configuration
type TestDB struct {
DB *sql.DB
DSN string
dbName string
}
// SetupTestDB creates a test database connection and runs migrations
func SetupTestDB(t *testing.T) *TestDB {
t.Helper()
@@ -60,7 +59,6 @@ func SetupTestDB(t *testing.T) *TestDB {
return testDB
}
// createSchema creates the signatures table for testing
func (tdb *TestDB) createSchema() error {
schema := `
-- Drop table if exists (for cleanup)
@@ -97,7 +95,6 @@ func (tdb *TestDB) createSchema() error {
return err
}
// Cleanup closes the database connection and cleans up
func (tdb *TestDB) Cleanup() {
if tdb.DB != nil {
// Drop all tables for cleanup
@@ -106,7 +103,6 @@ func (tdb *TestDB) Cleanup() {
}
}
// ClearTable removes all data from the signatures table
func (tdb *TestDB) ClearTable(t *testing.T) {
t.Helper()
_, err := tdb.DB.Exec("TRUNCATE TABLE signatures RESTART IDENTITY")
@@ -115,7 +111,6 @@ func (tdb *TestDB) ClearTable(t *testing.T) {
}
}
// GetTableCount returns the number of rows in signatures table
func (tdb *TestDB) GetTableCount(t *testing.T) int {
t.Helper()
var count int
@@ -126,10 +121,8 @@ func (tdb *TestDB) GetTableCount(t *testing.T) int {
return count
}
// SignatureFactory creates test signature objects
type SignatureFactory struct{}
// CreateValidSignature creates a valid signature for testing
func (f *SignatureFactory) CreateValidSignature() *models.Signature {
now := time.Now().UTC()
userName := "Test User"
@@ -149,14 +142,12 @@ func (f *SignatureFactory) CreateValidSignature() *models.Signature {
}
}
// CreateSignatureWithDoc creates a signature for a specific document
func (f *SignatureFactory) CreateSignatureWithDoc(docID string) *models.Signature {
sig := f.CreateValidSignature()
sig.DocID = docID
return sig
}
// CreateSignatureWithUser creates a signature for a specific user
func (f *SignatureFactory) CreateSignatureWithUser(userSub, userEmail string) *models.Signature {
sig := f.CreateValidSignature()
sig.UserSub = userSub
@@ -164,7 +155,6 @@ func (f *SignatureFactory) CreateSignatureWithUser(userSub, userEmail string) *m
return sig
}
// CreateSignatureWithDocAndUser creates a signature for specific doc and user
func (f *SignatureFactory) CreateSignatureWithDocAndUser(docID, userSub, userEmail string) *models.Signature {
sig := f.CreateValidSignature()
sig.DocID = docID
@@ -173,14 +163,12 @@ func (f *SignatureFactory) CreateSignatureWithDocAndUser(docID, userSub, userEma
return sig
}
// CreateChainedSignature creates a signature with previous hash for chaining tests
func (f *SignatureFactory) CreateChainedSignature(prevHashB64 string) *models.Signature {
sig := f.CreateValidSignature()
sig.PrevHash = &prevHashB64
return sig
}
// CreateMinimalSignature creates signature with only required fields
func (f *SignatureFactory) CreateMinimalSignature() *models.Signature {
now := time.Now().UTC()
@@ -239,7 +227,6 @@ func AssertSignatureEqual(t *testing.T, expected, actual *models.Signature) {
}
}
// isStringPtrEqual compares two string pointers
func isStringPtrEqual(a, b *string) bool {
if a == nil && b == nil {
return true
@@ -250,7 +237,6 @@ func isStringPtrEqual(a, b *string) bool {
return *a == *b
}
// NewSignatureFactory creates a new signature factory
func NewSignatureFactory() *SignatureFactory {
return &SignatureFactory{}
}

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package admin
import (
@@ -11,7 +12,6 @@ import (
"github.com/btouchard/ackify-ce/internal/infrastructure/database"
)
// AdminHandlers handles admin-specific HTTP requests
type AdminHandlers struct {
adminRepo *database.AdminRepository
userService userService
@@ -19,7 +19,6 @@ type AdminHandlers struct {
baseURL string
}
// NewAdminHandlers creates new admin handlers
func NewAdminHandlers(
adminRepo *database.AdminRepository,
userService userService,
@@ -34,7 +33,6 @@ func NewAdminHandlers(
}
}
// HandleDashboard handles GET /admin - lists documents with signature counts
func (h *AdminHandlers) HandleDashboard(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
@@ -73,7 +71,6 @@ func (h *AdminHandlers) HandleDashboard(w http.ResponseWriter, r *http.Request)
}
}
// HandleDocumentDetails handles GET /admin/docs/{docID} - shows document signataires
func (h *AdminHandlers) HandleDocumentDetails(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
docID := chi.URLParam(r, "docID")
@@ -134,7 +131,6 @@ func (h *AdminHandlers) HandleDocumentDetails(w http.ResponseWriter, r *http.Req
}
}
// HandleChainIntegrityAPI handles GET /admin/api/chain-integrity/{docID} - returns JSON
func (h *AdminHandlers) HandleChainIntegrityAPI(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
docID := chi.URLParam(r, "docID")

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package admin
import (
@@ -12,13 +13,11 @@ type userService interface {
GetUser(r *http.Request) (*models.User, error)
}
// AdminMiddleware provides admin authentication middleware
type AdminMiddleware struct {
userService userService
baseURL string
}
// NewAdminMiddleware creates a new admin middleware
func NewAdminMiddleware(userService userService, baseURL string) *AdminMiddleware {
return &AdminMiddleware{
userService: userService,
@@ -26,7 +25,6 @@ func NewAdminMiddleware(userService userService, baseURL string) *AdminMiddlewar
}
}
// RequireAdmin wraps a handler to require admin authentication
func (m *AdminMiddleware) RequireAdmin(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, err := m.userService.GetUser(r)
@@ -46,7 +44,6 @@ func (m *AdminMiddleware) RequireAdmin(next http.HandlerFunc) http.HandlerFunc {
}
}
// isAdminUser checks if the user is in the admin emails list
func (m *AdminMiddleware) isAdminUser(user *models.User) bool {
adminEmails := os.Getenv("ACKIFY_ADMIN_EMAILS")
if adminEmails == "" {
@@ -66,7 +63,6 @@ func (m *AdminMiddleware) isAdminUser(user *models.User) bool {
return false
}
// IsAdminUser is a public function to check if a user is admin (for templates)
func IsAdminUser(user *models.User) bool {
if user == nil {
return false

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package admin
import (

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handlers
import (
@@ -6,13 +7,11 @@ import (
"strings"
)
// AuthHandlers handles authentication-related HTTP requests
type AuthHandlers struct {
authService authService
baseURL string
authService authService
baseURL string
}
// NewAuthHandlers creates new authentication handlers
func NewAuthHandlers(authService authService, baseURL string) *AuthHandlers {
return &AuthHandlers{
authService: authService,
@@ -20,7 +19,6 @@ func NewAuthHandlers(authService authService, baseURL string) *AuthHandlers {
}
}
// HandleLogin handles login requests
func (h *AuthHandlers) HandleLogin(w http.ResponseWriter, r *http.Request) {
next := r.URL.Query().Get("next")
if next == "" {
@@ -32,13 +30,11 @@ func (h *AuthHandlers) HandleLogin(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, authURL, http.StatusFound)
}
// HandleLogout handles logout requests
func (h *AuthHandlers) HandleLogout(w http.ResponseWriter, r *http.Request) {
h.authService.Logout(w, r)
http.Redirect(w, r, "/", http.StatusFound)
}
// HandleOAuthCallback handles OAuth callback from the configured provider
func (h *AuthHandlers) HandleOAuthCallback(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
state := r.URL.Query().Get("state")

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handlers
import (
@@ -16,19 +17,16 @@ type checkService interface {
CheckUserSignature(ctx context.Context, docID, userIdentifier string) (bool, error)
}
// BadgeHandler handles badge generation
type BadgeHandler struct {
checkService checkService
checkService checkService
}
// NewBadgeHandler creates a new badge handler
func NewBadgeHandler(checkService checkService) *BadgeHandler {
return &BadgeHandler{
checkService: checkService,
}
}
// HandleStatusPNG generates a PNG badge showing signature status
func (h *BadgeHandler) HandleStatusPNG(w http.ResponseWriter, r *http.Request) {
docID, err := validateDocID(r)
if err != nil {
@@ -58,17 +56,15 @@ func (h *BadgeHandler) HandleStatusPNG(w http.ResponseWriter, r *http.Request) {
const badgeSize = 64
// BadgeColors represents the color scheme for badges
type BadgeColors struct {
Background color.RGBA
Icon color.RGBA
Border color.RGBA
Background color.RGBA
Icon color.RGBA
Border color.RGBA
}
// BadgeThemes contains predefined color schemes
var BadgeThemes = struct {
Success BadgeColors
Error BadgeColors
Success BadgeColors
Error BadgeColors
}{
Success: BadgeColors{
Background: color.RGBA{R: 240, G: 253, B: 244, A: 255}, // success-50
@@ -131,7 +127,6 @@ func (h *BadgeHandler) encodeToPNG(img *image.RGBA) []byte {
return buf.Bytes()
}
// drawCheckmark draws a checkmark icon
func (h *BadgeHandler) drawCheckmark(img *image.RGBA, size int, col color.RGBA) {
cx, cy := size/2, size/2
scale := float64(size) / 64.0
@@ -154,7 +149,6 @@ func (h *BadgeHandler) drawCheckmark(img *image.RGBA, size int, col color.RGBA)
cx+points[2][0]-cx, cy+points[2][1]-cy, thickness, col)
}
// drawX draws an X icon
func (h *BadgeHandler) drawX(img *image.RGBA, size int, col color.RGBA) {
cx, cy := size/2, size/2
offset := int(float64(size) * 0.3)
@@ -168,7 +162,7 @@ func (h *BadgeHandler) drawX(img *image.RGBA, size int, col color.RGBA) {
h.drawThickLine(img, cx-offset, cy+offset, cx+offset, cy-offset, thickness, col)
}
// drawThickLine draws a thick line using Bresenham's algorithm
// Rationale Use Bresenham's algorithm for integer-only line drawing (fast, no floats)
func (h *BadgeHandler) drawThickLine(img *image.RGBA, x0, y0, x1, y1, thickness int, col color.RGBA) {
dx := abs(x1 - x0)
dy := abs(y1 - y0)
@@ -210,7 +204,6 @@ func (h *BadgeHandler) drawThickLine(img *image.RGBA, x0, y0, x1, y1, thickness
}
}
// abs returns absolute value
func abs(x int) int {
if x < 0 {
return -x

View File

@@ -1,7 +1,9 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handlers
import (
"context"
"encoding/base64"
"errors"
"html/template"
"net/http"
@@ -14,7 +16,6 @@ import (
"github.com/btouchard/ackify-ce/internal/domain/models"
)
// Fake implementations for testing
type fakeAuthService struct {
shouldFailSetUser bool
@@ -25,6 +26,9 @@ type fakeAuthService struct {
callbackError error
authURL string
logoutCalled bool
verifyStateResult bool
lastVerifyToken string
}
func newFakeAuthService() *fakeAuthService {
@@ -32,6 +36,7 @@ func newFakeAuthService() *fakeAuthService {
authURL: "https://oauth.example.com/auth",
callbackUser: &models.User{Sub: "test-user", Email: "test@example.com", Name: "Test User"},
callbackNextURL: "/",
verifyStateResult: true,
}
}
@@ -47,7 +52,16 @@ func (f *fakeAuthService) Logout(_ http.ResponseWriter, _ *http.Request) {
}
func (f *fakeAuthService) GetAuthURL(nextURL string) string {
return f.authURL + "?next=" + url.QueryEscape(nextURL)
return f.authURL + "?next=" + url.QueryEscape(nextURL)
}
func (f *fakeAuthService) CreateAuthURL(_ http.ResponseWriter, _ *http.Request, nextURL string) string {
return f.GetAuthURL(nextURL)
}
func (f *fakeAuthService) VerifyState(_ http.ResponseWriter, _ *http.Request, token string) bool {
f.lastVerifyToken = token
return f.verifyStateResult
}
func (f *fakeAuthService) HandleCallback(_ context.Context, _, _ string) (*models.User, string, error) {
@@ -175,7 +189,6 @@ func (f *fakeSignatureService) CheckUserSignature(_ context.Context, _, _ string
return f.checkResult, nil
}
// Test helpers
func createTestTemplate() *template.Template {
tmpl := template.New("test")
@@ -267,29 +280,45 @@ func TestAuthHandlers_HandleLogout(t *testing.T) {
}
func TestAuthHandlers_HandleOAuthCallback(t *testing.T) {
tests := []struct {
name string
code string
state string
setupAuth func(*fakeAuthService)
expectedStatus int
expectedRedirect string
}{
{
name: "successful callback",
code: "test-code",
state: "test-state",
setupAuth: func(a *fakeAuthService) {},
expectedStatus: http.StatusFound,
expectedRedirect: "/",
},
{
name: "missing code",
code: "",
state: "test-state",
setupAuth: func(a *fakeAuthService) {},
expectedStatus: http.StatusBadRequest,
},
tests := []struct {
name string
code string
state string
setupAuth func(*fakeAuthService)
expectedStatus int
expectedRedirect string
}{
{
name: "successful callback",
code: "test-code",
state: "test-state",
setupAuth: func(a *fakeAuthService) {},
expectedStatus: http.StatusFound,
expectedRedirect: "/",
},
{
name: "missing state",
code: "test-code",
state: "",
setupAuth: func(a *fakeAuthService) {},
expectedStatus: http.StatusBadRequest,
},
{
name: "invalid state - verify fails",
code: "test-code",
state: "abc123:Lw",
setupAuth: func(a *fakeAuthService) {
a.verifyStateResult = false
},
expectedStatus: http.StatusBadRequest,
},
{
name: "missing code",
code: "",
state: "test-state",
setupAuth: func(a *fakeAuthService) {},
expectedStatus: http.StatusBadRequest,
},
{
name: "callback fails",
code: "test-code",
@@ -345,6 +374,22 @@ func TestAuthHandlers_HandleOAuthCallback(t *testing.T) {
}
}
func TestAuthHandlers_HandleOAuthCallback_VerifyStateToken(t *testing.T) {
authService := newFakeAuthService()
handlers := NewAuthHandlers(authService, "https://example.com")
token := "abc123"
state := token + ":" + base64.RawURLEncoding.EncodeToString([]byte("/"))
req := httptest.NewRequest("GET", "/oauth2/callback?code=ok&state="+url.QueryEscape(state), nil)
w := httptest.NewRecorder()
handlers.HandleOAuthCallback(w, req)
if authService.lastVerifyToken != token {
t.Errorf("expected VerifyState to receive token %q, got %q", token, authService.lastVerifyToken)
}
}
func TestSignatureHandlers_NewSignatureHandlers(t *testing.T) {
signatureService := newFakeSignatureService()
userService := newFakeUserService()
@@ -564,7 +609,6 @@ func TestSignatureHandlers_HandleSignPOST(t *testing.T) {
tmpl := createTestTemplate()
handlers := NewSignatureHandlers(signatureService, userService, tmpl, "https://example.com", "Organisation")
// Create form data
form := url.Values{}
for key, value := range tt.formData {
form.Set(key, value)

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handlers
import (
@@ -12,7 +13,6 @@ import (
"github.com/btouchard/ackify-ce/internal/domain/models"
)
// Badge Handler Tests
func TestBadgeHandler_NewBadgeHandler(t *testing.T) {
checkService := newFakeSignatureService()
@@ -114,7 +114,6 @@ func TestBadgeHandler_HandleStatusPNG(t *testing.T) {
}
}
// Health Handler Tests
func TestHealthHandler_NewHealthHandler(t *testing.T) {
handler := NewHealthHandler()
@@ -149,7 +148,6 @@ func TestHealthHandler_HandleHealth(t *testing.T) {
}
}
// OEmbed Handler Tests
func TestOEmbedHandler_NewOEmbedHandler(t *testing.T) {
service := newFakeSignatureService()
@@ -235,7 +233,6 @@ func TestOEmbedHandler_HandleOEmbed(t *testing.T) {
service := newFakeSignatureService()
tt.setupService(service)
tmpl := createTestTemplate()
// Add embed template for OEmbed tests
template.Must(tmpl.New("embed").Parse(`<div>{{.DocID}} - {{.Count}} signatures</div>`))
handler := NewOEmbedHandler(service, tmpl, "https://example.com", "Test Org")
@@ -303,7 +300,6 @@ func TestOEmbedHandler_HandleEmbedView(t *testing.T) {
service := newFakeSignatureService()
tt.setupService(service)
tmpl := createTestTemplate()
// Add embed template
template.Must(tmpl.New("embed").Parse(`<div>{{.DocID}} - {{.Count}} signatures</div>`))
handler := NewOEmbedHandler(service, tmpl, "https://example.com", "Test Org")
@@ -398,7 +394,6 @@ func TestOEmbedHandler_extractDocIDFromURL(t *testing.T) {
}
}
// Middleware Tests
func TestAuthMiddleware_NewAuthMiddleware(t *testing.T) {
userService := newFakeUserService()
@@ -444,7 +439,6 @@ func TestAuthMiddleware_RequireAuth(t *testing.T) {
tt.setupUser(userService)
middleware := NewAuthMiddleware(userService, "https://example.com")
// Create a test handler that returns 200 OK
testHandler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("OK"))
@@ -491,7 +485,6 @@ func TestSecureHeaders(t *testing.T) {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
// Check security headers
headers := map[string]string{
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
@@ -581,7 +574,6 @@ func TestHandleError(t *testing.T) {
}
}
// Utility function tests
func TestValidateDocID(t *testing.T) {
tests := []struct {

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handlers
import (
@@ -6,21 +7,17 @@ import (
"time"
)
// HealthHandler handles health check requests
type HealthHandler struct{}
// NewHealthHandler creates a new health handler
func NewHealthHandler() *HealthHandler {
return &HealthHandler{}
return &HealthHandler{}
}
// HealthResponse represents a health check response
type HealthResponse struct {
OK bool `json:"ok"`
Time time.Time `json:"time"`
OK bool `json:"ok"`
Time time.Time `json:"time"`
}
// HandleHealth returns the application health status
func (h *HealthHandler) HandleHealth(w http.ResponseWriter, r *http.Request) {
response := HealthResponse{
OK: true,

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handlers
import (

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handlers
import (
@@ -9,13 +10,11 @@ import (
"github.com/btouchard/ackify-ce/pkg/logger"
)
// AuthMiddleware provides authentication middleware
type AuthMiddleware struct {
userService userService
baseURL string
userService userService
baseURL string
}
// NewAuthMiddleware creates a new auth middleware
func NewAuthMiddleware(userService userService, baseURL string) *AuthMiddleware {
return &AuthMiddleware{
userService: userService,
@@ -23,7 +22,6 @@ func NewAuthMiddleware(userService userService, baseURL string) *AuthMiddleware
}
}
// RequireAuth wraps a handler to require authentication
func (m *AuthMiddleware) RequireAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, err := m.userService.GetUser(r)
@@ -37,7 +35,7 @@ func (m *AuthMiddleware) RequireAuth(next http.HandlerFunc) http.HandlerFunc {
}
}
// SecureHeaders middleware adds security headers with default configuration
// SecureHeaders Enforce baseline security headers (CSP, XFO, etc.) to mitigate clickjacking, MIME sniffing, and unsafe embedding by default.
func SecureHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
@@ -52,7 +50,7 @@ func SecureHeaders(next http.Handler) http.Handler {
})
}
// RequestLogger logs basic request info with latency and status code
// RequestLogger Minimal structured logging without PII; record latency and status for ops visibility.
func RequestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sr := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
@@ -78,7 +76,6 @@ func (sr *statusRecorder) WriteHeader(code int) {
sr.ResponseWriter.WriteHeader(code)
}
// ErrorResponse represents an error response
type ErrorResponse struct {
Error string `json:"error"`
Message string `json:"message,omitempty"`

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handlers
import (
@@ -12,7 +13,6 @@ import (
"github.com/btouchard/ackify-ce/internal/domain/models"
)
// OEmbedHandler handles oEmbed requests
type OEmbedHandler struct {
signatureService signatureService
template *template.Template
@@ -20,7 +20,6 @@ type OEmbedHandler struct {
organisation string
}
// NewOEmbedHandler creates a new oEmbed handler
func NewOEmbedHandler(signatureService signatureService, tmpl *template.Template, baseURL, organisation string) *OEmbedHandler {
return &OEmbedHandler{
signatureService: signatureService,
@@ -30,7 +29,6 @@ func NewOEmbedHandler(signatureService signatureService, tmpl *template.Template
}
}
// OEmbedResponse represents the oEmbed JSON response format
type OEmbedResponse struct {
Type string `json:"type"`
Version string `json:"version"`
@@ -45,7 +43,6 @@ type OEmbedResponse struct {
Height int `json:"height,omitempty"`
}
// SignatoryData represents data for rendering signatories
type SignatoryData struct {
DocID string
Signatures []SignatoryInfo
@@ -55,14 +52,12 @@ type SignatoryData struct {
SignURL string
}
// SignatoryInfo represents a signatory's information
type SignatoryInfo struct {
Name string
Email string
SignedAt string
}
// HandleOEmbed handles oEmbed requests for signature lists
func (h *OEmbedHandler) HandleOEmbed(w http.ResponseWriter, r *http.Request) {
targetURL := r.URL.Query().Get("url")
format := r.URL.Query().Get("format")
@@ -142,8 +137,7 @@ func (h *OEmbedHandler) HandleOEmbed(w http.ResponseWriter, r *http.Request) {
}
}
// Create oEmbed response
response := OEmbedResponse{
response := OEmbedResponse{
Type: "rich",
Version: "1.0",
Title: fmt.Sprintf("Signataires du document %s", docID),
@@ -161,7 +155,6 @@ func (h *OEmbedHandler) HandleOEmbed(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(response)
}
// HandleEmbedView handles direct embed view requests
func (h *OEmbedHandler) HandleEmbedView(w http.ResponseWriter, r *http.Request) {
docID := strings.TrimSpace(r.URL.Query().Get("doc"))
if docID == "" {

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handlers
import (
@@ -23,7 +24,6 @@ type signatureService interface {
CheckUserSignature(ctx context.Context, docID, userIdentifier string) (bool, error)
}
// SignatureHandlers handles signature-related HTTP requests
type SignatureHandlers struct {
signatureService signatureService
userService userService
@@ -32,7 +32,6 @@ type SignatureHandlers struct {
organisation string
}
// NewSignatureHandlers creates new signature handlers
func NewSignatureHandlers(signatureService signatureService, userService userService, tmpl *template.Template, baseURL, organisation string) *SignatureHandlers {
return &SignatureHandlers{
signatureService: signatureService,

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handlers
import (

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package crypto
import (

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package crypto
import (
@@ -13,13 +14,11 @@ import (
"github.com/btouchard/ackify-ce/internal/domain/models"
)
// Ed25519Signer handles Ed25519 cryptographic operations
type Ed25519Signer struct {
privateKey ed25519.PrivateKey
publicKey ed25519.PublicKey
privateKey ed25519.PrivateKey
publicKey ed25519.PublicKey
}
// NewEd25519Signer creates a new Ed25519 signer
func NewEd25519Signer() (*Ed25519Signer, error) {
privKey, pubKey, err := loadOrGenerateKeys()
if err != nil {
@@ -32,7 +31,6 @@ func NewEd25519Signer() (*Ed25519Signer, error) {
}, nil
}
// CreateSignature creates a cryptographic signature for a document
func (s *Ed25519Signer) CreateSignature(docID string, user *models.User, timestamp time.Time, nonce string) (string, string, error) {
payload := canonicalPayload(docID, user, timestamp, nonce)
hash := sha256.Sum256(payload)
@@ -41,7 +39,6 @@ func (s *Ed25519Signer) CreateSignature(docID string, user *models.User, timesta
return base64.StdEncoding.EncodeToString(hash[:]), base64.StdEncoding.EncodeToString(signature), nil
}
// GetPublicKey returns the base64 encoded public key
func (s *Ed25519Signer) GetPublicKey() string {
return base64.StdEncoding.EncodeToString(s.publicKey)
}

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package crypto
import (
@@ -16,7 +17,7 @@ import (
func TestEd25519Signer_NewEd25519Signer(t *testing.T) {
t.Run("creates new signer successfully", func(t *testing.T) {
// Clear environment variable to force generation
originalKey := os.Getenv("ACKIFY_ED25519_PRIVATE_KEY")
os.Unsetenv("ACKIFY_ED25519_PRIVATE_KEY")
defer func() {
@@ -29,21 +30,21 @@ func TestEd25519Signer_NewEd25519Signer(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, signer)
// Test that public key is accessible
pubKey := signer.GetPublicKey()
assert.NotEmpty(t, pubKey)
// Test that public key is valid base64
_, err = base64.StdEncoding.DecodeString(pubKey)
assert.NoError(t, err)
})
t.Run("loads signer from environment variable", func(t *testing.T) {
// Generate a test key pair
pubKey, privKey, err := ed25519.GenerateKey(nil)
require.NoError(t, err)
// Set environment variable
b64Key := base64.StdEncoding.EncodeToString(privKey)
os.Setenv("ACKIFY_ED25519_PRIVATE_KEY", b64Key)
defer os.Unsetenv("ACKIFY_ED25519_PRIVATE_KEY")
@@ -52,7 +53,7 @@ func TestEd25519Signer_NewEd25519Signer(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, signer)
// Verify the public key matches
expectedPubKey := base64.StdEncoding.EncodeToString(pubKey)
actualPubKey := signer.GetPublicKey()
assert.Equal(t, expectedPubKey, actualPubKey)
@@ -75,12 +76,12 @@ func TestEd25519Signer_NewEd25519Signer(t *testing.T) {
defer os.Unsetenv("ACKIFY_ED25519_PRIVATE_KEY")
if tc.value == "" || tc.value == " " {
// Empty or whitespace should generate new keys
signer, err := NewEd25519Signer()
require.NoError(t, err)
assert.NotNil(t, signer)
} else {
// Invalid keys should return error
signer, err := NewEd25519Signer()
assert.Error(t, err)
assert.Nil(t, signer)
@@ -92,7 +93,7 @@ func TestEd25519Signer_NewEd25519Signer(t *testing.T) {
}
func TestEd25519Signer_CreateSignature(t *testing.T) {
// Create signer for tests
signer, err := NewEd25519Signer()
require.NoError(t, err)
@@ -108,12 +109,12 @@ func TestEd25519Signer_CreateSignature(t *testing.T) {
assert.NotEmpty(t, hashB64)
assert.NotEmpty(t, sigB64)
// Verify hash is valid base64
hashBytes, err := base64.StdEncoding.DecodeString(hashB64)
require.NoError(t, err)
assert.Len(t, hashBytes, 32) // SHA-256 hash length
// Verify signature is valid base64
sigBytes, err := base64.StdEncoding.DecodeString(sigB64)
require.NoError(t, err)
assert.Len(t, sigBytes, ed25519.SignatureSize) // Ed25519 signature length
@@ -322,7 +323,7 @@ func TestEd25519Signer_PayloadGeneration(t *testing.T) {
hash1, _, err := signer.CreateSignature(docID, user, timestamp, nonce)
require.NoError(t, err)
// Manually create expected payload to verify format
expectedPayload := []byte("doc_id=payload-test\nuser_sub=user-123-alice\nuser_email=alice@example.com\nsigned_at=2024-04-01T12:00:00Z\nnonce=payload-nonce\n")
expectedHash := sha256.Sum256(expectedPayload)
expectedHashB64 := base64.StdEncoding.EncodeToString(expectedHash[:])
@@ -331,7 +332,7 @@ func TestEd25519Signer_PayloadGeneration(t *testing.T) {
})
t.Run("email normalization in payload", func(t *testing.T) {
// Create user with mixed case email
user := &models.User{
Sub: "user-email-test",
Email: "Test.User@EXAMPLE.COM",
@@ -345,7 +346,7 @@ func TestEd25519Signer_PayloadGeneration(t *testing.T) {
hash, _, err := signer.CreateSignature(docID, user, timestamp, nonce)
require.NoError(t, err)
// Create expected payload with normalized (lowercase) email
expectedPayload := []byte("doc_id=email-test\nuser_sub=user-email-test\nuser_email=test.user@example.com\nsigned_at=2024-05-01T10:00:00Z\nnonce=email-nonce\n")
expectedHash := sha256.Sum256(expectedPayload)
expectedHashB64 := base64.StdEncoding.EncodeToString(expectedHash[:])
@@ -358,7 +359,7 @@ func TestEd25519Signer_PayloadGeneration(t *testing.T) {
docID := "time-format-test"
nonce := "time-nonce"
// Test different timezone inputs but same UTC moment
utcTime := time.Date(2024, 6, 1, 15, 30, 45, 123456789, time.UTC)
localTime := utcTime.In(time.Local)
@@ -368,7 +369,7 @@ func TestEd25519Signer_PayloadGeneration(t *testing.T) {
hash2, _, err := signer.CreateSignature(docID, user, localTime, nonce)
require.NoError(t, err)
// Should produce same hash as both represent same UTC moment
assert.Equal(t, hash1, hash2, "Different timezone representations of same moment should produce same hash")
})
}
@@ -397,7 +398,7 @@ func TestEd25519Signer_GetPublicKey(t *testing.T) {
})
t.Run("different signers have different public keys", func(t *testing.T) {
// Clear environment to force generation of different keys
originalKey := os.Getenv("ACKIFY_ED25519_PRIVATE_KEY")
os.Unsetenv("ACKIFY_ED25519_PRIVATE_KEY")
defer func() {

View File

@@ -1,8 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package crypto
import "github.com/btouchard/ackify-ce/internal/domain/models"
// Internal test fixtures to avoid external dependencies
var (
testUserAlice = &models.User{

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package crypto
import (

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package crypto
import (
@@ -19,12 +20,10 @@ func TestGenerateNonce(t *testing.T) {
nonce, err := GenerateNonce()
require.NoError(t, err)
// Should be decodable as base64url
decoded, err := base64.RawURLEncoding.DecodeString(nonce)
decoded, err := base64.RawURLEncoding.DecodeString(nonce)
require.NoError(t, err)
// Should be 16 bytes (128 bits) when decoded
assert.Len(t, decoded, 16, "Decoded nonce should be 16 bytes")
assert.Len(t, decoded, 16, "Decoded nonce should be 16 bytes")
})
t.Run("generates unique nonces", func(t *testing.T) {
@@ -35,8 +34,7 @@ func TestGenerateNonce(t *testing.T) {
nonce, err := GenerateNonce()
require.NoError(t, err)
// Check for duplicates
assert.False(t, nonces[nonce], "Nonce %s should be unique", nonce)
assert.False(t, nonces[nonce], "Nonce %s should be unique", nonce)
nonces[nonce] = true
}
@@ -48,11 +46,9 @@ func TestGenerateNonce(t *testing.T) {
nonce, err := GenerateNonce()
require.NoError(t, err)
// Should not be empty
assert.NotEmpty(t, nonce)
assert.NotEmpty(t, nonce)
// Should not contain padding (RawURLEncoding)
assert.NotContains(t, nonce, "=", "Nonce should not contain padding")
assert.NotContains(t, nonce, "=", "Nonce should not contain padding")
// Should only contain valid base64url characters
assert.Regexp(t, `^[A-Za-z0-9_-]+$`, nonce, "Nonce should only contain base64url characters")
@@ -69,15 +65,12 @@ func TestGenerateNonce(t *testing.T) {
lengths = append(lengths, len(nonce))
}
// All nonces should have same length
expectedLength := lengths[0]
expectedLength := lengths[0]
for _, length := range lengths {
assert.Equal(t, expectedLength, length, "All nonces should have consistent length")
}
// For 16 bytes (128 bits), base64url without padding should be 22 characters
// 16 bytes = 128 bits = 128/6 = 21.33 -> 22 characters (rounded up)
assert.Equal(t, 22, expectedLength, "Nonce should be 22 characters long")
assert.Equal(t, 22, expectedLength, "Nonce should be 22 characters long")
})
t.Run("concurrent nonce generation", func(t *testing.T) {
@@ -87,8 +80,7 @@ func TestGenerateNonce(t *testing.T) {
nonceChan := make(chan string, numGoroutines*noncesPerGoroutine)
errorChan := make(chan error, numGoroutines*noncesPerGoroutine)
// Start multiple goroutines generating nonces
for i := 0; i < numGoroutines; i++ {
for i := 0; i < numGoroutines; i++ {
go func() {
for j := 0; j < noncesPerGoroutine; j++ {
nonce, err := GenerateNonce()
@@ -101,8 +93,7 @@ func TestGenerateNonce(t *testing.T) {
}()
}
// Collect results
nonces := make(map[string]bool)
nonces := make(map[string]bool)
for i := 0; i < numGoroutines*noncesPerGoroutine; i++ {
select {
case nonce := <-nonceChan:
@@ -127,8 +118,7 @@ func TestGenerateNonce(t *testing.T) {
decoded, err := base64.RawURLEncoding.DecodeString(nonce)
require.NoError(t, err)
// Count bit frequency
for _, b := range decoded {
for _, b := range decoded {
for bit := 0; bit < 8; bit++ {
if (b>>bit)&1 == 1 {
bitCounts[bit]++
@@ -137,9 +127,8 @@ func TestGenerateNonce(t *testing.T) {
}
}
// Each bit should appear roughly 50% of the time (within reasonable variance)
expectedCount := numNonces * 16 / 2 // 16 bytes per nonce, expect 50% ones
tolerance := expectedCount / 10 // 10% tolerance
expectedCount := numNonces * 16 / 2 // 16 bytes per nonce, expect 50% ones
tolerance := expectedCount / 10 // 10% tolerance
for bit, count := range bitCounts {
assert.InDelta(t, expectedCount, count, float64(tolerance),
@@ -153,19 +142,16 @@ func TestGenerateNonce(t *testing.T) {
nonce, err := GenerateNonce()
require.NoError(t, err)
// Should not contain characters that need URL encoding
assert.NotContains(t, nonce, "+", "Nonce should not contain + (use URL-safe base64)")
assert.NotContains(t, nonce, "/", "Nonce should not contain / (use URL-safe base64)")
assert.NotContains(t, nonce, "=", "Nonce should not contain = (use RawURLEncoding)")
assert.NotContains(t, nonce, "+", "Nonce should not contain + (use URL-safe base64)")
assert.NotContains(t, nonce, "/", "Nonce should not contain / (use URL-safe base64)")
assert.NotContains(t, nonce, "=", "Nonce should not contain = (use RawURLEncoding)")
// Should be safe for use in URLs and forms
assert.Regexp(t, `^[A-Za-z0-9_-]+$`, nonce, "Nonce should only contain URL-safe characters")
assert.Regexp(t, `^[A-Za-z0-9_-]+$`, nonce, "Nonce should only contain URL-safe characters")
}
})
t.Run("nonce anti-replay properties", func(t *testing.T) {
// Generate a large set of nonces to verify anti-replay properties
const numNonces = 10000
const numNonces = 10000
nonces := make([]string, 0, numNonces)
nonceSet := make(map[string]bool)
@@ -173,47 +159,38 @@ func TestGenerateNonce(t *testing.T) {
nonce, err := GenerateNonce()
require.NoError(t, err)
// Verify uniqueness (anti-replay)
assert.False(t, nonceSet[nonce], "Nonce should not repeat (anti-replay)")
assert.False(t, nonceSet[nonce], "Nonce should not repeat (anti-replay)")
nonceSet[nonce] = true
nonces = append(nonces, nonce)
}
// Verify we generated the expected number of unique nonces
assert.Len(t, nonces, numNonces)
assert.Len(t, nonceSet, numNonces)
assert.Len(t, nonces, numNonces)
assert.Len(t, nonceSet, numNonces)
// Verify sufficient entropy - no obvious patterns
// Check that first characters are well distributed
firstChars := make(map[byte]int)
firstChars := make(map[byte]int)
for _, nonce := range nonces {
firstChars[nonce[0]]++
}
// Should have reasonable distribution of first characters
assert.Greater(t, len(firstChars), 10, "First character should have good distribution")
assert.Greater(t, len(firstChars), 10, "First character should have good distribution")
})
t.Run("nonce cryptographic strength", func(t *testing.T) {
// Test that nonces have sufficient randomness
nonce1, err := GenerateNonce()
nonce1, err := GenerateNonce()
require.NoError(t, err)
nonce2, err := GenerateNonce()
require.NoError(t, err)
// Different nonces should be completely different
assert.NotEqual(t, nonce1, nonce2)
assert.NotEqual(t, nonce1, nonce2)
// Decode both nonces
decoded1, err := base64.RawURLEncoding.DecodeString(nonce1)
decoded1, err := base64.RawURLEncoding.DecodeString(nonce1)
require.NoError(t, err)
decoded2, err := base64.RawURLEncoding.DecodeString(nonce2)
require.NoError(t, err)
// Should have no common bytes (extremely unlikely with crypto/rand)
commonBytes := 0
commonBytes := 0
for i := range decoded1 {
if decoded1[i] == decoded2[i] {
commonBytes++

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package logger
import (

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package services
// ServiceInfo contains information about a detected service

View File

@@ -1,3 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package web
import (
@@ -19,7 +20,6 @@ import (
"github.com/btouchard/ackify-ce/pkg/crypto"
)
// Server represents the Ackify web server
type Server struct {
httpServer *http.Server
db *sql.DB
@@ -28,7 +28,6 @@ type Server struct {
baseURL string
}
// NewServer creates a new Ackify server instance
func NewServer(ctx context.Context) (*Server, error) {
cfg, db, tmpl, signer, err := initInfrastructure(ctx)
if err != nil {
@@ -74,12 +73,10 @@ func NewServer(ctx context.Context) (*Server, error) {
}, nil
}
// Start starts the HTTP server
func (s *Server) Start() error {
return s.httpServer.ListenAndServe()
}
// Shutdown gracefully shuts down the server
func (s *Server) Shutdown(ctx context.Context) error {
if err := s.httpServer.Shutdown(ctx); err != nil {
return err
@@ -90,32 +87,26 @@ func (s *Server) Shutdown(ctx context.Context) error {
return nil
}
// GetAddr returns the server address
func (s *Server) GetAddr() string {
return s.httpServer.Addr
}
// Router returns the underlying Chi router for composition
func (s *Server) Router() *chi.Mux {
return s.router
}
// RegisterRoutes allows external packages to register additional routes
func (s *Server) RegisterRoutes(fn func(r *chi.Mux)) {
fn(s.router)
}
// GetTemplates returns the server templates
func (s *Server) GetTemplates() *template.Template {
return s.templates
}
// GetBaseURL returns the server base URL
func (s *Server) GetBaseURL() string {
return s.baseURL
}
// GetDB returns the database connection (read-only access for route wiring)
func (s *Server) GetDB() *sql.DB {
return s.db
}

View File

@@ -1,4 +1,5 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-or-later
# Purpose: Local Docker smoke test with clear PASS/FAIL output
set -uo pipefail