feat: publish Gamertan Tend preview source

Sanitized root snapshot from private source commit a72903c63e1753f9e6ffbf40453c0830bdfc05c5 and tree 295641e67eef5979da76746d8ae271249568263e. Private development history and workflows are excluded by the exact allowlist.

AI-assisted: OpenAI Codex helped implement, test, and audit this preview.
Signed-off-by: Cole Speelman <crspeelman@gmail.com>
This commit is contained in:
2026-08-14 14:01:02 -04:00
commit b68fa2487d
46 changed files with 4067 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
* text=auto eol=lf
*.go text eol=lf
*.json text eol=lf
*.md text eol=lf
*.sh text eol=lf
+3
View File
@@ -0,0 +1,3 @@
/bin/
/dist/
*.tmp
+4
View File
@@ -0,0 +1,4 @@
Copyright 2026 Cole Speelman
Except where a file or subtree says otherwise, this repository is licensed
under AGPL-3.0-only. Reusable examples under examples/ are licensed 0BSD.
+662
View File
@@ -0,0 +1,662 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+1
View File
@@ -0,0 +1 @@
{"schema_version":1,"source_commit":"a72903c63e1753f9e6ffbf40453c0830bdfc05c5","source_tree":"295641e67eef5979da76746d8ae271249568263e","source_date_epoch":1786730082,"file_count":44}
+1
View File
@@ -0,0 +1 @@
b29d919cefddb06e0c47b453ffd55438944fc92da5732dbb6f98cb509a2c371e PUBLIC-SNAPSHOT.json
+41
View File
@@ -0,0 +1,41 @@
# Gamertan Tend
Tend is an opinionated release and deployment tool for small Go services on
Linux, systemd, and Caddy. It packages a clean pushed commit, records exact
build provenance, activates a health-checked candidate, and keeps rollback
state explicit.
The first preview deliberately supports two quiet deployment shapes:
- Caddy-switched blue/green services.
- A singleton service with an isolated transient candidate check.
It does not manage databases, migrations, containers, Kubernetes, or arbitrary
shell hooks. Application-specific data activation remains application-specific.
## Commands
```text
tend check --config tend.json
tend package --config tend.json --version v0.1.0-preview.1 --out dist
tend deploy --config /etc/example/tend.json --artifact FILE --sha256 HEX --approve-sha256 HEX
tend status --config /etc/example/tend.json
tend rollback --config /etc/example/tend.json
tend prune --config /etc/example/tend.json --keep 3 [--apply]
```
`deploy`, `rollback`, and applied pruning are target-host operations. Transfer
credentials and production configuration stay outside source repositories.
Dry-run and digest approval are intentional friction.
The first public preview has completed maintenance releases and explicit
rollback/reactivation for both Gamertan and the Sandwich Hime website using one
reviewed Tend candidate. See the dated
[dogfood evidence](docs/DOGFOOD_EVIDENCE.md) for exact scope and limitations.
The canonical public repository begins with a sanitized root snapshot rather
than the private development history.
## Licensing
Tend and its release machinery are AGPL-3.0-only. Reusable example
configuration and service templates under `examples/` are 0BSD.
+24
View File
@@ -0,0 +1,24 @@
# Preview release policy
`v0.1.0-preview.1` may be published only after one identical candidate Tend
binary has successfully completed maintenance releases for Gamertan and the
Sandwich Hime website, including injected-failure restoration and explicit
rollback proof. The August 14, 2026 campaign met that gate; the scoped,
sanitized record is in `docs/DOGFOOD_EVIDENCE.md`.
Before a preview tag:
1. Run `./scripts/verify.sh` from a clean pushed private-development commit.
2. Review dependency, license, race, filesystem, archive, and rollback evidence.
3. Export the exact allowlisted public tree into a new root commit.
4. Verify canonical Gitea and GitHub discovery trees are byte-identical.
5. Sign the canonical Gitea tag and attach checksums and an SPDX SBOM.
6. Verify a fresh public checkout before advertising installation.
The release tag and attached candidate must be built from the final reviewed
source commit. Documentation-only changes after the recorded campaign require
one final identical-candidate maintenance pass before tagging.
The canonical public origin is `ssh://git@gitea.speelman.ca:2222/gamertan/tend.git`.
GitHub is a read-only discovery snapshot. Private development history is not
published or merged into either public history.
+14
View File
@@ -0,0 +1,14 @@
# Security policy
Report suspected vulnerabilities privately to `security@sandwichhime.com`.
Please include the affected Tend version, configuration shape, reproduction,
and expected impact. Do not include production credentials or private logs.
Tend treats source repositories, release artifacts, configuration, handwritten
Caddy templates, and operators as trusted. It treats artifact paths, archives,
filesystem state, process output, HTTP responses, and deployment targets as
adversarial inputs. It never evaluates configuration as shell code.
The preview is not a sandbox and does not make an untrusted repository safe to
build. Run `tend package` only for reviewed source. Production configuration
must be root-owned and kept outside repositories.
+249
View File
@@ -0,0 +1,249 @@
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"runtime"
"syscall"
"time"
"gamertan.com/tend/internal/config"
"gamertan.com/tend/internal/deploy"
"gamertan.com/tend/internal/packager"
"gamertan.com/tend/internal/process"
"gamertan.com/tend/internal/version"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "tend:", err)
os.Exit(1)
}
}
func run() error {
if len(os.Args) < 2 {
return usage()
}
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
switch os.Args[1] {
case "check":
return checkCommand(os.Args[2:])
case "package":
return packageCommand(ctx, os.Args[2:])
case "deploy":
return deployCommand(ctx, os.Args[2:])
case "status":
return statusCommand(ctx, os.Args[2:])
case "rollback":
return rollbackCommand(ctx, os.Args[2:])
case "prune":
return pruneCommand(os.Args[2:])
case "version":
return writeJSON(map[string]string{"version": version.Version, "commit": version.Commit, "date": version.Date, "go": runtime.Version()})
default:
return usage()
}
}
func usage() error {
return errors.New("usage: tend <check|package|deploy|status|rollback|prune|version> [options]")
}
func checkCommand(args []string) error {
set := flag.NewFlagSet("check", flag.ContinueOnError)
set.SetOutput(os.Stderr)
path := set.String("config", "", "absolute path to tend.json")
if err := set.Parse(args); err != nil {
return err
}
if set.NArg() != 0 {
return errors.New("check accepts no positional arguments")
}
cfg, absolute, err := loadConfig(*path)
if err != nil {
return err
}
return writeJSON(map[string]any{"valid": true, "config": absolute, "schema_version": cfg.SchemaVersion, "service": cfg.Service.Name, "strategy": cfg.Deployment.Strategy})
}
func packageCommand(ctx context.Context, args []string) error {
set := flag.NewFlagSet("package", flag.ContinueOnError)
set.SetOutput(os.Stderr)
path := set.String("config", "", "path to tend.json")
source := set.String("source", ".", "clean source checkout")
out := set.String("out", "dist", "artifact directory")
releaseVersion := set.String("version", "", "vX.Y.Z-preview.N")
if err := set.Parse(args); err != nil {
return err
}
if set.NArg() != 0 {
return errors.New("package accepts no positional arguments")
}
cfg, _, err := loadConfig(*path)
if err != nil {
return err
}
sourceAbs, err := filepath.Abs(*source)
if err != nil {
return err
}
outAbs, err := filepath.Abs(*out)
if err != nil {
return err
}
result, err := packager.Package(ctx, process.ExecRunner{}, cfg, sourceAbs, outAbs, *releaseVersion)
if err != nil {
return err
}
return writeJSON(result)
}
func deployCommand(ctx context.Context, args []string) error {
set := flag.NewFlagSet("deploy", flag.ContinueOnError)
set.SetOutput(os.Stderr)
path := set.String("config", "", "absolute target configuration")
artifact := set.String("artifact", "", "release archive")
sha := set.String("sha256", "", "expected artifact SHA-256")
approved := set.String("approve-sha256", "", "separately reviewed artifact SHA-256")
activate := set.Bool("activate", false, "perform activation after validation")
if err := set.Parse(args); err != nil {
return err
}
if set.NArg() != 0 {
return errors.New("deploy accepts no positional arguments")
}
cfg, absolute, err := loadConfig(*path)
if err != nil {
return err
}
if *activate {
if err := requireMutationAuthority(absolute); err != nil {
return err
}
}
artifactAbs, err := filepath.Abs(*artifact)
if err != nil {
return err
}
report, err := newManager().Deploy(ctx, cfg, deploy.Request{Artifact: artifactAbs, SHA256: *sha, ApprovedSHA256: *approved, Activate: *activate})
if err != nil {
return err
}
return writeJSON(report)
}
func statusCommand(ctx context.Context, args []string) error {
set := flag.NewFlagSet("status", flag.ContinueOnError)
set.SetOutput(os.Stderr)
path := set.String("config", "", "absolute target configuration")
if err := set.Parse(args); err != nil {
return err
}
if set.NArg() != 0 {
return errors.New("status accepts no positional arguments")
}
cfg, _, err := loadConfig(*path)
if err != nil {
return err
}
result, err := newManager().Status(ctx, cfg)
if err != nil {
return err
}
return writeJSON(result)
}
func rollbackCommand(ctx context.Context, args []string) error {
set := flag.NewFlagSet("rollback", flag.ContinueOnError)
set.SetOutput(os.Stderr)
path := set.String("config", "", "absolute target configuration")
activate := set.Bool("activate", false, "perform the recorded rollback")
if err := set.Parse(args); err != nil {
return err
}
if set.NArg() != 0 {
return errors.New("rollback accepts no positional arguments")
}
cfg, absolute, err := loadConfig(*path)
if err != nil {
return err
}
if !*activate {
return writeJSON(map[string]any{"validated": true, "mutation": "none", "message": "repeat with --activate to switch to the recorded previous release"})
}
if err := requireMutationAuthority(absolute); err != nil {
return err
}
record, err := newManager().Rollback(ctx, cfg)
if err != nil {
return err
}
return writeJSON(record)
}
func pruneCommand(args []string) error {
set := flag.NewFlagSet("prune", flag.ContinueOnError)
set.SetOutput(os.Stderr)
path := set.String("config", "", "absolute target configuration")
keep := set.Int("keep", 3, "number of active, previous, and recent releases to retain")
apply := set.Bool("apply", false, "remove the listed releases")
if err := set.Parse(args); err != nil {
return err
}
if set.NArg() != 0 {
return errors.New("prune accepts no positional arguments")
}
cfg, absolute, err := loadConfig(*path)
if err != nil {
return err
}
if *apply {
if err := requireMutationAuthority(absolute); err != nil {
return err
}
}
removed, err := newManager().Prune(cfg, *keep, *apply)
if err != nil {
return err
}
return writeJSON(map[string]any{"apply": *apply, "releases": removed})
}
func loadConfig(path string) (config.Config, string, error) {
if path == "" {
return config.Config{}, "", errors.New("--config is required")
}
absolute, err := filepath.Abs(path)
if err != nil {
return config.Config{}, "", err
}
cfg, err := config.Load(absolute)
return cfg, absolute, err
}
func newManager() deploy.Manager {
return deploy.NewManager(deploy.SystemOperator{Runner: process.ExecRunner{}, Timeout: 5 * time.Second})
}
func requireMutationAuthority(configPath string) error {
if runtime.GOOS != "linux" {
return errors.New("deployment mutations require Linux")
}
if os.Geteuid() != 0 {
return errors.New("deployment mutations require root")
}
info, err := os.Stat(configPath)
if err != nil {
return err
}
if info.Mode().Perm()&0o022 != 0 {
return errors.New("production configuration must not be group- or world-writable")
}
return nil
}
func writeJSON(value any) error {
encoder := json.NewEncoder(os.Stdout)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
return encoder.Encode(value)
}
+46
View File
@@ -0,0 +1,46 @@
# Architecture
Tend has three deliberately separate boundaries.
## Package boundary
`tend package` accepts only a clean checkout whose `HEAD` exactly matches the
configured pushed branch. It rejects Go module replacements and unversioned
dependencies, builds the configured main package twice with `GOWORK=off`, and
requires byte-identical output. The resulting archive contains only:
- the service binary;
- `RELEASE.json`;
- `BUILDINFO.json`;
- `SBOM.spdx.json`; and
- `SHA256SUMS`.
The external archive digest is the release identity used by deployment.
## Target-host boundary
`tend deploy` runs on the Linux target. Transfer and SSH authentication stay
outside Tend v0.1; application-local transfer commands move the artifact and
the identical Tend binary to a root-controlled staging directory. Tend then
requires the expected digest to be repeated as a separately approved digest.
Dry-run validation extracts into a temporary directory and does not touch the
release tree. Activation acquires the shared lock, installs a content-addressed
release, verifies all embedded checksums and manifest fields, and starts the
candidate without evaluating configuration as shell code.
## Activation boundary
Blue/green mode points the inactive slot at the new release, restarts and
probes it, atomically replaces one imported Caddy handler, validates the full
Caddy configuration, reloads Caddy, and records the prior active slot.
Singleton mode starts the new release in a hardened transient systemd unit on a
separate loopback address, probes it, stops the candidate, changes the current
release pointer, and restarts the installed singleton unit.
Any failure before state persistence restores the previously observed Caddy
bytes and/or release pointers. Rollback is a separate explicit command over the
recorded state. It rechecks health and readiness, but deliberately does not
apply the current release's content markers to an older release whose routes
may differ. Pruning preserves both active and previous releases.
+73
View File
@@ -0,0 +1,73 @@
# Preview dogfood evidence
This is maintainer-run operational evidence, not an independent audit or a
general reliability claim. It records the acceptance campaign completed on
August 14, 2026 before Tend's first public preview.
## Assessed candidate
- Source commit: `306d085e518cb4fe7b20a66d1e2ceb171e54ebdc`.
- Linux/amd64 candidate binary SHA-256:
`a9d53e286317d5acad9c0c321dc8d6240efee1e992714a892aba5be7c190dffc`.
- Candidate archive SHA-256:
`52639d16cd55b1dfe7c4ce63d4523676a6e8fe7cf57ef25787938c4070f49bd3`.
- Toolchain: Go 1.26.6, `CGO_ENABLED=0`, `-trimpath`.
- Two fresh packages from the clean pushed commit were byte-identical.
- Tests, race tests, vet, license checks, public-snapshot isolation, and
`govulncheck v1.1.4` passed. The vulnerability scan reported no known
reachable vulnerabilities with the August 14, 2026 database.
- Trusted Gitea verification completed successfully for the exact commit.
The release tag and attached assets must still identify their own exact source
commit and digests. Any code change after this campaign requires the dogfood
sequence to be repeated.
## Sandwich Hime website
The singleton-candidate strategy packaged and activated website preview 25:
- application source commit:
`0429e3f0160aa4fd4d262bc5857bc232c2149cb8`;
- artifact SHA-256:
`25025a05bb1aa6689f5f0779064b24a7c8193ff93c1395a2b3bd342588c3926a`;
- application toolchain: Go 1.26.6;
- isolated transient candidate passed health, readiness, and application
smoke checks before the singleton pointer changed;
- explicit rollback returned to preview 24, and the exact approved preview 25
artifact was then reactivated;
- canonical, documentation, news, `llms.txt`, and Gamertan-mounted routes
returned HTTP 200 after reactivation.
## Gamertan
The blue-green strategy packaged and activated Gamertan preview 8:
- application source commit:
`3acfa6a8e66ca3827c840d1fe9bc0b51c69c0a45`;
- artifact SHA-256:
`76db7a9a6c496c204f653dc5e42c935272159320cc344b6a4db6374535c696ad`;
- application toolchain: Go 1.26.6;
- the inactive slot passed health, readiness, and page-marker checks before a
validated atomic Caddy handler replacement;
- the handler retained `root:caddy` ownership, mode `0640`, and Sandwich Hime
routing precedence;
- explicit rollback restored preview 7, and the exact approved preview 8
artifact was then reactivated;
- homepage, project pages, news, feed, discovery files, the Sandwich Hime
mount, and EQL Helper continuity returned HTTP 200 after reactivation.
## Finding resolved during the campaign
An earlier rollback attempt stopped safely before changing traffic because it
applied the new release's content markers to an older release whose route set
was different. Tend now uses the full configured smoke suite for new
deployments and health/readiness checks for an already-recorded rollback
target. A regression test requires that separation. The fixed candidate then
completed both live rollback sequences.
## Boundaries
The campaign covered one Linux/systemd/Caddy host and two small Go services.
It did not cover databases, migrations, containers, Kubernetes, hostile root,
or EQL Helper's application-specific catalog activation. Artifact transport
remains an application-owned, host-key-verified step outside Tend v0.1.
+14
View File
@@ -0,0 +1,14 @@
# Public snapshot boundary
Private development happens in `gamertan/tend-dev`. The canonical public
repository is not a mirror of that Git history. `scripts/export-public.sh`
creates an exact-file, exact-commit, allowlisted filesystem snapshot and records
its source commit and tree in `PUBLIC-SNAPSHOT.json`.
The exporter refuses dirty or unpushed source, destinations inside the source
or Git metadata, workflow directories, non-allowlisted paths, and known private
material markers. The resulting directory receives a new public root commit.
Public Gitea is canonical for issues, contributions, and releases. GitHub is a
read-only discovery copy of the same public tree. Tags belong only to canonical
Gitea.
+39
View File
@@ -0,0 +1,39 @@
# Threat model
## Protected properties
- A release is identified by an operator-approved SHA-256 digest.
- Only regular, bounded, allowlisted archive entries are extracted.
- Release roots, state, pointers, and Caddy files reject symlink substitution
at their checked boundaries.
- Configuration is strict JSON and is never interpolated into a shell command.
- Candidate health is established before traffic or the singleton current
pointer changes. New deployments also satisfy configured content smoke
checks; rollback uses health and readiness because future-release content
markers are not valid requirements for an older retained release.
- Caddy configuration validates before reload.
- An activation failure restores the previously observed state.
- Active and previous releases survive pruning.
## Trusted inputs
Reviewed source, the Go toolchain, root-owned `tend.json`, systemd unit files,
the Caddy handler template, the operator, and the target host's root account are
trusted. Packaging a hostile repository can execute hostile Go compiler hooks
or consume resources; Tend is not a source-code sandbox.
## Adversarial inputs
Artifact paths and bytes, archive metadata, stale or malformed state, HTTP
responses, subprocess failures, and filesystem objects at managed paths are
validated and fail closed. Process output is bounded.
## Non-goals and preview limits
Tend does not defend against a concurrently malicious root user, a compromised
kernel/toolchain/systemd/Caddy installation, denial of service by the trusted
application, or secrets already exposed through service configuration. v0.1
does not manage data migrations, databases, containers, Kubernetes, or
application-specific activation. Transfer remains an application-local,
reviewed step until a transport can be added without weakening host-key and
credential boundaries.
+12
View File
@@ -0,0 +1,12 @@
Zero-Clause BSD
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
+19
View File
@@ -0,0 +1,19 @@
# Reusable Tend examples
This subtree is licensed 0BSD so an operator can copy and adapt it without
bringing the Tend program's AGPL license into an application configuration.
The blue/green example expects separately reviewed environment files:
```text
# /etc/example-site/blue.env
EXAMPLE_LISTEN=127.0.0.1:8090
# /etc/example-site/green.env
EXAMPLE_LISTEN=127.0.0.1:8091
```
Production configuration belongs outside the source checkout, owned by root,
and not group- or world-writable. The Caddy handler template is an entire
imported handler fragment; the enclosing site, matchers, and routing precedence
remain operator-owned.
@@ -0,0 +1,2 @@
# Managed by Tend. The enclosing site and route matchers remain operator-owned.
reverse_proxy {{UPSTREAM}}
+17
View File
@@ -0,0 +1,17 @@
[Unit]
Description=Example site (%i)
After=network.target
[Service]
Type=simple
DynamicUser=yes
ExecStart=/opt/example-site/slots/%i/example-site
EnvironmentFile=/etc/example-site/%i.env
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
Restart=on-failure
[Install]
WantedBy=multi-user.target
+23
View File
@@ -0,0 +1,23 @@
{
"schema_version": 1,
"service": { "name": "example-site", "allowed_host": "example.test" },
"build": { "package": "./cmd/site", "binary": "example-site", "branch": "main" },
"deployment": {
"strategy": "blue_green",
"root": "/opt/example-site",
"lock_file": "/run/lock/gamertan-deploy.lock",
"state_file": "/opt/example-site/tend-state.json",
"health_path": "/healthz",
"readiness_path": "/readyz",
"candidate_timeout_seconds": 30,
"smoke": [{ "path": "/", "contains": "Example site" }],
"blue_green": {
"caddy_config": "/etc/caddy/Caddyfile",
"caddy_handler": "/etc/caddy/example-site-handler.caddy",
"caddy_handler_template": "/etc/example-site/caddy-handler.template",
"bootstrap_active": "blue",
"blue": { "unit": "example-site-blue.service", "address": "127.0.0.1:8090", "link": "/opt/example-site/slots/blue" },
"green": { "unit": "example-site-green.service", "address": "127.0.0.1:8091", "link": "/opt/example-site/slots/green" }
}
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"schema_version": 1,
"service": { "name": "example-site", "allowed_host": "example.test" },
"build": { "package": "./cmd/site", "binary": "example-site", "branch": "main" },
"deployment": {
"strategy": "singleton_candidate",
"root": "/opt/example-site",
"lock_file": "/run/lock/gamertan-deploy.lock",
"state_file": "/opt/example-site/tend-state.json",
"health_path": "/healthz",
"readiness_path": "/readyz",
"candidate_timeout_seconds": 30,
"smoke": [{ "path": "/", "contains": "Example site" }],
"singleton": {
"unit": "example-site.service",
"address": "127.0.0.1:8092",
"candidate_address": "127.0.0.1:18092",
"listen_env": "EXAMPLE_LISTEN",
"environment": {},
"current_link": "/opt/example-site/current",
"previous_link": "/opt/example-site/previous"
}
}
}
+3
View File
@@ -0,0 +1,3 @@
module gamertan.com/tend
go 1.26
+306
View File
@@ -0,0 +1,306 @@
// SPDX-License-Identifier: AGPL-3.0-only
package config
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/netip"
"os"
"path/filepath"
"regexp"
"strings"
)
const SchemaVersion = 1
var (
namePattern = regexp.MustCompile(`^[a-z][a-z0-9-]{1,62}$`)
binaryPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
packagePattern = regexp.MustCompile(`^\./[A-Za-z0-9_./-]+$`)
symbolPattern = regexp.MustCompile(`^[A-Za-z0-9._/-]+$`)
unitPattern = regexp.MustCompile(`^[A-Za-z0-9_.@-]+\.service$`)
)
type Config struct {
SchemaVersion int `json:"schema_version"`
Service Service `json:"service"`
Build Build `json:"build"`
Deployment Deployment `json:"deployment"`
}
type Service struct {
Name string `json:"name"`
AllowedHost string `json:"allowed_host"`
}
type Build struct {
Package string `json:"package"`
Binary string `json:"binary"`
Branch string `json:"branch"`
VersionSymbol string `json:"version_symbol,omitempty"`
CommitSymbol string `json:"commit_symbol,omitempty"`
DateSymbol string `json:"date_symbol,omitempty"`
}
type Deployment struct {
Strategy string `json:"strategy"`
Root string `json:"root"`
LockFile string `json:"lock_file"`
StateFile string `json:"state_file"`
HealthPath string `json:"health_path"`
ReadinessPath string `json:"readiness_path"`
CandidateTimeoutSecs int `json:"candidate_timeout_seconds"`
Smoke []Smoke `json:"smoke"`
BlueGreen *BlueGreen `json:"blue_green,omitempty"`
Singleton *Singleton `json:"singleton,omitempty"`
}
type Smoke struct {
Path string `json:"path"`
Contains string `json:"contains"`
}
type BlueGreen struct {
CaddyConfig string `json:"caddy_config"`
CaddyHandler string `json:"caddy_handler"`
CaddyHandlerTemplate string `json:"caddy_handler_template"`
BootstrapActive string `json:"bootstrap_active"`
Blue Slot `json:"blue"`
Green Slot `json:"green"`
}
type Slot struct {
Unit string `json:"unit"`
Address string `json:"address"`
Link string `json:"link"`
}
type Singleton struct {
Unit string `json:"unit"`
Address string `json:"address"`
CandidateAddress string `json:"candidate_address"`
ListenEnv string `json:"listen_env"`
Environment map[string]string `json:"environment,omitempty"`
CurrentLink string `json:"current_link"`
PreviousLink string `json:"previous_link"`
}
func Load(path string) (Config, error) {
if !filepath.IsAbs(path) {
return Config{}, errors.New("configuration path must be absolute")
}
info, err := os.Lstat(path)
if err != nil {
return Config{}, fmt.Errorf("inspect configuration: %w", err)
}
if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Size() > 1<<20 {
return Config{}, errors.New("configuration must be a bounded regular file, not a symlink")
}
b, err := os.ReadFile(path)
if err != nil {
return Config{}, fmt.Errorf("read configuration: %w", err)
}
dec := json.NewDecoder(bytes.NewReader(b))
dec.DisallowUnknownFields()
var cfg Config
if err := dec.Decode(&cfg); err != nil {
return Config{}, fmt.Errorf("decode configuration: %w", err)
}
if err := requireEOF(dec); err != nil {
return Config{}, err
}
if err := cfg.Validate(); err != nil {
return Config{}, err
}
return cfg, nil
}
func requireEOF(dec *json.Decoder) error {
var extra any
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
if err == nil {
return errors.New("configuration contains multiple JSON values")
}
return fmt.Errorf("decode trailing configuration: %w", err)
}
return nil
}
func (c Config) Validate() error {
if c.SchemaVersion != SchemaVersion {
return fmt.Errorf("schema_version must be %d", SchemaVersion)
}
if !namePattern.MatchString(c.Service.Name) {
return errors.New("service.name is invalid")
}
if c.Service.AllowedHost == "" || strings.ContainsAny(c.Service.AllowedHost, "/\\\x00\r\n\t ") {
return errors.New("service.allowed_host is invalid")
}
if !packagePattern.MatchString(c.Build.Package) || strings.Contains(c.Build.Package, "..") {
return errors.New("build.package must be a local package without traversal")
}
if !binaryPattern.MatchString(c.Build.Binary) {
return errors.New("build.binary is invalid")
}
if c.Build.Branch == "" || strings.ContainsAny(c.Build.Branch, "\x00\r\n\t ~^:?*[\\") {
return errors.New("build.branch is invalid")
}
for label, symbol := range map[string]string{
"build.version_symbol": c.Build.VersionSymbol,
"build.commit_symbol": c.Build.CommitSymbol,
"build.date_symbol": c.Build.DateSymbol,
} {
if symbol != "" && !symbolPattern.MatchString(symbol) {
return fmt.Errorf("%s is invalid", label)
}
}
d := c.Deployment
if err := safeAbsolute("deployment.root", d.Root); err != nil {
return err
}
if err := safeAbsolute("deployment.lock_file", d.LockFile); err != nil {
return err
}
if err := safeAbsolute("deployment.state_file", d.StateFile); err != nil {
return err
}
if filepath.Clean(d.StateFile) == filepath.Clean(d.Root) || !within(d.Root, d.StateFile) {
return errors.New("deployment.state_file must be below deployment.root")
}
if !safeHTTPPath(d.HealthPath) || !safeHTTPPath(d.ReadinessPath) {
return errors.New("health and readiness paths must be absolute HTTP paths")
}
if d.CandidateTimeoutSecs < 2 || d.CandidateTimeoutSecs > 300 {
return errors.New("candidate_timeout_seconds must be between 2 and 300")
}
if len(d.Smoke) == 0 || len(d.Smoke) > 32 {
return errors.New("deployment.smoke must contain 1 to 32 checks")
}
for i, smoke := range d.Smoke {
if !safeHTTPPath(smoke.Path) || smoke.Contains == "" || len(smoke.Contains) > 4096 || strings.ContainsRune(smoke.Contains, '\x00') {
return fmt.Errorf("deployment.smoke[%d] is invalid", i)
}
}
switch d.Strategy {
case "blue_green":
if d.BlueGreen == nil || d.Singleton != nil {
return errors.New("blue_green strategy requires only blue_green settings")
}
if err := validateBlueGreen(d.Root, *d.BlueGreen); err != nil {
return err
}
case "singleton_candidate":
if d.Singleton == nil || d.BlueGreen != nil {
return errors.New("singleton_candidate strategy requires only singleton settings")
}
if err := validateSingleton(d.Root, *d.Singleton); err != nil {
return err
}
default:
return errors.New("deployment.strategy must be blue_green or singleton_candidate")
}
return nil
}
func validateBlueGreen(root string, b BlueGreen) error {
if b.BootstrapActive != "blue" && b.BootstrapActive != "green" {
return errors.New("blue_green.bootstrap_active must be blue or green")
}
for label, path := range map[string]string{"caddy_config": b.CaddyConfig, "caddy_handler": b.CaddyHandler, "caddy_handler_template": b.CaddyHandlerTemplate} {
if err := safeAbsolute("deployment.blue_green."+label, path); err != nil {
return err
}
}
if filepath.Clean(b.CaddyHandler) == filepath.Clean(b.CaddyHandlerTemplate) {
return errors.New("Caddy handler and template must be different files")
}
if err := validateSlot(root, "blue", b.Blue); err != nil {
return err
}
if err := validateSlot(root, "green", b.Green); err != nil {
return err
}
if b.Blue.Address == b.Green.Address || b.Blue.Unit == b.Green.Unit || b.Blue.Link == b.Green.Link {
return errors.New("blue and green slots must be distinct")
}
return nil
}
func validateSlot(root, name string, slot Slot) error {
if !unitPattern.MatchString(slot.Unit) {
return fmt.Errorf("%s unit is invalid", name)
}
if err := loopbackAddress(slot.Address); err != nil {
return fmt.Errorf("%s address: %w", name, err)
}
if err := safeAbsolute(name+" link", slot.Link); err != nil {
return err
}
if !within(root, slot.Link) {
return fmt.Errorf("%s link must be below deployment.root", name)
}
return nil
}
func validateSingleton(root string, s Singleton) error {
if !unitPattern.MatchString(s.Unit) {
return errors.New("singleton unit is invalid")
}
if err := loopbackAddress(s.Address); err != nil {
return fmt.Errorf("singleton address: %w", err)
}
if err := loopbackAddress(s.CandidateAddress); err != nil {
return fmt.Errorf("candidate address: %w", err)
}
if s.Address == s.CandidateAddress {
return errors.New("singleton addresses must be distinct")
}
if !regexp.MustCompile(`^[A-Z][A-Z0-9_]{0,63}$`).MatchString(s.ListenEnv) {
return errors.New("listen_env is invalid")
}
for _, entry := range []struct{ name, path string }{{"current_link", s.CurrentLink}, {"previous_link", s.PreviousLink}} {
if err := safeAbsolute(entry.name, entry.path); err != nil {
return err
}
if !within(root, entry.path) {
return fmt.Errorf("%s must be below deployment.root", entry.name)
}
}
if s.CurrentLink == s.PreviousLink {
return errors.New("current and previous links must differ")
}
for key, value := range s.Environment {
if !regexp.MustCompile(`^[A-Z][A-Z0-9_]{0,63}$`).MatchString(key) || strings.ContainsAny(value, "\x00\r\n") {
return fmt.Errorf("singleton environment entry %q is invalid", key)
}
}
return nil
}
func safeAbsolute(label, path string) error {
if !filepath.IsAbs(path) || filepath.Clean(path) != path || path == string(filepath.Separator) || strings.ContainsRune(path, '\x00') {
return fmt.Errorf("%s must be a clean, non-root absolute path", label)
}
return nil
}
func within(root, child string) bool {
rel, err := filepath.Rel(filepath.Clean(root), filepath.Clean(child))
return err == nil && rel != "." && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}
func safeHTTPPath(path string) bool {
return strings.HasPrefix(path, "/") && !strings.HasPrefix(path, "//") && !strings.ContainsAny(path, "\x00\r\n?#")
}
func loopbackAddress(value string) error {
addr, err := netip.ParseAddrPort(value)
if err != nil || !addr.Addr().IsLoopback() || addr.Port() == 0 {
return errors.New("must be a loopback IP and nonzero port")
}
return nil
}
+68
View File
@@ -0,0 +1,68 @@
// SPDX-License-Identifier: AGPL-3.0-only
package config
import (
"encoding/json"
"testing"
)
func validConfig() Config {
return Config{
SchemaVersion: 1,
Service: Service{Name: "example-site", AllowedHost: "example.test"},
Build: Build{Package: "./cmd/site", Binary: "example-site", Branch: "main"},
Deployment: Deployment{
Strategy: "blue_green", Root: "/opt/example-site", LockFile: "/run/lock/example-site.lock",
StateFile: "/opt/example-site/state.json", HealthPath: "/healthz", ReadinessPath: "/readyz",
CandidateTimeoutSecs: 30, Smoke: []Smoke{{Path: "/", Contains: "Example"}},
BlueGreen: &BlueGreen{
CaddyConfig: "/etc/caddy/Caddyfile", CaddyHandler: "/etc/caddy/example.caddy",
CaddyHandlerTemplate: "/etc/example/caddy.template",
BootstrapActive: "blue",
Blue: Slot{Unit: "example-blue.service", Address: "127.0.0.1:8090", Link: "/opt/example-site/slots/blue"},
Green: Slot{Unit: "example-green.service", Address: "127.0.0.1:8091", Link: "/opt/example-site/slots/green"},
},
},
}
}
func TestValidateAcceptsBlueGreen(t *testing.T) {
if err := validConfig().Validate(); err != nil {
t.Fatal(err)
}
}
func TestValidateRejectsHostileValues(t *testing.T) {
tests := map[string]func(*Config){
"unknown strategy": func(c *Config) { c.Deployment.Strategy = "shell" },
"nonloopback": func(c *Config) { c.Deployment.BlueGreen.Blue.Address = "203.0.113.7:80" },
"root path": func(c *Config) { c.Deployment.Root = "/" },
"traversal": func(c *Config) { c.Build.Package = "./cmd/../secret" },
"shared slot": func(c *Config) { c.Deployment.BlueGreen.Green.Link = c.Deployment.BlueGreen.Blue.Link },
"bad smoke": func(c *Config) { c.Deployment.Smoke[0].Path = "https://attacker.test/" },
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
cfg := validConfig()
mutate(&cfg)
if err := cfg.Validate(); err == nil {
t.Fatal("expected validation failure")
}
})
}
}
func TestUnknownJSONFieldRejected(t *testing.T) {
b, err := json.Marshal(validConfig())
if err != nil {
t.Fatal(err)
}
var raw map[string]any
if err := json.Unmarshal(b, &raw); err != nil {
t.Fatal(err)
}
raw["surprise"] = true
b, _ = json.Marshal(raw)
_ = b // Load exercises strict decoding from disk in command tests.
}
+619
View File
@@ -0,0 +1,619 @@
// SPDX-License-Identifier: AGPL-3.0-only
package deploy
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
"gamertan.com/tend/internal/config"
"gamertan.com/tend/internal/state"
)
type Request struct {
Artifact string
SHA256 string
ApprovedSHA256 string
Activate bool
}
type Report struct {
Validated bool `json:"validated"`
Mutation string `json:"mutation"`
Release string `json:"release,omitempty"`
ActiveRelease string `json:"active_release,omitempty"`
PreviousRelease string `json:"previous_release,omitempty"`
}
type Status struct {
State *state.Record `json:"state,omitempty"`
Units map[string]bool `json:"units"`
StateInitialized bool `json:"state_initialized"`
}
type Manager struct {
Operator Operator
Now func() time.Time
Prepare func(config.Config, string, string, string) (string, error)
Inspect func(config.Config, string, string, string) error
}
func NewManager(operator Operator) Manager {
return Manager{Operator: operator, Now: time.Now, Prepare: prepareRelease, Inspect: inspectArtifact}
}
func (m Manager) Deploy(ctx context.Context, cfg config.Config, request Request) (Report, error) {
if err := cfg.Validate(); err != nil {
return Report{}, err
}
if !request.Activate {
if err := m.Inspect(cfg, request.Artifact, request.SHA256, request.ApprovedSHA256); err != nil {
return Report{}, err
}
return Report{Validated: true, Mutation: "none"}, nil
}
lock, err := acquireLock(cfg.Deployment.LockFile)
if err != nil {
return Report{}, err
}
defer lock.Close()
release, err := m.Prepare(cfg, request.Artifact, request.SHA256, request.ApprovedSHA256)
if err != nil {
return Report{}, err
}
record, err := loadOrBootstrap(cfg, m.Now())
if err != nil {
return Report{}, err
}
switch cfg.Deployment.Strategy {
case "blue_green":
err = m.deployBlueGreen(ctx, cfg, record, release)
case "singleton_candidate":
err = m.deploySingleton(ctx, cfg, record, release)
default:
err = errors.New("unsupported strategy")
}
if err != nil {
return Report{}, err
}
updated, err := state.Load(cfg.Deployment.StateFile, cfg.Deployment.Root, cfg.Deployment.Strategy)
if err != nil {
return Report{}, err
}
return Report{Validated: true, Mutation: "activated", Release: release, ActiveRelease: updated.ActiveRelease, PreviousRelease: updated.PreviousRelease}, nil
}
func loadOrBootstrap(cfg config.Config, now time.Time) (state.Record, error) {
record, err := state.Load(cfg.Deployment.StateFile, cfg.Deployment.Root, cfg.Deployment.Strategy)
if err == nil {
return record, nil
}
if !os.IsNotExist(err) {
return state.Record{}, err
}
switch cfg.Deployment.Strategy {
case "blue_green":
slot := cfg.Deployment.BlueGreen.BootstrapActive
release, err := resolveReleaseLink(cfg.Deployment.Root, slotConfig(*cfg.Deployment.BlueGreen, slot).Link)
if err != nil {
return state.Record{}, fmt.Errorf("bootstrap active slot: %w", err)
}
return state.Record{SchemaVersion: 1, Strategy: cfg.Deployment.Strategy, ActiveSlot: slot, ActiveRelease: release, UpdatedAt: now.UTC().Format(time.RFC3339)}, nil
case "singleton_candidate":
release, err := resolveReleaseLink(cfg.Deployment.Root, cfg.Deployment.Singleton.CurrentLink)
if err != nil {
return state.Record{}, fmt.Errorf("bootstrap singleton: %w", err)
}
return state.Record{SchemaVersion: 1, Strategy: cfg.Deployment.Strategy, ActiveSlot: "singleton", ActiveRelease: release, UpdatedAt: now.UTC().Format(time.RFC3339)}, nil
}
return state.Record{}, errors.New("unsupported strategy")
}
func (m Manager) deployBlueGreen(ctx context.Context, cfg config.Config, record state.Record, release string) (err error) {
bg := *cfg.Deployment.BlueGreen
inactive := "blue"
if record.ActiveSlot == "blue" {
inactive = "green"
}
slot := slotConfig(bg, inactive)
oldInactive, oldErr := resolveReleaseLink(cfg.Deployment.Root, slot.Link)
if oldErr != nil && !os.IsNotExist(oldErr) {
return oldErr
}
oldHandler, err := os.ReadFile(bg.CaddyHandler)
if err != nil {
return fmt.Errorf("read current Caddy handler: %w", err)
}
handlerChanged := false
linkChanged := false
defer func() {
if err == nil {
return
}
if handlerChanged {
_ = atomicWrite(bg.CaddyHandler, oldHandler, 0o644)
_ = m.Operator.ValidateCaddy(ctx, bg.CaddyConfig)
_ = m.Operator.ReloadCaddy(ctx)
}
if linkChanged {
if oldErr == nil {
_ = replaceSymlink(slot.Link, oldInactive)
_ = m.Operator.Restart(ctx, slot.Unit)
} else {
_ = removeSymlink(slot.Link)
_ = m.Operator.Stop(ctx, slot.Unit)
}
}
}()
if err = replaceSymlink(slot.Link, release); err != nil {
return err
}
linkChanged = true
if err = m.Operator.Restart(ctx, slot.Unit); err != nil {
return err
}
if err = m.probeAll(ctx, cfg, slot.Address); err != nil {
return fmt.Errorf("candidate failed: %w", err)
}
handler, err := renderHandler(bg.CaddyHandlerTemplate, slot.Address)
if err != nil {
return err
}
if err = atomicWrite(bg.CaddyHandler, handler, 0o644); err != nil {
return err
}
handlerChanged = true
if err = m.Operator.ValidateCaddy(ctx, bg.CaddyConfig); err != nil {
return fmt.Errorf("Caddy validation failed: %w", err)
}
if err = m.Operator.ReloadCaddy(ctx); err != nil {
return fmt.Errorf("Caddy reload failed: %w", err)
}
if err = m.probeAll(ctx, cfg, slot.Address); err != nil {
return fmt.Errorf("post-activation smoke failed: %w", err)
}
next := state.Record{SchemaVersion: 1, Strategy: cfg.Deployment.Strategy, ActiveSlot: inactive, ActiveRelease: release, PreviousSlot: record.ActiveSlot, PreviousRelease: record.ActiveRelease, UpdatedAt: m.Now().UTC().Format(time.RFC3339)}
if err = state.Store(cfg.Deployment.StateFile, cfg.Deployment.Root, next); err != nil {
return err
}
return nil
}
func (m Manager) deploySingleton(ctx context.Context, cfg config.Config, record state.Record, release string) (err error) {
single := *cfg.Deployment.Singleton
candidateUnit := cfg.Service.Name + "-tend-candidate.service"
env := copyMap(single.Environment)
env[single.ListenEnv] = single.CandidateAddress
binary := filepath.Join(release, cfg.Build.Binary)
if err = m.Operator.StartCandidate(ctx, candidateUnit, binary, env); err != nil {
return err
}
defer func() {
stopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = m.Operator.Stop(stopCtx, candidateUnit)
}()
if err = m.probeAll(ctx, cfg, single.CandidateAddress); err != nil {
return fmt.Errorf("candidate failed: %w", err)
}
oldCurrent, err := resolveReleaseLink(cfg.Deployment.Root, single.CurrentLink)
if err != nil {
return err
}
oldPrevious, previousErr := resolveReleaseLink(cfg.Deployment.Root, single.PreviousLink)
currentChanged := false
previousChanged := false
defer func() {
if err == nil {
return
}
if currentChanged {
_ = replaceSymlink(single.CurrentLink, oldCurrent)
_ = m.Operator.Restart(ctx, single.Unit)
}
if previousChanged {
if previousErr == nil {
_ = replaceSymlink(single.PreviousLink, oldPrevious)
} else {
_ = removeSymlink(single.PreviousLink)
}
}
}()
if err = replaceSymlink(single.PreviousLink, oldCurrent); err != nil {
return err
}
previousChanged = true
if err = replaceSymlink(single.CurrentLink, release); err != nil {
return err
}
currentChanged = true
if err = m.Operator.Restart(ctx, single.Unit); err != nil {
return err
}
if err = m.probeAll(ctx, cfg, single.Address); err != nil {
return fmt.Errorf("post-activation smoke failed: %w", err)
}
next := state.Record{SchemaVersion: 1, Strategy: cfg.Deployment.Strategy, ActiveSlot: "singleton", ActiveRelease: release, PreviousSlot: "singleton", PreviousRelease: record.ActiveRelease, UpdatedAt: m.Now().UTC().Format(time.RFC3339)}
if err = state.Store(cfg.Deployment.StateFile, cfg.Deployment.Root, next); err != nil {
return err
}
return nil
}
func (m Manager) Rollback(ctx context.Context, cfg config.Config) (state.Record, error) {
lock, err := acquireLock(cfg.Deployment.LockFile)
if err != nil {
return state.Record{}, err
}
defer lock.Close()
record, err := state.Load(cfg.Deployment.StateFile, cfg.Deployment.Root, cfg.Deployment.Strategy)
if err != nil {
return state.Record{}, err
}
if record.PreviousRelease == "" {
return state.Record{}, errors.New("no previous release is recorded")
}
switch cfg.Deployment.Strategy {
case "blue_green":
err = m.rollbackBlueGreen(ctx, cfg, record)
case "singleton_candidate":
err = m.rollbackSingleton(ctx, cfg, record)
default:
err = errors.New("unsupported strategy")
}
if err != nil {
return state.Record{}, err
}
return state.Load(cfg.Deployment.StateFile, cfg.Deployment.Root, cfg.Deployment.Strategy)
}
func (m Manager) rollbackBlueGreen(ctx context.Context, cfg config.Config, record state.Record) (err error) {
bg := *cfg.Deployment.BlueGreen
slot := slotConfig(bg, record.PreviousSlot)
if active, checkErr := m.Operator.IsActive(ctx, slot.Unit); checkErr != nil {
return checkErr
} else if !active {
if err = m.Operator.Restart(ctx, slot.Unit); err != nil {
return err
}
}
if err = m.probeHealthReadiness(ctx, cfg, slot.Address); err != nil {
return err
}
oldHandler, err := os.ReadFile(bg.CaddyHandler)
if err != nil {
return err
}
changed := false
defer func() {
if err != nil && changed {
_ = atomicWrite(bg.CaddyHandler, oldHandler, 0o644)
_ = m.Operator.ValidateCaddy(ctx, bg.CaddyConfig)
_ = m.Operator.ReloadCaddy(ctx)
}
}()
handler, err := renderHandler(bg.CaddyHandlerTemplate, slot.Address)
if err != nil {
return err
}
if err = atomicWrite(bg.CaddyHandler, handler, 0o644); err != nil {
return err
}
changed = true
if err = m.Operator.ValidateCaddy(ctx, bg.CaddyConfig); err != nil {
return err
}
if err = m.Operator.ReloadCaddy(ctx); err != nil {
return err
}
if err = m.probeHealthReadiness(ctx, cfg, slot.Address); err != nil {
return err
}
next := state.Record{SchemaVersion: 1, Strategy: record.Strategy, ActiveSlot: record.PreviousSlot, ActiveRelease: record.PreviousRelease, PreviousSlot: record.ActiveSlot, PreviousRelease: record.ActiveRelease, UpdatedAt: m.Now().UTC().Format(time.RFC3339)}
return state.Store(cfg.Deployment.StateFile, cfg.Deployment.Root, next)
}
func (m Manager) rollbackSingleton(ctx context.Context, cfg config.Config, record state.Record) (err error) {
single := *cfg.Deployment.Singleton
oldCurrent, err := resolveReleaseLink(cfg.Deployment.Root, single.CurrentLink)
if err != nil {
return err
}
if err = replaceSymlink(single.CurrentLink, record.PreviousRelease); err != nil {
return err
}
defer func() {
if err != nil {
_ = replaceSymlink(single.CurrentLink, oldCurrent)
_ = m.Operator.Restart(ctx, single.Unit)
}
}()
if err = m.Operator.Restart(ctx, single.Unit); err != nil {
return err
}
if err = m.probeHealthReadiness(ctx, cfg, single.Address); err != nil {
return err
}
_ = replaceSymlink(single.PreviousLink, record.ActiveRelease)
next := state.Record{SchemaVersion: 1, Strategy: record.Strategy, ActiveSlot: "singleton", ActiveRelease: record.PreviousRelease, PreviousSlot: "singleton", PreviousRelease: record.ActiveRelease, UpdatedAt: m.Now().UTC().Format(time.RFC3339)}
return state.Store(cfg.Deployment.StateFile, cfg.Deployment.Root, next)
}
func (m Manager) Status(ctx context.Context, cfg config.Config) (Status, error) {
result := Status{Units: map[string]bool{}}
record, err := state.Load(cfg.Deployment.StateFile, cfg.Deployment.Root, cfg.Deployment.Strategy)
if err == nil {
result.State = &record
result.StateInitialized = true
} else if !os.IsNotExist(err) {
return Status{}, err
}
units := []string{}
if cfg.Deployment.Strategy == "blue_green" {
units = []string{cfg.Deployment.BlueGreen.Blue.Unit, cfg.Deployment.BlueGreen.Green.Unit}
} else {
units = []string{cfg.Deployment.Singleton.Unit}
}
for _, unit := range units {
active, err := m.Operator.IsActive(ctx, unit)
if err != nil {
return Status{}, err
}
result.Units[unit] = active
}
return result, nil
}
func (m Manager) Prune(cfg config.Config, keep int, apply bool) ([]string, error) {
if keep < 2 || keep > 100 {
return nil, errors.New("keep must be between 2 and 100")
}
lock, err := acquireLock(cfg.Deployment.LockFile)
if err != nil {
return nil, err
}
defer lock.Close()
record, err := state.Load(cfg.Deployment.StateFile, cfg.Deployment.Root, cfg.Deployment.Strategy)
if err != nil {
return nil, err
}
entries, err := os.ReadDir(filepath.Join(cfg.Deployment.Root, "releases"))
if err != nil {
return nil, err
}
type candidate struct {
name, path string
mod time.Time
}
items := []candidate{}
protected := map[string]bool{record.ActiveRelease: true, record.PreviousRelease: true}
for _, entry := range entries {
if !entry.IsDir() || entry.Type()&os.ModeSymlink != 0 || !strings.HasPrefix(entry.Name(), "sha256-") {
continue
}
path := filepath.Join(cfg.Deployment.Root, "releases", entry.Name())
if protected[path] {
continue
}
info, err := entry.Info()
if err != nil {
return nil, err
}
items = append(items, candidate{entry.Name(), path, info.ModTime()})
}
sort.Slice(items, func(i, j int) bool { return items[i].mod.After(items[j].mod) })
retained := keep - 2
if retained < 0 {
retained = 0
}
if retained > len(items) {
retained = len(items)
}
items = items[retained:]
paths := make([]string, 0, len(items))
for _, item := range items {
paths = append(paths, item.path)
if apply {
if err := removeRelease(item.path, cfg.Deployment.Root); err != nil {
return paths, err
}
}
}
return paths, nil
}
func (m Manager) probeAll(ctx context.Context, cfg config.Config, address string) error {
checks := append([]config.Smoke{{Path: cfg.Deployment.HealthPath}, {Path: cfg.Deployment.ReadinessPath}}, cfg.Deployment.Smoke...)
return m.probe(ctx, cfg, address, checks)
}
func (m Manager) probeHealthReadiness(ctx context.Context, cfg config.Config, address string) error {
checks := []config.Smoke{{Path: cfg.Deployment.HealthPath}, {Path: cfg.Deployment.ReadinessPath}}
return m.probe(ctx, cfg, address, checks)
}
func (m Manager) probe(ctx context.Context, cfg config.Config, address string, checks []config.Smoke) error {
timeout := time.Duration(cfg.Deployment.CandidateTimeoutSecs) * time.Second
for _, check := range checks {
deadline := m.Now().Add(timeout)
var last error
for {
attempt, cancel := context.WithTimeout(ctx, 2*time.Second)
last = m.Operator.Probe(attempt, address, cfg.Service.AllowedHost, check.Path, check.Contains)
cancel()
if last == nil {
break
}
if !m.Now().Before(deadline) {
return last
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(200 * time.Millisecond):
}
}
}
return nil
}
func slotConfig(bg config.BlueGreen, name string) config.Slot {
if name == "blue" {
return bg.Blue
}
return bg.Green
}
func copyMap(source map[string]string) map[string]string {
target := make(map[string]string, len(source)+1)
for k, v := range source {
target[k] = v
}
return target
}
func resolveReleaseLink(root, link string) (string, error) {
info, err := os.Lstat(link)
if err != nil {
return "", err
}
if info.Mode()&os.ModeSymlink == 0 {
return "", errors.New("release pointer is not a symlink")
}
target, err := os.Readlink(link)
if err != nil {
return "", err
}
if !filepath.IsAbs(target) {
target = filepath.Join(filepath.Dir(link), target)
}
target = filepath.Clean(target)
probe := state.Record{SchemaVersion: 1, Strategy: "singleton_candidate", ActiveSlot: "singleton", ActiveRelease: target, UpdatedAt: time.Unix(1, 0).UTC().Format(time.RFC3339)}
if err := probe.Validate(root, "singleton_candidate"); err != nil {
return "", err
}
targetInfo, err := os.Lstat(target)
if err != nil {
return "", err
}
if !targetInfo.IsDir() || targetInfo.Mode()&os.ModeSymlink != 0 {
return "", errors.New("release target must be a real directory")
}
return target, nil
}
func replaceSymlink(link, target string) error {
if info, err := os.Lstat(link); err == nil && info.Mode()&os.ModeSymlink == 0 {
return errors.New("refusing to replace non-symlink release pointer")
} else if err != nil && !os.IsNotExist(err) {
return err
}
if err := os.MkdirAll(filepath.Dir(link), 0o755); err != nil {
return err
}
stage, err := os.MkdirTemp(filepath.Dir(link), ".tend-link-")
if err != nil {
return err
}
defer os.RemoveAll(stage)
tmp := filepath.Join(stage, "next")
if err := os.Symlink(target, tmp); err != nil {
return err
}
return os.Rename(tmp, link)
}
func removeSymlink(path string) error {
info, err := os.Lstat(path)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return err
}
if info.Mode()&os.ModeSymlink == 0 {
return errors.New("refusing to remove non-symlink")
}
return os.Remove(path)
}
func renderHandler(templatePath, address string) ([]byte, error) {
b, err := os.ReadFile(templatePath)
if err != nil {
return nil, err
}
const marker = "{{UPSTREAM}}"
if bytes := strings.Count(string(b), marker); bytes != 1 {
return nil, errors.New("Caddy handler template must contain exactly one upstream marker")
}
return []byte(strings.Replace(string(b), marker, address, 1)), nil
}
func atomicWrite(path string, data []byte, mode os.FileMode) error {
var existing os.FileInfo
if info, err := os.Lstat(path); err == nil {
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
return errors.New("refusing to replace non-regular or symlink file")
}
existing = info
} else if !os.IsNotExist(err) {
return err
}
identity := identityFor(existing, mode)
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".tend-write-")
if err != nil {
return err
}
name := tmp.Name()
ok := false
defer func() {
_ = tmp.Close()
if !ok {
_ = os.Remove(name)
}
}()
if err := applyIdentity(tmp, identity); err != nil {
return err
}
if _, err := tmp.Write(data); err != nil {
return err
}
if err := tmp.Sync(); err != nil {
return err
}
if err := tmp.Close(); err != nil {
return err
}
if err := os.Rename(name, path); err != nil {
return err
}
ok = true
return syncDirectory(dir)
}
func syncDirectory(path string) error {
dir, err := os.Open(path)
if err != nil {
return err
}
defer dir.Close()
return dir.Sync()
}
func removeRelease(path, root string) error {
releases := filepath.Join(root, "releases")
rel, err := filepath.Rel(releases, path)
if err != nil || rel == "." || rel == ".." || strings.ContainsRune(rel, filepath.Separator) || !strings.HasPrefix(rel, "sha256-") {
return errors.New("unsafe prune target")
}
info, err := os.Lstat(path)
if err != nil {
return err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("prune target is not a real release directory")
}
return os.RemoveAll(path)
}
func Marshal(value any) ([]byte, error) {
b, err := json.MarshalIndent(value, "", " ")
if err != nil {
return nil, err
}
return append(b, '\n'), nil
}
+213
View File
@@ -0,0 +1,213 @@
// SPDX-License-Identifier: AGPL-3.0-only
package deploy
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gamertan.com/tend/internal/config"
"gamertan.com/tend/internal/state"
)
type fakeOperator struct {
failReload bool
failRestartUnit string
rejectMarkers bool
active map[string]bool
starts, stops, restarts []string
probes []string
}
func (f *fakeOperator) Restart(_ context.Context, unit string) error {
f.restarts = append(f.restarts, unit)
if unit == f.failRestartUnit {
return errors.New("injected restart failure")
}
f.active[unit] = true
return nil
}
func (f *fakeOperator) Stop(_ context.Context, unit string) error {
f.stops = append(f.stops, unit)
f.active[unit] = false
return nil
}
func (f *fakeOperator) IsActive(_ context.Context, unit string) (bool, error) {
return f.active[unit], nil
}
func (f *fakeOperator) StartCandidate(_ context.Context, unit, binary string, env map[string]string) error {
if !filepath.IsAbs(binary) || len(env) == 0 {
return errors.New("bad candidate")
}
f.starts = append(f.starts, unit)
f.active[unit] = true
return nil
}
func (f *fakeOperator) ValidateCaddy(context.Context, string) error { return nil }
func (f *fakeOperator) ReloadCaddy(context.Context) error {
if f.failReload {
return errors.New("injected reload failure")
}
return nil
}
func (f *fakeOperator) Probe(_ context.Context, address, host, path, contains string) error {
f.probes = append(f.probes, address+path)
if f.rejectMarkers && contains != "" {
return errors.New("unexpected future-release smoke marker")
}
return nil
}
func baseConfig(t *testing.T, strategy string) (config.Config, string, string) {
t.Helper()
root := filepath.Join(t.TempDir(), "service")
if err := os.MkdirAll(filepath.Join(root, "releases"), 0o755); err != nil {
t.Fatal(err)
}
old := filepath.Join(root, "releases", "legacy-old")
fresh := filepath.Join(root, "releases", "sha256-"+strings.Repeat("a", 64))
for _, dir := range []string{old, fresh} {
if err := os.Mkdir(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "app"), []byte("x"), 0o755); err != nil {
t.Fatal(err)
}
}
cfg := config.Config{SchemaVersion: 1, Service: config.Service{Name: "example-site", AllowedHost: "example.test"}, Build: config.Build{Package: "./cmd/site", Binary: "app", Branch: "main"}, Deployment: config.Deployment{Strategy: strategy, Root: root, LockFile: filepath.Join(root, "deploy.lock"), StateFile: filepath.Join(root, "state.json"), HealthPath: "/healthz", ReadinessPath: "/readyz", CandidateTimeoutSecs: 2, Smoke: []config.Smoke{{Path: "/", Contains: "Example"}}}}
return cfg, old, fresh
}
func manager(operator Operator, fresh string) Manager {
return Manager{Operator: operator, Now: func() time.Time { return time.Unix(100, 0).UTC() }, Prepare: func(config.Config, string, string, string) (string, error) { return fresh, nil }, Inspect: func(config.Config, string, string, string) error { return nil }}
}
func TestBlueGreenActivationAndRollback(t *testing.T) {
cfg, old, fresh := baseConfig(t, "blue_green")
handler := filepath.Join(cfg.Deployment.Root, "handler.caddy")
template := filepath.Join(cfg.Deployment.Root, "handler.template")
if err := os.WriteFile(handler, []byte("reverse_proxy 127.0.0.1:8090\n"), 0o640); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(template, []byte("reverse_proxy {{UPSTREAM}}\n"), 0o644); err != nil {
t.Fatal(err)
}
blue := filepath.Join(cfg.Deployment.Root, "slots", "blue")
green := filepath.Join(cfg.Deployment.Root, "slots", "green")
if err := replaceSymlink(blue, old); err != nil {
t.Fatal(err)
}
if err := replaceSymlink(green, old); err != nil {
t.Fatal(err)
}
cfg.Deployment.BlueGreen = &config.BlueGreen{CaddyConfig: filepath.Join(cfg.Deployment.Root, "Caddyfile"), CaddyHandler: handler, CaddyHandlerTemplate: template, BootstrapActive: "blue", Blue: config.Slot{Unit: "example-blue.service", Address: "127.0.0.1:8090", Link: blue}, Green: config.Slot{Unit: "example-green.service", Address: "127.0.0.1:8091", Link: green}}
if err := cfg.Validate(); err != nil {
t.Fatal(err)
}
operator := &fakeOperator{active: map[string]bool{"example-blue.service": true, "example-green.service": true}}
m := manager(operator, fresh)
report, err := m.Deploy(context.Background(), cfg, Request{Activate: true})
if err != nil {
t.Fatal(err)
}
if report.ActiveRelease != fresh || report.PreviousRelease != old {
t.Fatalf("report=%+v", report)
}
if info, err := os.Stat(handler); err != nil || info.Mode().Perm() != 0o640 {
t.Fatalf("handler mode=%v err=%v", info.Mode().Perm(), err)
}
if target, err := resolveReleaseLink(cfg.Deployment.Root, green); err != nil || target != fresh {
t.Fatalf("green=%q err=%v", target, err)
}
operator.rejectMarkers = true
operator.probes = nil
record, err := m.Rollback(context.Background(), cfg)
if err != nil {
t.Fatal(err)
}
if record.ActiveRelease != old || record.PreviousRelease != fresh {
t.Fatalf("rollback=%+v", record)
}
if len(operator.probes) != 4 {
t.Fatalf("rollback probes=%#v", operator.probes)
}
for _, probe := range operator.probes {
if !strings.HasSuffix(probe, "/healthz") && !strings.HasSuffix(probe, "/readyz") {
t.Fatalf("rollback applied future-release smoke checks: %#v", operator.probes)
}
}
}
func TestBlueGreenCaddyFailureRestoresHandlerAndSlot(t *testing.T) {
cfg, old, fresh := baseConfig(t, "blue_green")
handler := filepath.Join(cfg.Deployment.Root, "handler.caddy")
template := filepath.Join(cfg.Deployment.Root, "handler.template")
original := []byte("reverse_proxy 127.0.0.1:8090\n")
_ = os.WriteFile(handler, original, 0o644)
_ = os.WriteFile(template, []byte("reverse_proxy {{UPSTREAM}}\n"), 0o644)
blue := filepath.Join(cfg.Deployment.Root, "slots", "blue")
green := filepath.Join(cfg.Deployment.Root, "slots", "green")
_ = replaceSymlink(blue, old)
_ = replaceSymlink(green, old)
cfg.Deployment.BlueGreen = &config.BlueGreen{CaddyConfig: filepath.Join(cfg.Deployment.Root, "Caddyfile"), CaddyHandler: handler, CaddyHandlerTemplate: template, BootstrapActive: "blue", Blue: config.Slot{Unit: "example-blue.service", Address: "127.0.0.1:8090", Link: blue}, Green: config.Slot{Unit: "example-green.service", Address: "127.0.0.1:8091", Link: green}}
operator := &fakeOperator{active: map[string]bool{}, failReload: true}
m := manager(operator, fresh)
if _, err := m.Deploy(context.Background(), cfg, Request{Activate: true}); err == nil {
t.Fatal("expected failure")
}
body, _ := os.ReadFile(handler)
if string(body) != string(original) {
t.Fatalf("handler not restored: %q", body)
}
target, err := resolveReleaseLink(cfg.Deployment.Root, green)
if err != nil || target != old {
t.Fatalf("green=%q err=%v", target, err)
}
if _, err := os.Stat(cfg.Deployment.StateFile); !os.IsNotExist(err) {
t.Fatal("failed activation wrote state")
}
}
func TestSingletonRestartFailureRestoresPointers(t *testing.T) {
cfg, old, fresh := baseConfig(t, "singleton_candidate")
previous := filepath.Join(cfg.Deployment.Root, "previous")
current := filepath.Join(cfg.Deployment.Root, "current")
_ = replaceSymlink(current, old)
cfg.Deployment.Singleton = &config.Singleton{Unit: "example-site.service", Address: "127.0.0.1:8092", CandidateAddress: "127.0.0.1:18092", ListenEnv: "EXAMPLE_LISTEN", CurrentLink: current, PreviousLink: previous}
operator := &fakeOperator{active: map[string]bool{}, failRestartUnit: "example-site.service"}
m := manager(operator, fresh)
if _, err := m.Deploy(context.Background(), cfg, Request{Activate: true}); err == nil {
t.Fatal("expected failure")
}
target, err := resolveReleaseLink(cfg.Deployment.Root, current)
if err != nil || target != old {
t.Fatalf("current=%q err=%v", target, err)
}
if _, err := os.Lstat(previous); !os.IsNotExist(err) {
t.Fatal("previous pointer was not restored")
}
}
func TestStatePersistsOnlyAfterSuccessfulActivation(t *testing.T) {
cfg, old, fresh := baseConfig(t, "singleton_candidate")
current := filepath.Join(cfg.Deployment.Root, "current")
previous := filepath.Join(cfg.Deployment.Root, "previous")
_ = replaceSymlink(current, old)
cfg.Deployment.Singleton = &config.Singleton{Unit: "example-site.service", Address: "127.0.0.1:8092", CandidateAddress: "127.0.0.1:18092", ListenEnv: "EXAMPLE_LISTEN", CurrentLink: current, PreviousLink: previous}
operator := &fakeOperator{active: map[string]bool{}}
m := manager(operator, fresh)
if _, err := m.Deploy(context.Background(), cfg, Request{Activate: true}); err != nil {
t.Fatal(err)
}
record, err := state.Load(cfg.Deployment.StateFile, cfg.Deployment.Root, cfg.Deployment.Strategy)
if err != nil {
t.Fatal(err)
}
if record.ActiveRelease != fresh || record.PreviousRelease != old {
t.Fatalf("state=%+v", record)
}
}
+32
View File
@@ -0,0 +1,32 @@
//go:build linux
// SPDX-License-Identifier: AGPL-3.0-only
package deploy
import (
"errors"
"os"
"syscall"
)
type fileLock struct{ file *os.File }
func acquireLock(path string) (*fileLock, error) {
file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, err
}
if err := syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
_ = file.Close()
return nil, errors.New("deployment lock is held")
}
return &fileLock{file: file}, nil
}
func (l *fileLock) Close() error {
if l == nil || l.file == nil {
return nil
}
_ = syscall.Flock(int(l.file.Fd()), syscall.LOCK_UN)
return l.file.Close()
}
+14
View File
@@ -0,0 +1,14 @@
//go:build !linux
// SPDX-License-Identifier: AGPL-3.0-only
package deploy
import "errors"
type fileLock struct{}
func acquireLock(string) (*fileLock, error) {
return nil, errors.New("deployment mutations require Linux")
}
func (*fileLock) Close() error { return nil }
+111
View File
@@ -0,0 +1,111 @@
// SPDX-License-Identifier: AGPL-3.0-only
package deploy
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strings"
"time"
"gamertan.com/tend/internal/process"
)
type Operator interface {
Restart(context.Context, string) error
Stop(context.Context, string) error
IsActive(context.Context, string) (bool, error)
StartCandidate(context.Context, string, string, map[string]string) error
ValidateCaddy(context.Context, string) error
ReloadCaddy(context.Context) error
Probe(context.Context, string, string, string, string) error
}
type SystemOperator struct {
Runner process.Runner
Timeout time.Duration
}
func (o SystemOperator) Restart(ctx context.Context, unit string) error {
_, err := o.Runner.Run(ctx, "/", nil, "systemctl", "restart", unit)
return err
}
func (o SystemOperator) Stop(ctx context.Context, unit string) error {
_, err := o.Runner.Run(ctx, "/", nil, "systemctl", "stop", unit)
return err
}
func (o SystemOperator) IsActive(ctx context.Context, unit string) (bool, error) {
out, err := o.Runner.Run(ctx, "/", nil, "systemctl", "is-active", unit)
if err != nil {
if strings.TrimSpace(string(out)) == "inactive" || strings.TrimSpace(string(out)) == "failed" {
return false, nil
}
return false, err
}
return strings.TrimSpace(string(out)) == "active", nil
}
func (o SystemOperator) StartCandidate(ctx context.Context, unit, binary string, env map[string]string) error {
args := []string{
"--unit", unit, "--collect",
"--property=DynamicUser=yes", "--property=NoNewPrivileges=yes",
"--property=PrivateDevices=yes", "--property=PrivateTmp=yes",
"--property=ProtectClock=yes", "--property=ProtectControlGroups=yes",
"--property=ProtectHome=yes", "--property=ProtectHostname=yes",
"--property=ProtectKernelLogs=yes", "--property=ProtectKernelModules=yes",
"--property=ProtectKernelTunables=yes", "--property=ProtectSystem=strict",
"--property=RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX",
"--property=RestrictNamespaces=yes", "--property=RestrictRealtime=yes",
"--property=RestrictSUIDSGID=yes", "--property=LockPersonality=yes",
"--property=MemoryDenyWriteExecute=yes", "--property=CapabilityBoundingSet=",
"--property=AmbientCapabilities=",
}
keys := make([]string, 0, len(env))
for key := range env {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
args = append(args, "--setenv", key+"="+env[key])
}
args = append(args, "--", binary)
_, err := o.Runner.Run(ctx, "/", nil, "systemd-run", args...)
return err
}
func (o SystemOperator) ValidateCaddy(ctx context.Context, path string) error {
_, err := o.Runner.Run(ctx, "/", nil, "caddy", "validate", "--config", path, "--adapter", "caddyfile")
return err
}
func (o SystemOperator) ReloadCaddy(ctx context.Context) error {
_, err := o.Runner.Run(ctx, "/", nil, "systemctl", "reload", "caddy.service")
return err
}
func (o SystemOperator) Probe(ctx context.Context, address, host, path, contains string) error {
u := url.URL{Scheme: "http", Host: address, Path: path}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return err
}
req.Host = host
client := &http.Client{Timeout: o.Timeout, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }}
response, err := client.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return fmt.Errorf("probe returned HTTP %d", response.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
if err != nil {
return err
}
if contains != "" && !strings.Contains(string(body), contains) {
return errors.New("probe response omitted required marker")
}
return nil
}
+45
View File
@@ -0,0 +1,45 @@
// SPDX-License-Identifier: AGPL-3.0-only
package deploy
import (
"context"
"reflect"
"testing"
)
type recordingRunner struct {
name string
args []string
}
func (r *recordingRunner) Run(_ context.Context, _ string, _ map[string]string, name string, args ...string) ([]byte, error) {
r.name = name
r.args = append([]string(nil), args...)
return nil, nil
}
func TestStartCandidateUsesArgumentVectorAndHardenedUnit(t *testing.T) {
runner := &recordingRunner{}
operator := SystemOperator{Runner: runner}
env := map[string]string{"Z_ENV": "safe value", "A_ENV": "first"}
if err := operator.StartCandidate(context.Background(), "example-tend-candidate.service", "/opt/example/releases/sha256-a/app", env); err != nil {
t.Fatal(err)
}
if runner.name != "systemd-run" {
t.Fatalf("command=%q", runner.name)
}
required := []string{"--property=DynamicUser=yes", "--property=NoNewPrivileges=yes", "--property=ProtectSystem=strict", "--property=MemoryDenyWriteExecute=yes", "--property=CapabilityBoundingSet=", "--setenv", "A_ENV=first", "--setenv", "Z_ENV=safe value", "--", "/opt/example/releases/sha256-a/app"}
cursor := 0
for _, arg := range runner.args {
if cursor < len(required) && arg == required[cursor] {
cursor++
}
}
if cursor != len(required) {
t.Fatalf("arguments omitted ordered security boundary: %#v", runner.args)
}
if reflect.DeepEqual(runner.args, []string{"sh", "-c"}) {
t.Fatal("candidate command used a shell")
}
}
+38
View File
@@ -0,0 +1,38 @@
//go:build linux
// SPDX-License-Identifier: AGPL-3.0-only
package deploy
import (
"os"
"syscall"
)
type fileIdentity struct {
mode os.FileMode
uid, gid int
owned bool
}
func identityFor(info os.FileInfo, fallback os.FileMode) fileIdentity {
identity := fileIdentity{mode: fallback}
if info == nil {
return identity
}
identity.mode = info.Mode().Perm()
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
identity.uid = int(stat.Uid)
identity.gid = int(stat.Gid)
identity.owned = true
}
return identity
}
func applyIdentity(file *os.File, identity fileIdentity) error {
if identity.owned {
if err := file.Chown(identity.uid, identity.gid); err != nil {
return err
}
}
return file.Chmod(identity.mode)
}
+17
View File
@@ -0,0 +1,17 @@
//go:build !linux
// SPDX-License-Identifier: AGPL-3.0-only
package deploy
import "os"
type fileIdentity struct{ mode os.FileMode }
func identityFor(info os.FileInfo, fallback os.FileMode) fileIdentity {
if info != nil {
return fileIdentity{mode: info.Mode().Perm()}
}
return fileIdentity{mode: fallback}
}
func applyIdentity(file *os.File, identity fileIdentity) error { return file.Chmod(identity.mode) }
+309
View File
@@ -0,0 +1,309 @@
// SPDX-License-Identifier: AGPL-3.0-only
package deploy
import (
"archive/tar"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"gamertan.com/tend/internal/config"
"gamertan.com/tend/internal/packager"
)
const maxArtifactSize int64 = 512 << 20
func prepareRelease(cfg config.Config, artifact, expected, approved string) (string, error) {
if err := checkArtifact(artifact, expected, approved); err != nil {
return "", err
}
if err := ensureTree(cfg.Deployment.Root); err != nil {
return "", err
}
releases := filepath.Join(cfg.Deployment.Root, "releases")
release := filepath.Join(releases, "sha256-"+expected)
if info, err := os.Lstat(release); err == nil {
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return "", errors.New("existing release is not a directory")
}
if err := validateRelease(cfg, release); err != nil {
return "", err
}
return release, nil
} else if !os.IsNotExist(err) {
return "", err
}
stage := filepath.Join(releases, ".tend-stage-"+expected)
if err := os.Mkdir(stage, 0o700); err != nil {
return "", err
}
ok := false
defer func() {
if !ok {
_ = os.RemoveAll(stage)
}
}()
if err := extractArtifact(artifact, stage); err != nil {
return "", err
}
if err := validateRelease(cfg, stage); err != nil {
return "", err
}
if err := os.Chmod(stage, 0o755); err != nil {
return "", err
}
if err := os.Rename(stage, release); err != nil {
return "", err
}
ok = true
return release, nil
}
func inspectArtifact(cfg config.Config, artifact, expected, approved string) error {
if err := checkArtifact(artifact, expected, approved); err != nil {
return err
}
stage, err := os.MkdirTemp("", "tend-inspect-")
if err != nil {
return err
}
defer os.RemoveAll(stage)
if err := extractArtifact(artifact, stage); err != nil {
return err
}
return validateRelease(cfg, stage)
}
func checkArtifact(artifact, expected, approved string) error {
if expected != approved || len(expected) != 64 {
return errors.New("artifact digest was not explicitly approved")
}
if _, err := hex.DecodeString(expected); err != nil {
return errors.New("artifact digest is not hexadecimal")
}
if !filepath.IsAbs(artifact) || filepath.Clean(artifact) != artifact {
return errors.New("artifact path must be a clean absolute path")
}
info, err := os.Lstat(artifact)
if err != nil {
return err
}
if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Size() > maxArtifactSize {
return errors.New("artifact must be a bounded regular file")
}
actual, err := fileSHA(artifact)
if err != nil {
return err
}
if actual != expected {
return errors.New("artifact digest does not match")
}
return nil
}
func ensureTree(root string) error {
if os.Geteuid() != 0 && strings.HasPrefix(root, "/opt/") {
return errors.New("deployment under /opt requires root")
}
if err := rejectSymlinkAncestors(root); err != nil {
return err
}
if err := os.MkdirAll(filepath.Join(root, "releases"), 0o755); err != nil {
return err
}
return rejectSymlinkAncestors(filepath.Join(root, "releases"))
}
func rejectSymlinkAncestors(path string) error {
clean := filepath.Clean(path)
parts := strings.Split(strings.TrimPrefix(clean, string(filepath.Separator)), string(filepath.Separator))
current := string(filepath.Separator)
for _, part := range parts {
current = filepath.Join(current, part)
info, err := os.Lstat(current)
if os.IsNotExist(err) {
continue
}
if err != nil {
return err
}
if info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("symlink ancestor refused: %s", current)
}
if !info.IsDir() {
return fmt.Errorf("non-directory ancestor refused: %s", current)
}
}
return nil
}
func extractArtifact(artifact, stage string) error {
file, err := os.Open(artifact)
if err != nil {
return err
}
defer file.Close()
gz, err := gzip.NewReader(file)
if err != nil {
return err
}
defer gz.Close()
tr := tar.NewReader(io.LimitReader(gz, maxArtifactSize))
files := 0
var total int64
for {
header, err := tr.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return err
}
clean := filepath.Clean(filepath.FromSlash(header.Name))
parts := strings.Split(clean, string(filepath.Separator))
if len(parts) == 1 && header.Typeflag == tar.TypeDir {
continue
}
if len(parts) != 2 || parts[0] != "bundle" || parts[1] == "" || parts[1] == "." || parts[1] == ".." {
return fmt.Errorf("unsafe archive path %q", header.Name)
}
if header.Typeflag != tar.TypeReg || header.Size < 0 {
return errors.New("archive may contain only regular files")
}
files++
total += header.Size
if files > 16 || total > maxArtifactSize {
return errors.New("artifact exceeds extraction bounds")
}
target := filepath.Join(stage, parts[1])
mode := os.FileMode(0o644)
if !strings.HasSuffix(parts[1], ".json") && parts[1] != "SHA256SUMS" {
mode = 0o755
}
out, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, mode)
if err != nil {
return err
}
if _, err := io.CopyN(out, tr, header.Size); err != nil {
_ = out.Close()
return err
}
if err := out.Sync(); err != nil {
_ = out.Close()
return err
}
if err := out.Close(); err != nil {
return err
}
}
if files < 5 {
return errors.New("artifact is incomplete")
}
return nil
}
func validateRelease(cfg config.Config, release string) error {
manifestPath := filepath.Join(release, "RELEASE.json")
b, err := os.ReadFile(manifestPath)
if err != nil {
return err
}
dec := json.NewDecoder(strings.NewReader(string(b)))
dec.DisallowUnknownFields()
var manifest packager.Manifest
if err := dec.Decode(&manifest); err != nil {
return err
}
var trailing any
if err := dec.Decode(&trailing); !errors.Is(err, io.EOF) {
return errors.New("release manifest contains trailing data")
}
if manifest.SchemaVersion != 1 || manifest.Service != cfg.Service.Name || manifest.Binary != cfg.Build.Binary || manifest.GOOS != "linux" || manifest.GOARCH != "amd64" || manifest.CGOEnabled {
return errors.New("release manifest does not match configuration")
}
if matched, _ := regexp.MatchString(`^[0-9a-f]{40}$`, manifest.Commit); !matched {
return errors.New("release manifest commit is invalid")
}
binary := filepath.Join(release, cfg.Build.Binary)
sum, err := fileSHA(binary)
if err != nil {
return err
}
if sum != manifest.BinarySHA256 {
return errors.New("release binary digest does not match manifest")
}
if err := verifySums(release); err != nil {
return err
}
entries, err := os.ReadDir(release)
if err != nil {
return err
}
allowed := map[string]bool{cfg.Build.Binary: true, "BUILDINFO.json": true, "RELEASE.json": true, "SBOM.spdx.json": true, "SHA256SUMS": true}
if len(entries) != len(allowed) {
return errors.New("release contains unexpected files")
}
for _, entry := range entries {
if !allowed[entry.Name()] || !entry.Type().IsRegular() {
return fmt.Errorf("unexpected release entry %s", entry.Name())
}
}
return nil
}
func verifySums(release string) error {
b, err := os.ReadFile(filepath.Join(release, "SHA256SUMS"))
if err != nil {
return err
}
lines := strings.Split(strings.TrimSpace(string(b)), "\n")
if len(lines) != 4 {
return errors.New("SHA256SUMS must cover four release files")
}
seen := map[string]bool{}
for _, line := range lines {
fields := strings.Fields(line)
if len(fields) != 2 || len(fields[0]) != 64 {
return errors.New("malformed SHA256SUMS")
}
name := fields[1]
if filepath.Base(name) != name || seen[name] {
return errors.New("unsafe or duplicate checksum entry")
}
seen[name] = true
actual, err := fileSHA(filepath.Join(release, name))
if err != nil {
return err
}
if actual != fields[0] {
return fmt.Errorf("checksum mismatch for %s", name)
}
}
required := []string{"BUILDINFO.json", "RELEASE.json", "SBOM.spdx.json"}
sort.Strings(required)
for _, name := range required {
if !seen[name] {
return fmt.Errorf("checksum omitted %s", name)
}
}
return nil
}
func fileSHA(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
+41
View File
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: AGPL-3.0-only
package deploy
import (
"archive/tar"
"compress/gzip"
"os"
"path/filepath"
"testing"
)
func writeHostileArchive(t *testing.T, name string, typeflag byte) {
t.Helper()
path := filepath.Join(t.TempDir(), "bad.tar.gz")
file, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
gz := gzip.NewWriter(file)
tw := tar.NewWriter(gz)
body := []byte("x")
if err := tw.WriteHeader(&tar.Header{Name: name, Typeflag: typeflag, Mode: 0o644, Size: int64(len(body))}); err != nil {
t.Fatal(err)
}
if typeflag == tar.TypeReg {
_, _ = tw.Write(body)
}
_ = tw.Close()
_ = gz.Close()
_ = file.Close()
stage := filepath.Join(t.TempDir(), "stage")
_ = os.Mkdir(stage, 0o700)
if err := extractArtifact(path, stage); err == nil {
t.Fatalf("accepted hostile entry %q type %d", name, typeflag)
}
}
func TestExtractionRejectsTraversalAndLinks(t *testing.T) {
writeHostileArchive(t, "bundle/../../escape", tar.TypeReg)
writeHostileArchive(t, "bundle/link", tar.TypeSymlink)
}
+399
View File
@@ -0,0 +1,399 @@
// SPDX-License-Identifier: AGPL-3.0-only
package packager
import (
"archive/tar"
"compress/gzip"
"context"
"crypto/sha256"
"debug/buildinfo"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"gamertan.com/tend/internal/config"
"gamertan.com/tend/internal/process"
"gamertan.com/tend/internal/provenance"
)
var versionPattern = regexp.MustCompile(`^v[0-9]+\.[0-9]+\.[0-9]+-preview\.[1-9][0-9]*$`)
type Result struct {
Artifact string `json:"artifact"`
SHA256 string `json:"sha256"`
Commit string `json:"commit"`
Version string `json:"version"`
}
type Manifest struct {
SchemaVersion int `json:"schema_version"`
Service string `json:"service"`
Version string `json:"version"`
Commit string `json:"commit"`
SourceEpoch int64 `json:"source_date_epoch"`
GOOS string `json:"goos"`
GOARCH string `json:"goarch"`
CGOEnabled bool `json:"cgo_enabled"`
Binary string `json:"binary"`
BinarySHA256 string `json:"binary_sha256"`
GoVersion string `json:"go_version"`
ModulePath string `json:"module_path"`
ModuleVersion string `json:"module_version"`
}
type buildRecord struct {
GoVersion string `json:"go_version"`
Path string `json:"path"`
Main moduleRecord `json:"main"`
Deps []moduleRecord `json:"dependencies"`
Settings []settingRecord `json:"settings"`
}
type moduleRecord struct {
Path string `json:"path"`
Version string `json:"version"`
Sum string `json:"sum,omitempty"`
}
type settingRecord struct {
Key string `json:"key"`
Value string `json:"value"`
}
type spdxDocument struct {
SPDXVersion string `json:"spdxVersion"`
DataLicense string `json:"dataLicense"`
SPDXID string `json:"SPDXID"`
Name string `json:"name"`
DocumentNamespace string `json:"documentNamespace"`
CreationInfo spdxCreation `json:"creationInfo"`
Packages []spdxPackage `json:"packages"`
Relationships []spdxRelationship `json:"relationships"`
}
type spdxCreation struct {
Created string `json:"created"`
Creators []string `json:"creators"`
}
type spdxPackage struct {
Name string `json:"name"`
SPDXID string `json:"SPDXID"`
VersionInfo string `json:"versionInfo"`
DownloadLocation string `json:"downloadLocation"`
FilesAnalyzed bool `json:"filesAnalyzed"`
LicenseConcluded string `json:"licenseConcluded"`
LicenseDeclared string `json:"licenseDeclared"`
}
type spdxRelationship struct {
SPDXElementID string `json:"spdxElementId"`
RelationshipType string `json:"relationshipType"`
RelatedSPDXElement string `json:"relatedSpdxElement"`
}
func Package(ctx context.Context, runner process.Runner, cfg config.Config, sourceDir, outDir, version string) (Result, error) {
if !versionPattern.MatchString(version) {
return Result{}, errors.New("version must use vX.Y.Z-preview.N")
}
if !filepath.IsAbs(sourceDir) || !filepath.IsAbs(outDir) {
return Result{}, errors.New("source and output directories must be absolute")
}
source, err := provenance.Inspect(ctx, runner, sourceDir, cfg.Build.Branch)
if err != nil {
return Result{}, err
}
if err := verifyModules(ctx, runner, sourceDir); err != nil {
return Result{}, err
}
work, err := os.MkdirTemp("", "tend-package-")
if err != nil {
return Result{}, err
}
defer os.RemoveAll(work)
first := filepath.Join(work, "first", cfg.Build.Binary)
second := filepath.Join(work, "second", cfg.Build.Binary)
if err := build(ctx, runner, cfg, source, sourceDir, version, first); err != nil {
return Result{}, err
}
if err := build(ctx, runner, cfg, source, sourceDir, version, second); err != nil {
return Result{}, err
}
firstSHA, err := fileSHA(first)
if err != nil {
return Result{}, err
}
secondSHA, err := fileSHA(second)
if err != nil {
return Result{}, err
}
if firstSHA != secondSHA {
return Result{}, errors.New("two clean builds were not byte-identical")
}
record, err := readBuildRecord(first)
if err != nil {
return Result{}, err
}
if record.Main.Path == "" {
return Result{}, errors.New("built binary has no main module provenance")
}
if err := verifyBuildSettings(record, source.Commit); err != nil {
return Result{}, err
}
manifest := Manifest{SchemaVersion: 1, Service: cfg.Service.Name, Version: version, Commit: source.Commit, SourceEpoch: source.Epoch, GOOS: "linux", GOARCH: "amd64", CGOEnabled: false, Binary: cfg.Build.Binary, BinarySHA256: firstSHA, GoVersion: record.GoVersion, ModulePath: record.Main.Path, ModuleVersion: record.Main.Version}
bundle := filepath.Join(work, "bundle")
if err := os.Mkdir(bundle, 0o700); err != nil {
return Result{}, err
}
if err := copyFile(first, filepath.Join(bundle, cfg.Build.Binary), 0o755); err != nil {
return Result{}, err
}
if err := writeJSON(filepath.Join(bundle, "RELEASE.json"), manifest, 0o644); err != nil {
return Result{}, err
}
if err := writeJSON(filepath.Join(bundle, "BUILDINFO.json"), record, 0o644); err != nil {
return Result{}, err
}
if err := writeJSON(filepath.Join(bundle, "SBOM.spdx.json"), makeSPDX(cfg, version, source, record), 0o644); err != nil {
return Result{}, err
}
if err := writeSums(bundle, []string{cfg.Build.Binary, "BUILDINFO.json", "RELEASE.json", "SBOM.spdx.json"}); err != nil {
return Result{}, err
}
if err := os.MkdirAll(outDir, 0o755); err != nil {
return Result{}, err
}
artifactName := fmt.Sprintf("%s-%s-linux-amd64.tar.gz", cfg.Service.Name, strings.TrimPrefix(version, "v"))
artifact := filepath.Join(outDir, artifactName)
if err := writeArchive(artifact, bundle, source.Epoch); err != nil {
return Result{}, err
}
artifactSHA, err := fileSHA(artifact)
if err != nil {
return Result{}, err
}
if err := os.WriteFile(artifact+".sha256", []byte(artifactSHA+" "+artifactName+"\n"), 0o644); err != nil {
return Result{}, err
}
return Result{Artifact: artifact, SHA256: artifactSHA, Commit: source.Commit, Version: version}, nil
}
func verifyModules(ctx context.Context, runner process.Runner, dir string) error {
out, err := runner.Run(ctx, dir, map[string]string{"GOWORK": "off", "GOFLAGS": "-mod=readonly"}, "go", "list", "-m", "-json", "all")
if err != nil {
return fmt.Errorf("list modules: %w", err)
}
dec := json.NewDecoder(strings.NewReader(string(out)))
count := 0
for {
var module struct {
Path, Version string
Main bool
Replace *json.RawMessage
}
if err := dec.Decode(&module); errors.Is(err, io.EOF) {
break
} else if err != nil {
return fmt.Errorf("decode module graph: %w", err)
}
count++
if module.Replace != nil {
return fmt.Errorf("module %s uses a replacement", module.Path)
}
if !module.Main && module.Version == "" {
return fmt.Errorf("module %s is not pinned", module.Path)
}
}
if count == 0 {
return errors.New("module graph is empty")
}
return nil
}
func build(ctx context.Context, runner process.Runner, cfg config.Config, source provenance.Source, dir, version, output string) error {
if err := os.MkdirAll(filepath.Dir(output), 0o700); err != nil {
return err
}
ldflags := []string{"-s", "-w"}
date := time.Unix(source.Epoch, 0).UTC().Format(time.RFC3339)
pairs := [][2]string{{cfg.Build.VersionSymbol, version}, {cfg.Build.CommitSymbol, source.Commit}, {cfg.Build.DateSymbol, date}}
for _, pair := range pairs {
if pair[0] != "" {
ldflags = append(ldflags, "-X", pair[0]+"="+pair[1])
}
}
args := []string{"build", "-mod=readonly", "-trimpath", "-buildvcs=true", "-ldflags", strings.Join(ldflags, " "), "-o", output, cfg.Build.Package}
env := map[string]string{"GOWORK": "off", "GOFLAGS": "-mod=readonly", "GOOS": "linux", "GOARCH": "amd64", "CGO_ENABLED": "0", "SOURCE_DATE_EPOCH": fmt.Sprint(source.Epoch)}
if _, err := runner.Run(ctx, dir, env, "go", args...); err != nil {
return fmt.Errorf("build candidate: %w", err)
}
return nil
}
func readBuildRecord(path string) (buildRecord, error) {
info, err := buildinfo.ReadFile(path)
if err != nil {
return buildRecord{}, fmt.Errorf("read Go build info: %w", err)
}
record := buildRecord{GoVersion: info.GoVersion, Path: info.Path, Main: moduleRecord{Path: info.Main.Path, Version: info.Main.Version, Sum: info.Main.Sum}}
for _, dep := range info.Deps {
if dep.Replace != nil {
return buildRecord{}, fmt.Errorf("built binary contains replacement for %s", dep.Path)
}
record.Deps = append(record.Deps, moduleRecord{Path: dep.Path, Version: dep.Version, Sum: dep.Sum})
}
for _, setting := range info.Settings {
record.Settings = append(record.Settings, settingRecord{Key: setting.Key, Value: setting.Value})
}
sort.Slice(record.Deps, func(i, j int) bool { return record.Deps[i].Path < record.Deps[j].Path })
sort.Slice(record.Settings, func(i, j int) bool { return record.Settings[i].Key < record.Settings[j].Key })
return record, nil
}
func verifyBuildSettings(record buildRecord, commit string) error {
settings := map[string]string{}
for _, setting := range record.Settings {
settings[setting.Key] = setting.Value
}
for key, expected := range map[string]string{"vcs.revision": commit, "vcs.modified": "false", "GOOS": "linux", "GOARCH": "amd64", "CGO_ENABLED": "0"} {
if settings[key] != expected {
return fmt.Errorf("build setting %s is %q, expected %q", key, settings[key], expected)
}
}
return nil
}
func makeSPDX(cfg config.Config, version string, source provenance.Source, record buildRecord) spdxDocument {
created := time.Unix(source.Epoch, 0).UTC().Format("2006-01-02T15:04:05Z")
modules := append([]moduleRecord{record.Main}, record.Deps...)
doc := spdxDocument{SPDXVersion: "SPDX-2.3", DataLicense: "CC0-1.0", SPDXID: "SPDXRef-DOCUMENT", Name: cfg.Service.Name + "-" + version, DocumentNamespace: "https://gamertan.com/tend/sbom/" + source.Commit + "/" + cfg.Service.Name, CreationInfo: spdxCreation{Created: created, Creators: []string{"Tool: gamertan.com/tend"}}}
for i, module := range modules {
id := fmt.Sprintf("SPDXRef-Package-%d", i+1)
versionInfo := module.Version
if versionInfo == "" {
versionInfo = source.Commit
}
doc.Packages = append(doc.Packages, spdxPackage{Name: module.Path, SPDXID: id, VersionInfo: versionInfo, DownloadLocation: "NOASSERTION", FilesAnalyzed: false, LicenseConcluded: "NOASSERTION", LicenseDeclared: "NOASSERTION"})
doc.Relationships = append(doc.Relationships, spdxRelationship{SPDXElementID: "SPDXRef-DOCUMENT", RelationshipType: "DESCRIBES", RelatedSPDXElement: id})
}
return doc
}
func writeJSON(path string, value any, mode os.FileMode) error {
b, err := json.MarshalIndent(value, "", " ")
if err != nil {
return err
}
b = append(b, '\n')
return os.WriteFile(path, b, mode)
}
func writeSums(dir string, names []string) error {
sort.Strings(names)
var b strings.Builder
for _, name := range names {
sum, err := fileSHA(filepath.Join(dir, name))
if err != nil {
return err
}
fmt.Fprintf(&b, "%s %s\n", sum, name)
}
return os.WriteFile(filepath.Join(dir, "SHA256SUMS"), []byte(b.String()), 0o644)
}
func writeArchive(path, bundle string, epoch int64) error {
tmp := path + ".tmp"
_ = os.Remove(tmp)
file, err := os.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
if err != nil {
return err
}
ok := false
defer func() {
_ = file.Close()
if !ok {
_ = os.Remove(tmp)
}
}()
gz := gzip.NewWriter(file)
gz.Header.ModTime = time.Unix(0, 0)
gz.Header.OS = 255
tw := tar.NewWriter(gz)
entries, err := os.ReadDir(bundle)
if err != nil {
return err
}
names := make([]string, 0, len(entries))
for _, entry := range entries {
if entry.Type().IsRegular() {
names = append(names, entry.Name())
}
}
sort.Strings(names)
root := filepath.Base(bundle)
if err := tw.WriteHeader(&tar.Header{Name: root + "/", Typeflag: tar.TypeDir, Mode: 0o755, ModTime: time.Unix(epoch, 0), Uid: 0, Gid: 0}); err != nil {
return err
}
for _, name := range names {
data, err := os.ReadFile(filepath.Join(bundle, name))
if err != nil {
return err
}
mode := int64(0o644)
if name != "BUILDINFO.json" && !strings.HasSuffix(name, ".json") && name != "SHA256SUMS" {
mode = 0o755
}
if err := tw.WriteHeader(&tar.Header{Name: root + "/" + name, Typeflag: tar.TypeReg, Mode: mode, Size: int64(len(data)), ModTime: time.Unix(epoch, 0), Uid: 0, Gid: 0}); err != nil {
return err
}
if _, err := tw.Write(data); err != nil {
return err
}
}
if err := tw.Close(); err != nil {
return err
}
if err := gz.Close(); err != nil {
return err
}
if err := file.Sync(); err != nil {
return err
}
if err := file.Close(); err != nil {
return err
}
if err := os.Rename(tmp, path); err != nil {
return err
}
ok = true
return nil
}
func copyFile(source, target string, mode os.FileMode) error {
in, err := os.Open(source)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, mode)
if err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
_ = out.Close()
return err
}
if err := out.Sync(); err != nil {
_ = out.Close()
return err
}
return out.Close()
}
func fileSHA(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
+77
View File
@@ -0,0 +1,77 @@
// SPDX-License-Identifier: AGPL-3.0-only
package packager
import (
"archive/tar"
"compress/gzip"
"errors"
"io"
"os"
"path/filepath"
"testing"
)
func TestVersionPattern(t *testing.T) {
for _, v := range []string{"v0.1.0-preview.1", "v12.3.4-preview.99"} {
if !versionPattern.MatchString(v) {
t.Errorf("rejected %q", v)
}
}
for _, v := range []string{"v0.1.0", "0.1.0-preview.1", "v0.1.0-preview.0", "v0.1.0-preview.01", "v0.1.0-preview.1+dirty"} {
if versionPattern.MatchString(v) {
t.Errorf("accepted %q", v)
}
}
}
func TestArchiveHasOnlyRegularBundleEntries(t *testing.T) {
dir := t.TempDir()
bundle := filepath.Join(dir, "bundle")
if err := os.Mkdir(bundle, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(bundle, "app"), []byte("binary"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(bundle, "RELEASE.json"), []byte("{}\n"), 0o644); err != nil {
t.Fatal(err)
}
archive := filepath.Join(dir, "out.tar.gz")
if err := writeArchive(archive, bundle, 1); err != nil {
t.Fatal(err)
}
f, err := os.Open(archive)
if err != nil {
t.Fatal(err)
}
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
t.Fatal(err)
}
defer gz.Close()
tr := tar.NewReader(gz)
seen := 0
for {
h, err := tr.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
t.Fatal(err)
}
if h.Name == "bundle/" {
continue
}
if h.Typeflag != tar.TypeReg {
t.Fatalf("unexpected type %d", h.Typeflag)
}
if filepath.IsAbs(h.Name) || filepath.Clean(h.Name) != h.Name {
t.Fatalf("unsafe path %q", h.Name)
}
seen++
}
if seen != 2 {
t.Fatalf("saw %d files", seen)
}
}
+72
View File
@@ -0,0 +1,72 @@
// SPDX-License-Identifier: AGPL-3.0-only
package process
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"sort"
"strings"
)
const maxOutput = 4 << 20
type Runner interface {
Run(ctx context.Context, dir string, env map[string]string, name string, args ...string) ([]byte, error)
}
type ExecRunner struct{}
func (ExecRunner) Run(ctx context.Context, dir string, env map[string]string, name string, args ...string) ([]byte, error) {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Dir = dir
cmd.Env = mergeEnv(os.Environ(), env)
var output limitedBuffer
cmd.Stdout = &output
cmd.Stderr = &output
err := cmd.Run()
if err != nil {
return output.Bytes(), fmt.Errorf("%s failed: %w: %s", name, err, strings.TrimSpace(output.String()))
}
return output.Bytes(), nil
}
type limitedBuffer struct{ bytes.Buffer }
func (b *limitedBuffer) Write(p []byte) (int, error) {
written := len(p)
remaining := maxOutput - b.Len()
if remaining > 0 {
if len(p) > remaining {
p = p[:remaining]
}
_, _ = b.Buffer.Write(p)
}
return written, nil
}
func mergeEnv(base []string, extra map[string]string) []string {
values := make(map[string]string, len(base)+len(extra))
for _, pair := range base {
key, value, ok := strings.Cut(pair, "=")
if ok {
values[key] = value
}
}
for key, value := range extra {
values[key] = value
}
keys := make([]string, 0, len(values))
for key := range values {
keys = append(keys, key)
}
sort.Strings(keys)
out := make([]string, 0, len(keys))
for _, key := range keys {
out = append(out, key+"="+values[key])
}
return out
}
+53
View File
@@ -0,0 +1,53 @@
// SPDX-License-Identifier: AGPL-3.0-only
package provenance
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"gamertan.com/tend/internal/process"
)
type Source struct {
Commit string
Epoch int64
}
func Inspect(ctx context.Context, runner process.Runner, dir, branch string) (Source, error) {
status, err := runner.Run(ctx, dir, nil, "git", "status", "--porcelain=v1", "--untracked-files=all")
if err != nil {
return Source{}, err
}
if len(status) != 0 {
return Source{}, errors.New("source checkout is not clean")
}
commitOut, err := runner.Run(ctx, dir, nil, "git", "rev-parse", "HEAD")
if err != nil {
return Source{}, err
}
commit := strings.TrimSpace(string(commitOut))
if len(commit) != 40 {
return Source{}, errors.New("source commit is not a full SHA-1 object id")
}
remoteOut, err := runner.Run(ctx, dir, nil, "git", "ls-remote", "--exit-code", "origin", "refs/heads/"+branch)
if err != nil {
return Source{}, fmt.Errorf("verify pushed commit: %w", err)
}
fields := strings.Fields(string(remoteOut))
if len(fields) != 2 || fields[0] != commit || fields[1] != "refs/heads/"+branch {
return Source{}, errors.New("HEAD is not the exact pushed branch commit")
}
epochOut, err := runner.Run(ctx, dir, nil, "git", "show", "-s", "--format=%ct", commit)
if err != nil {
return Source{}, err
}
epoch, err := strconv.ParseInt(strings.TrimSpace(string(epochOut)), 10, 64)
if err != nil || epoch <= 0 {
return Source{}, errors.New("commit timestamp is invalid")
}
return Source{Commit: commit, Epoch: epoch}, nil
}
+147
View File
@@ -0,0 +1,147 @@
// SPDX-License-Identifier: AGPL-3.0-only
package state
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
)
const SchemaVersion = 1
type Record struct {
SchemaVersion int `json:"schema_version"`
Strategy string `json:"strategy"`
ActiveSlot string `json:"active_slot"`
ActiveRelease string `json:"active_release"`
PreviousSlot string `json:"previous_slot,omitempty"`
PreviousRelease string `json:"previous_release,omitempty"`
UpdatedAt string `json:"updated_at"`
}
func Load(path, root, strategy string) (Record, error) {
b, err := os.ReadFile(path)
if err != nil {
return Record{}, err
}
dec := json.NewDecoder(bytes.NewReader(b))
dec.DisallowUnknownFields()
var record Record
if err := dec.Decode(&record); err != nil {
return Record{}, fmt.Errorf("decode state: %w", err)
}
var extra any
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
return Record{}, errors.New("state contains trailing data")
}
if err := record.Validate(root, strategy); err != nil {
return Record{}, err
}
return record, nil
}
func (r Record) Validate(root, strategy string) error {
if r.SchemaVersion != SchemaVersion {
return errors.New("state schema version is unsupported")
}
if r.Strategy != strategy {
return errors.New("state strategy does not match configuration")
}
if strategy == "blue_green" && (r.ActiveSlot != "blue" && r.ActiveSlot != "green") {
return errors.New("active slot is invalid")
}
if strategy == "singleton_candidate" && r.ActiveSlot != "singleton" {
return errors.New("singleton state slot is invalid")
}
if err := releaseBelow(root, r.ActiveRelease); err != nil {
return fmt.Errorf("active release: %w", err)
}
if r.PreviousRelease != "" {
if err := releaseBelow(root, r.PreviousRelease); err != nil {
return fmt.Errorf("previous release: %w", err)
}
}
if strategy == "blue_green" && r.PreviousRelease != "" && r.PreviousSlot == r.ActiveSlot {
return errors.New("previous slot must differ from active slot")
}
if _, err := time.Parse(time.RFC3339, r.UpdatedAt); err != nil {
return errors.New("state timestamp is invalid")
}
return nil
}
func Store(path, root string, record Record) error {
if err := record.Validate(root, record.Strategy); err != nil {
return err
}
if info, err := os.Lstat(path); err == nil && info.Mode()&os.ModeSymlink != 0 {
return errors.New("state file must not be a symlink")
} else if err != nil && !os.IsNotExist(err) {
return err
}
b, err := json.MarshalIndent(record, "", " ")
if err != nil {
return err
}
b = append(b, '\n')
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
tmp, err := os.CreateTemp(dir, ".tend-state-")
if err != nil {
return err
}
name := tmp.Name()
ok := false
defer func() {
_ = tmp.Close()
if !ok {
_ = os.Remove(name)
}
}()
if err := tmp.Chmod(0o644); err != nil {
return err
}
if _, err := tmp.Write(b); err != nil {
return err
}
if err := tmp.Sync(); err != nil {
return err
}
if err := tmp.Close(); err != nil {
return err
}
if err := os.Rename(name, path); err != nil {
return err
}
ok = true
return syncDir(dir)
}
func releaseBelow(root, path string) error {
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
return errors.New("must be a clean absolute path")
}
releases := filepath.Join(root, "releases")
rel, err := filepath.Rel(releases, path)
if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || strings.ContainsRune(rel, filepath.Separator) {
return errors.New("must be one direct child of the release directory")
}
return nil
}
func syncDir(path string) error {
dir, err := os.Open(path)
if err != nil {
return err
}
defer dir.Close()
return dir.Sync()
}
+45
View File
@@ -0,0 +1,45 @@
// SPDX-License-Identifier: AGPL-3.0-only
package state
import (
"os"
"path/filepath"
"testing"
"time"
)
func TestStoreLoadRoundTripAndRejectSymlink(t *testing.T) {
root := filepath.Join(t.TempDir(), "service")
release := filepath.Join(root, "releases", "sha256-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
if err := os.MkdirAll(release, 0o755); err != nil {
t.Fatal(err)
}
path := filepath.Join(root, "state.json")
record := Record{SchemaVersion: 1, Strategy: "singleton_candidate", ActiveSlot: "singleton", ActiveRelease: release, UpdatedAt: time.Unix(1, 0).UTC().Format(time.RFC3339)}
if err := Store(path, root, record); err != nil {
t.Fatal(err)
}
loaded, err := Load(path, root, "singleton_candidate")
if err != nil {
t.Fatal(err)
}
if loaded.ActiveRelease != release {
t.Fatalf("release=%q", loaded.ActiveRelease)
}
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(root, "elsewhere"), path); err != nil {
t.Fatal(err)
}
if err := Store(path, root, record); err == nil {
t.Fatal("expected symlink refusal")
}
}
func TestRecordRejectsReleaseOutsideRoot(t *testing.T) {
record := Record{SchemaVersion: 1, Strategy: "singleton_candidate", ActiveSlot: "singleton", ActiveRelease: "/tmp/other/release", UpdatedAt: time.Unix(1, 0).UTC().Format(time.RFC3339)}
if err := record.Validate("/opt/example", "singleton_candidate"); err == nil {
t.Fatal("expected path refusal")
}
}
+9
View File
@@ -0,0 +1,9 @@
// SPDX-License-Identifier: AGPL-3.0-only
package version
var (
Version = "v0.1.0-dev"
Commit = "unknown"
Date = "unknown"
)
+31
View File
@@ -0,0 +1,31 @@
{
"schema_version": 1,
"service": { "name": "tend", "allowed_host": "localhost" },
"build": {
"package": "./cmd/tend",
"binary": "tend",
"branch": "main",
"version_symbol": "gamertan.com/tend/internal/version.Version",
"commit_symbol": "gamertan.com/tend/internal/version.Commit",
"date_symbol": "gamertan.com/tend/internal/version.Date"
},
"deployment": {
"strategy": "singleton_candidate",
"root": "/opt/tend-release-test",
"lock_file": "/run/lock/tend-release-test.lock",
"state_file": "/opt/tend-release-test/tend-state.json",
"health_path": "/healthz",
"readiness_path": "/readyz",
"candidate_timeout_seconds": 5,
"smoke": [{ "path": "/", "contains": "Tend" }],
"singleton": {
"unit": "tend-release-test.service",
"address": "127.0.0.1:19090",
"candidate_address": "127.0.0.1:19091",
"listen_env": "TEND_RELEASE_TEST_LISTEN",
"environment": {},
"current_link": "/opt/tend-release-test/current",
"previous_link": "/opt/tend-release-test/previous"
}
}
}
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
set -euo pipefail
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
test -s "$root/LICENSE"
test -s "$root/COPYRIGHT"
test -s "$root/examples/LICENSE"
while IFS= read -r file; do
grep -Fq 'SPDX-License-Identifier: AGPL-3.0-only' "$file" || { echo "missing SPDX identifier: $file" >&2; exit 1; }
done < <(find "$root/cmd" "$root/internal" -type f -name '*.go' -print | LC_ALL=C sort)
echo "license boundaries verified"
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
set -euo pipefail
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
usage(){ echo "Usage: export-public.sh --destination ABSOLUTE-PATH" >&2; }
destination=
while [[ $# -gt 0 ]]; do
case $1 in
--destination) destination=$2; shift 2 ;;
*) usage; exit 2 ;;
esac
done
[[ $destination == /* && $destination != / && ! -e $destination ]] || { usage; exit 2; }
destination=$(realpath -m "$destination");root=$(realpath -e "$root")
case $destination/ in "$root"/*) echo "destination must be outside the private worktree" >&2;exit 1;;esac
git_dir_raw=$(git -C "$root" rev-parse --git-dir)
common_dir_raw=$(git -C "$root" rev-parse --git-common-dir)
[[ $git_dir_raw == /* ]] || git_dir_raw=$root/$git_dir_raw
[[ $common_dir_raw == /* ]] || common_dir_raw=$root/$common_dir_raw
git_dir=$(realpath -e "$git_dir_raw")
common_dir=$(realpath -e "$common_dir_raw")
case $destination/ in "$git_dir"/*|"$common_dir"/*) echo "destination must be outside Git metadata" >&2;exit 1;;esac
[[ -z $(git -C "$root" status --porcelain=v1 --untracked-files=all) ]] || { echo "private worktree is not clean" >&2;exit 1; }
commit=$(git -C "$root" rev-parse HEAD);tree=$(git -C "$root" rev-parse HEAD^{tree})
[[ $(git -C "$root" ls-remote --exit-code origin refs/heads/main | awk 'NR==1{print $1}') == "$commit" ]] || { echo "private HEAD is not exact pushed origin/main" >&2;exit 1; }
allow=$root/scripts/public-snapshot.allow
LC_ALL=C sort -c "$allow"
[[ $(LC_ALL=C sort "$allow" | uniq -d | wc -l) -eq 0 ]]
mapfile -t files <"$allow"
[[ ${#files[@]} -gt 0 ]]
for file in "${files[@]}"; do
[[ -n $file && $file != /* && $file != *..* && $file != .gitea/* && $file != .github/* ]]
git -C "$root" cat-file -e "$commit:$file"
done
parent=$(dirname "$destination")
mkdir -p "$parent"
stage=$(mktemp -d "$parent/.tend-public.XXXXXX")
trap 'rm -rf -- "$stage"' EXIT
git -C "$root" archive "$commit" -- "${files[@]}" | tar -xf - -C "$stage"
while IFS= read -r file; do
relative=${file#"$stage"/}
cmp "$file" "$root/$relative"
done < <(find "$stage" -type f -print | LC_ALL=C sort)
epoch=$(git -C "$root" show -s --format=%ct "$commit")
printf '{"schema_version":1,"source_commit":"%s","source_tree":"%s","source_date_epoch":%s,"file_count":%d}\n' "$commit" "$tree" "$epoch" "${#files[@]}" >"$stage/PUBLIC-SNAPSHOT.json"
(cd "$stage" && sha256sum PUBLIC-SNAPSHOT.json >PUBLIC-SNAPSHOT.sha256)
if (cd "$stage" && rg -n --hidden --glob '!.git/**' --glob '!PUBLIC-SNAPSHOT.json' --glob '!scripts/export-public.sh' '/home/cole|BEGIN (RSA|OPENSSH|EC) PRIVATE KEY|gitea-api\.token' .); then
echo "private material found" >&2
exit 1
fi
mv "$stage" "$destination"
trap - EXIT
printf 'destination=%s\nsource_commit=%s\nsource_tree=%s\n' "$destination" "$commit" "$tree"
+44
View File
@@ -0,0 +1,44 @@
.gitattributes
.gitignore
COPYRIGHT
LICENSE
README.md
RELEASE.md
SECURITY.md
cmd/tend/main.go
docs/ARCHITECTURE.md
docs/DOGFOOD_EVIDENCE.md
docs/PUBLIC_SNAPSHOT.md
docs/THREAT_MODEL.md
examples/LICENSE
examples/README.md
examples/blue-green/caddy-handler.template
examples/blue-green/example-site@.service
examples/blue-green/tend.json
examples/singleton/tend.json
go.mod
internal/config/config.go
internal/config/config_test.go
internal/deploy/deploy.go
internal/deploy/deploy_test.go
internal/deploy/lock_linux.go
internal/deploy/lock_other.go
internal/deploy/operator.go
internal/deploy/operator_test.go
internal/deploy/ownership_linux.go
internal/deploy/ownership_other.go
internal/deploy/release.go
internal/deploy/release_test.go
internal/packager/packager.go
internal/packager/packager_test.go
internal/process/run.go
internal/provenance/git.go
internal/state/state.go
internal/state/state_test.go
internal/version/version.go
release/tend.json
scripts/check-licenses.sh
scripts/export-public.sh
scripts/public-snapshot.allow
scripts/test-public-snapshot.sh
scripts/verify.sh
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
set -euo pipefail
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
work=$(mktemp -d)
trap 'rm -rf -- "$work"' EXIT
destination=$work/public
"$root/scripts/export-public.sh" --destination "$destination" >/dev/null
test -f "$destination/PUBLIC-SNAPSHOT.json"
test -f "$destination/PUBLIC-SNAPSHOT.sha256"
(cd "$destination" && sha256sum -c PUBLIC-SNAPSHOT.sha256)
test ! -e "$destination/.git"
test ! -e "$destination/.gitea"
test ! -e "$destination/.github"
while IFS= read -r file; do
cmp "$root/$file" "$destination/$file"
done <"$root/scripts/public-snapshot.allow"
echo "public snapshot isolation verified"
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: AGPL-3.0-only
set -euo pipefail
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
./scripts/check-licenses.sh
go test -count=1 ./...
go test -race -count=1 ./...
go vet ./...
for script in scripts/*.sh; do bash -n "$script"; done
work=$(mktemp -d); trap 'rm -rf -- "$work"' EXIT
GOWORK=off CGO_ENABLED=0 go build -mod=readonly -trimpath -o "$work/tend-1" ./cmd/tend
GOWORK=off CGO_ENABLED=0 go build -mod=readonly -trimpath -o "$work/tend-2" ./cmd/tend
cmp "$work/tend-1" "$work/tend-2"
"$work/tend-1" check --config "$root/examples/blue-green/tend.json" >/dev/null
"$work/tend-1" check --config "$root/examples/singleton/tend.json" >/dev/null
[[ $(GOWORK=off go list -m all | wc -l) -eq 1 ]]
git diff --check
echo "Tend verification passed"