docs: publish Preview 19 dogfood evidence

Export the reviewed allowlisted snapshot from private source commit 05928cebd01b586cf9e9d4b8c8537a7605a6068c. This records the exact candidate, bounded capacity result, stateful migration scratch requirement, authenticated batch identity proof, and immediate live acceptance evidence.

AI-Assisted: OpenAI Codex
Signed-off-by: Cole Speelman <crspeelman@gmail.com>
This commit is contained in:
2026-08-18 21:47:08 -04:00
commit 92a66db3df
201 changed files with 38227 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
# SPDX-License-Identifier: AGPL-3.0-only
* text=auto
*.go text eol=lf
*.sando text eol=lf
*.sh text eol=lf
*.md text eol=lf
*.json text eol=lf
*.svg text eol=lf
*.css text eol=lf
*.js text eol=lf
LICENSE text eol=lf
+11
View File
@@ -0,0 +1,11 @@
# SPDX-License-Identifier: AGPL-3.0-only
/bin/
/dist/
/.cache/
*.local.json
*.db
*.db-shm
*.db-wal
/test/browser/node_modules/
/test/browser/playwright-report/
/test/browser/test-results/
+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/>.
+20
View File
@@ -0,0 +1,20 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Licence map
| Path | Licence |
| --- | --- |
| Go application and internal packages | AGPL-3.0-only |
| `scripts/`, `.gitea/`, documentation, and release machinery | AGPL-3.0-only |
| `examples/` | 0BSD |
| Browser campaign source and tooling | AGPL-3.0-only |
The browser campaign pins Apache-2.0-licensed Playwright as a development-only
dependency. Its optional macOS watcher is MIT-licensed. Neither is linked into
or packaged with the Observatory binary.
Every text source file carries an SPDX identifier or, where strict JSON cannot
accept comments, a matching `.license` sidecar or machine-readable licence
field. Generated Sandwich Hime outputs inherit the licence of their adjacent
`.sando` source and retain exact generator provenance. The complete AGPL and
0BSD licence texts are included in `LICENSE` and `examples/LICENSE`.
+1
View File
@@ -0,0 +1 @@
{"schema_version":1,"source_commit":"05928cebd01b586cf9e9d4b8c8537a7605a6068c","source_tree":"4f1a87967c842c19141c03018e9350261f4d2a50","source_date_epoch":1787103921,"file_count":199}
+1
View File
@@ -0,0 +1 @@
4757b0ca0e9ae9930006510bc1e277d8adb4398abf7b27b271704028dee7d5fb PUBLIC-SNAPSHOT.json
+159
View File
@@ -0,0 +1,159 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Gamertan Observatory
Gamertan Observatory is a self-hosted, organization-aware observability platform in active private development. It is being built for logs, metrics, traces, incidents, and deployment evidence on modest Linux servers.
This repository currently contains the first security and durability vertical slice. It is not a public preview yet.
## Current development surface
- strict, versioned server configuration;
- organization/project/environment/service-scoped ingestion sources;
- hashed, rotatable source credentials;
- bounded log, metric, trace, and deployment batches;
- immutable checksummed zstd raw segments committed before acknowledgement,
with an atomic cold forensic tier instead of destructive hot-window expiry;
- SQLite control state and independently migratable per-organization projections;
- sequence deduplication, replay rejection, and crash recovery;
- enforced organization-aware hot/cold retention, crash-recoverable archival,
indefinite forensic preservation by default, explicitly enabled final
retirement, projection compaction, budgeted cold queries, and
queryable five-minute metric rollups;
- an exact five-minute HTTP-status/normalized-route log projection for the
common error-count view, with one bounded raw fragment at an unaligned time
boundary rather than a whole-window rescan;
- an offline, explicitly approved per-organization projection rebuild that
validates checksummed raw truth, rebuilds activated descriptors beside the
live database, and atomically replaces only the disposable projection;
- pinned Web Foundations `v0.1.0-preview.3` users, secure sessions,
personal organizations, teams, invitations, and scoped access grants;
- local single-use operator bootstrap with an application-generated one-time
credential, mandatory password replacement, and transactional session
revocation; platform operation remains deliberately separated from
telemetry access;
- a typed, bounded query AST and parser;
- one validated AST shared by text and visual-builder inputs, including safe
regular expressions, aggregates, grouping, windows, sorting, and limits;
- explain planning that injects resource scope independently, resolves field
descriptors, reports indexes and estimated scan, enforces budgets, and
requires a separate permission for sensitive or unknown fields;
- bounded typed execution over per-organization projections, including
filters, safe regular expressions, lookback windows, aggregation buckets,
grouping, exact raw-sample percentiles, explicitly marked approximate
rollup percentiles, sorting, and stable tabular results;
- same-origin session, health, readiness, native ingestion, query-parse,
query-explain, and authenticated query-execution HTTP endpoints;
- strict agent configuration, private outage spooling, and HTTPS delivery;
- continuous bounded file tailing with durable cursors, truncation/rename
handling, independent stream ordering, and crash recovery from spool
checkpoints;
- short-lived, single-use, scope-bound agent enrollment and self-revocation if
a newly issued credential cannot be persisted;
- whitelist-only adapters for Caddy access JSON, Web Foundations requestlog
JSONL, and Tend deployment events; minimized defaults omit queries,
addresses, referrers, user agents, cookies, credentials, and arbitrary
fields, while explicitly configured privacy-policy-backed fields remain
bounded and individually selectable.
- authenticated OTLP/HTTP protobuf endpoints for logs, metrics, and traces,
with bounded identity/gzip decoding, source-owned scope, secret-key
deny rules, typed signal conversion, and automatic per-stream sequencing.
- unprivileged Linux host metrics from bounded `/proc`, cgroup v2, named
filesystems, and explicitly selected PID files; no shell, root agent,
Docker socket, environment read, or command-line capture is involved.
- idempotent per-organization descriptor proposals aggregated once per raw
segment; unknown fields remain sensitive, high-cardinality, and unindexed
until an organization owner reviews them;
- explicit descriptor activation from a strict private review file, with each
custom index built beside the active per-organization version and switched
atomically; prior index versions remain intact and later ingestion follows
the active descriptor registry;
- versioned saved queries and dashboard definitions with organization-scoped
panel references, optimistic revisions, server-generated identifiers, and a
source-control export that omits tenant and operator runtime metadata;
- authorized CLI export and explicitly approved atomic import of those strict
dashboard bundles, with all destination identities and resource scopes
independently revalidated;
- a server-rendered Sandwich Hime interface for public orientation, local
sign-in, organization selection, recent log/metric/trace/deployment tables,
typed-text and assisted saved-query creation, one-panel dashboard creation,
bounded dashboard execution, accessible visual summaries with full table
alternatives, and strict source-control-safe JSON export;
- a bounded organization-authorized SSE invalidation channel that carries only
generic refresh events; the interface, tables, navigation, and sign-out flow
remain functional without JavaScript;
- durable organization-scoped alert rules that execute bounded saved-query
ASTs, open incidents after configurable consecutive matches, and preserve
pending, firing, acknowledged, silenced, and resolved lifecycle events;
- an accessible server-rendered incident inbox with ordinary CSRF-protected
response forms and no telemetry or incident detail in SSE payloads;
- an installable PWA shell, application badge state, and an explicit opt-in
read-only offline incident snapshot that excludes response capabilities and
high-risk private fields;
- optional privacy-preserving Web Push with an explicit user gesture,
organization-scoped subscriptions, delivery-time authorization, a bounded
non-blocking queue, and one fixed generic encrypted message;
- content-addressed static assets and a strict CSP with no inline-style or
inline-script exception; the production Sandwich Hime dependency boundary
contains only the pinned Apache-2.0 Sando runtime, not the Hime-san compiler.
- a Tend schema-2 singleton deployment contract with a stateless, loopback-only
candidate that cannot open or mutate Observatory data, followed by routed
public-origin validation and automatic last-good restoration.
The server injects resource scope from an authenticated source. Payloads cannot select an organization or resource. Unknown fields remain stored in raw truth, but are not indexed by default.
## Deliberate current limits
Self-service invitation delivery is deliberately excluded from the first
preview, and the visual query builder remains deliberately smaller than the
complete typed query language. Tend activation, rollback, and identical-
artifact redeployment have been exercised against the live Observatory
service. The separate medium-fleet agent soak and browser-vendor Web Push
delivery evidence are not complete. No release tag should be created until the
published preview gates in `docs/ROADMAP.md` are satisfied.
## Development
```sh
./scripts/preview-gate.sh
```
Linux is the supported deployment platform. Development requires Go 1.26.6 with `GOTOOLCHAIN=local`.
The local first-operator procedure is documented in
[`docs/BOOTSTRAP.md`](docs/BOOTSTRAP.md). It is a development surface, not yet
a public-preview installation promise.
The typed text/builder query contract and authorized local workflow are
documented in [`docs/QUERY.md`](docs/QUERY.md).
Descriptor discovery and its current review boundary are documented in
[`docs/SCHEMA.md`](docs/SCHEMA.md).
Retention, approved per-organization overrides, quota enforcement, and metric
rollup behavior are documented in [`docs/RETENTION.md`](docs/RETENTION.md).
The bounded preview gate includes the complete verifier, short fuzz smoke, and
a development capacity proof. Extended security, release-scale capacity, fleet,
and soak campaigns remain explicit milestone evidence. See
[`docs/CAPACITY.md`](docs/CAPACITY.md).
The retained optimization ledger and ordered lower-level storage case studies
are documented in [`docs/PERFORMANCE.md`](docs/PERFORMANCE.md).
The proposed raw-first, lazy/eager time-partitioned read model is documented as
an unimplemented design in
[`docs/ADAPTIVE_PROJECTIONS.md`](docs/ADAPTIVE_PROJECTIONS.md).
The persisted dashboard model and export boundary are documented in
[`docs/DASHBOARDS.md`](docs/DASHBOARDS.md).
The current Sandwich Hime interface and progressive-enhancement boundary are
documented in [`docs/INTERFACE.md`](docs/INTERFACE.md).
The bounded rule evaluator and durable response lifecycle are documented in
[`docs/INCIDENTS.md`](docs/INCIDENTS.md).
The installable shell and opt-in offline privacy boundary are documented in
[`docs/PWA.md`](docs/PWA.md).
The strict, non-authoritative Tend deployment-evidence boundary is documented
in [`docs/TEND.md`](docs/TEND.md).
The application deployment and isolated candidate boundary are documented in
[`docs/DEPLOYMENT.md`](docs/DEPLOYMENT.md).
Offline corruption recovery and projection rebuild are documented in
[`docs/RECOVERY.md`](docs/RECOVERY.md).
## Licensing
Application, agent, query, storage, migration, and release code is AGPL-3.0-only. Copyable files under `examples/` are 0BSD. See `LICENSES.md`.
+110
View File
@@ -0,0 +1,110 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Security policy
Observatory is pre-release software and has no supported public version yet. Please report suspected vulnerabilities privately to `security@sandwichhime.com`. Do not include credentials, production telemetry, raw request bodies, personal data, or exploit traffic in an initial report.
The maintainer aims to acknowledge a report within three business days, provide an initial triage within seven business days, and send progress updates at least every fourteen days. These are best-effort targets, not a service-level agreement or bounty promise.
## Current trust boundary
Agents, server operators, enrolled source configuration, the host kernel, SQLite, and the pinned Go dependency graph are trusted. Telemetry payloads, compressed input, query text, files being tailed, archive paths, and network peers are untrusted.
Current demonstrated controls include:
- source scope is loaded from a hashed credential rather than payload fields;
- production configuration and credentials remain absolute, root-owned,
mode-`0600` regular files; the unprivileged agent consumes systemd-provided
runtime copies confined to `CREDENTIALS_DIRECTORY`;
- decompressed input, batches, records, attributes, query stages, rows, memory, time, and scanned bytes have explicit bounds;
- OTLP/HTTP authenticates a source before parsing, accepts protobuf over
identity or gzip only, independently caps compressed and decompressed bytes,
discards known credential-bearing attribute keys, and derives tenant scope
exclusively from the enrolled source;
- raw segments are checksummed, compressed, synchronized, and atomically renamed before acknowledgement;
- sequence gaps, old replay, and altered duplicate sequences fail closed;
- organization projections are separate SQLite files;
- control and projection databases, SQLite sidecars, process locks, agent
state, spool entries, tailed files, and reviewed descriptors reject
symlinks; database and lock files also reject additional hard links;
- live commands hold a shared data-directory lock while offline migration and
projection replacement require exclusive ownership;
- error responses do not echo source values;
- browser sessions use opaque digest-backed credentials in Secure, HttpOnly,
`SameSite=Strict`, `__Host-` cookies. Ordinary HTML forms require a
purpose-bound CSRF token; JSON and JavaScript endpoints independently
require canonical same-origin evidence;
- platform operator permission grants no telemetry access; query planning
separately checks an organization/resource-scoped grant and sensitive-field
permission;
- invitations are single-use and expiring, team grants remain organization
scoped, revoked bindings stop authorizing, and short-lived break-glass
access creates an organization-visible append-only audit event;
- first-operator bootstrap is local and serialized by an OS lock. The primary
flow generates a one-time credential into a new mode-`0600`, non-symlink
file; the account cannot use application or API features until replacing
that credential, which revokes every session and requires a fresh login;
- administrative credential recovery is local-only and creates a new private
file rather than accepting a password argument. Credential replacement,
mandatory rotation, all-session revocation, and a secret-free audit event
commit atomically; Observatory exposes no public reset endpoint;
- every HTML form uses an ordinary server POST and a session- or cookie-bound
purpose token as its primary CSRF proof. Origin and Fetch Metadata provide a
second contradiction check: explicit cross-site evidence and tokenless
requests fail closed, while absent or opaque browser metadata cannot strand
a valid server-rendered form;
- initial file adapters use positive field whitelists and remove query strings,
credentials, cookies, client addresses, bodies, and arbitrary headers before
durable agent spooling;
- Linux metrics read a fixed bounded file set without shell execution,
enumerate no processes, require explicit PID-file/cgroup/filesystem
selectors, reject symlink sources, and retain stable configured names rather
than local paths, command lines, environments, or raw PIDs;
- spool deletion requires the local content digest and a path beneath the
private pending root.
- collected file records advance only after an envelope containing the next
cursor is durably spooled; discarded complete records advance only after the
cursor and bounded counters are saved, and startup repairs cursors from
pending envelopes before reading more source bytes;
- collectors refuse symlink sources, cap one cycle's read work, preserve
partial lines, and detect truncation and same-directory inode rotation;
- enrollment tokens are hashed, short-lived, scope-bound, single-use, and
exchanged over a redirect-refusing HTTPS client; a source credential can
revoke itself when local persistence fails;
- visual and textual queries share one validated AST; organization scope is a
separate planner input, unknown fields require sensitive-data permission,
projection files are opened in query-only mode, and execution enforces
independent time, decoded-byte, memory, and result-row budgets.
- unknown fields generate only idempotent per-segment proposal counts, byte
estimates, inferred types, and generic example queries; proposals retain no
observed values, default to sensitive/unindexed, and require an independent
organization-scoped schema-management permission to review; batches with
more than 1,024 distinct attribute keys are rejected before raw commit.
- reviewed descriptor files are bounded, strict JSON held in private regular
non-symlink files; activation caps the active descriptor registry, validates
typed values without coercing failures, builds a new index beside the live
version, and atomically switches only after the complete build succeeds;
ingestion and activation coordinate per organization, and prior versions
remain intact.
- saved query text is bounded and parsed before storage, its versioned typed
AST is revalidated against the text on every read, and dashboard panel
foreign keys include the organization boundary; optimistic revisions reject
lost updates, and dashboard exports omit organization/operator runtime
metadata.
- an approved offline rebuild reads every organization segment through the
checksum-verifying raw store, reconstructs base and activated descriptor
projections beside live, and atomically replaces only that organization's
disposable projection; corrupt raw truth fails closed before activation.
- PWA offline incident snapshots require an explicit browser action and omit
response capabilities and high-risk fields; optional Web Push reauthorizes
at delivery and encrypts one fixed generic sentence through a bounded,
non-blocking queue.
This is a maintainer self-assessment, not an independent audit. Invitation UI,
the real-browser PWA campaign, production deployment, and the capacity/fleet
soak remain unfinished and must not be described as supported yet. Bootstrap
is intentionally single-use; a storage failure after the user row is
committed but before all personal-organization grants complete currently
requires restoring the empty control database before retrying. The current
executable evidence map is in
[`docs/SECURITY_CAMPAIGN.md`](docs/SECURITY_CAMPAIGN.md).
+1607
View File
@@ -0,0 +1,1607 @@
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"bytes"
"context"
"crypto/ecdh"
"crypto/rand"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"net/netip"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
obsagent "gamertan.com/observatory/internal/agent"
"gamertan.com/observatory/internal/agentclient"
"gamertan.com/observatory/internal/config"
"gamertan.com/observatory/internal/httpserver"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/query"
"gamertan.com/observatory/internal/schema"
"gamertan.com/observatory/internal/storage"
"gamertan.com/observatory/internal/version"
"gamertan.com/observatory/internal/webpush"
"gamertan.com/web/access"
"gamertan.com/web/auth"
"gamertan.com/web/organizations"
)
func main() {
if err := run(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, "observatory:", err)
os.Exit(1)
}
}
func run(args []string) error {
if len(args) == 0 {
if address := os.Getenv("OBSERVATORY_TEND_CANDIDATE_LISTEN"); address != "" {
return serveTendCandidate(address)
}
return errors.New("command required: check, server, agent, admin, migrate, query, export, import, version")
}
switch args[0] {
case "version":
fs := flag.NewFlagSet("version", flag.ContinueOnError)
asJSON := fs.Bool("json", false, "print machine-readable version information")
if err := fs.Parse(args[1:]); err != nil {
return err
}
info := version.Current()
if *asJSON {
return json.NewEncoder(os.Stdout).Encode(info)
}
fmt.Printf("observatory %s (%s, %s)\n", info.Version, info.Commit, info.Go)
return nil
case "check":
cfg, err := commandConfig(args[0], args[1:])
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
if err := store.Recover(context.Background()); err != nil {
return err
}
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
fmt.Println("ok")
return nil
case "migrate":
return migrateCommand(args[1:])
case "server":
cfg, err := commandConfig("server", args[1:])
if err != nil {
return err
}
return serve(cfg)
case "admin":
return adminCommand(args[1:])
case "agent":
return agentCommand(args[1:])
case "query":
return queryCommand(args[1:])
case "export":
return exportCommand(args[1:])
case "import":
return importCommand(args[1:])
default:
return fmt.Errorf("unknown command %q", args[0])
}
}
func serveTendCandidate(value string) error {
address, err := netip.ParseAddrPort(value)
if err != nil || !address.Addr().IsLoopback() || address.Port() == 0 {
return errors.New("OBSERVATORY_TEND_CANDIDATE_LISTEN must be a loopback IP address with a nonzero port")
}
server := &http.Server{
Addr: address.String(),
Handler: tendCandidateHandler(),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 30 * time.Second,
MaxHeaderBytes: 16 << 10,
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
result := make(chan error, 1)
go func() { result <- server.ListenAndServe() }()
select {
case listenErr := <-result:
if errors.Is(listenErr, http.ErrServerClosed) {
return nil
}
return listenErr
case <-ctx.Done():
shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return server.Shutdown(shutdown)
}
}
func tendCandidateHandler() http.Handler {
const marker = "Gamertan Observatory candidate\n"
plain := func(body string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body)))
if r.Method != http.MethodHead {
_, _ = io.WriteString(w, body)
}
}
}
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", plain("ok\n"))
mux.HandleFunc("HEAD /healthz", plain("ok\n"))
mux.HandleFunc("GET /readyz", plain("ready\n"))
mux.HandleFunc("HEAD /readyz", plain("ready\n"))
mux.HandleFunc("GET /{$}", plain(marker))
mux.HandleFunc("HEAD /{$}", plain(marker))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Security-Policy", "default-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'")
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
w.Header().Set("Permissions-Policy", "camera=(), geolocation=(), microphone=()")
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("X-Content-Type-Options", "nosniff")
mux.ServeHTTP(w, r)
})
}
func exportCommand(args []string) error {
fs := flag.NewFlagSet("export", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow a non-root config owner for local development")
actor := fs.String("actor-user-id", "", "authorized user exporting the dashboard")
organizationID := fs.String("organization-id", "", "organization identifier")
dashboard := fs.String("dashboard", "", "dashboard slug")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("export accepts no positional arguments")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
scope := access.Scope{OrganizationID: *organizationID}
if err = identities.ValidateResourceScope(context.Background(), scope); err != nil {
return err
}
decision, err := identities.Access.Authorize(context.Background(), *actor, scope, identity.PermissionDashboardsRead)
if err != nil {
return err
}
if !decision.Allowed {
return errors.New("actor is not authorized to export dashboards for the requested organization")
}
bundle, err := store.ExportDashboard(context.Background(), *organizationID, *dashboard)
if err != nil {
return err
}
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
return encoder.Encode(bundle)
}
func importCommand(args []string) error {
fs := flag.NewFlagSet("import", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow a non-root config owner for local development")
actor := fs.String("actor-user-id", "", "authorized user importing the dashboard")
organizationID := fs.String("organization-id", "", "destination organization identifier")
approveOrganization := fs.String("approve-organization", "", "exact destination organization identifier approving the import")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("import accepts no positional arguments; provide one dashboard bundle on stdin")
}
if *organizationID == "" || *approveOrganization != *organizationID {
return errors.New("dashboard import requires the exact organization identifier in approve-organization")
}
bundle, err := readDashboardBundle(os.Stdin)
if err != nil {
return err
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
scope := access.Scope{OrganizationID: *organizationID}
if err = identities.ValidateResourceScope(context.Background(), scope); err != nil {
return err
}
decision, err := identities.Access.Authorize(context.Background(), *actor, scope, identity.PermissionDashboardsManage)
if err != nil {
return err
}
if !decision.Allowed {
return errors.New("actor is not authorized to import dashboards for the requested organization")
}
for _, definition := range bundle.SavedQueries {
requested := access.Scope{OrganizationID: *organizationID, ProjectID: definition.Scope.ProjectID, EnvironmentID: definition.Scope.EnvironmentID, ServiceID: definition.Scope.ServiceID}
if err = identities.ValidateResourceScope(context.Background(), requested); err != nil {
return errors.New("dashboard import references an unavailable resource scope")
}
}
imported, err := store.ImportDashboard(context.Background(), storage.DashboardImportInput{OrganizationID: *organizationID, ActorUserID: *actor, MaxRows: cfg.Query.MaxRows, Bundle: bundle}, time.Now().UTC())
if err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(struct {
Version int `json:"version"`
OrganizationID string `json:"organization_id"`
DashboardID string `json:"dashboard_id"`
Slug string `json:"slug"`
}{storage.DashboardVersion, imported.OrganizationID, imported.ID, imported.Slug})
}
func readDashboardBundle(reader io.Reader) (storage.DashboardExport, error) {
const maximum = 1 << 20
body, err := io.ReadAll(io.LimitReader(reader, maximum+1))
if err != nil || len(body) > maximum {
return storage.DashboardExport{}, errors.New("dashboard import must contain one JSON value no larger than 1 MiB")
}
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
var bundle storage.DashboardExport
if err = decoder.Decode(&bundle); err != nil {
return storage.DashboardExport{}, errors.New("dashboard import JSON is invalid")
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return storage.DashboardExport{}, errors.New("dashboard import must contain one JSON value no larger than 1 MiB")
}
return bundle, nil
}
func migrateCommand(args []string) error {
fs := flag.NewFlagSet("migrate", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow a non-root config owner for local development")
rebuildOrganization := fs.String("rebuild-organization", "", "organization projection to rebuild from raw truth")
approveRebuildOrganization := fs.String("approve-rebuild-organization", "", "exact organization identifier approving destructive projection replacement")
applyRetention := fs.Bool("apply-retention", false, "apply configured retention and compaction after recovery")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("migrate accepts no positional arguments")
}
if *rebuildOrganization == "" && *approveRebuildOrganization != "" {
return errors.New("approve-rebuild-organization requires rebuild-organization")
}
if *rebuildOrganization != "" && *approveRebuildOrganization != *rebuildOrganization {
return errors.New("projection rebuild requires the exact organization identifier in approve-rebuild-organization")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, true)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
var report *storage.RebuildReport
var retentionReport *storage.RetentionReport
if *rebuildOrganization != "" {
rebuilt, rebuildErr := store.RebuildOrganization(context.Background(), *rebuildOrganization, time.Now().UTC())
if rebuildErr != nil {
return rebuildErr
}
report = &rebuilt
}
if err = store.Recover(context.Background()); err != nil {
return err
}
if *applyRetention {
retained, retentionErr := store.ApplyRetention(context.Background(), retentionPolicy(cfg), time.Now().UTC())
if retentionErr != nil {
return retentionErr
}
retentionReport = &retained
}
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
if *applyRetention {
if _, err = identities.PruneEvidence(context.Background(), cfg.Retention.EvidenceDays, time.Now().UTC()); err != nil {
return err
}
}
if report != nil && retentionReport != nil {
return json.NewEncoder(os.Stdout).Encode(struct {
Rebuild *storage.RebuildReport `json:"rebuild"`
Retention *storage.RetentionReport `json:"retention"`
}{report, retentionReport})
}
if report != nil {
return json.NewEncoder(os.Stdout).Encode(report)
}
if retentionReport != nil {
return json.NewEncoder(os.Stdout).Encode(retentionReport)
}
fmt.Println("ok")
return nil
}
func queryCommand(args []string) error {
fs := flag.NewFlagSet("query", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root config ownership for local development")
actor := fs.String("actor-user-id", "", "authorized user executing the local query")
organizationID := fs.String("organization-id", "", "organization identifier")
projectID := fs.String("project-id", "", "optional project identifier")
environmentID := fs.String("environment-id", "", "optional environment identifier")
serviceID := fs.String("service-id", "", "optional service identifier")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("query accepts no positional arguments; provide query text on stdin")
}
text, err := io.ReadAll(io.LimitReader(os.Stdin, 16_385))
if err != nil || len(text) > 16_384 {
return errors.New("query input exceeds 16384 bytes")
}
ast, err := query.Parse(strings.TrimSpace(string(text)), 10_000)
if err != nil {
return err
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
requested := access.Scope{OrganizationID: *organizationID, ProjectID: *projectID, EnvironmentID: *environmentID, ServiceID: *serviceID}
decision, err := identities.Access.Authorize(context.Background(), *actor, requested, identity.PermissionTelemetryQuery)
if err != nil {
return err
}
if !decision.Allowed {
return errors.New("actor is not authorized to query the requested scope")
}
if err = identities.ValidateResourceScope(context.Background(), requested); err != nil {
return err
}
sensitive, err := identities.Access.Authorize(context.Background(), *actor, requested, identity.PermissionTelemetryReadSensitive)
if err != nil {
return err
}
result, err := store.Query(context.Background(), ast, query.Scope{
OrganizationID: *organizationID, ProjectID: *projectID,
EnvironmentID: *environmentID, ServiceID: *serviceID,
Sensitive: sensitive.Allowed,
}, query.Budget{MaxDuration: cfg.Query.MaxDuration, MaxRows: cfg.Query.MaxRows, MaxScannedBytes: cfg.Query.MaxScannedBytes, MaxMemoryBytes: cfg.Query.MaxMemoryBytes}, time.Now().UTC())
if err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(result)
}
func agentCommand(args []string) error {
if len(args) > 0 && args[0] == "enroll" {
return agentEnrollCommand(args[1:])
}
fs := flag.NewFlagSet("agent", flag.ContinueOnError)
path := fs.String("config", "/etc/gamertan-observatory/agent.json", "absolute agent configuration path")
credentialPath := fs.String("credential-file", "", "absolute credential path overriding credential_file")
systemdCredentials := fs.Bool("systemd-credentials", false, "read config and credential from CREDENTIALS_DIRECTORY")
once := fs.Bool("once", false, "run one collect-and-deliver cycle")
unsafeOwner := fs.Bool("development-allow-nonroot-config", false, "allow non-root config and credential ownership for local development")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("agent accepts no positional arguments")
}
policy := config.FilePolicy{RequireRoot: !*unsafeOwner}
if *systemdCredentials {
if *unsafeOwner {
return errors.New("systemd-credentials and development-allow-nonroot-config are mutually exclusive")
}
var err error
policy, err = config.SystemdCredentialPolicy()
if err != nil {
return err
}
}
cfg, err := config.LoadAgent(*path, policy)
if err != nil {
return err
}
selectedCredentialPath := cfg.CredentialFile
if *credentialPath != "" {
selectedCredentialPath = *credentialPath
}
credential, err := config.LoadCredential(selectedCredentialPath, policy)
if err != nil {
return err
}
runner, err := obsagent.Open(cfg, credential, nil)
if err != nil {
return err
}
if *once {
return runner.RunOnce(context.Background(), time.Now().UTC())
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
ticker := time.NewTicker(cfg.FlushEvery)
defer ticker.Stop()
for {
if err = runner.RunOnce(ctx, time.Now().UTC()); err != nil && !errors.Is(err, context.Canceled) {
log.Printf("observatory agent cycle: %v", err)
}
select {
case <-ctx.Done():
return nil
case <-ticker.C:
}
}
}
func agentEnrollCommand(args []string) error {
fs := flag.NewFlagSet("agent enroll", flag.ContinueOnError)
path := fs.String("config", "/etc/gamertan-observatory/agent.json", "absolute agent configuration path")
enrollmentFile := fs.String("enrollment-file", "", "absolute private enrollment-token file")
unsafeOwner := fs.Bool("development-allow-nonroot-config", false, "allow non-root config and enrollment ownership for local development")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("agent enroll accepts no positional arguments")
}
cfg, err := config.LoadAgent(*path, config.FilePolicy{RequireRoot: !*unsafeOwner})
if err != nil {
return err
}
token, err := config.LoadEnrollmentToken(*enrollmentFile, config.FilePolicy{RequireRoot: !*unsafeOwner})
if err != nil {
return err
}
result, err := agentclient.Enroll(context.Background(), cfg.ServerURL, token, nil)
if err != nil {
return err
}
if err = config.WriteCredential(cfg.CredentialFile, result.Credential); err != nil {
if revokeErr := agentclient.RevokeSource(context.Background(), cfg.ServerURL, result.Credential, nil); revokeErr != nil {
return fmt.Errorf("persist enrolled credential: %w; automatic source revocation also failed: %v", err, revokeErr)
}
return fmt.Errorf("persist enrolled credential: %w; enrolled source was revoked", err)
}
return json.NewEncoder(os.Stdout).Encode(struct {
SourceID string `json:"source_id"`
}{result.SourceID})
}
type serverConfigFlags struct {
path *string
allowNonRoot *bool
systemdCredential *bool
}
func addServerConfigFlags(fs *flag.FlagSet, developmentHelp string) serverConfigFlags {
return serverConfigFlags{
path: fs.String("config", "/etc/gamertan-observatory/server.json", "absolute server configuration path"),
allowNonRoot: fs.Bool("development-allow-nonroot-config", false, developmentHelp),
systemdCredential: fs.Bool("systemd-credential-config", false, "load the server configuration from CREDENTIALS_DIRECTORY"),
}
}
func (flags serverConfigFlags) load() (config.Server, error) {
if *flags.allowNonRoot && *flags.systemdCredential {
return config.Server{}, errors.New("development non-root configuration and systemd credentials are mutually exclusive")
}
policy := config.FilePolicy{RequireRoot: !*flags.allowNonRoot}
if *flags.systemdCredential {
var err error
policy, err = config.SystemdCredentialPolicy()
if err != nil {
return config.Server{}, err
}
}
return config.LoadServer(*flags.path, policy)
}
func (flags serverConfigFlags) requireRootAuxiliaryFile() bool {
return !*flags.allowNonRoot
}
func commandConfig(name string, args []string) (config.Server, error) {
fs := flag.NewFlagSet(name, flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow a non-root config owner for local development")
if err := fs.Parse(args); err != nil {
return config.Server{}, err
}
if fs.NArg() != 0 {
return config.Server{}, fmt.Errorf("%s accepts no positional arguments", name)
}
return configFlags.load()
}
func optionalPushDispatcher(notifier *webpush.Notifier) httpserver.PushDispatcher {
if notifier == nil {
return nil
}
return notifier
}
func serve(cfg config.Server) error {
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
if err := store.RecoverRaw(context.Background()); err != nil {
return err
}
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
var pushNotifier *webpush.Notifier
var pushPublicKey string
if cfg.WebPush != nil {
pushSender, senderErr := webpush.New(webpush.Options{PrivateKey: cfg.WebPush.PrivateKey, Subject: cfg.WebPush.Subject, Timeout: cfg.WebPush.Timeout})
if senderErr != nil {
return senderErr
}
pushNotifier, err = webpush.NewNotifier(store, identities.Access, pushSender, cfg.WebPush.QueueCapacity)
if err != nil {
return err
}
pushPublicKey = pushSender.PublicKey()
}
application, err := httpserver.New(store, identities, httpserver.Options{
PublicOrigin: cfg.PublicURL, MaxBodyBytes: cfg.MaxBodyBytes, MaxConcurrentIngest: cfg.MaxConcurrentIngest,
MaxQueryRows: cfg.Query.MaxRows, SessionLifetime: cfg.SessionLifetime,
QueryBudget: query.Budget{MaxDuration: cfg.Query.MaxDuration, MaxRows: cfg.Query.MaxRows, MaxScannedBytes: cfg.Query.MaxScannedBytes, MaxMemoryBytes: cfg.Query.MaxMemoryBytes},
PushPublicKey: pushPublicKey, PushDispatcher: optionalPushDispatcher(pushNotifier),
})
if err != nil {
return err
}
handler := application.Handler()
server := &http.Server{Addr: cfg.Listen, Handler: handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second, IdleTimeout: 90 * time.Second, MaxHeaderBytes: 32 << 10}
listener, err := net.Listen("tcp", cfg.Listen)
if err != nil {
return fmt.Errorf("listen: %w", err)
}
defer listener.Close()
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
backgroundJobs := make([]func(context.Context), 0, 4)
backgroundJobs = append(backgroundJobs, func(background context.Context) {
store.RunProjector(background, time.Second, func(error) {
log.Print("observatory projection temporarily unavailable")
})
})
if pushNotifier != nil {
backgroundJobs = append(backgroundJobs, pushNotifier.Run)
}
backgroundJobs = append(backgroundJobs, func(background context.Context) {
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
apply := func(now time.Time) {
if _, retentionErr := store.ApplyRetention(background, retentionPolicy(cfg), now.UTC()); retentionErr != nil && !errors.Is(retentionErr, context.Canceled) {
log.Print("observatory retention unavailable")
}
if _, retentionErr := identities.PruneEvidence(background, cfg.Retention.EvidenceDays, now.UTC()); retentionErr != nil && !errors.Is(retentionErr, context.Canceled) {
log.Print("observatory identity retention unavailable")
}
}
apply(time.Now())
for {
select {
case <-background.Done():
return
case now := <-ticker.C:
apply(now)
}
}
})
backgroundJobs = append(backgroundJobs, func(background context.Context) {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for {
if _, evaluationErr := application.EvaluateAlerts(background); evaluationErr != nil && !errors.Is(evaluationErr, context.Canceled) {
log.Print("observatory alert evaluation unavailable")
}
select {
case <-background.Done():
return
case <-ticker.C:
}
}
})
return serveHTTPWithBackground(ctx, server, listener, backgroundJobs...)
}
func serveHTTPWithBackground(ctx context.Context, server *http.Server, listener net.Listener, jobs ...func(context.Context)) error {
background, stopBackground := context.WithCancel(ctx)
var backgroundJobs sync.WaitGroup
defer func() {
stopBackground()
backgroundJobs.Wait()
}()
result := make(chan error, 1)
go func() { result <- server.Serve(listener) }()
for _, job := range jobs {
backgroundJobs.Add(1)
go func() {
defer backgroundJobs.Done()
job(background)
}()
}
select {
case err := <-result:
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
case <-ctx.Done():
shutdown, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := server.Shutdown(shutdown); err != nil {
return fmt.Errorf("shutdown: %w", err)
}
log.Print("observatory server stopped")
return nil
}
}
func adminCommand(args []string) error {
if len(args) == 0 {
return errors.New("admin command required: bootstrap, user create or reset-password, project create, environment create, service create, invitation create or accept, enrollment create, web-push generate-key, descriptors list, activate, reject, or retention set")
}
switch args[0] {
case "bootstrap":
return adminBootstrapCommand(args[1:])
case "user":
if len(args) < 2 {
return errors.New("admin user command required: create or reset-password")
}
switch args[1] {
case "create":
return adminUserCreateCommand(args[2:])
case "reset-password":
return adminUserResetPasswordCommand(args[2:])
default:
return errors.New("admin user command required: create or reset-password")
}
case "project":
if len(args) < 2 || args[1] != "create" {
return errors.New("admin project command required: create")
}
return adminProjectCreateCommand(args[2:])
case "environment":
if len(args) < 2 || args[1] != "create" {
return errors.New("admin environment command required: create")
}
return adminEnvironmentCreateCommand(args[2:])
case "service":
if len(args) < 2 || args[1] != "create" {
return errors.New("admin service command required: create")
}
return adminServiceCreateCommand(args[2:])
case "invitation":
if len(args) < 2 {
return errors.New("admin invitation command required: create or accept")
}
switch args[1] {
case "create":
return adminInvitationCreateCommand(args[2:])
case "accept":
return adminInvitationAcceptCommand(args[2:])
default:
return errors.New("admin invitation command required: create or accept")
}
case "enrollment":
if len(args) < 2 || args[1] != "create" {
return errors.New("admin enrollment command required: create")
}
return adminEnrollmentCreateCommand(args[2:])
case "web-push":
if len(args) < 2 || args[1] != "generate-key" {
return errors.New("admin web-push command required: generate-key")
}
return adminWebPushGenerateKeyCommand(args[2:])
case "descriptors":
if len(args) < 2 {
return errors.New("admin descriptors command required: list, activate, or reject")
}
switch args[1] {
case "list":
return adminDescriptorListCommand(args[2:])
case "activate":
return adminDescriptorActivateCommand(args[2:])
case "reject":
return adminDescriptorRejectCommand(args[2:])
default:
return errors.New("admin descriptors command required: list, activate, or reject")
}
case "retention":
if len(args) < 2 || args[1] != "set" {
return errors.New("admin retention command required: set")
}
return adminRetentionSetCommand(args[2:])
default:
return errors.New("admin command required: bootstrap, user create or reset-password, project create, environment create, service create, invitation create or accept, enrollment create, web-push generate-key, descriptors list, activate, reject, or retention set")
}
}
func retentionPolicy(cfg config.Server) storage.RetentionPolicy {
return storage.RetentionPolicy{
RawLogsDays: cfg.Retention.RawLogsDays, RawTracesDays: cfg.Retention.RawTracesDays,
RawMetricsDays: cfg.Retention.RawMetricsDays, ColdRawDays: cfg.Retention.ColdRawDays, MetricRollupsDays: cfg.Retention.MetricRollupsDays,
DeleteColdRaw: cfg.Retention.DeleteColdRaw, EvidenceDays: cfg.Retention.EvidenceDays,
}
}
func adminRetentionSetCommand(args []string) error {
fs := flag.NewFlagSet("admin retention set", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root configuration ownership for local development")
actor := fs.String("actor-user-id", "", "organization owner changing retention")
organizationID := fs.String("organization-id", "", "organization identifier")
rawLogs := fs.Int("raw-logs-days", 0, "raw log retention in days")
rawTraces := fs.Int("raw-traces-days", 0, "raw trace retention in days")
rawMetrics := fs.Int("raw-metrics-days", 0, "raw metric retention in days")
coldRaw := fs.Int("cold-raw-days", 0, "cold forensic raw-segment retention in days")
deleteColdRaw := fs.Bool("delete-cold-raw", false, "explicitly delete cold raw segments after their retention window")
metricRollups := fs.Int("metric-rollups-days", 0, "five-minute metric rollup retention in days")
evidence := fs.Int("evidence-days", 0, "deployment, incident, and audit evidence retention in days")
approveExtension := fs.String("approve-extension", "", "exact organization identifier approving retention beyond server defaults")
quotaBytes := fs.Int64("quota-bytes", 0, "positive storage quota required for an approved extension")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("admin retention set accepts no positional arguments")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
requested := access.Scope{OrganizationID: *organizationID}
if err = identities.ValidateResourceScope(context.Background(), requested); err != nil {
return err
}
decision, err := identities.Access.Authorize(context.Background(), *actor, requested, identity.PermissionOrganizationManage)
if err != nil {
return err
}
if !decision.Allowed {
return errors.New("actor is not authorized to change retention for the requested organization")
}
policy, err := store.SetOrganizationRetention(context.Background(), storage.SetRetentionInput{
OrganizationID: *organizationID, ActorUserID: *actor, Defaults: retentionPolicy(cfg),
Policy: storage.RetentionPolicy{RawLogsDays: *rawLogs, RawTracesDays: *rawTraces, RawMetricsDays: *rawMetrics, ColdRawDays: *coldRaw, DeleteColdRaw: *deleteColdRaw, MetricRollupsDays: *metricRollups, EvidenceDays: *evidence},
ApproveExtensionFor: *approveExtension, QuotaBytes: *quotaBytes,
}, time.Now().UTC())
if err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(policy)
}
func adminWebPushGenerateKeyCommand(args []string) error {
fs := flag.NewFlagSet("admin web-push generate-key", flag.ContinueOnError)
output := fs.String("output-file", "", "new mode-0600 Web Push private-key file")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 || *output == "" {
return errors.New("admin web-push generate-key requires --output-file and no positional arguments")
}
key, err := ecdh.P256().GenerateKey(rand.Reader)
if err != nil {
return errors.New("generate Web Push private key")
}
if err = config.WriteWebPushPrivateKey(*output, key.Bytes()); err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(struct {
PrivateKeyFile string `json:"private_key_file"`
}{*output})
}
func adminDescriptorActivateCommand(args []string) error {
fs := flag.NewFlagSet("admin descriptors activate", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root configuration and descriptor ownership for local development")
actor := fs.String("actor-user-id", "", "organization member activating the reviewed descriptor")
organizationID := fs.String("organization-id", "", "organization identifier")
descriptorFile := fs.String("descriptor-file", "", "absolute private reviewed-descriptor JSON file")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("admin descriptors activate accepts no positional arguments")
}
reviewed, err := readReviewedDescriptor(*descriptorFile, configFlags.requireRootAuxiliaryFile())
if err != nil {
return err
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
requested := access.Scope{OrganizationID: *organizationID}
decision, err := identities.Access.Authorize(context.Background(), *actor, requested, identity.PermissionSchemaManage)
if err != nil {
return err
}
if !decision.Allowed {
return errors.New("actor is not authorized to activate descriptors for the requested organization")
}
if err = identities.ValidateResourceScope(context.Background(), requested); err != nil {
return err
}
activation, err := store.ActivateDescriptor(context.Background(), *organizationID, reviewed, time.Now().UTC())
if err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(activation)
}
func adminDescriptorRejectCommand(args []string) error {
fs := flag.NewFlagSet("admin descriptors reject", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root configuration ownership for local development")
actor := fs.String("actor-user-id", "", "organization member rejecting the descriptor proposal")
organizationID := fs.String("organization-id", "", "organization identifier")
signalName := fs.String("signal", "", "proposal signal: logs, metrics, traces, or deployments")
field := fs.String("field", "", "proposal field")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("admin descriptors reject accepts no positional arguments")
}
signal := model.Signal(*signalName)
switch signal {
case model.SignalLogs, model.SignalMetrics, model.SignalTraces, model.SignalDeployments:
default:
return errors.New("descriptor signal is invalid")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
requested := access.Scope{OrganizationID: *organizationID}
decision, err := identities.Access.Authorize(context.Background(), *actor, requested, identity.PermissionSchemaManage)
if err != nil {
return err
}
if !decision.Allowed {
return errors.New("actor is not authorized to reject descriptors for the requested organization")
}
if err = identities.ValidateResourceScope(context.Background(), requested); err != nil {
return err
}
if err = store.RejectDescriptorProposal(context.Background(), *organizationID, signal, *field); err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(struct {
OrganizationID string `json:"organization_id"`
Signal model.Signal `json:"signal"`
Field string `json:"field"`
Status string `json:"status"`
}{*organizationID, signal, query.CanonicalField(*field), "rejected"})
}
func readReviewedDescriptor(path string, requireRoot bool) (schema.Descriptor, error) {
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
return schema.Descriptor{}, errors.New("reviewed descriptor path must be absolute and clean")
}
info, err := os.Lstat(path)
if err != nil {
return schema.Descriptor{}, fmt.Errorf("inspect reviewed descriptor: %w", err)
}
if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Mode().Perm() != 0o600 || info.Size() < 2 || info.Size() > 64<<10 {
return schema.Descriptor{}, errors.New("reviewed descriptor must be a private regular non-symlink file no larger than 64 KiB")
}
if requireRoot {
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok || stat.Uid != 0 {
return schema.Descriptor{}, errors.New("reviewed descriptor must be owned by root")
}
}
file, err := os.Open(path)
if err != nil {
return schema.Descriptor{}, fmt.Errorf("open reviewed descriptor: %w", err)
}
defer file.Close()
decoder := json.NewDecoder(io.LimitReader(file, 64<<10))
decoder.DisallowUnknownFields()
var descriptor schema.Descriptor
if err = decoder.Decode(&descriptor); err != nil {
return schema.Descriptor{}, errors.New("reviewed descriptor JSON is invalid")
}
var extra any
if err = decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return schema.Descriptor{}, errors.New("reviewed descriptor JSON must contain one value")
}
if err = descriptor.Validate(); err != nil {
return schema.Descriptor{}, fmt.Errorf("reviewed descriptor: %w", err)
}
return descriptor, nil
}
func adminDescriptorListCommand(args []string) error {
fs := flag.NewFlagSet("admin descriptors list", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root configuration ownership for local development")
actor := fs.String("actor-user-id", "", "organization member reviewing descriptor proposals")
organizationID := fs.String("organization-id", "", "organization identifier")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("admin descriptors list accepts no positional arguments")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
requested := access.Scope{OrganizationID: *organizationID}
decision, err := identities.Access.Authorize(context.Background(), *actor, requested, identity.PermissionSchemaManage)
if err != nil {
return err
}
if !decision.Allowed {
return errors.New("actor is not authorized to review descriptors for the requested organization")
}
if err = identities.ValidateResourceScope(context.Background(), requested); err != nil {
return err
}
proposals, err := store.DescriptorProposals(context.Background(), *organizationID)
if err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(proposals)
}
func adminBootstrapCommand(args []string) error {
fs := flag.NewFlagSet("admin bootstrap", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root config and secret ownership for local development")
username := fs.String("username", "", "first operator username")
email := fs.String("email", "", "first operator email address")
displayName := fs.String("display-name", "", "first operator display name")
passwordFile := fs.String("password-file", "", "absolute path to a private one-line password file")
generatedPasswordFile := fs.String("generate-password-file", "", "create an exclusive private one-time password file at this absolute path")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("admin bootstrap accepts no positional arguments")
}
if (*passwordFile == "") == (*generatedPasswordFile == "") {
return errors.New("provide exactly one of --password-file or --generate-password-file")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
password := ""
requirePasswordChange := *generatedPasswordFile != ""
if requirePasswordChange {
password, err = auth.GenerateTemporaryPassword(nil)
if err == nil {
err = identity.WriteSecret(*generatedPasswordFile, password)
}
} else {
password, err = identity.ReadSecret(*passwordFile, configFlags.requireRootAuxiliaryFile())
}
if err != nil {
return err
}
result, err := identities.Bootstrap(context.Background(), identity.BootstrapInput{Username: *username, Email: *email, DisplayName: *displayName, Password: password, RequirePasswordChange: requirePasswordChange})
if err != nil {
if requirePasswordChange {
return errors.Join(err, identity.RemoveSecret(*generatedPasswordFile, configFlags.requireRootAuxiliaryFile()))
}
return err
}
return json.NewEncoder(os.Stdout).Encode(struct {
UserID string `json:"user_id"`
OrganizationID string `json:"personal_organization_id"`
PasswordChangeRequired bool `json:"password_change_required"`
}{result.User.ID, result.Organization.ID, result.User.PasswordChangeRequired})
}
func adminUserCreateCommand(args []string) error {
fs := flag.NewFlagSet("admin user create", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root config and secret ownership for local development")
username := fs.String("username", "", "new user's username")
email := fs.String("email", "", "new user's email address")
displayName := fs.String("display-name", "", "new user's display name")
passwordFile := fs.String("password-file", "", "absolute path to a private one-line password file")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("admin user create accepts no positional arguments")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
password, err := identity.ReadSecret(*passwordFile, configFlags.requireRootAuxiliaryFile())
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
provisioned, err := identities.ProvisionUser(context.Background(), auth.CreateUser{Username: *username, Email: *email, DisplayName: *displayName, Password: password})
if err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(struct {
UserID string `json:"user_id"`
Email string `json:"email"`
PersonalOrganizationID string `json:"personal_organization_id"`
}{provisioned.User.ID, provisioned.User.Email, provisioned.Organization.ID})
}
func adminUserResetPasswordCommand(args []string) error {
fs := flag.NewFlagSet("admin user reset-password", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root config and secret ownership for local development")
identifier := fs.String("identifier", "", "existing username or email address")
generatedPasswordFile := fs.String("generate-password-file", "", "create an exclusive private one-time password file at this absolute path")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("admin user reset-password accepts no positional arguments")
}
if strings.TrimSpace(*identifier) == "" || *generatedPasswordFile == "" {
return errors.New("admin user reset-password requires --identifier and --generate-password-file")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
password, err := auth.GenerateTemporaryPassword(nil)
if err == nil {
err = identity.WriteSecret(*generatedPasswordFile, password)
}
if err != nil {
return err
}
removeCredential := func(requireRoot bool) error {
return identity.RemoveSecret(*generatedPasswordFile, requireRoot)
}
persisted, err := identity.ReadSecret(*generatedPasswordFile, configFlags.requireRootAuxiliaryFile())
if err != nil || persisted != password {
return errors.Join(errors.New("admin user reset-password could not verify private credential delivery"), removeCredential(false))
}
user, err := identities.Auth.ResetPassword(context.Background(), auth.AdministrativePasswordReset{Identifier: *identifier, TemporaryPassword: password})
if err != nil {
return errors.Join(err, removeCredential(configFlags.requireRootAuxiliaryFile()))
}
return json.NewEncoder(os.Stdout).Encode(struct {
UserID string `json:"user_id"`
Username string `json:"username"`
PasswordChangeRequired bool `json:"password_change_required"`
SessionsRevoked bool `json:"sessions_revoked"`
}{user.ID, user.Username, user.PasswordChangeRequired, true})
}
func adminProjectCreateCommand(args []string) error {
fs := flag.NewFlagSet("admin project create", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root configuration ownership for local development")
actor := fs.String("actor-user-id", "", "organization owner creating the project")
organizationID := fs.String("organization-id", "", "organization identifier")
slug := fs.String("slug", "", "project slug")
name := fs.String("name", "", "project name")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("admin project create accepts no positional arguments")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
scope := access.Scope{OrganizationID: *organizationID}
decision, err := identities.Access.Authorize(context.Background(), *actor, scope, identity.PermissionOrganizationManage)
if err != nil {
return err
}
if !decision.Allowed {
return errors.New("actor is not authorized to create projects for the requested organization")
}
if err = identities.ValidateResourceScope(context.Background(), scope); err != nil {
return err
}
project, err := identities.Organizations.CreateProject(context.Background(), organizations.CreateProject{OrganizationID: *organizationID, Slug: *slug, Name: *name})
if err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(struct {
OrganizationID string `json:"organization_id"`
ProjectID string `json:"project_id"`
Slug string `json:"slug"`
}{project.OrganizationID, project.ID, project.Slug})
}
func adminEnvironmentCreateCommand(args []string) error {
fs := flag.NewFlagSet("admin environment create", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root configuration ownership for local development")
actor := fs.String("actor-user-id", "", "organization owner creating the environment")
organizationID := fs.String("organization-id", "", "organization identifier")
projectID := fs.String("project-id", "", "parent project identifier")
slug := fs.String("slug", "", "environment slug")
name := fs.String("name", "", "environment name")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("admin environment create accepts no positional arguments")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
organizationScope := access.Scope{OrganizationID: *organizationID}
decision, err := identities.Access.Authorize(context.Background(), *actor, organizationScope, identity.PermissionOrganizationManage)
if err != nil {
return err
}
if !decision.Allowed {
return errors.New("actor is not authorized to create environments for the requested organization")
}
if err = identities.ValidateResourceScope(context.Background(), access.Scope{OrganizationID: *organizationID, ProjectID: *projectID}); err != nil {
return err
}
environment, err := identities.Organizations.CreateEnvironment(context.Background(), organizations.CreateEnvironment{OrganizationID: *organizationID, ProjectID: *projectID, Slug: *slug, Name: *name})
if err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(struct {
OrganizationID string `json:"organization_id"`
ProjectID string `json:"project_id"`
EnvironmentID string `json:"environment_id"`
Slug string `json:"slug"`
}{environment.OrganizationID, environment.ProjectID, environment.ID, environment.Slug})
}
func adminServiceCreateCommand(args []string) error {
fs := flag.NewFlagSet("admin service create", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root configuration ownership for local development")
actor := fs.String("actor-user-id", "", "organization owner creating the application service")
organizationID := fs.String("organization-id", "", "organization identifier")
projectID := fs.String("project-id", "", "parent project identifier")
environmentID := fs.String("environment-id", "", "parent environment identifier")
slug := fs.String("slug", "", "application service slug")
name := fs.String("name", "", "application service name")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("admin service create accepts no positional arguments")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
organizationScope := access.Scope{OrganizationID: *organizationID}
parentScope := access.Scope{OrganizationID: *organizationID, ProjectID: *projectID, EnvironmentID: *environmentID}
decision, err := identities.Access.Authorize(context.Background(), *actor, organizationScope, identity.PermissionOrganizationManage)
if err != nil {
return err
}
if !decision.Allowed {
return errors.New("actor is not authorized to create application services for the requested organization")
}
if err = identities.ValidateResourceScope(context.Background(), parentScope); err != nil {
return err
}
application, err := identities.Organizations.CreateApplicationService(context.Background(), organizations.CreateApplicationService{OrganizationID: *organizationID, ProjectID: *projectID, EnvironmentID: *environmentID, Slug: *slug, Name: *name})
if err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(struct {
OrganizationID string `json:"organization_id"`
ProjectID string `json:"project_id"`
EnvironmentID string `json:"environment_id"`
ServiceID string `json:"service_id"`
Slug string `json:"slug"`
}{application.OrganizationID, application.ProjectID, application.EnvironmentID, application.ID, application.Slug})
}
func adminInvitationCreateCommand(args []string) error {
fs := flag.NewFlagSet("admin invitation create", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root configuration and token ownership for local development")
actor := fs.String("actor-user-id", "", "organization owner creating the invitation")
organizationID := fs.String("organization-id", "", "organization identifier")
email := fs.String("email", "", "invited user's exact email address")
lifetime := fs.Duration("lifetime", 15*time.Minute, "single-use invitation lifetime")
output := fs.String("output-file", "", "new mode-0600 invitation-token file")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 || *output == "" {
return errors.New("admin invitation create requires --output-file and no positional arguments")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
requested := access.Scope{OrganizationID: *organizationID}
if err = identities.ValidateResourceScope(context.Background(), requested); err != nil {
return err
}
decision, err := identities.Access.Authorize(context.Background(), *actor, requested, identity.PermissionOrganizationManage)
if err != nil {
return err
}
if !decision.Allowed {
return errors.New("actor is not authorized to create invitations for the requested organization")
}
raw, invitation, err := identities.Organizations.Invite(context.Background(), *organizationID, *email, *actor, *lifetime)
if err != nil {
return err
}
if err = identity.WriteSecret(*output, raw); err != nil {
if cancelErr := identities.CancelUnusedInvitation(context.Background(), invitation.Digest); cancelErr != nil {
return fmt.Errorf("persist invitation token: %w; automatic invitation cancellation also failed: %v", err, cancelErr)
}
return fmt.Errorf("persist invitation token: %w; invitation was cancelled", err)
}
return json.NewEncoder(os.Stdout).Encode(struct {
OrganizationID string `json:"organization_id"`
Email string `json:"email"`
ExpiresAt time.Time `json:"expires_at"`
InvitationFile string `json:"invitation_file"`
}{invitation.OrganizationID, invitation.Email, invitation.ExpiresAt, *output})
}
func adminInvitationAcceptCommand(args []string) error {
fs := flag.NewFlagSet("admin invitation accept", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root configuration and token ownership for local development")
userID := fs.String("user-id", "", "invited user's identifier")
invitationFile := fs.String("invitation-file", "", "absolute private invitation-token file")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("admin invitation accept accepts no positional arguments")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
raw, err := identity.ReadSecret(*invitationFile, configFlags.requireRootAuxiliaryFile())
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
if err = identities.Organizations.AcceptInvitation(context.Background(), raw, *userID); err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(struct {
UserID string `json:"user_id"`
Status string `json:"status"`
}{*userID, "accepted"})
}
func adminEnrollmentCreateCommand(args []string) error {
fs := flag.NewFlagSet("admin enrollment create", flag.ContinueOnError)
configFlags := addServerConfigFlags(fs, "allow non-root configuration ownership for local development")
actor := fs.String("actor-user-id", "", "organization member creating the enrollment")
sourceID := fs.String("source-id", "", "new source identifier")
organizationID := fs.String("organization-id", "", "organization identifier")
projectID := fs.String("project-id", "", "project identifier")
environmentID := fs.String("environment-id", "", "environment identifier")
serviceID := fs.String("service-id", "", "service identifier")
lifetime := fs.Duration("lifetime", 15*time.Minute, "single-use enrollment lifetime")
output := fs.String("output-file", "", "new mode-0600 enrollment-token file")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 {
return errors.New("admin enrollment create accepts no positional arguments")
}
cfg, err := configFlags.load()
if err != nil {
return err
}
processLock, err := storage.AcquireProcessLock(cfg.DataDir, false)
if err != nil {
return err
}
defer processLock.Close()
store, err := storage.Open(cfg.DataDir)
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(cfg.DataDir)
if err != nil {
return err
}
defer identities.Close()
requested := access.Scope{OrganizationID: *organizationID, ProjectID: *projectID, EnvironmentID: *environmentID, ServiceID: *serviceID}
decision, err := identities.Access.Authorize(context.Background(), *actor, requested, identity.PermissionSourcesManage)
if err != nil {
return err
}
if !decision.Allowed {
return errors.New("actor is not authorized to manage sources in the requested scope")
}
if err = identities.ValidateResourceScope(context.Background(), requested); err != nil {
return err
}
scope := model.Scope{OrganizationID: *organizationID, ProjectID: *projectID, EnvironmentID: *environmentID, ServiceID: *serviceID}
now := time.Now().UTC()
token, enrollment, err := store.CreateEnrollment(context.Background(), *sourceID, scope, *actor, *lifetime, now)
if err != nil {
return err
}
if err = config.WriteEnrollmentToken(*output, token); err != nil {
if cancelErr := store.CancelEnrollment(context.Background(), token); cancelErr != nil {
return fmt.Errorf("persist enrollment token: %w; automatic cancellation also failed: %v", err, cancelErr)
}
return fmt.Errorf("persist enrollment token: %w; enrollment was cancelled", err)
}
return json.NewEncoder(os.Stdout).Encode(struct {
SourceID string `json:"source_id"`
ExpiresAt time.Time `json:"expires_at"`
}{enrollment.SourceID, enrollment.ExpiresAt})
}
+824
View File
@@ -0,0 +1,824 @@
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
"gamertan.com/observatory/internal/config"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/schema"
"gamertan.com/observatory/internal/storage"
"gamertan.com/web/access"
"gamertan.com/web/auth"
)
func TestNoCommandRequiresAnExplicitTendCandidateAddress(t *testing.T) {
t.Setenv("OBSERVATORY_TEND_CANDIDATE_LISTEN", "")
if err := run(nil); err == nil || !strings.Contains(err.Error(), "command required") {
t.Fatalf("run without command err=%v", err)
}
}
func TestTendCandidateHandlerIsStatelessAndBounded(t *testing.T) {
handler := tendCandidateHandler()
for _, test := range []struct {
method, path, body string
}{
{http.MethodGet, "/", "Gamertan Observatory candidate\n"},
{http.MethodHead, "/", ""},
{http.MethodGet, "/healthz", "ok\n"},
{http.MethodHead, "/healthz", ""},
{http.MethodGet, "/readyz", "ready\n"},
{http.MethodHead, "/readyz", ""},
} {
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(test.method, "http://observatory.example"+test.path, nil))
response := recorder.Result()
body, err := io.ReadAll(response.Body)
response.Body.Close()
if err != nil || response.StatusCode != http.StatusOK || string(body) != test.body {
t.Fatalf("%s %s status=%d body=%q err=%v", test.method, test.path, response.StatusCode, body, err)
}
if response.Header.Get("Cache-Control") != "no-store" || response.Header.Get("X-Content-Type-Options") != "nosniff" || response.Header.Get("Content-Security-Policy") == "" {
t.Fatalf("%s %s security headers=%v", test.method, test.path, response.Header)
}
}
for _, test := range []struct {
method, path string
}{
{http.MethodPost, "/"},
{http.MethodGet, "/api/v1/ingest/native"},
{http.MethodGet, "/app/"},
} {
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(test.method, "http://observatory.example"+test.path, nil))
if recorder.Code == http.StatusOK {
t.Fatalf("candidate exposed %s %s", test.method, test.path)
}
}
}
func TestTendCandidateAddressRejectsNonLoopbackAndMalformedValues(t *testing.T) {
for _, value := range []string{"", "localhost:18094", "0.0.0.0:18094", "192.0.2.1:18094", "127.0.0.1:0", "127.0.0.1", "127.0.0.1:70000"} {
if err := serveTendCandidate(value); err == nil || !strings.Contains(err.Error(), "loopback IP address") {
t.Fatalf("unsafe candidate address %q err=%v", value, err)
}
}
}
func TestTendCandidateProcessIsReadOnly(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
if errors.Is(err, syscall.EPERM) {
t.Skip("loopback sockets are prohibited by this test sandbox")
}
t.Fatal(err)
}
address := listener.Addr().String()
if err = listener.Close(); err != nil {
t.Fatal(err)
}
workingDirectory := t.TempDir()
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestTendCandidateProcessHelper$")
command.Dir = workingDirectory
command.Env = append(os.Environ(), "OBSERVATORY_TEND_CANDIDATE_HELPER=1", "OBSERVATORY_TEND_CANDIDATE_LISTEN="+address)
var output bytes.Buffer
command.Stdout = &output
command.Stderr = &output
if err = command.Start(); err != nil {
t.Fatal(err)
}
client := &http.Client{Timeout: 250 * time.Millisecond}
ready := false
for ctx.Err() == nil {
response, requestErr := client.Get("http://" + address + "/readyz")
if requestErr == nil {
body, readErr := io.ReadAll(response.Body)
response.Body.Close()
if readErr == nil && response.StatusCode == http.StatusOK && string(body) == "ready\n" {
ready = true
break
}
}
time.Sleep(20 * time.Millisecond)
}
if !ready {
_ = command.Process.Kill()
_ = command.Wait()
t.Fatalf("candidate did not become ready: %s", output.String())
}
if err = command.Process.Signal(os.Interrupt); err != nil {
_ = command.Process.Kill()
t.Fatal(err)
}
if err = command.Wait(); err != nil {
t.Fatalf("candidate exit err=%v output=%s", err, output.String())
}
entries, err := os.ReadDir(workingDirectory)
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Fatalf("candidate wrote files: %v", entries)
}
}
func TestTendCandidateProcessHelper(t *testing.T) {
if os.Getenv("OBSERVATORY_TEND_CANDIDATE_HELPER") != "1" {
return
}
if err := run(nil); err != nil {
t.Fatal(err)
}
}
func TestHTTPServerAnswersReadinessWhileBackgroundMaintenanceIsBlocked(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
if errors.Is(err, syscall.EPERM) {
t.Skip("loopback sockets are prohibited by this test sandbox")
}
t.Fatal(err)
}
ctx, cancel := context.WithCancel(t.Context())
maintenanceStarted := make(chan struct{})
maintenanceStopped := make(chan struct{})
server := &http.Server{Handler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if request.URL.Path != "/readyz" {
http.NotFound(writer, request)
return
}
_, _ = io.WriteString(writer, "ready\n")
})}
result := make(chan error, 1)
go func() {
result <- serveHTTPWithBackground(ctx, server, listener, func(background context.Context) {
close(maintenanceStarted)
<-background.Done()
close(maintenanceStopped)
})
}()
select {
case <-maintenanceStarted:
case <-time.After(time.Second):
cancel()
t.Fatal("background maintenance did not start")
}
client := &http.Client{Timeout: 250 * time.Millisecond}
response, err := client.Get("http://" + listener.Addr().String() + "/readyz")
if err != nil {
cancel()
t.Fatal(err)
}
body, readErr := io.ReadAll(response.Body)
response.Body.Close()
if readErr != nil || response.StatusCode != http.StatusOK || string(body) != "ready\n" {
cancel()
t.Fatalf("readiness status=%d body=%q err=%v", response.StatusCode, body, readErr)
}
cancel()
select {
case err = <-result:
if err != nil {
t.Fatal(err)
}
case <-time.After(2 * time.Second):
t.Fatal("server did not stop after cancellation")
}
select {
case <-maintenanceStopped:
default:
t.Fatal("server returned before background maintenance stopped")
}
}
func TestCommandConfigSupportsConfinedSystemdCredentials(t *testing.T) {
root := t.TempDir()
credentialDirectory := filepath.Join(root, "credentials")
if err := os.Mkdir(credentialDirectory, 0o700); err != nil {
t.Fatal(err)
}
data := filepath.Join(root, "data")
path := writeTestServerConfig(t, credentialDirectory, data)
if err := os.Chmod(path, 0o400); err != nil {
t.Fatal(err)
}
t.Setenv("CREDENTIALS_DIRECTORY", credentialDirectory)
cfg, err := commandConfig("server", []string{"--config", path, "--systemd-credential-config"})
if err != nil || cfg.DataDir != data {
t.Fatalf("config=%+v err=%v", cfg, err)
}
if err = os.Chmod(path, 0o440); err != nil {
t.Fatal(err)
}
if cfg, err = commandConfig("server", []string{"--config", path, "--systemd-credential-config"}); err != nil || cfg.DataDir != data {
t.Fatalf("systemd mode-0440 config=%+v err=%v", cfg, err)
}
if _, err = commandConfig("server", []string{"--config", path, "--systemd-credential-config", "--development-allow-nonroot-config"}); err == nil || !strings.Contains(err.Error(), "mutually exclusive") {
t.Fatalf("conflicting config policy err=%v", err)
}
out := filepath.Join(root, "outside.json")
body, readErr := os.ReadFile(path)
if readErr != nil {
t.Fatal(readErr)
}
if err = os.WriteFile(out, body, 0o400); err != nil {
t.Fatal(err)
}
if _, err = commandConfig("server", []string{"--config", out, "--systemd-credential-config"}); err == nil || !strings.Contains(err.Error(), "direct child") {
t.Fatalf("outside credential err=%v", err)
}
}
func TestOptionalPushDispatcherDoesNotBoxANilNotifier(t *testing.T) {
if dispatcher := optionalPushDispatcher(nil); dispatcher != nil {
t.Fatalf("nil notifier became non-nil dispatcher: %#v", dispatcher)
}
}
func TestAdminWebPushKeyGenerationIsPrivateAndExclusive(t *testing.T) {
path := filepath.Join(t.TempDir(), "web-push.json")
if err := adminWebPushGenerateKeyCommand([]string{"--output-file", path}); err != nil {
t.Fatal(err)
}
key, err := config.LoadWebPushPrivateKey(path, config.FilePolicy{})
if err != nil || len(key) != 32 {
t.Fatalf("key length=%d err=%v", len(key), err)
}
info, err := os.Stat(path)
if err != nil || info.Mode().Perm() != 0o600 {
t.Fatalf("mode=%v err=%v", info, err)
}
if err = adminWebPushGenerateKeyCommand([]string{"--output-file", path}); err == nil {
t.Fatal("key generation overwrote an existing secret")
}
}
func TestAdminBootstrapUsesSecretFileAndIsSingleUse(t *testing.T) {
root := t.TempDir()
data := filepath.Join(root, "data")
configPath := filepath.Join(root, "server.json")
passwordPath := filepath.Join(root, "password")
configuration := fmt.Sprintf(`{"schema":1,"listen":"127.0.0.1:9010","public_url":"https://observatory.example","data_dir":%q,"max_body_bytes":1048576,"session_lifetime":"12h","query":{"max_duration":"2s","max_rows":1000,"max_scanned_bytes":10485760,"max_memory_bytes":8388608},"retention":{"raw_logs_days":30,"raw_traces_days":30,"raw_metrics_days":14,"cold_raw_days":400,"metric_rollups_days":400,"evidence_days":400}}`, data)
if err := os.WriteFile(configPath, []byte(configuration), 0o600); err != nil {
t.Fatal(err)
}
const password = "correct horse battery staple"
if err := os.WriteFile(passwordPath, []byte(password+"\n"), 0o600); err != nil {
t.Fatal(err)
}
args := []string{"admin", "bootstrap", "--config", configPath, "--username", "operator", "--email", "operator@example.test", "--display-name", "First Operator", "--password-file", passwordPath, "--development-allow-nonroot-config"}
if err := run(args); err != nil {
t.Fatal(err)
}
if err := run(args); !errors.Is(err, identity.ErrAlreadyBootstrapped) {
t.Fatalf("second bootstrap err=%v", err)
}
entries, err := os.ReadDir(data)
if err != nil {
t.Fatal(err)
}
for _, entry := range entries {
if entry.IsDir() || entry.Name() == ".bootstrap.lock" {
continue
}
body, readErr := os.ReadFile(filepath.Join(data, entry.Name()))
if readErr == nil && strings.Contains(string(body), password) {
t.Fatalf("password leaked into %s", entry.Name())
}
}
}
func TestAdminBootstrapGeneratesExclusiveOneTimeCredential(t *testing.T) {
root := t.TempDir()
data := filepath.Join(root, "data")
configPath := writeTestServerConfig(t, root, data)
passwordPath := filepath.Join(root, "generated-bootstrap-password")
args := []string{"--config", configPath, "--username", "speelman", "--email", "crspeelman@gmail.com", "--display-name", "Cole Speelman", "--generate-password-file", passwordPath, "--development-allow-nonroot-config"}
var result struct {
UserID string `json:"user_id"`
OrganizationID string `json:"personal_organization_id"`
PasswordChangeRequired bool `json:"password_change_required"`
}
captureCommandJSON(t, adminBootstrapCommand, args, &result)
if result.UserID == "" || result.OrganizationID == "" || !result.PasswordChangeRequired {
t.Fatalf("result=%+v", result)
}
info, err := os.Lstat(passwordPath)
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0o600 {
t.Fatalf("password file info=%v err=%v", info, err)
}
password, err := identity.ReadSecret(passwordPath, false)
if err != nil || len(password) != 43 || strings.ContainsAny(password, "\r\n") {
t.Fatalf("generated credential length=%d err=%v", len(password), err)
}
identities, err := identity.Open(data)
if err != nil {
t.Fatal(err)
}
_, principal, err := identities.Auth.Authenticate(t.Context(), "speelman", password, time.Hour)
if err != nil || principal.User.Email != "crspeelman@gmail.com" || principal.User.DisplayName != "Cole Speelman" || !principal.User.PasswordChangeRequired {
identities.Close()
t.Fatalf("principal=%+v err=%v", principal, err)
}
if err = identities.Close(); err != nil {
t.Fatal(err)
}
secondPath := filepath.Join(root, "second-bootstrap-password")
second := append([]string{}, args...)
second[9] = secondPath
if err = adminBootstrapCommand(second); !errors.Is(err, identity.ErrAlreadyBootstrapped) {
t.Fatalf("second bootstrap err=%v", err)
}
if _, err = os.Lstat(secondPath); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("failed bootstrap retained generated credential: %v", err)
}
for _, invalid := range [][]string{
{"--config", configPath, "--username", "x", "--email", "x@example.test", "--display-name", "X", "--development-allow-nonroot-config"},
{"--config", configPath, "--username", "x", "--email", "x@example.test", "--display-name", "X", "--password-file", passwordPath, "--generate-password-file", secondPath, "--development-allow-nonroot-config"},
} {
if err = adminBootstrapCommand(invalid); err == nil || !strings.Contains(err.Error(), "exactly one") {
t.Fatalf("invalid bootstrap flags err=%v", err)
}
}
}
func TestAdminBootstrapSupportsConfinedSystemdCredentials(t *testing.T) {
root := t.TempDir()
credentials := filepath.Join(root, "credentials")
if err := os.Mkdir(credentials, 0o700); err != nil {
t.Fatal(err)
}
data := filepath.Join(root, "data")
configPath := writeTestServerConfig(t, credentials, data)
if err := os.Chmod(configPath, 0o440); err != nil {
t.Fatal(err)
}
passwordPath := filepath.Join(root, "generated-password")
t.Setenv("CREDENTIALS_DIRECTORY", credentials)
args := []string{"--config", configPath, "--username", "operator", "--email", "operator@example.test", "--display-name", "First Operator", "--generate-password-file", passwordPath, "--systemd-credential-config"}
var result struct {
PasswordChangeRequired bool `json:"password_change_required"`
}
captureCommandJSON(t, adminBootstrapCommand, args, &result)
if !result.PasswordChangeRequired {
t.Fatalf("result=%+v", result)
}
if _, err := identity.ReadSecret(passwordPath, false); err != nil {
t.Fatal(err)
}
conflicting := append(append([]string{}, args...), "--development-allow-nonroot-config")
if err := adminBootstrapCommand(conflicting); err == nil || !strings.Contains(err.Error(), "mutually exclusive") {
t.Fatalf("conflicting config policies err=%v", err)
}
}
func TestAdminUserResetPasswordGeneratesPrivateCredentialAndRevokesSessions(t *testing.T) {
root := t.TempDir()
data := filepath.Join(root, "data")
configPath := writeTestServerConfig(t, root, data)
bootstrapPath := filepath.Join(root, "bootstrap-password")
common := []string{"--config", configPath, "--development-allow-nonroot-config"}
var bootstrap struct {
UserID string `json:"user_id"`
}
captureCommandJSON(t, adminBootstrapCommand, append(append([]string{}, common...), "--username", "speelman", "--email", "operator@example.test", "--display-name", "Operator", "--generate-password-file", bootstrapPath), &bootstrap)
bootstrapPassword, err := identity.ReadSecret(bootstrapPath, false)
if err != nil {
t.Fatal(err)
}
identities, err := identity.Open(data)
if err != nil {
t.Fatal(err)
}
token, _, err := identities.Auth.Authenticate(t.Context(), "speelman", bootstrapPassword, time.Hour)
if err != nil {
identities.Close()
t.Fatal(err)
}
if err = identities.Close(); err != nil {
t.Fatal(err)
}
recoveryPath := filepath.Join(root, "recovery-password")
var result struct {
UserID string `json:"user_id"`
Username string `json:"username"`
PasswordChangeRequired bool `json:"password_change_required"`
SessionsRevoked bool `json:"sessions_revoked"`
}
body := captureCommandJSON(t, adminUserResetPasswordCommand, append(append([]string{}, common...), "--identifier", "operator@example.test", "--generate-password-file", recoveryPath), &result)
if result.UserID != bootstrap.UserID || result.Username != "speelman" || !result.PasswordChangeRequired || !result.SessionsRevoked {
t.Fatalf("result=%+v", result)
}
recoveryPassword, err := identity.ReadSecret(recoveryPath, false)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(body), recoveryPassword) || strings.Contains(string(body), recoveryPath) {
t.Fatal("command output disclosed the recovery credential or its path")
}
identities, err = identity.Open(data)
if err != nil {
t.Fatal(err)
}
defer identities.Close()
if _, err = identities.Auth.Session(t.Context(), token); !errors.Is(err, auth.ErrSessionNotFound) {
t.Fatalf("old session survived recovery: %v", err)
}
if _, _, err = identities.Auth.Authenticate(t.Context(), "speelman", bootstrapPassword, time.Hour); !errors.Is(err, auth.ErrInvalidCredentials) {
t.Fatalf("bootstrap credential survived recovery: %v", err)
}
_, principal, err := identities.Auth.Authenticate(t.Context(), "speelman", recoveryPassword, time.Hour)
if err != nil || !principal.User.PasswordChangeRequired {
t.Fatalf("recovery principal=%+v err=%v", principal, err)
}
if err = adminUserResetPasswordCommand(append(append([]string{}, common...), "--identifier", "speelman", "--generate-password-file", recoveryPath)); err == nil {
t.Fatal("recovery credential file was overwritten")
}
missingPath := filepath.Join(root, "missing-user-password")
if err = adminUserResetPasswordCommand(append(append([]string{}, common...), "--identifier", "missing-user", "--generate-password-file", missingPath)); !errors.Is(err, auth.ErrUserNotFound) {
t.Fatalf("missing user err=%v", err)
}
if _, err = os.Lstat(missingPath); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("failed recovery retained credential: %v", err)
}
}
func TestAdminHierarchyAndEnrollmentSupportConfinedSystemdCredentials(t *testing.T) {
root := t.TempDir()
credentials := filepath.Join(root, "credentials")
if err := os.Mkdir(credentials, 0o700); err != nil {
t.Fatal(err)
}
data := filepath.Join(root, "data")
configPath := writeTestServerConfig(t, credentials, data)
if err := os.Chmod(configPath, 0o440); err != nil {
t.Fatal(err)
}
t.Setenv("CREDENTIALS_DIRECTORY", credentials)
common := []string{"--config", configPath, "--systemd-credential-config"}
passwordPath := filepath.Join(root, "generated-password")
var owner struct {
UserID string `json:"user_id"`
OrganizationID string `json:"personal_organization_id"`
}
bootstrap := append(append([]string{}, common...), "--username", "operator", "--email", "operator@example.test", "--display-name", "Operator", "--generate-password-file", passwordPath)
captureCommandJSON(t, adminBootstrapCommand, bootstrap, &owner)
var project struct {
ProjectID string `json:"project_id"`
}
projectArgs := append(append([]string{}, common...), "--actor-user-id", owner.UserID, "--organization-id", owner.OrganizationID, "--slug", "observatory", "--name", "Gamertan Observatory")
captureCommandJSON(t, adminProjectCreateCommand, projectArgs, &project)
var environment struct {
EnvironmentID string `json:"environment_id"`
}
environmentArgs := append(append([]string{}, common...), "--actor-user-id", owner.UserID, "--organization-id", owner.OrganizationID, "--project-id", project.ProjectID, "--slug", "production", "--name", "Production")
captureCommandJSON(t, adminEnvironmentCreateCommand, environmentArgs, &environment)
var service struct {
ServiceID string `json:"service_id"`
}
serviceArgs := append(append([]string{}, common...), "--actor-user-id", owner.UserID, "--organization-id", owner.OrganizationID, "--project-id", project.ProjectID, "--environment-id", environment.EnvironmentID, "--slug", "observatory", "--name", "Observatory")
captureCommandJSON(t, adminServiceCreateCommand, serviceArgs, &service)
enrollmentFile := filepath.Join(root, "enrollment-token")
var enrollment struct {
SourceID string `json:"source_id"`
}
enrollmentArgs := append(append([]string{}, common...), "--actor-user-id", owner.UserID, "--source-id", "observatory-production", "--organization-id", owner.OrganizationID, "--project-id", project.ProjectID, "--environment-id", environment.EnvironmentID, "--service-id", service.ServiceID, "--output-file", enrollmentFile)
captureCommandJSON(t, adminEnrollmentCreateCommand, enrollmentArgs, &enrollment)
if project.ProjectID == "" || environment.EnvironmentID == "" || service.ServiceID == "" || enrollment.SourceID != "observatory-production" {
t.Fatalf("project=%+v environment=%+v service=%+v enrollment=%+v", project, environment, service, enrollment)
}
if _, err := config.LoadEnrollmentToken(enrollmentFile, config.FilePolicy{}); err != nil {
t.Fatal(err)
}
var proposals []schema.Proposal
descriptors := append(append([]string{}, common...), "--actor-user-id", owner.UserID, "--organization-id", owner.OrganizationID)
captureCommandJSON(t, adminDescriptorListCommand, descriptors, &proposals)
}
func TestAdminResourceCommandsCreateAnAuthorizedEnrollableHierarchy(t *testing.T) {
root := t.TempDir()
data := filepath.Join(root, "data")
configPath := writeTestServerConfig(t, root, data)
ownerPassword := filepath.Join(root, "owner-password")
memberPassword := filepath.Join(root, "member-password")
if err := os.WriteFile(ownerPassword, []byte("correct horse battery staple\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(memberPassword, []byte("another correct horse battery staple\n"), 0o600); err != nil {
t.Fatal(err)
}
common := []string{"--config", configPath, "--development-allow-nonroot-config"}
var owner struct {
UserID string `json:"user_id"`
OrganizationID string `json:"personal_organization_id"`
}
captureCommandJSON(t, adminBootstrapCommand, append(append([]string{}, common...), "--username", "operator", "--email", "operator@example.test", "--display-name", "First Operator", "--password-file", ownerPassword), &owner)
var project struct {
OrganizationID string `json:"organization_id"`
ProjectID string `json:"project_id"`
Slug string `json:"slug"`
}
projectArgs := append([]string{"admin", "project", "create"}, common...)
projectArgs = append(projectArgs, "--actor-user-id", owner.UserID, "--organization-id", owner.OrganizationID, "--slug", "gamertan", "--name", "Gamertan")
captureCommandJSON(t, run, projectArgs, &project)
if project.OrganizationID != owner.OrganizationID || project.ProjectID == "" || project.Slug != "gamertan" {
t.Fatalf("project=%+v", project)
}
var environment struct {
OrganizationID string `json:"organization_id"`
ProjectID string `json:"project_id"`
EnvironmentID string `json:"environment_id"`
Slug string `json:"slug"`
}
environmentArgs := append([]string{"admin", "environment", "create"}, common...)
environmentArgs = append(environmentArgs, "--actor-user-id", owner.UserID, "--organization-id", owner.OrganizationID, "--project-id", project.ProjectID, "--slug", "production", "--name", "Production")
captureCommandJSON(t, run, environmentArgs, &environment)
if environment.ProjectID != project.ProjectID || environment.EnvironmentID == "" || environment.Slug != "production" {
t.Fatalf("environment=%+v", environment)
}
var application struct {
OrganizationID string `json:"organization_id"`
ProjectID string `json:"project_id"`
EnvironmentID string `json:"environment_id"`
ServiceID string `json:"service_id"`
Slug string `json:"slug"`
}
serviceArgs := append([]string{"admin", "service", "create"}, common...)
serviceArgs = append(serviceArgs, "--actor-user-id", owner.UserID, "--organization-id", owner.OrganizationID, "--project-id", project.ProjectID, "--environment-id", environment.EnvironmentID, "--slug", "observatory", "--name", "Gamertan Observatory")
captureCommandJSON(t, run, serviceArgs, &application)
if application.EnvironmentID != environment.EnvironmentID || application.ServiceID == "" || application.Slug != "observatory" {
t.Fatalf("application=%+v", application)
}
identities, err := identity.Open(data)
if err != nil {
t.Fatal(err)
}
if err = identities.ValidateResourceScope(context.Background(), access.Scope{OrganizationID: owner.OrganizationID, ProjectID: project.ProjectID, EnvironmentID: environment.EnvironmentID, ServiceID: application.ServiceID}); err != nil {
identities.Close()
t.Fatal(err)
}
if err = identities.Close(); err != nil {
t.Fatal(err)
}
var member struct {
UserID string `json:"user_id"`
}
captureCommandJSON(t, adminUserCreateCommand, append(append([]string{}, common...), "--username", "member", "--email", "member@example.test", "--display-name", "Member", "--password-file", memberPassword), &member)
unauthorized := append(append([]string{}, common...), "--actor-user-id", member.UserID, "--organization-id", owner.OrganizationID, "--slug", "forbidden", "--name", "Forbidden")
if err = adminProjectCreateCommand(unauthorized); err == nil || !strings.Contains(err.Error(), "not authorized") {
t.Fatalf("unauthorized project err=%v", err)
}
wrongParent := append(append([]string{}, common...), "--actor-user-id", owner.UserID, "--organization-id", owner.OrganizationID, "--project-id", member.UserID, "--slug", "invalid", "--name", "Invalid")
if err = adminEnvironmentCreateCommand(wrongParent); !errors.Is(err, identity.ErrResourceNotFound) {
t.Fatalf("wrong parent err=%v", err)
}
}
func captureCommandJSON(t *testing.T, command func([]string) error, args []string, target any) []byte {
t.Helper()
reader, writer, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
original := os.Stdout
os.Stdout = writer
commandErr := command(args)
closeErr := writer.Close()
os.Stdout = original
body, readErr := io.ReadAll(reader)
reader.Close()
if commandErr != nil {
t.Fatal(commandErr)
}
if closeErr != nil || readErr != nil {
t.Fatalf("capture close=%v read=%v", closeErr, readErr)
}
if err = json.Unmarshal(body, target); err != nil {
t.Fatalf("decode command output: %v", err)
}
return body
}
func TestAdminUserAndInvitationCommandsProvisionPrivateAndSharedAccess(t *testing.T) {
root := t.TempDir()
data := filepath.Join(root, "data")
configPath := writeTestServerConfig(t, root, data)
ownerPassword := filepath.Join(root, "owner-password")
memberPassword := filepath.Join(root, "member-password")
otherPassword := filepath.Join(root, "other-password")
invitationPath := filepath.Join(root, "invitation")
if err := os.WriteFile(ownerPassword, []byte("correct horse battery staple\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(memberPassword, []byte("another correct horse battery staple\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(otherPassword, []byte("a third correct horse battery staple\n"), 0o600); err != nil {
t.Fatal(err)
}
common := []string{"--config", configPath, "--development-allow-nonroot-config"}
if err := adminBootstrapCommand(append(append([]string{}, common...), "--username", "operator", "--email", "operator@example.test", "--display-name", "First Operator", "--password-file", ownerPassword)); err != nil {
t.Fatal(err)
}
if err := adminUserCreateCommand(append(append([]string{}, common...), "--username", "responder", "--email", "responder@example.test", "--display-name", "Incident Responder", "--password-file", memberPassword)); err != nil {
t.Fatal(err)
}
if err := adminUserCreateCommand(append(append([]string{}, common...), "--username", "other-user", "--email", "other@example.test", "--display-name", "Other User", "--password-file", otherPassword)); err != nil {
t.Fatal(err)
}
identities, err := identity.Open(data)
if err != nil {
t.Fatal(err)
}
_, owner, err := identities.Auth.Authenticate(t.Context(), "operator", "correct horse battery staple", time.Hour)
if err != nil {
identities.Close()
t.Fatal(err)
}
_, member, err := identities.Auth.Authenticate(t.Context(), "responder", "another correct horse battery staple", time.Hour)
if err != nil {
identities.Close()
t.Fatal(err)
}
_, other, err := identities.Auth.Authenticate(t.Context(), "other-user", "a third correct horse battery staple", time.Hour)
if err != nil {
identities.Close()
t.Fatal(err)
}
ownerOrganizations, err := identities.OrganizationsForUser(t.Context(), owner.User.ID)
if err != nil || len(ownerOrganizations) != 1 || !ownerOrganizations[0].Personal {
identities.Close()
t.Fatalf("owner organizations=%+v err=%v", ownerOrganizations, err)
}
memberOrganizations, err := identities.OrganizationsForUser(t.Context(), member.User.ID)
if err != nil || len(memberOrganizations) != 1 || !memberOrganizations[0].Personal {
identities.Close()
t.Fatalf("member organizations=%+v err=%v", memberOrganizations, err)
}
if err = identities.Close(); err != nil {
t.Fatal(err)
}
createArgs := append(append([]string{}, common...), "--actor-user-id", owner.User.ID, "--organization-id", ownerOrganizations[0].ID, "--email", member.User.Email, "--output-file", invitationPath)
if err = adminInvitationCreateCommand(createArgs); err != nil {
t.Fatal(err)
}
info, err := os.Lstat(invitationPath)
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0o600 {
t.Fatalf("invitation file=%v err=%v", info, err)
}
acceptArgs := append(append([]string{}, common...), "--user-id", member.User.ID, "--invitation-file", invitationPath)
wrongUserArgs := append(append([]string{}, common...), "--user-id", other.User.ID, "--invitation-file", invitationPath)
if err = adminInvitationAcceptCommand(wrongUserArgs); err == nil {
t.Fatal("invitation was accepted by a user with a different email")
}
if err = adminInvitationAcceptCommand(acceptArgs); err != nil {
t.Fatal(err)
}
if err = adminInvitationAcceptCommand(acceptArgs); err == nil {
t.Fatal("single-use invitation was accepted twice")
}
identities, err = identity.Open(data)
if err != nil {
t.Fatal(err)
}
defer identities.Close()
memberOrganizations, err = identities.OrganizationsForUser(t.Context(), member.User.ID)
if err != nil || len(memberOrganizations) != 2 {
t.Fatalf("member organizations=%+v err=%v", memberOrganizations, err)
}
unauthorized := append(append([]string{}, common...), "--actor-user-id", member.User.ID, "--organization-id", ownerOrganizations[0].ID, "--email", "other@example.test", "--output-file", filepath.Join(root, "unauthorized-invitation"))
if err = adminInvitationCreateCommand(unauthorized); err == nil || !strings.Contains(err.Error(), "not authorized") {
t.Fatalf("unauthorized invitation err=%v", err)
}
}
func TestMigrateProjectionRebuildRequiresExactApproval(t *testing.T) {
if err := migrateCommand([]string{"--rebuild-organization", "organization-a"}); err == nil || !strings.Contains(err.Error(), "exact organization identifier") {
t.Fatalf("missing approval err=%v", err)
}
if err := migrateCommand([]string{"--approve-rebuild-organization", "organization-a"}); err == nil || !strings.Contains(err.Error(), "requires rebuild-organization") {
t.Fatalf("orphan approval err=%v", err)
}
if err := migrateCommand([]string{"--rebuild-organization", "organization-a", "--approve-rebuild-organization", "organization-b"}); err == nil || !strings.Contains(err.Error(), "exact organization identifier") {
t.Fatalf("mismatched approval err=%v", err)
}
}
func TestDashboardImportJSONIsStrictBoundedAndExplicitlyApproved(t *testing.T) {
valid := `{"version":1,"dashboard":{"slug":"operations","name":"Operations","description":"Portable view.","panels":[{"id":"panel-old","position":0,"title":"Requests","visualization":"table","saved_query_id":"query-old"}]},"saved_queries":[{"id":"query-old","name":"Requests","description":"Recent requests.","query":"logs | limit 10","scope":{}}]}`
bundle, err := readDashboardBundle(strings.NewReader(valid))
if err != nil || bundle.Version != storage.DashboardVersion || bundle.Dashboard.Slug != "operations" {
t.Fatalf("bundle=%+v err=%v", bundle, err)
}
for name, body := range map[string]string{
"unknown": strings.Replace(valid, `"version":1`, `"version":1,"secret":"no"`, 1),
"trailing": valid + `{}`,
"oversize": valid + strings.Repeat(" ", 1<<20),
} {
t.Run(name, func(t *testing.T) {
if _, err := readDashboardBundle(strings.NewReader(body)); err == nil {
t.Fatal("unsafe dashboard bundle was accepted")
}
})
}
if err = importCommand([]string{"--organization-id", "organization-a"}); err == nil || !strings.Contains(err.Error(), "exact organization identifier") {
t.Fatalf("missing approval err=%v", err)
}
}
func TestOfflineMigrationRefusesLiveDataDirectory(t *testing.T) {
root := t.TempDir()
data := filepath.Join(root, "data")
configPath := writeTestServerConfig(t, root, data)
lock, err := storage.AcquireProcessLock(data, false)
if err != nil {
t.Fatal(err)
}
defer lock.Close()
err = migrateCommand([]string{"--config", configPath, "--development-allow-nonroot-config"})
if err == nil || !strings.Contains(err.Error(), "active in another process") {
t.Fatalf("migration overlapped live lock: %v", err)
}
}
func writeTestServerConfig(t *testing.T, root, data string) string {
t.Helper()
path := filepath.Join(root, "server.json")
body := fmt.Sprintf(`{"schema":1,"listen":"127.0.0.1:9010","public_url":"https://observatory.example","data_dir":%q,"max_body_bytes":1048576,"session_lifetime":"12h","query":{"max_duration":"2s","max_rows":1000,"max_scanned_bytes":10485760,"max_memory_bytes":8388608},"retention":{"raw_logs_days":30,"raw_traces_days":30,"raw_metrics_days":14,"cold_raw_days":400,"metric_rollups_days":400,"evidence_days":400}}`, data)
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
return path
}
func TestReviewedDescriptorFileIsStrictPrivateAndNonSymlink(t *testing.T) {
descriptor := schema.Descriptor{
Version: schema.DescriptorVersion, Signal: model.SignalMetrics, Field: "workshop.queue_depth",
Type: schema.TypeInteger, Meaning: "Reviewed queue depth for one service.",
Sensitivity: schema.SensitivityInternal, Cardinality: schema.CardinalityLow,
Index: schema.IndexRange, Retention: schema.RetentionRaw, ProjectionVersion: 1,
}
body, err := json.Marshal(descriptor)
if err != nil {
t.Fatal(err)
}
path := filepath.Join(t.TempDir(), "descriptor.json")
if err = os.WriteFile(path, append(body, '\n'), 0o600); err != nil {
t.Fatal(err)
}
got, err := readReviewedDescriptor(path, false)
if err != nil || got != descriptor {
t.Fatalf("descriptor=%+v err=%v", got, err)
}
if err = os.WriteFile(path, []byte(`{"version":1,"signal":"metrics","field":"workshop.queue_depth","type":"integer","meaning":"Reviewed queue depth for one service.","sensitivity":"internal","cardinality":"low","index":"range","retention":"raw","projection_version":1,"unknown":true}`), 0o600); err != nil {
t.Fatal(err)
}
if _, err = readReviewedDescriptor(path, false); err == nil {
t.Fatal("unknown descriptor property was accepted")
}
if err = os.WriteFile(path, body, 0o644); err != nil {
t.Fatal(err)
}
if err = os.Chmod(path, 0o644); err != nil {
t.Fatal(err)
}
if _, err = readReviewedDescriptor(path, false); err == nil {
t.Fatal("weak descriptor mode was accepted")
}
if err = os.Chmod(path, 0o600); err != nil {
t.Fatal(err)
}
link := filepath.Join(filepath.Dir(path), "descriptor-link.json")
if err = os.Symlink(path, link); err == nil {
if _, err = readReviewedDescriptor(link, false); err == nil {
t.Fatal("descriptor symlink was accepted")
}
}
}
+225
View File
@@ -0,0 +1,225 @@
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"bytes"
"encoding/json"
"errors"
"io"
"os"
"strings"
"testing"
"gamertan.com/observatory/internal/config"
)
func TestReleaseWebPushUsesAServiceScopedSystemdCredential(t *testing.T) {
serverBody, err := os.ReadFile("../../release/server.json")
if err != nil {
t.Fatal(err)
}
decoder := json.NewDecoder(bytes.NewReader(serverBody))
decoder.DisallowUnknownFields()
var server config.Server
if err = decoder.Decode(&server); err != nil {
t.Fatal(err)
}
if err = decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
t.Fatal("release server configuration contains trailing JSON")
}
const runtimeKey = "/run/credentials/gamertan-observatory.service/web-push.json"
if server.MaxBodyBytes != 32<<20 || server.MaxConcurrentIngest != 8 || server.WebPush == nil || server.WebPush.PrivateKeyFile != runtimeKey || server.WebPush.Subject != "mailto:security@sandwichhime.com" || server.WebPush.QueueCapacity != 64 || server.WebPush.RequestTimeout != "10s" {
t.Fatalf("web push release configuration=%+v", server.WebPush)
}
unitBody, err := os.ReadFile("../../release/observatory.service")
if err != nil {
t.Fatal(err)
}
unit := string(unitBody)
for _, required := range []string{
"LoadCredential=server.json:/etc/gamertan-observatory/server.json",
"LoadCredential=web-push.json:/etc/gamertan-observatory/web-push.json",
"ExecStart=/opt/gamertan-observatory/current/observatory server --config %d/server.json --systemd-credential-config",
} {
if strings.Count(unit, required) != 1 {
t.Fatalf("release unit requires one %q", required)
}
}
if bytes.Contains(serverBody, []byte("private_key\"")) || bytes.Contains(serverBody, []byte("BEGIN PRIVATE KEY")) {
t.Fatal("release server configuration contains private-key material")
}
}
func TestReleaseCaddyAccessLogIsFilteredAndBounded(t *testing.T) {
body, err := os.ReadFile("../../release/Caddyfile.observatory")
if err != nil {
t.Fatal(err)
}
configuration := string(body)
for _, required := range []string{
"log observatory_access {",
"output file /var/log/caddy/observatory-access.jsonl {",
"mode 0640",
"roll_size 100mb",
"roll_keep 10",
"roll_keep_for 720h",
`request>uri regexp \?.*$ ""`,
"request>remote_ip delete",
"request>remote_port delete",
"request>client_ip delete",
"request>headers delete",
"resp_headers delete",
"user_id delete",
"log_append request_id {http.response.header.X-Request-ID}",
} {
if strings.Count(configuration, required) != 1 {
t.Fatalf("release Caddy configuration requires one %q", required)
}
}
for _, forbidden := range []string{"log_credentials", "Cookie", "Authorization", "query {"} {
if strings.Contains(configuration, forbidden) {
t.Fatalf("release Caddy configuration contains forbidden %q", forbidden)
}
}
}
func TestReleaseAgentIsUnprivilegedScopedAndPrivacyMinimized(t *testing.T) {
body, err := os.ReadFile("../../release/agent.json")
if err != nil {
t.Fatal(err)
}
testPath := t.TempDir() + "/agent.json"
if err = os.WriteFile(testPath, body, 0o600); err != nil {
t.Fatal(err)
}
agent, err := config.LoadAgent(testPath, config.FilePolicy{})
if err != nil {
t.Fatalf("validate release agent configuration: %v", err)
}
if agent.Schema != 1 || agent.ServerURL != "https://observatory.gamertan.com" || agent.CredentialFile != "/etc/gamertan-observatory/agent-credential.json" || agent.SpoolDir != "/var/lib/gamertan-observatory-agent" || agent.StateFile != "/var/lib/gamertan-observatory-agent/state.json" || agent.MaxSpoolBytes != 5<<30 || agent.MaxSpoolAgeText != "72h" || agent.BatchRecords != 5000 || agent.FlushInterval != "1s" {
t.Fatalf("release agent configuration=%+v", agent)
}
if len(agent.Sources) != 6 {
t.Fatalf("release agent source count=%d", len(agent.Sources))
}
wantSources := []struct{ kind, path, stream string }{
{"caddy_json", "/var/log/caddy/eqlwiki-edge.jsonl", "eql-edge"},
{"requestlog_jsonl", "/var/log/eqlwiki/access.jsonl", "eql-application"},
{"tend_events_jsonl", "/opt/gamertancom/deployment-events.jsonl", "tend-gamertancom"},
{"tend_events_jsonl", "/opt/sandwich-hime-site/deployment-events.jsonl", "tend-sandwich-hime-site"},
{"tend_events_jsonl", "/opt/gamertan-observatory/deployment-events.jsonl", "tend-observatory"},
{"linux_metrics", "", "public-node-host-metrics"},
}
for index, want := range wantSources {
source := agent.Sources[index]
if source.Kind != want.kind || source.Path != want.path || source.StreamID != want.stream || len(source.SensitiveFields) != 0 {
t.Fatalf("release agent source[%d]=%+v", index, source)
}
}
metrics := agent.Sources[5].LinuxMetrics
if metrics == nil || metrics.ProcRoot != "/proc" || metrics.CgroupRoot != "/sys/fs/cgroup" || len(metrics.Filesystems) != 1 || metrics.Filesystems[0].Name != "root" || metrics.Filesystems[0].Path != "/" || len(metrics.ControlGroups) != 6 {
t.Fatalf("release Linux metrics=%+v", metrics)
}
wantCgroups := map[string]string{
"caddy": "system.slice/caddy.service",
"eql": "system.slice/system-eqlwiki.slice",
"gamertan": "system.slice/system-gamertancom.slice",
"sandwich-hime": "system.slice/sandwich-hime-site.service",
"observatory": "system.slice/gamertan-observatory.service",
"observatory-agent": "system.slice/gamertan-observatory-agent.service",
}
for _, selected := range metrics.ControlGroups {
if wantCgroups[selected.Name] != selected.Path {
t.Fatalf("unexpected release cgroup selector=%+v", selected)
}
delete(wantCgroups, selected.Name)
}
if len(wantCgroups) != 0 {
t.Fatalf("missing release cgroup selectors=%v", wantCgroups)
}
if bytes.Contains(body, []byte("observatory-access")) || bytes.Contains(body, []byte("sensitive_fields")) {
t.Fatal("release agent enables a feedback loop or sensitive evidence")
}
unitBody, err := os.ReadFile("../../release/observatory-agent.service")
if err != nil {
t.Fatal(err)
}
unit := string(unitBody)
for _, required := range []string{
"User=observatory-agent",
"Group=observatory-agent",
"SupplementaryGroups=caddy eqlwiki gamertancom",
"PartOf=gamertan-observatory.service",
"LoadCredential=agent.json:/etc/gamertan-observatory/agent.json",
"LoadCredential=agent-credential.json:/etc/gamertan-observatory/agent-credential.json",
"ExecStart=/opt/gamertan-observatory/current/observatory agent --systemd-credentials --config %d/agent.json --credential-file %d/agent-credential.json",
"StateDirectory=gamertan-observatory-agent",
"StateDirectoryMode=0700",
"NoNewPrivileges=yes",
"ProtectSystem=strict",
"ProtectProc=invisible",
"CapabilityBoundingSet=",
"AmbientCapabilities=",
"ReadOnlyPaths=/proc /sys/fs/cgroup /var/log/caddy /var/log/eqlwiki /opt/gamertancom/deployment-events.jsonl /opt/sandwich-hime-site/deployment-events.jsonl /opt/gamertan-observatory/deployment-events.jsonl",
"ReadWritePaths=/var/lib/gamertan-observatory-agent",
"MemoryMax=256M",
} {
if strings.Count(unit, required) != 1 {
t.Fatalf("release agent unit requires one %q", required)
}
}
for _, forbidden := range []string{"User=root", "docker.sock", "sh -c", "curl ", "wget ", "PrivateNetwork=yes"} {
if strings.Contains(unit, forbidden) {
t.Fatalf("release agent unit contains forbidden %q", forbidden)
}
}
}
func TestSensitiveCaddyExampleKeepsAnExplicitProducerBoundary(t *testing.T) {
body, err := os.ReadFile("../../examples/Caddyfile.sensitive-access-log")
if err != nil {
t.Fatal(err)
}
configuration := string(body)
for _, required := range []string{
"mode 0640",
"roll_size 100mb",
"roll_keep 10",
"roll_keep_for 720h",
"request>uri query {",
"delete access_token",
"delete api_key",
"delete authorization",
"delete code",
"delete credential",
"delete key",
"delete password",
"delete secret",
"\n\t\t\t\tdelete session\n",
"delete session_id",
"delete token",
"client_ip ip_mask 24 56",
"request>remote_ip delete",
"request>remote_port delete",
"request>client_ip delete",
"request>headers delete",
"resp_headers delete",
"user_id delete",
"log_append request_id {http.response.header.X-Request-ID}",
"log_append client_ip {http.request.client_ip}",
"log_append referrer {http.request.header.Referer}",
"log_append user_agent {http.request.header.User-Agent}",
} {
if strings.Count(configuration, required) != 1 {
t.Fatalf("sensitive Caddy example requires one %q", required)
}
}
for _, forbidden := range []string{"log_credentials", "Cookie", "Authorization"} {
if strings.Contains(configuration, forbidden) {
t.Fatalf("sensitive Caddy example contains forbidden %q", forbidden)
}
}
}
+293
View File
@@ -0,0 +1,293 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Adaptive time-partitioned projections
Status: design candidate; not an implemented capability or release claim.
## Purpose
Observatory should preserve forensic evidence by default without requiring
every accepted observation to become a fully indexed row immediately. The raw
segment and control catalogue already contain the durable identity, tenant,
signal, source, sequence, byte size, and observed-time range needed to defer
most read-model work.
The proposed model is an event lake with adaptive materializations:
1. acknowledge immutable raw evidence and its small catalogue entry;
2. keep a bounded recent window available for live authorized views;
3. incrementally maintain only projections required by currently observed
views, explicitly warmed workloads, or reviewed central correlations;
4. build ad-hoc historical materializations on demand from the relevant raw
time partitions; and
5. evict any derived projection that no longer justifies its storage cost.
Raw evidence remains authoritative. Every memory view, SQLite partition,
index, rollup, and query cache remains disposable and reconstructable.
## Batch identity, not per-record deduplication
An enrolled agent is trusted to classify and serialize the records it was
configured to collect. Observatory does not need to maintain a global
per-record deduplication index in the ingestion path. The durable unit is one
bounded authenticated batch identified by its enrolled source, stream, and
monotonic sequence. Its retained segment catalogue records the first and last
observed timestamps, record and byte counts, and the exact segment and
canonical logical-batch digests. Agent epochs separately namespace locally
generated alert-transition sequences across process-state replacement.
The server derives organization, project, environment, and service scope from
the enrollment. It commits the immutable batch once, advances the stream
watermark atomically, and acknowledges its exact identity. Retrying the same
sequence and digest is an idempotent no-op. Reusing a sequence with different
bytes is quarantined as corruption. A sequence gap is retained as an explicit
continuity event rather than hidden. Timestamp ranges select storage and query
partitions but are not deduplication keys because legitimate batches may
overlap and host clocks may drift.
### Implemented native v2 early-replay envelope
The agent sends new native batches to `/api/v2/ingest/native`. A small
authenticated header envelope is available before the JSON record body, so an
exact replay takes a cheaper path. The envelope contains only:
- protocol version, stream ID, signal, and monotonic sequence;
- the SHA-256 of the exact encoded body and the canonical logical-batch digest;
- record count and encoded byte count; and
- first and last observed timestamps.
Source and tenant scope remain server-derived from the enrolled credential.
For a sequence already acknowledged with both digests, the server hashes and
discards the bounded body, returns the retained raw-segment identity, and avoids
JSON decoding, compression, catalogue writes, or projection wakeups. It must
still read the complete bounded body and verify its encoded digest before
acknowledging; trusting an enrolled agent does not make a buggy reused sequence
safe to accept without checking the bytes.
For a new sequence, the existing validation and raw-first commit remain
mandatory. The server checks the declared count, byte size, signal, and time
bounds against the decoded batch before it commits or acknowledges it. An
envelope mismatch is a rejected batch, not a reason to rewrite telemetry.
Overlapping time ranges, late data, and repeated values remain valid. This is
an ingestion-cost optimization and audit index, not content-based record
deduplication.
The legacy `/api/v1/ingest/native` endpoint remains available during the
preview compatibility window. A stream last accepted through v1 has blank
envelope columns. Its first matching v2 retry follows the full validation path
once, verifies the retained segment identity, and backfills the v2 metadata;
later exact retries use the early path.
## Partition shape
Partition first by organization, signal, and UTC time—not by arbitrary field
names or user-supplied identifiers. A starting comparison should use one
SQLite database per organization, signal, and UTC day. This keeps a normal
30-day hot window near 90 files per organization, permits logs, metrics, and
traces to project concurrently, narrows index working sets, and makes expiry a
bounded file operation.
Hourly partitions may be evaluated for unusually high-volume days only after
the daily prototype is measured. Five-minute, hourly, and daily *rollups* are
aggregation resolutions; they should not be confused with the physical file
boundary. The partition catalogue must tell the planner which exact files and
rollup resolutions cover a requested window.
Each materialized partition records:
- organization, signal, UTC start and end;
- projection schema and generation;
- the exact raw segment digests or a durable high-watermark plus delta ledger;
- row, byte, and rollup counts;
- creation, last-query, and expiry times;
- build state and failure state; and
- the reviewed query evidence that justified eager or cached materialization.
Late observations update only their observed-time partition. The new
generation is built beside the active one and atomically activated. Queries
must either use one complete generation or merge its explicit delta; they may
never silently omit late evidence.
## Materialization classes
### Live tail
A bounded per-organization memory ring receives records only after their raw
segment has been durably acknowledged. It is keyed by segment digest and record
index, capped by both age and bytes, and safe to lose. It serves the recent log
tail, current metric samples, and trace arrivals while the disk projector is
behind. Authorization is checked before the ring is opened, and disk results
are deduplicated when a query overlaps the ring.
SSE is the default UI transport for these server-to-client updates. It works
through ordinary HTTPS, has browser reconnection semantics, and is directly
testable. WebSockets remain a future option for a feature that needs genuine
bidirectional streaming; form mutations continue to use server-side POST,
redirect, and flash-message flows.
### Agent-owned alert evaluation
Single-source alert rules should normally execute at the enrolled agent that
already sees the stream. Rules are bounded, declarative, locally configured,
and versioned. The server cannot remotely add a source path, collector, shell
command, or executable rule. An agent evaluates its hot in-memory batch state
without requiring the server to project that stream and emits only bounded
rule-evaluation results: matched, clear, or an explicit evaluation error. The
server remains the authority that applies consecutive-match policy and turns
those evaluations into pending, firing, acknowledged, silenced, and resolved
incident states.
Each transition is authenticated by its enrolled source and binds:
- rule identifier and version;
- source, stream, and agent epoch;
- evaluation window and state;
- exact raw batch sequence range and segment digest evidence; and
- a monotonic transition sequence and observed timestamp.
It contains no telemetry values by default. The server deduplicates the
transition and binds it to the exact retained raw segment before accepting it.
One agent cannot assert another source's scope. Reusing a sequence with
different bytes is corruption, while replaying the same sequence and digest
is an idempotent no-op. During the compatibility phase the server records this
source evidence without mutating incident state; the existing central
evaluator remains the oracle until differential comparisons prove equivalent
results and failure behavior.
This model deliberately trusts an authenticated agent to classify and
evaluate its own data. It still protects ordinary retries, crashes, replay,
configuration drift, and a buggy agent. It cannot prove that a compromised or
offline agent reported honestly. The server therefore retains source
heartbeat, sequence-gap, and enrollment-revocation checks: a dead agent cannot
report its own absence. Cross-source or cross-service correlation remains an
explicit, bounded central workload rather than the default alert path.
The first implementation slice evaluates filter-only log rules over one exact
durable batch. It deliberately excludes historical windows and cross-batch
state while the source and central results are compared. A raw batch remains
in the agent spool until both the raw admission and its source evaluation have
matching acknowledgements. This gives the transition durable retry behavior
without introducing a second telemetry store at the edge.
Incident evidence labels distinguish `source_reported`,
`server_observed_absence`, and `centrally_correlated` conclusions. The current
server-side saved-query evaluator remains the compatibility oracle until edge
evaluation passes differential tests, disconnect/replay testing, and a
production soak. Merely pinning or saving a dashboard never enables eager
evaluation.
### Warm
Frequently used saved queries retain their materializations for a configured
period. Query evidence may propose warming or eviction, but an administrator
approves durable storage-policy changes.
### Observed leases
An authorized live Explore or dashboard session may create a bounded
materialization lease for its exact organization, query, and time window.
Every observer of the same materialization key shares one build/cache entry;
50 or 1,000 viewers increase notification fan-out, not projection work. The
SSE connection carries invalidation notices and renews demand; it does not
carry telemetry and is not itself storage authority. Equivalent future
WebSocket transport would obey the same lease contract.
The key includes the canonical typed query AST, authorized scope, bounded time
window, descriptor generation, and materialization schema. A leased
materialization may contain a query-specific temporary index, but Observatory
does not create a permanent organization-wide index for every dashboard.
Repeated measured benefit may produce a reviewed warm-index proposal with its
estimated build, storage, and write-amplification cost. Approval and quota—not
viewer count alone—promote it to durable policy.
Leases are deduplicated, expire after a disconnect grace period, and are
limited per user and organization. Connection churn cannot create a new
unbounded job, extend retention, or bypass query cost and sensitive-field
permissions. A completed materialization may cool into the ordinary warm cache
or be evicted. Agent-owned rules and server heartbeat checks remain
independent of browser observers; a central cross-source rule acquires its own
explicit, bounded lease.
### Lazy
An ad-hoc historical query first uses the segment catalogue to identify exact
time and scope candidates. A small query may scan them directly under the
ordinary time, byte, row, and memory budgets. A larger query creates a bounded
materialization job. The UI reports its state and progress, then refreshes the
result through SSE; the no-JavaScript path remains a normal status page with a
manual refresh.
The first query is allowed to be slower. It is not allowed to become an
unbounded request, hold an HTTP connection indefinitely, or bypass query
budgets. A materialization that exceeds its approved budget stops with a
specific, resumable status rather than the generic “temporarily unavailable”
response.
## Read and write separation
The ingestion plane is append-oriented: validate, compress, checksum, sync,
catalogue, acknowledge. It does not wait for query indexing.
The read plane is projection-oriented: select only authorized organization,
signal, and time partitions; use exact rollups where semantically valid; merge
partition-local partial results; then apply the final sort and limit. Query
planning limits partition fan-out and reports the raw bytes, materializations,
indexes, permissions, and expected cold work in `explain`.
This preserves SQLite's operational simplicity while allowing concurrent
writers across independent partition files. It also creates a fair test of
SQLite itself: if partition-local insertion remains the measured bottleneck
after index review, the same raw segments and partition contract can be used
to compare another embedded representation.
## What this does not solve automatically
- A memory tail improves visibility, not durable projector throughput.
- Lazy materialization trades continuous background cost for first-query cost.
- Too many tiny partitions increase file, migration, and planning overhead.
- Cross-partition summaries need deterministic mergeable aggregate state.
- Agent rules still consume bounded local CPU and memory, and central
heartbeat checks still run when no user is online.
- Cross-source rules require reviewed central work and cannot be reduced to
one agent's local stream.
- Agent compromise or suppression remains a trust boundary; authentication
proves which enrolled source reported an event, not that the host itself was
honest.
- Historical regular-expression or high-cardinality queries still require
strict scan and memory budgets.
- Application-supplied sensitive data remains governed by descriptor,
authorization, retention, and export policy regardless of storage tier.
## Staged proof
1. Add aggregate cost-centre instrumentation without changing behavior.
2. Generalize the existing budgeted cold-segment reader to prove authorized
bounded queries over selected hot raw segments; compare every result with
the current SQLite projection.
3. Add a strict partition catalogue and build one signal/day materialization
beside the current projection. Differentially test queries, late data,
duplicates, corruption, cancellation, and restart.
4. Add the bounded recent-memory view and prove overlap deduplication.
5. Move one single-source rule to agent evaluation and one observed dashboard
to a shared lease. Differentially compare the rule with the current server
evaluator and prove that many dashboard viewers do not duplicate work.
6. Prove agent restart, offline spool, sequence gaps, duplicate transitions,
changed rule versions, unavailable-node detection, and lazy evidence
verification. Keep one reviewed cross-source rule central.
7. Run same-host 100,000- and one-million-observation comparisons, then the
four-CPU/eight-GiB release campaign.
8. Stop universal row projection only after the adaptive path reproduces the
current query, incident, retention, rebuild, and authorization behavior.
The first slice of step 2 is implemented as a logs-only, non-public candidate
that reads both hot and cold retained batches under the ordinary typed-query
budgets. Differential tests cover filters, sorting, summaries, regular
expressions, resource scope, an absent projection, and incomplete retention
transitions. The production projection remains the oracle. This candidate
holds the organization lock during its scan and therefore is not yet the
catalogue-snapshot or shared-lease implementation described above.
The published capacity gate is not weakened to make this design pass. If the
product intentionally changes first-query behavior, that contract and its
separate warm-query boundary must be reviewed explicitly before the fixture is
changed.
+263
View File
@@ -0,0 +1,263 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Agent boundary
The Observatory agent is an unprivileged outbound collector. Its local JSON
configuration is authoritative: the server cannot add a path, collector,
command, socket, or environment value remotely.
Configuration and the enrolled credential remain separate root-owned
mode-`0600` regular files under `/etc`. The example systemd unit uses
`LoadCredential=` to expose private, read-only runtime copies to the dedicated
service account. `observatory agent --systemd-credentials` confines both paths
to direct children of systemd's `CREDENTIALS_DIRECTORY`; the agent itself does
not run as root. Its service account receives read access only to the explicitly
selected Caddy, application, and Tend streams. It does not need a Docker socket,
an inbound port, a shell plugin, or write access to the source logs.
The producer and its operator remain authoritative for what a source log is
allowed to contain. Observatory is not a universal DLP system and cannot infer
an organization's private vocabulary or prove that a renamed field is safe.
The initial adapters therefore use a documented fixed field set before durable
spooling, plus a small source-specific `sensitive_fields` list. This is a
defence-in-depth boundary and a useful safe default—not permission to log a
secret upstream. An absent list means the privacy-minimized fields below, and
Observatory never widens it remotely.
- Caddy: method, query-free path, status, response bytes, duration, and a
syntactically bounded request ID. The shipped Caddy example appends that ID
from the completed response as a dedicated top-level field, then removes
the complete request-header and response-header maps, client addresses,
user identity, and the URI query before the edge record reaches disk;
- Web Foundations requestlog: method, normalized route, status, response bytes,
duration, authorization outcome, and request ID;
- Tend: the strict version-1 bounded activation and rollback event fields;
unknown, malformed, unsafe, oversized, or trailing data is rejected.
The optional `linux_metrics` source reads aggregate CPU ticks, load, uptime,
memory, network counters, named filesystem capacity, selected cgroup v2
counters, and processes named by explicit PID files. It never enumerates all
processes, reads command lines or environments, invokes a shell, or opens a
collector port. Configuration assigns stable public labels so local paths and
PIDs are not stored as telemetry attributes. A disappearing selected process
or cgroup emits an `up=0` metric while other host evidence remains durable.
Cookies, authorization headers, request and response bodies, arbitrary
headers, and unknown JSON fields never enter the native batch. By default,
raw query strings, client addresses, referrers, user agents, and anonymous
session identifiers do not enter it either. An application whose documented
privacy policy and operating need permit richer evidence may opt in per source:
```json
{
"kind": "caddy_json",
"path": "/var/log/caddy/example-access.jsonl",
"stream_id": "caddy-access",
"sensitive_fields": ["client_ip", "query", "referrer", "user_agent"]
}
```
`caddy_json` accepts `client_ip`, `query`, `referrer`, and `user_agent`.
`requestlog_jsonl` accepts those fields plus `session_id`. Unsupported and
duplicate names fail configuration validation. Values remain bounded, and IP
addresses must parse as IPv4 or IPv6. Selected values enter Observatory as
unknown sensitive, high-cardinality, unindexed raw fields until an authorized
schema review explicitly classifies them. Query and referrer values can carry
credentials or personal data even when collection is disclosed; filter known
secret-bearing parameters at the producer, restrict access, and choose a
retention window appropriate to the application's policy. The copyable
`Caddyfile.sensitive-access-log` demonstrates the intended producer boundary.
Source scope is not read from any log; it comes from the server-side enrollment
record after credential verification.
## Batching and delivery cadence
`flush_interval` is the maximum delay between collection cycles while the
agent is healthy. `batch_records` caps the number of observations read into
one durable batch for one stream during that cycle; it is not a reason to wait
for a quiet stream to fill. Each batch is committed to the local spool before
its source cursor advances, and delivery removes it only after an exact server
acknowledgement.
Larger batches amortize filesystem, compression, HTTPS, and server admission
costs. A shorter interval reduces live-view latency. The checked-in profile
uses up to 5,000 records once per second. Operators can select any validated
combination from 1 to 5,000 records and 100 milliseconds to one minute based
on source volume and desired freshness. The tailer also caps bytes read during
one cycle, so an existing multi-gigabyte file is caught up over bounded cycles
rather than loaded into memory at once.
The file tailer reads at most 4 MiB of source data per cycle while the checked-
in server accepts at most 32 MiB per authenticated request. That headroom
accounts for native-batch JSON framing without making request memory
unbounded. The server also admits at most eight concurrent authenticated
ingestion bodies. A future byte-aware batcher should make the source/request
relationship explicit for custom profiles that choose different ceilings.
The spool fails closed at its configured byte or age budget. A server
acknowledgement must match the exact source, stream, sequence, and canonical
logical-batch digest before the agent removes its local batch. The local spool
envelope retains a separate digest because it also contains the cursor
checkpoint; private storage encodings are not treated as protocol identities.
Each pending envelope carries
a bounded cursor checkpoint. Startup applies those checkpoints before it reads
new bytes, so a crash between the spool commit and state-file replacement
cannot duplicate a different payload under the same sequence. Collected records
advance only after that envelope is durable; deliberately discarded complete
records advance only after their bounded counters and cursor are durably saved.
Delivery uses the versioned native v2 endpoint. The agent supplies bounded
stream, sequence, signal, exact encoded-body digest, canonical logical-batch
digest, record/byte counts, and first/last observation times as request
metadata. Source and organization scope still come only from the enrolled
credential. On an exact retry the server reads and hashes the complete bounded
body but does not decode, recompress, recatalogue, or reproject it. Time ranges
help select storage and query partitions; overlapping ranges and repeated
values remain valid and are never treated as record-level duplicates.
## Local alert rules
An agent may evaluate an optional, locally configured rule against one exact
log batch after that batch is durable. The first supported rule shape is
deliberately narrow: one `caddy_json` or `requestlog_jsonl` stream, one or more
typed `where` filters, no sort, summary, or historical window, and a bounded
minimum match count. It uses the same typed filter implementation as the
central query evaluator.
```json
{
"alert_rules": [
{
"version": 1,
"id": "http-failures",
"revision": 1,
"stream_id": "application-request",
"query": "logs | where status >= 500 | limit 10",
"minimum_matches": 1
}
]
}
```
The identifier and revision must name an enabled, source-scoped server rule
whose saved query has the same intended semantics. Configuration remains
local; the server cannot install or edit this rule. After the raw batch is
acknowledged, the agent reports only `matched`, `clear`, or `error`, its local
rule identity, the exact raw segment identity, the batch time range, and a
monotonic sequence. It sends no telemetry values in that transition.
The raw spool entry is removed only after both acknowledgements match. If the
transition request fails, retrying first replays the same raw batch as an
idempotent no-op and then replays the same transition. During this
compatibility phase the server stores the authenticated source result but does
not mutate incident state from it. The existing central evaluator remains the
oracle until differential tests and a production soak demonstrate equivalent
results and failures. Multi-batch windows, cross-source rules, and server-owned
incident confirmation remain central work in this preview.
The tailer preserves incomplete lines, discards oversized or malformed
complete records without retaining their contents, caps read work per cycle,
detects copy-truncation, and follows an unread inode through a rename in the
configured file's directory. If the old inode has already disappeared, the
agent records a discontinuity and begins the new file; it does not claim that
unrecoverable bytes were observed.
An organization-authorized local administrator writes a short-lived
enrollment token directly to a new mode-`0600` file. `observatory agent enroll`
exchanges it once over HTTPS and creates the configured credential file without
overwriting any existing secret. If the credential cannot be written, the
client asks the server to revoke the newly enrolled source.
Create the source's resource hierarchy through the supported offline
administration commands before issuing an enrollment. Each command acquires
the same shared process lock as the live server, validates its exact parent
scope, requires the actor's `organization.manage` grant, and returns only
generated public identifiers. Normal hierarchy and enrollment administration
can run while the server is live. Exclusive migrations still require the
server to stop. Never edit the control database directly.
```sh
sudo observatory admin project create \
--config /etc/gamertan-observatory/server.json \
--actor-user-id USER_ID \
--organization-id ORGANIZATION_ID \
--slug gamertan \
--name 'Gamertan'
sudo observatory admin environment create \
--config /etc/gamertan-observatory/server.json \
--actor-user-id USER_ID \
--organization-id ORGANIZATION_ID \
--project-id PROJECT_ID \
--slug production \
--name 'Production'
sudo observatory admin service create \
--config /etc/gamertan-observatory/server.json \
--actor-user-id USER_ID \
--organization-id ORGANIZATION_ID \
--project-id PROJECT_ID \
--environment-id ENVIRONMENT_ID \
--slug web \
--name 'Web application'
```
Creating the hierarchy is intentionally incremental: a successfully created
project remains a valid resource if a later environment or service command is
rejected. Slugs are unique within their parent, and failed authorization or
parent validation creates nothing.
```sh
sudo observatory admin enrollment create \
--config /etc/gamertan-observatory/server.json \
--actor-user-id USER_ID \
--source-id HOST_SOURCE_ID \
--organization-id ORGANIZATION_ID \
--project-id PROJECT_ID \
--environment-id ENVIRONMENT_ID \
--service-id SERVICE_ID \
--lifetime 15m \
--output-file /etc/gamertan-observatory/new-agent-enrollment.json
sudo observatory agent enroll \
--config /etc/gamertan-observatory/agent.json \
--enrollment-file /etc/gamertan-observatory/new-agent-enrollment.json
sudo systemctl enable --now observatory-agent.service
```
The token and credential never appear in command arguments: only their file
paths do. Remove the enrollment-token file after a successful exchange. The
copyable unit in `examples/observatory-agent.service` documents the supported
unprivileged runtime boundary.
## Production dogfood profile
The checked-in `release/agent.json` and `release/observatory-agent.service`
describe the first production profile. One host-scoped source credential is
bound to the public application node. Locally authoritative collectors keep
EQL's edge and application evidence in distinct streams and collect aggregate
Linux and selected service-cgroup metrics. This scope does not imply that all
telemetry belongs to the Observatory application merely because Observatory
receives it.
The profile intentionally omits `sensitive_fields`. Client addresses, query
strings, referrers, user agents, and session identifiers therefore remain out
of the agent spool and server. They may be enabled later, per stream, only
after the producer filter, privacy policy, access grants, and retention window
have been reviewed. The capability remains supported; privacy minimization is
the production default rather than an architectural prohibition.
The Observatory origin's own Caddy access log is not collected by this first
profile. Ingesting the agent's requests from that log would create a perpetual
self-observation loop. The profile does collect the bounded Tend event files
for Gamertan, Sandwich Hime, and Observatory as three independent streams.
Their application release state remains authoritative; ingestion is evidence,
not a deployment dependency.
The service account has supplementary read-only membership in the `caddy` and
`eqlwiki` groups, write access only to its private state directory, no inbound
listener, no Docker socket, and no shell. `PartOf=gamertan-observatory.service`
restarts the agent when a Tend activation moves the shared `current` binary,
so server and agent do not drift across releases.
+201
View File
@@ -0,0 +1,201 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Architecture
Observatory preserves three independent evidence layers:
1. an agent's local spool retains unacknowledged batches;
2. immutable raw segments are committed and checksummed before acknowledgement,
then move unchanged from hot to cold forensic storage;
3. per-organization SQLite projections are disposable query accelerators.
Durable acceptance and query visibility are deliberately separate. A source
may receive an exact acknowledgement as soon as its immutable segment and
control-plane identity are durable. A bounded background projector then makes
that evidence visible to queries. The authenticated interface reports this
lag for the selected organization instead of pretending that accepted and
indexed mean the same thing.
The control database stores Web Foundations identities, organizations, scoped
access grants, source credential digests, sequence watermarks, segment
projection state, dashboards, alert rules, incident metadata, and optional
user-owned Web Push endpoints and their organization-scoped mappings. Every
organization's query projection is stored in a distinct SQLite database.
Authorization is applied before opening that projection.
Saved queries and dashboards live in the control database, but every key and
foreign-key relationship includes the organization identifier. Saved query
text is parsed into the same typed AST at write time; both representations are
stored and revalidated for exact semantic agreement when read. Updates use
optimistic revisions. Dashboard panels reference only saved queries from the
same organization. Source-control exports deliberately omit tenant IDs,
operator IDs, timestamps, and internal revisions.
The web interface is an ordinary `net/http` application rendered through
compiler-generated Sandwich Hime components. The application buffers complete
HTML before committing status and headers. Hime-san remains a development and
CI tool; the service links only the pinned Sando runtime. Content-hashed CSS
and JavaScript are embedded in the binary and served under immutable URLs.
JavaScript opens an authenticated SSE connection only to learn that newer data
exists. The stream carries no telemetry or resource labels, and dropping it
does not remove any navigation, query result, table, or authentication
function.
The text language and visual builder both produce the same versioned typed AST.
Planning receives an already-authorized organization/resource scope separately
from that AST; query text cannot select a tenant. Explain output names the
scoped projected source, reviewed descriptors and indexes, estimated scan,
cache eligibility, budgets, and required permissions. Unknown fields remain
raw-query candidates but default to sensitive, high-cardinality, and unindexed.
Execution opens only the already-authorized organization's projection in
query-only mode. Server-owned project, environment, and service constraints
are added independently of the AST; the executor applies typed comparisons,
bounded RE2 regular expressions, time windows, grouping buckets, aggregates,
sorting, row limits, and separate time, decoded-byte, and memory ceilings.
Only default safe columns and fields explicitly referenced by the query enter
the result table. `window 24h` is a lookback; `window(5m)` is a distinct
aggregation bucket in the versioned AST.
Alert rules reference a saved query in the same organization. A single
evaluator claims each due rule by advancing its next-evaluation time before it
opens the organization's query projection, preventing concurrent duplicate
evaluation. The ordinary query budget remains authoritative. A configured row
threshold determines whether an evaluation matches; consecutive matches move
an incident from pending to firing. Query failure records only the bounded
code `query_unavailable` and leaves an existing incident unchanged. Incident
state and its append-only event sequence live in the control database, contain
no query result or telemetry value, and remain organization-keyed on every
relationship.
Web Push remains downstream of durable incident state. Only a committed
transition into `firing` enters a bounded, deduplicated in-memory queue. The
dispatcher reauthorizes `incidents.read`, encrypts one fixed generic sentence,
and uses a redirect-free HTTPS client that rejects non-public DNS results.
Vendor delivery cannot block rule evaluation, and delivery failure cannot
change incident state. The service worker ignores payload content and opens
the authenticated application rather than carrying a tenant or incident
identifier through the push relay.
Unknown attribute keys produce descriptor proposals only after their raw
segment is committed. Proposal evidence is aggregated once per segment using
the segment digest, organization, and field as the idempotency identity. The
control database stores counts, estimated bytes, inferred type, first/last
observation times, and a generic example query—not observed values. Built-in
reviewed fields are excluded. Proposals remain sensitive, high-cardinality,
and unindexed; proposal persistence does not activate a descriptor.
Descriptor activation is an explicit organization-authorized operation. A
reviewed descriptor is loaded from a bounded private JSON file; unknown
properties and weak or symlinked files are rejected. Observatory copies the
currently active descriptors into a new per-organization projection version,
builds a typed custom-field index by scanning the disposable observation
projection, and changes the active version in the same SQLite transaction.
Invalid historical values are omitted rather than coerced. Existing and newly
ingested observations use the active registry after commit, while prior index
tables remain available for recovery. The control-database proposal status is
held under a write claim during the build and acknowledged only after the
projection commit; retry repairs an interrupted acknowledgement idempotently.
## Ingestion transaction
1. Authenticate the source credential and load its server-owned scope.
2. For native v2, validate the bounded transport envelope. If it exactly
matches the current acknowledged stream watermark, hash and discard the
complete body, recheck the watermark under the source lock, and return the
retained acknowledgement without decoding or writing it again.
3. For a new batch, validate decompressed size, record count, field bounds,
timestamps, signal type, sequence, and every envelope/body field.
4. Commit a content-addressed zstd raw segment with `fsync` and atomic rename.
5. Serialize organization quota admission and reject the exact segment before
cataloguing it when the approved quota is exhausted.
6. In one control-database transaction, catalogue the committed segment and
advance the `(source, stream)` watermark with its bounded envelope metadata.
7. Acknowledge the exact sequence,
raw-segment digest, and canonical logical-batch digest.
8. Outside the acknowledgement path, group a bounded number of one
organization's pending segments into one projection transaction. Project
at most four distinct organizations concurrently, while keeping each
tenant's base projection, active custom index, metric rollups, and replay
ledgers in its own transaction.
9. Aggregate unknown-field proposal evidence without retaining observed
values, then mark each projected segment complete in the control database.
The dogfood server bounds an authenticated request at 32 MiB and admits at
most eight ingestion bodies concurrently. File agents read no more than 4 MiB
of source text into a cycle. These independent bounds preserve batching
headroom while preventing source credentials from creating unbounded request
memory pressure.
A retry of the same sequence and digest is idempotently acknowledged even
while projection is pending. Reusing a sequence with different bytes or
submitting an older sequence is rejected. If projection fails, the durable
segment remains pending and the projector retries it without holding the
source or listener hostage. Work is bounded and selected fairly across
organizations so one tenant's corrupt segment cannot prevent other tenants
from advancing.
Server startup first reconciles raw objects and control metadata without
decoding already catalogued objects, then opens the listener and drains
pending projections in the background. The one-shot `check` and `migrate`
commands retain a blocking recovery path for offline verification.
Every projected metric sample also updates a five-minute aggregate in the same
organization projection transaction. Rollups retain exact count, sum, minimum,
and maximum plus a deterministic bounded histogram for explicitly approximate
percentiles. Only reviewed, non-sensitive, bounded-cardinality dimensions with
the `metric` retention class enter that longer-lived projection. Unknown and
sensitive attributes remain raw-only. Summary queries that can be represented
faithfully select the rollup explicitly in their explain plan; unsupported
query shapes continue to use raw samples.
The server applies retention after recovery and once per hour. Projected rows
expire at their signal's hot cutoff. Once every record in a segment is outside
that hot window, the control database first records an exact cold destination,
then the unchanged zstd object is atomically renamed into the private cold
tree, and finally its catalog path and tier advance. Recovery completes either
side of that rename idempotently. Cold segments remain checksum-verifiable and
queryable through a slower scan path with the ordinary authorization and
resource budgets. Cold raw evidence is preserved indefinitely by default.
Only a policy with `delete_cold_raw` explicitly enabled marks segments beyond
its final cold cutoff as retiring and removes them through a separate
crash-recoverable lifecycle. Resolved incidents and security audit evidence
use the configured evidence window. Organization overrides may shorten
defaults. Extending a finite server policy to indefinite preservation requires
an exact organization approval and an enforceable storage quota.
The agent has a separate durability boundary. It commits a private,
checksummed zstd envelope before attempting HTTPS delivery and removes it only
after an acknowledgement binds the exact logical batch. Its envelope digest
continues to protect the checkpoint and compressed local bytes. Collection
adapters use fixed whitelists so known credentials and high-risk fields are
absent before the spool write. Server configuration cannot alter the agent's
selected local sources.
OTLP/HTTP accepts the standard protobuf wire shape for logs, metrics, and
traces without enabling gRPC, a collector listener, or remote configuration.
The server authenticates the enrolled source before decoding, applies limits
to both compressed and decompressed bytes, removes known credential-bearing
attribute keys, and injects the source's stored resource scope. OTLP payloads
cannot select an organization, project, environment, or service. Automatic
stream sequences are assigned under a per-source lock; native batches retain
their explicit replay-safe sequence and digest acknowledgement contract.
Linux host metrics are collected in the same unprivileged agent cycle and
enter the same durable spool. The collector reads a fixed set of bounded
`/proc` and cgroup v2 files, named filesystem statistics, and only process IDs
resolved through explicitly configured PID files. Files are required to be
regular and non-symlinked; cgroup traversal is confined component-by-component
beneath the configured root. Local paths, raw PIDs, command lines, and
environment values are not projected.
## Tenant boundary
Payloads contain no organization, project, environment, or service selector.
Those values come from the enrolled source record after credential
verification. Published Web Foundations Preview 3 supplies user identities,
personal and shared organizations, resources, teams, invitations, and scoped
query grants, plus the forced initial-password rotation contract. Platform
operator status is a separate policy and does not authorize telemetry access.
A query request names a desired resource, but the server independently
authorizes that scope and computes sensitive-field access before it constructs
the planner input.
+152
View File
@@ -0,0 +1,152 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Local platform bootstrap
Bootstrap is deliberately local and single-use. It creates the first user,
marks that user as a platform operator, creates their personal organization,
and grants owner access only inside that organization. Platform operation does
not imply access to another organization's telemetry.
Production configuration and the generated password file must be root-owned,
mode `0600`, regular files. Observatory creates the file exclusively and
refuses an existing path. The password is never a command argument, output
field, manifest value, log value, or persisted cleartext value.
```sh
sudo observatory admin bootstrap \
--config /etc/gamertan-observatory/server.json \
--username operator \
--email operator@example.com \
--display-name 'First Operator' \
--generate-password-file /root/observatory-bootstrap-password
```
The command returns only the opaque user and personal-organization IDs plus
`password_change_required: true`. Read the file locally, sign in, and replace
the temporary credential. That session is restricted to password rotation,
logout, health, and immutable application-shell assets. A successful change
revokes every session, clears the browser cookie, and requires a fresh login.
Delete the generated file only after the replacement login succeeds.
## Recover local access
If an operator loses a credential, recover it only from the host. Observatory
does not expose a password-reset route, email flow, recovery token API, or
registration window:
```sh
sudo env CREDENTIALS_DIRECTORY=/run/credentials/gamertan-observatory.service \
observatory admin user reset-password \
--config /run/credentials/gamertan-observatory.service/server.json \
--systemd-credential-config \
--identifier speelman \
--generate-password-file /root/observatory-password-recovery
```
The command creates the output file exclusively as a root-owned regular file
with mode `0600`. It then atomically installs that one-time credential, restores
the password-change requirement, revokes every session, and appends a generic
audit event without the credential or its path. If the database operation
fails, the generated file is removed. Read the file locally, complete the
server-rendered password-change form, and delete the file after the new login
succeeds. Never place the credential in shell arguments, chat, logs, manifests,
or deployment state.
There is no public first-user registration window. The bootstrap command is
single-use, local, and refuses a second platform user. If an operator already
has an appropriately generated password, `--password-file` remains available;
that explicitly supplied credential is treated as permanent and does not set
the forced-change flag. The two password flags are mutually exclusive.
If bootstrap fails after creating a generated credential, Observatory removes
the file after revalidating its exact path, type, owner, and mode. A process
crash between file creation and database bootstrap can leave a credential with
no account; inspect the control database and remove that exact file before a
reviewed retry. Never replace the path with a symlink or broaden its mode.
When the installed service loads its configuration and Web Push key through
systemd credentials, use that same confined runtime view rather than copying
or changing credential modes:
```sh
sudo env CREDENTIALS_DIRECTORY=/run/credentials/gamertan-observatory.service \
observatory admin bootstrap \
--config /run/credentials/gamertan-observatory.service/server.json \
--systemd-credential-config \
--username operator \
--email operator@example.com \
--display-name 'First Operator' \
--generate-password-file /root/observatory-bootstrap-password
```
The systemd mode accepts only a direct child of the declared credential
directory, owned by root or the current service user, with mode `0400`, `0440`,
or `0600`. It is mutually exclusive with the local non-root development flag.
Every command that loads the server configuration—including user, invitation,
resource, enrollment, descriptor, retention, query, import, export, and
migration operations—accepts the same `--systemd-credential-config` boundary.
Operators do not need to copy a runtime credential or weaken its mode merely
to run an administrative command.
The browser login form carries an independent, short-lived, unpredictable
token in a Secure, HttpOnly, SameSite=Strict cookie and the rendered form.
Authenticated forms use separate purpose-bound tokens derived from the opaque
session. These tokens are the primary CSRF proof for ordinary server POSTs.
`Origin` and Fetch Metadata are independent contradiction checks: explicitly
cross-site requests and tokenless requests remain rejected, while missing or
opaque metadata from privacy tools cannot prevent a valid form submission.
Failures return a fresh server-rendered form with bounded guidance and never
echo the submitted identifier or password.
## Add a user through an invitation
Later users are provisioned locally. Each receives an automatically created
personal organization, but no access to anyone else's telemetry. Create a
private password file without placing the password in shell history, then run:
```sh
sudo observatory admin user create \
--config /etc/gamertan-observatory/server.json \
--username responder \
--email responder@example.com \
--display-name 'Incident Responder' \
--password-file /etc/gamertan-observatory/responder-password
```
An owner of the destination organization creates an expiring, single-use
invitation. The owner must supply their opaque user and organization IDs:
```sh
sudo observatory admin invitation create \
--config /etc/gamertan-observatory/server.json \
--actor-user-id USER_ID \
--organization-id ORGANIZATION_ID \
--email responder@example.com \
--lifetime 15m \
--output-file /etc/gamertan-observatory/responder-invitation
```
The token is written only to the new mode-`0600` file. Existing paths,
symlinks, multiline values, and weak files fail closed; a database invitation
is cancelled automatically if its token file cannot be persisted. Command
output contains metadata, never the token. Transfer the file through a
separately protected channel and accept it locally:
```sh
sudo observatory admin invitation accept \
--config /etc/gamertan-observatory/server.json \
--user-id INVITED_USER_ID \
--invitation-file /etc/gamertan-observatory/responder-invitation
```
Acceptance requires the provisioned user's exact normalized email address.
The token cannot be reused. Remove both password and invitation files after
the user confirms access. The preview intentionally has no public registration,
email-delivery protocol, or self-service invitation UI.
Bootstrap and later user provisioning each create a user, personal
organization, and access grant through separately checked storage operations.
Until that sequence becomes one control-database transaction, retain a
verified control-database backup before provisioning identities. If a command
reports a partial provisioning failure, stop and restore or inspect the
database rather than blindly retrying it.
+186
View File
@@ -0,0 +1,186 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Capacity campaign
Observatory's release capacity gate is executable and intentionally narrow. It
measures this implementation on one 4-vCPU/8-GiB Linux boundary; it is not a
claim of generic superiority or unlimited scale.
The campaign:
- sustains 2,000 mixed observations per second for one hour across four
equally weighted organizations so concurrent isolation and all four
constrained CPUs are exercised;
- absorbs 10,000 mixed observations per second for 60 seconds;
- requires p95 ingestion-to-query visibility below two seconds;
- expands the primary organization to at least ten million observations and
runs indexed log and metric-rollup views over its last 24 hours, requiring
every p95 below three seconds;
- places 72 ordered batches at the edge of the 72-hour outage budget, replays
them, recognizes a duplicate, and removes local evidence only after an exact
logical-batch acknowledgement;
- archives expired raw objects unchanged, queries cold evidence, and removes
only material beyond the final cold cutoff; and
- records bounded RSS and disk growth without emitting a path, host, user,
credential, source value, or telemetry value.
The aggregate release gate is not a claim that one organization can ingest
10,000 observations per second through its deliberately serialized SQLite
projection. The same fixture accepts `-primary-phase-weight 7` for a separate
70-percent hot-tenant diagnostic and records that weight in its JSON report.
The ten-million-observation query corpus is still built in the primary
organization after the timed phases.
The workload producer and visibility observer run independently. The observer
queries each primary log batch while traffic continues and records when that
timestamp reaches the read model; it never makes the producer wait for its own
query. The achieved ingest rate therefore measures scheduled durable
acceptance, while the separate visibility distribution still captures
background projection lag under the same load.
Run a short development proof with:
```sh
./scripts/capacity-campaign.sh
```
The ordinary public-preview gate runs that development proof after the
complete deterministic verifier and five-second smoke passes for each fuzz
target:
```sh
./scripts/preview-gate.sh
```
This is the default dogfood gate. The hour, ten-million-observation, extended
fuzz, fleet, and 24-hour campaigns are milestone tools. They are not required
for every interface iteration and must not be implied by a preview that did
not run them.
The release campaign must run inside an externally enforced four-CPU,
8-GiB cgroup and requires an explicit mode:
```sh
OBSERVATORY_CAPACITY_MODE=release ./scripts/capacity-campaign.sh
```
The resulting JSON is aggregate evidence. A passing development run does not
replace a run against the exact packaged release commit, its immutable digest,
or the later medium-fleet soak. A campaign that completes every stage but
misses a terminal rate, visibility, query, or memory gate still emits the same
aggregate report with `pass: false` before returning a failure. Earlier stage
failures remain fail-closed and may produce only the bounded stage marker and
error. Individual visibility samples may be observed for up to 30 seconds so
one outlier does not erase the phase evidence; the release boundary remains
the aggregate p95 below two seconds.
Report schema version 2 adds the backlog present immediately after synthetic
fill, projection-drain duration, storage bytes by raw/control/projection class,
and primary-projection SQLite page bytes by checked-in schema object. These are
aggregate performance counters, not telemetry export.
## August 17 constrained-run observations
The first full-duration campaign found a concurrent first-write directory
creation race after completing its one-hour sustain phase. The directory
validator was corrected to tolerate `EEXIST` only long enough to re-inspect the
exact private, non-symlink directory chain, and a 64-writer regression now
protects that boundary.
The corrected implementation was then exercised in a disposable Debian 12
container with four CPUs, 8 GiB of memory, a 1,024-process ceiling, a read-only
root filesystem, no network, all Linux capabilities dropped,
`no-new-privileges`, and a non-root user. The container used the pinned image
digest:
```text
debian@sha256:936abff852736f951dab72d91a1b6337cf04217b2a77a5eaadc7c0f2f1ec1758
```
That run completed 7,200,000 mixed observations in 3,600.38 seconds: about
1,999.79 observations per second, within the one-percent sustain tolerance.
It did not pass the burst gate. The 600,000-observation burst required
227.73 seconds, about 2,634.66 observations per second rather than the required
10,000. The container never reached its memory boundary or an OOM condition;
its observed memory remained below 2 GiB. Aggregate block-I/O counters reached
approximately 57.1 GB while retained test data was approximately 8.1 GB,
identifying synchronous durable-write amplification as the next measured
engineering boundary rather than CPU or memory exhaustion.
Once the burst miss was conclusive, the disposable run was stopped during its
ten-million-observation fill. Its dataset was removed by the fixture's normal
signal cleanup; timestamped stage logs and container exit evidence were
retained. Queries, outage replay, retention, and the final aggregate report
from that run are therefore not release evidence. Observatory will not lower
or relabel the published gate: durable-write grouping and projection work must
be measured, reviewed, and followed by a complete exact-candidate rerun.
## August 18 query-boundary observation
A later constrained candidate reached the complete ten-million-observation
primary corpus but stopped at the first required query. The indexed
`status >= 500` path still scanned and grouped the matching raw log rows, and
the ten-second execution budget expired before it produced the route/window
summary. No aggregate report was emitted, so that run is failure evidence—not
a capacity pass.
The response is an additive, exact five-minute status/route projection. It is
updated in the same SQLite transaction as the primary projection, uses a
per-segment ledger for replay idempotence, backfills older projections once,
and expires with the hot-log projection. A non-aligned lower window boundary
still scans its exact raw fragment, bounded to less than five minutes. Queries
that need cold evidence or do not match the narrow typed shape stay on the raw
path.
Before another full release campaign, the implementation completed the entire
development fixture and a separate one-million-observation diagnostic inside
the release cgroup boundary. The diagnostic used four CPUs and 8 GiB of memory;
the error summary completed five times with a 12.94 ms maximum sample, the
ordinary indexed item view with a 4.59 ms maximum, and the metric rollup with a
3.73 ms maximum. Maximum RSS was 205,545,472 bytes and the dataset was
1,005,353,808 bytes. Those measurements are a scale diagnostic only. They do
not replace the required one-hour, ten-million-observation exact-candidate
campaign or its three-second p95 gate.
## August 18 asynchronous-projection diagnostic
After durable acknowledgement was separated from grouped background
projection, a short local Linux/WSL2 development run exercised the same mixed
fixture with a two-second sustain, two-second burst, 100,000-observation query
corpus, four organizations, and a 500-millisecond visibility target. It was not
run inside the release cgroup and is not release evidence.
The sustain reached about 2,530 observations per second with 31.92 ms p95
ingest time and 201 ms p95 visibility. The burst reached about 10,787
observations per second with 29.83 ms p95 ingest time and 404 ms p95
visibility. The three required query shapes completed with p95 samples of
2.264 ms, 1.992 ms, and 1.512 ms. Maximum RSS was approximately 208 MB and the
dataset approximately 164 MB.
This diagnostic is evidence that acknowledgement-path projection writes were
the measured burst bottleneck and that the revised shape is worth the full
campaign. It does not close the four-CPU/eight-GiB gate, the one-hour sustain,
the 60-second burst, the ten-million-observation corpus, outage replay, or the
exact packaged-candidate requirement.
## August 18 exact-candidate boundary
The exact asynchronous-projection candidate was then run in the release
four-CPU/eight-GiB container. It completed the one-hour sustain, burst, and
ten-million-observation fill without an out-of-memory condition. After a
ten-minute projection drain, 1,118 committed raw segments (922,788,512 bytes)
remained pending and the oldest projection lag was 12 minutes 22 seconds. The
campaign therefore failed closed before the query, outage-replay, retention,
and terminal aggregate stages.
This is useful negative evidence: durable acceptance and bounded memory held,
but projection throughput at that synthetic scale is not yet a supported
claim. The result does not block lower-volume public dogfooding. It does block
calling the release-scale capacity gate complete, and it is the reason that
extended capacity remains a milestone campaign rather than the default
preview loop.
The retained baseline comparisons, rejected multi-row and durability
experiments, and ordered lower-level case studies are recorded in
[PERFORMANCE.md](PERFORMANCE.md). Rejected experiments must not be repeated
without a materially changed premise and a new same-host baseline.
+72
View File
@@ -0,0 +1,72 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Saved queries and dashboards
Observatory persists query definitions before building the web interface on
top of them. A saved query contains bounded human metadata, one organization,
an optional project/environment/service scope, the reviewed query text, and
the exact versioned typed AST produced from that text. Reads reparse the text,
hydrate its duration fields, validate the stored AST, and require the two
representations to match.
Dashboards are versioned ordered collections of at most 16 panels. Each panel
selects one saved query and one deliberately small visualization contract:
`table`, `stat`, or `timeseries`. Composite foreign keys prevent a panel from
referencing another organization's query. Updates to saved queries and
dashboards require their current revision so concurrent edits fail instead of
silently overwriting one another.
Identifiers are generated from cryptographic randomness; randomness failure
fails the write and never falls back to time or a predictable counter.
## Source-control export
`ExportDashboard` produces strict version-1 JSON containing the dashboard
definition and each referenced query once. It keeps the stable definition IDs
needed by panels, but omits organization IDs, operator user IDs, timestamps,
internal revisions, and redundant stored AST bytes.
`observatory export` performs the same organization-authorized read from the
local server data directory. `observatory import` accepts exactly one strict,
bounded JSON bundle on standard input and requires the destination
organization twice: once as `--organization-id` and again as the exact
`--approve-organization` value. Import reparses every query, validates each
resource scope against the destination organization, replaces all portable
identifiers with cryptographically generated local identities, and commits
the queries, dashboard, and panels in one SQLite transaction. A bundle cannot
select its tenant or actor.
Example:
```sh
observatory export --organization-id organization-id \
--actor-user-id user-id --dashboard operations >operations.json
observatory import --organization-id organization-id \
--approve-organization organization-id --actor-user-id user-id \
<operations.json
```
The Sandwich Hime interface creates saved queries and one-panel dashboards
through organization-authorized, CSRF-protected forms. A first assisted builder
serializes fixed, bounded controls into ordinary text and then uses the same
parser and stored AST contract as the text editor. It never sends a caller-
constructed AST around query validation.
An authorized dashboard page exposes ordinary server-rendered forms for its
metadata and panels. Metadata changes, panel additions, panel edits, and panel
removals submit the dashboard's opaque identity and current revision. The
server reloads the organization-owned dashboard, preserves every untouched
panel, validates saved-query ownership and presentation compatibility, and
uses the storage transaction's optimistic revision check. A concurrent edit
returns `409 Conflict` and requires a reload; it never silently overwrites the
newer definition. These controls remain fully usable without JavaScript.
Dashboard pages execute every saved panel through the same bounded query
engine and retain the full table for every presentation. Time-series panels
may add a native `meter` summary for at most 48 finite, nonnegative numeric
points; unsupported values fail closed to the table alone. Strict JSON export
exposes only the source-control definition. The first preview intentionally
keeps assisted editing to bounded controls and leaves richer expressions to
the complete typed query editor; a second browser-side query language is not a
release requirement.
+305
View File
@@ -0,0 +1,305 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Tend deployment boundary
Observatory pins Tend `v0.2.0-preview.2` as a checksum-verified Go tool and uses
its schema-2 singleton-candidate strategy on Linux. The
release configuration is [`release/tend.json`](../release/tend.json). It pins
the public origin, live and candidate loopback addresses, health paths,
application marker, release root, state path, shared host lock, and exact build
package. It contains no secret values.
## Two deliberately different processes
The installed service explicitly runs:
```text
observatory server --config %d/server.json --systemd-credential-config
```
Systemd copies the root-owned mode-`0600` configuration and Web Push private
key into the service's private credential directory. Systemd 255 presents each
runtime copy as a root-owned mode-`0440` credential confined to the unit;
Observatory accepts that mode only when explicit systemd-credential validation
also proves the credential-directory boundary and owner. The static
`gamertan-observatory` service user can read those copies and write only its
state directory. The originals stay root-owned mode `0600` under
`/etc/gamertan-observatory/`.
Local operator commands that read the server configuration use the same
explicit `--systemd-credential-config` flag and confined credential-directory
policy. This applies to bootstrap, resource and enrollment management,
retention and schema review, local queries, dashboard import/export, and
migrations; no operator workflow needs a less restrictive duplicate config.
Tend executes a candidate binary without arguments and supplies only
`OBSERVATORY_TEND_CANDIDATE_LISTEN=127.0.0.1:18093`. That narrowly named mode:
- accepts only a numeric loopback address and nonzero port;
- exposes only `/`, `/healthz`, and `/readyz` over plain loopback HTTP;
- returns a fixed marker and security headers;
- does not read configuration, open storage, acquire a process lock, run a
migration, evaluate alerts, send Web Push, access the network, or write a
file.
The candidate proves that the exact binary starts and answers its bounded
contract. It does not pretend to prove a live data migration. After the
candidate passes, Tend stops it, atomically selects the immutable release,
restarts the installed service, probes the real loopback application, and
probes the routed HTTPS origin. A failure restores the previous release.
The candidate listen variable must never appear in the shared Tend environment
file. Tend's server policy rejects that mistake. The live address remains in
the root-owned Observatory configuration.
## Installed files
The reviewed deployment inputs are:
- `release/observatory.service`: hardened non-root service;
- `release/server.json`: non-secret dogfood server configuration;
- `release/observatory.env.example`: intentionally empty shared environment;
- `release/Caddyfile.observatory`: initial origin handler;
- `release/tend.json`: application-owned packaging and activation contract.
The Caddy handler also defines a bounded, rotated JSON edge log. It strips the
entire query, request and response header maps, client addresses, and Caddy
user identity before writing. A late `log_append` copies only the bounded
application response request ID into a dedicated top-level field, allowing the
agent to correlate accepted edge and application records without retaining
cookies, credentials, referrers, user agents, or query values. The log file is
not an application authorization record and remains separate evidence.
That installed handler is the privacy-minimized deployment policy, not a
platform prohibition. Applications that disclose and require richer traffic
evidence can use per-source `sensitive_fields` with a separately reviewed Caddy
filter, such as `examples/Caddyfile.sensitive-access-log`. The richer policy
still removes both header maps and never retains cookies or authorization
headers. Its query-key deny list is only a starting point: the application must
add every secret-bearing parameter it accepts before enabling query collection.
On the host, their controlled destinations are:
```text
/etc/gamertan-observatory/server.json root:root 0600
/etc/gamertan-observatory/web-push.json root:root 0600
/etc/tend/environment/observatory.env root:root 0600
/etc/tend/services/observatory.json root:root 0644
/etc/systemd/system/gamertan-observatory.service
/opt/gamertan-observatory/
/var/lib/gamertan-observatory/
```
The initial Caddy stanza is an explicit infrastructure change performed before
the first Tend activation. Tend validates and uses the existing routed origin;
it does not silently edit the host's top-level Caddyfile for a new service.
## First installation and the first Tend maintenance release
Tend intentionally bootstraps singleton state from an existing, validated
`current` release pointer. It does not invent a service account, Caddy origin,
root-owned configuration, or first live release. Observatory's one-time
installation therefore uses a twice-built, checksum-approved Tend package from
an exact clean pushed commit, exercises that binary in the stateless candidate
mode, installs its immutable release, creates the first `current` pointer, and
starts the reviewed service and Caddy origin under direct operator control.
The next exact pushed commit became the real Tend maintenance campaign:
candidate health and application smoke, pointer activation, service restart,
routed public-origin smoke, state recording, rollback, and identical-artifact
redeployment. The observation below separates the one-time bootstrap from that
completed dogfood exercise.
## Initial dogfood bootstrap observation
On August 17, 2026, the initial live Observatory bootstrap used a Tend package
built twice from one clean pushed development source. Both package runs
produced the same SHA-256 digest:
```text
42c21deba0519955ea7cbb140ea37321403cb26622d54d69c68bcfd19fe2764e
```
The installed `v0.0.1-preview.3` development binary reports Go 1.26.6. Tend
validated and safely extracted the immutable archive, and the stateless
candidate contract passed before the directly controlled first activation.
The resulting non-root systemd service remained ready with zero restarts while
the canonical HTTPS origin and the pre-existing EQL Helper, Gamertan, and
Sandwich Hime origins were rechecked.
The bootstrap found two real integration defects before activation was
accepted:
- systemd 255 presents a copied `LoadCredential` file as root-owned mode
`0440`, although the original remains root-owned mode `0600`; Observatory
originally rejected the runtime copy. The validator now permits `0440` only
when explicit systemd-credential mode also proves that the file is inside
the unit's credential directory and owned by root;
- an omitted Web Push notifier was stored as a typed nil pointer in a non-nil
interface, so the first incident evaluation panicked. Optional push
construction now returns a genuinely nil interface when no notifier is
configured, and its regression test exercises an incident with Web Push
disabled.
Neither failure altered an existing application origin. Failed Observatory
artifacts were retained as diagnostic evidence, and the service was accepted
only after the corrected package passed its checks. Tend state remained
intentionally uninitialized until the first maintenance activation.
## First Tend maintenance and rollback observation
Trusted CI run 220 passed the exact pushed maintenance source. Tend built it
twice with Go 1.26.6 and module downloads disabled; both archives were
byte-identical at:
```text
3afed7dcc719d98d9bc9a4e13790ce0a71036c339f1a354fa4e0d67abab3ccdb
```
On August 17, 2026, `tend push` sent that approved digest through the dedicated
forced-command deployment account. The host policy accepted only the
`observatory` service and validated the archive before Tend exercised the
stateless candidate, activated `v0.0.1-preview.4`, restarted the installed
unit, checked loopback health and readiness, probed the routed HTTPS origin,
and initialized deployment state with `v0.0.1-preview.3` as the previous
release.
The recorded Tend rollback then restored the exact preview.3 release and
swapped preview.4 into the previous position. Loopback health, the public
Observatory origin, and EQL Helper continuity passed before the same approved
preview.4 archive was sent through the restricted transport again. Tend
revalidated and reactivated its existing content-addressed release. Final
state records preview.4 active and preview.3 previous.
The candidate port and shared host lock were free after the exercise. The
service reported zero restarts and no warning-or-higher journal entries, and
the Observatory, EQL Helper, Gamertan, and Sandwich Hime origins all returned
success. This closes Observatory's initial Tend maintenance-and-rollback
dogfood claim; it does not close the separate medium-fleet, capacity, or public
preview release gates.
## Startup-readiness dogfood finding
On August 18, 2026, Tend correctly refused Observatory
`v0.0.1-preview.13` after the activated process did not bind its loopback
socket inside the 30-second post-activation window. Tend restored the exact
preview.12 release, preserved the earlier rollback release, recorded the failed
digest, and returned the service to active state with zero restarts.
The package and stateless candidate had passed. The full server then performed
raw retention and identity-evidence pruning synchronously before opening its
listener. Those maintenance passes are bounded and valid, but their elapsed
time depends on accumulated data and cold filesystem state; they are not a safe
availability prerequisite. Observatory now completes mandatory raw recovery,
opens the configured listener, and only then runs retention and evidence
pruning through the same background path used for hourly maintenance. A
maintenance failure remains visible in bounded logs but does not prevent the
otherwise healthy server from answering readiness probes.
This also records a Tend integration limitation: a stateless candidate proves
the packaged binary and candidate process boundary, not a stateful
application's complete startup path. Tend should continue to restore on a
missed activation window, but a future release should report this distinction
more explicitly and reject linked-worktree packaging before the build rather
than after Go omits `vcs.revision`. The trusted Gitea release workflow produced
and verified identical preview.13 bytes, but the Gitea Actions artifact API did
not list the successfully uploaded artifact; the independently reproduced
local digest and CI log therefore remained the review evidence for this
attempt.
Preview.14 exposed a second, independent startup boundary on the accumulated
production archive. Mandatory recovery enumerated every hot raw segment by
checksum-verifying, decompressing, and retaining every decoded batch before it
compared the archive with the control catalog. With 20,550 small segments this
exceeded the service's 768 MiB memory limit before the listener opened. Tend
restored the recorded release, but the same archive-bound algorithm also
prevented that older binary from becoming ready; Tend therefore correctly
left its bounded stateless candidate routed for operator recovery instead of
claiming a successful rollback.
Recovery now walks only private filesystem metadata and compares each object
with a prepared catalog lookup. It decodes one segment only when the catalog
is missing that committed object, and it replays unprojected catalog rows in
pages of 128. This fixes the availability defect rather than hiding it behind
a larger memory allocation. Full checksum verification remains part of
orphan admission, reads, cold archival, deletion, export, and explicit
projection rebuild. A deployment with production-scale retained evidence must
exercise the stateful startup path under its configured memory limit before
activation; the stateless package candidate remains a separate gate.
## Preview.19 native-batch and stateful-Compose observation
Trusted Gitea release-candidate run 380 passed exact source commit
`2b00be0984188b0c59d6a843921e03c9b182b881` with Go 1.26.6. Two independent
Tend package runs and the retained CI artifact produced the same archive:
```text
6ce16931412f618fa4a3d0130fc0f69e7f96f994b1f12e6be3a66a0e49a9af95
```
The public-preview capacity gate passed at 221 observations/second sustained,
1,315/second burst, approximately 60 ms visibility p95, approximately 2.1 ms
query p95, and approximately 173 MiB maximum RSS. These are bounded synthetic
gate results, not a medium-fleet or generic production-capacity claim.
Before activation, the exact candidate was exercised against a copy of the
accumulated production control database, organization projection, and
immutable raw archive. The first migration failed closed while building the
new presence-only projection index: SQLite reported `database or disk is full`
with the service's 64 MiB `/tmp` tmpfs. The same image, data, limits, and
migration passed with a 512 MiB tmpfs, drained 986 pending raw segments to
zero, and finished with 27,788 retained segments. The database was not corrupt;
the index sort needed a larger bounded temporary working area. The reviewed
Compose definition now records that scratch budget explicitly.
Observatory's production topology is a Docker Compose singleton, which Tend
does not yet model. The maintainer therefore paused the durable agent, verified
mode-`0600` SQLite backups and their SHA-256 digests, migrated the live data
offline, and started the exact candidate under the staged Compose definition.
Direct health and readiness passed approximately 3.25 seconds after the final
start; the routed public origin settled approximately one second later.
The first activation script probed the public origin only once. That eager
probe observed a transient `503` and invoked its rollback path even though the
candidate had passed direct readiness. The rollback then demonstrated an
important second boundary: Preview.18 correctly rejected the newly migrated
control schema 11 and entered a fail-closed restart loop. The verified backups
remained intact, but restoring them would have discarded valid forward
migration work. The operator instead stopped the old agent, started the
schema-compatible Preview.19 candidate, waited through bounded direct and
public-origin readiness loops, and then started the matching Preview.19 agent.
An independent observer recorded a bounded `502`/`503` interruption during
the failed rollback and recovery. No continuous-delivery claim is made.
At the immediate post-activation check on August 19, 2026:
- the server and agent both reported the exact Preview.19 image, zero restarts,
no OOM event, and no warning-or-higher log entry;
- `/`, `/healthz`, and `/readyz` returned success through the public origin,
while `/app/` returned its expected authenticated redirect;
- `observatory check` returned `ok` against the live configuration and data;
- all 27,998 retained segments were projected with zero pending work; and
- the first stream advanced by the new agent had non-empty native-v2 batch and
encoded-body digests, proving the authenticated batch-identity path in the
live control catalogue.
This is staging dogfood evidence for an unreleased development build. It does
not create a public tag, close the medium-fleet soak, or make the current
Compose handoff a supported Tend strategy. It does prove that authenticated
`(source, stream, sequence)` batch identity, exact digest replay protection,
raw-first durability, and overlapping-time-window semantics work together on
the live data plane without a global per-record deduplication index.
## Secrets and administration
No secret belongs in `tend.json`, the release manifest, process arguments, or
the shared environment file. Web Push keys and later credentials use systemd
credentials. Local operator bootstrap creates a one-time password in a new
private file and is performed while the application is stopped or through a
separately reviewed administrative procedure; it is not part of deployment
activation. The first browser or API session can reach only rotation, logout,
health, and immutable shell assets until the password is replaced.
The first dogfood deployment is an unreleased development build. A public tag
requires the capacity campaign, rollback exercise, medium-fleet soak, reviewed
public snapshot, checksums, SBOM, signatures, and release gates in the roadmap.
+40
View File
@@ -0,0 +1,40 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Incidents and alert rules
Observatory alert rules reuse a stored, versioned query. They do not introduce
a second expression language, arbitrary SQL, shell execution, or a remote
plugin surface.
Each rule defines:
- one organization-owned saved query;
- a bounded minimum result-row count;
- one to ten required consecutive matching evaluations;
- a severity and a 15-second to 24-hour evaluation interval; and
- an enabled state.
The evaluator claims at most 64 due rules per pass. Every query retains the
server's ordinary time, row, decoded-byte, and memory budgets. Rules execute
without sensitive-field permission; a query that requires sensitive or
unknown fields fails closed as `query_unavailable`. Query failure never clears
an existing incident.
The durable lifecycle is:
1. The first matching evaluation opens a `pending` incident.
2. The configured consecutive-match count promotes it to `firing`.
3. An authorized responder may `acknowledge`, `silence`, or `resolve` it.
4. A non-matching successful evaluation resolves the open incident.
5. An expired silence returns to `firing` if the rule still matches.
Every transition appends a sequenced organization-scoped event. Events record
only the transition, actor identifier, and time. They do not copy query text,
query results, resource labels, or telemetry values into the control database.
The SSE channel carries only a generic refresh hint.
PWA installation, explicit offline inbox access, application badge state, and
generic Web Push are progressive layers over this durable lifecycle. Web Push
is optional and best effort; it cannot create, update, resolve, or otherwise
replace an incident record. Its exact privacy boundary is documented in
[`PWA.md`](PWA.md).
+76
View File
@@ -0,0 +1,76 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Sandwich Hime interface
Observatory's web interface is server-rendered with Hime-san
`v1.0.0-beta.2`. Generated `.sando.go` files are committed and verified for
two-pass byte and modification-time stability. The production binary links
only `gamertan.com/sandwich-hime/sando@v1.0.0-beta.1`; the compiler does not
enter the service dependency graph.
The current surface provides:
- a public project explanation;
- local session sign-in and CSRF-protected sign-out;
- selection among the authenticated user's active organizations;
- bounded one-hour tables for logs, metrics, traces, and deployment evidence;
- organization-authorized creation of persisted queries through typed text or
the first assisted visual builder;
- one-panel dashboards, bounded panel execution, nonnegative numeric meter
summaries with complete table alternatives, and strict JSON export;
- a progressive SSE notification when newer observations are available;
- an organization-scoped incident inbox with durable lifecycle state and
ordinary acknowledge, silence, and resolve forms; and
- bounded alert-rule creation over an existing saved query;
- an installable manifest, deterministic service worker, and offline public
shell; and
- explicit opt-in storage of a read-only incident snapshot with badge state.
Every organization selection is checked against both active membership and
the scoped `dashboards.read` grant. The query executor receives the authorized
organization separately from query text. No browser field can select a tenant
without that server-side decision.
The SSE stream is deliberately an invalidation hint rather than a telemetry
transport. It emits fixed `ready` and `refresh` events with `{}` payloads,
coalesces pending refreshes, caps total and per-organization subscribers, and
is authorized independently when the connection opens. If JavaScript is
disabled, disconnected, or blocked, the same HTML tables and ordinary refresh
links remain usable.
CSS and JavaScript are embedded, content-addressed, and served with immutable
cache policy. The application CSP permits only same-origin styles, scripts,
images, forms, and SSE connections; it does not use `unsafe-inline`.
The assisted builder deliberately produces one optional comparison and one
optional aggregate/group/bucket stage from fixed controls. It serializes that
selection into ordinary query text and submits it to the same parser used by
the text editor; it does not maintain a second query language. More complex
queries remain available through typed text.
Time-series panels render at most 48 finite, nonnegative points with native
`meter` elements. The complete result table is always rendered beside the
summary and remains the canonical accessible representation. Negative,
non-numeric, missing, or unsupported results simply omit the visual summary.
Alert evaluation counts bounded saved-query rows, requires a configured number
of consecutive matches before promotion from pending to firing, and never
resolves an existing incident when query execution itself fails. The incident
event trail records system transitions and authorized human responses without
copying query results or telemetry values into control state.
The service worker precaches only public content-addressed shell assets. It
stores no private response by default. An authorized user must activate the
offline control before the worker fetches a separate read-only incident page
and stores it under that organization's ordinary inbox URL. The snapshot has
no actions, CSRF material, query text, telemetry values, actors, or project,
environment, and service identifiers. Signing out asks the worker to delete
the complete private cache. Session expiry cannot itself reach an offline
browser, so this remains an explicit device-local privacy decision.
Dashboard metadata and panel editing use optimistic revisions, and the bounded
assisted query builder shares the same parser as the complete typed editor.
The incident inbox provides an installable shell, explicit read-only offline
copy, badge state, and optional generic Web Push without making JavaScript an
authority for incident response. Richer visual editing remains future work,
not an alternate query authority or a hidden first-preview gate.
+232
View File
@@ -0,0 +1,232 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Performance engineering ledger
This document preserves measured optimization work, including changes that
were deliberately rejected. It prevents an attractive idea from being
reimplemented and rerun without a materially different premise.
The capacity fixture is a synthetic engineering instrument. Its local results
are useful for comparing two exact implementations on the same host; they are
not production sizing claims and do not replace the constrained release
campaign in [CAPACITY.md](CAPACITY.md).
## Current data path
Observatory deliberately separates four jobs:
1. the agent batches typed observations;
2. the server validates and durably acknowledges an immutable, checksummed,
zstd-compressed raw segment;
3. a background projector builds disposable per-organization SQLite read
models, typed indexes, and rollups; and
4. queries read authorized projections or budgeted cold evidence.
Raw segments are the forensic truth. SQLite is currently a replaceable query
accelerator, not the only copy of an observation. A bounded in-memory layer may
accelerate the recent live window, but it must populate only after raw
acknowledgement and must remain safe to lose and rebuild.
## Experiment ledger
All August 18 local comparisons used the same Linux/WSL2 checkout based on
private commit `7c4f834aee8afcb2e9c3ae534b1b37b03259c9a3`, Go 1.26.6, the same synthetic
mixed workload, and an unconstrained 16-logical-CPU host. They are comparative
diagnostics, not release evidence.
| Experiment | Corpus | Sustain / burst | Visibility p95 | Fill or query notes | Result |
| --- | ---: | ---: | ---: | --- | --- |
| Existing prepared single-row projection writes | 100,000 | 2,630.64/s / 13,084.50/s | 84.7 ms / 228.1 ms | about 198 MB peak RSS; about 176.9 MB dataset | Baseline retained. |
| 256-row multi-value SQLite inserts | 100,000 | 2,631.28/s / 13,015.34/s | 200.7 ms / 382.3 ms | about 197 MB peak RSS; about 205.6 MB dataset | Rejected and removed: no throughput gain, worse visibility and storage. |
| `synchronous=NORMAL` projection plus transaction receipts and recovery reconciliation | 100,000 | 2,630.13/s / 12,991.85/s | 175.35 ms / 230.76 ms | 199,081,984-byte peak RSS; 177,218,281-byte dataset | Rejected and removed: added recovery machinery without a measurable throughput gain. |
| Existing prepared single-row projection writes | 1,000,000 | 3,815.33/s / 18,901.41/s | 121.83 ms / 257.26 ms | fill 6.604 s; queries 6.226/1.839/1.557 ms; 1,090,726,860-byte dataset | Larger baseline retained. |
| `synchronous=NORMAL` projection plus receipts | 1,000,000 | 3,823.49/s / 18,766.63/s | 173.67 ms / 219.41 ms | fill 6.789 s; queries 6.637/1.721/1.586 ms; 1,092,327,298-byte dataset | Rejected and removed: within noise on throughput, slower fill, larger dataset. |
Do not repeat either rejected experiment unless the transaction shape, schema,
SQLite version, storage medium, or workload has materially changed. Record the
new premise and a same-host baseline before doing so.
## Native v2 exact-replay envelope
The native v2 endpoint places bounded batch identity metadata in authenticated
request headers before the JSON record body. A retry of the current
acknowledged `(source, stream, sequence)` can therefore hash and discard the
complete bounded body, recheck the watermark under the source lock, and return
the retained acknowledgement without JSON decoding, zstd compression,
catalogue writes, or projection notification. New batches still follow the
complete validation and raw-first transaction.
An August 18, 2026 Linux/amd64 Go 1.26.6 HTTP-handler microbenchmark used an
exact 500-record, approximately 60.6-KB JSON retry on an Intel i7-10700K. Five
independent benchmark samples recorded:
| Path | Median time | Bytes allocated/op | Allocations/op |
| --- | ---: | ---: | ---: |
| Legacy native v1 exact retry | 4.105 ms | about 22.4 MB | about 14,760 |
| Framed native v2 exact retry | 0.275 ms | about 49.9 KB | 301 |
For this one retry workload, v2 used about 14.9 times less wall time, 449 times
fewer allocated bytes, and 49 times fewer allocations. Reproduce with:
```sh
go test -buildvcs=false ./internal/httpserver \
-run '^$' -bench '^BenchmarkNativeExactReplay$' -benchmem -count=5
```
This is not new-batch throughput, whole-agent delivery latency, or a production
capacity result. It proves only that the early exact-replay path removes the
intended duplicate work. The server still reads and hashes every replay byte;
transport integrity and the immutable retained segment remain authoritative.
## First cost-centre diagnostic
The capacity report now records projection backlog/drain time, raw/control/
projection file bytes, and SQLite page use by schema object. The fields contain
only aggregate counts and checked-in schema names; they contain no telemetry
values, tenant identifiers, or local paths.
An unconstrained local 100,000-primary/109,000-total observation diagnostic on
the same August 18 baseline recorded:
- 19 pending segments and 14,936,883 decoded bytes at the start of drain;
- 4.580 seconds to drain that backlog;
- 446,217 bytes of compressed raw segments;
- 158,247,552 bytes across all organization projection SQLite files and
sidecars;
- 1,705,496 bytes of control SQLite files and sidecars; and
- 97,124,352 allocated SQLite page bytes in the primary projection, comprising
28,409,856 table bytes, 68,702,208 index bytes, and 12,288 internal bytes.
The synthetic observations compress unusually well, so the roughly 355:1
projection-to-compressed-raw ratio must not be extrapolated to real telemetry.
The within-SQLite result is still actionable: indexes consumed about 2.42
times the table bytes and about 70.7 percent of allocated primary-projection
pages. Index write amplification is therefore the first implementation case
study. This one short diagnostic is not a release capacity result.
## Presence-only base-index candidate
The first index case study replaced four full projection indexes with partial
indexes that contain only observations where the indexed value is present:
metric value, HTTP route, HTTP status, and request duration. Severity remains
a full index because its current storage representation uses an empty string
for absence. The migration is independently versioned and changes the old and
new index sets in one SQLite transaction; an interrupted migration therefore
retains the complete prior set and safely retries.
Same-host comparisons against the cost-centre baseline recorded:
| Corpus | Baseline index bytes | Candidate index bytes | All projection SQLite | Projection drain | Query p95 notes |
| ---: | ---: | ---: | ---: | ---: | --- |
| 100,000 primary observations | 68,702,208 | 57,135,104 (-16.8%) | 158,247,552 to 143,429,744 (-9.4%) | 4.580 s to 4.704 s | Same millisecond range; drain difference is within short-run noise. |
| 1,000,000 primary observations | 693,755,904 | 572,768,256 (-17.4%) | 1,087,731,688 to 954,606,472 (-12.2%) | 58.267 s to 54.535 s (-6.4%) | Baseline 6.157/1.908/1.659 ms; candidate 6.156/5.444/1.680 ms. The isolated recent-items increase remains only milliseconds and needs repetition before interpretation. |
The million-observation candidate retained the identical 283,639,808 table
bytes and reduced the primary projection from 977,408,000 to 856,420,352
allocated bytes. Synthetic compressed raw sizes were 4,011,063 and 4,031,350
bytes respectively; that small corpus variance is not attributed to the index
change.
This is a promising bounded schema improvement, not proof that continuous
universal projection is the final architecture. Migration and selective-query
tests must pass from legacy preview databases, followed by the full verifier
and trusted CI, before adoption. The adaptive raw-first design remains the
larger direction.
## What the evidence says
SQLite is not yet proven to be the limiting technology. The failed
ten-million-observation campaign proves that the current *projection shape*
cannot drain the synthetic fill inside the published window. It does not
separate SQLite's engine cost from Observatory's choices around row shape,
index count, JSON expression indexes, typed descriptor indexing, rollups, WAL
checkpoints, or single-organization serialization.
The two rejected experiments also show that transaction syntax and one
durability pragma are not the dominant cost. The next work must measure cost
centres instead of swapping databases or adding cache infrastructure by
intuition.
## Required cost-centre evidence
Add aggregate, value-free timing and byte counters to the synthetic fixture
for:
- native batch validation, JSON encoding, zstd compression, file write,
file `fsync`, directory `fsync`, and control-catalog commit;
- raw-segment open, checksum, decompression, and decode;
- base observation insertion, built-in index maintenance, reviewed custom
index maintenance, metric rollups, log rollups, WAL commit, and checkpoint;
- projector queue depth, oldest lag, rows and bytes per transaction, active
writer time, and time waiting for an organization lock; and
- query planning, rows/bytes scanned, SQLite execution, cold decode, and result
encoding.
These counters belong only in the capacity fixture or bounded internal
instrumentation. They must not include telemetry values, local paths,
credentials, host names, or tenant identifiers.
Projection backlog/drain and file/page accounting above are implemented. The
per-operation CPU/wall-time breakdown remains open.
## Ordered technical case studies
The larger lazy/eager partition design is specified in
[ADAPTIVE_PROJECTIONS.md](ADAPTIVE_PROJECTIONS.md). The ordered experiments
below are its evidence path, not independent promises to ship every idea.
### 1. Index write amplification
The base observation table currently maintains its primary key plus general
scope/time/name indexes and signal-specific severity, value, correlation, HTTP
JSON-expression, trace, and span access paths. Measure per-index bytes and
projection time. Compare only reviewed alternatives such as partial
signal-specific indexes or replacing a generic expression index with an exact
rollup already used by the supported query shape. Every candidate must rerun
the existing query and cold-evidence gates.
### 2. Time and signal partitioning
One organization currently has one SQLite writer. A partition per bounded time
window and/or signal could let logs, metrics, and traces project concurrently,
limit index working sets, and make retention a file-level operation. The cost
is a more complex planner, bounded multi-database queries, atomic partition
catalogue changes, and additional recovery cases. Prototype this only after
the index-cost campaign identifies single-database write amplification.
### 3. Bounded recent-memory view
A per-organization ring keyed by segment digest can make the latest live tail
visible immediately after durable raw acknowledgement while disk projection
continues. Queries would merge the bounded memory window with disk results and
deduplicate by segment/record identity. This improves live experience and
absorbs short projection bursts; it does not increase durable projector
throughput and must never become acknowledgement truth.
### 4. Durable admission group commit
Each accepted native batch currently creates and synchronizes its own raw file
and directory, then commits the control catalogue. A bounded group-commit
coordinator could acknowledge several independent streams after one directory
sync and one control transaction. It must preserve per-stream ordering,
organization quota checks, exact digest acknowledgements, cancellation, and a
small maximum wait. This is relevant only if cost-centre evidence places the
limit on durable admission rather than projection.
### 5. Projection representation
If row/index tuning and partitioning remain insufficient, compare a compact
typed projection representation against SQLite on identical raw segments.
Candidates must retain authorization-before-open, bounded queries, atomic
replacement, offline rebuild, corruption handling, and small-server operation.
An external database is not an optimization if it merely moves the same write
amplification into more infrastructure.
## Database decision boundary
Keep SQLite while it satisfies the measured small-server boundary with simpler
operations. Consider another embedded or external engine only after an exact
candidate demonstrates that the required workload remains blocked by SQLite
itself after index, partition, and batching work. Any replacement must beat the
same fixture while preserving tenant isolation, raw replay, deterministic
recovery, query budgets, deployment simplicity, and idle resource use.
+28
View File
@@ -0,0 +1,28 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Public snapshot boundary
Observatory uses a private development repository and a separate canonical
public source repository. Public history is not a mirror of private history.
Each publication is a reviewed root snapshot of one exact, clean, pushed
private `main` commit.
`scripts/public-snapshot.allow` is the complete public file boundary. The
exporter refuses workflow directories, absolute or parent-traversing paths,
missing tracked files, dirty worktrees, and a private HEAD that differs from
`origin/main`. It archives only the allowlisted paths from the committed Git
tree, byte-compares them with the worktree, scans the result for known private
material, and records the source commit, tree, date, and file count in
`PUBLIC-SNAPSHOT.json` with a SHA-256 sidecar.
The generated snapshot has no `.git` directory. Publication tooling creates a
new reviewed public commit; it must never push private refs, tags, workflows,
reflogs, or historical objects. The canonical public Gitea commit and GitHub
discovery commit may have different Git identities, but their exported file
trees and snapshot manifest must be byte-identical.
Before the first preview, the public snapshot, release archive, SBOM,
checksums, signature, canonical tag, and installed module must all be traced
back to the same reviewed private source commit. A public snapshot does not by
itself make an unreleased development build supported.
+90
View File
@@ -0,0 +1,90 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Progressive web application boundary
Observatory's PWA support adds availability without turning browser storage
into an implicit telemetry replica.
The deterministic service worker precaches only:
- the public offline explanation;
- content-addressed CSS and JavaScript; and
- the content-addressed application icon.
It does not automatically cache authenticated navigation responses. On the
incident page, an authorized user may explicitly save a separate read-only
snapshot. The worker validates both same-origin URLs, requires one matching
organization selector, fetches with the current session, verifies a successful
HTML response, and stores that response under the ordinary inbox URL.
The saved page contains the organization name plus current incident titles,
states, severities, and times. It excludes incident identifiers, response
forms, CSRF tokens, saved-query text, telemetry values, actor identifiers, and
project, environment, and service identifiers. The page is not an authority
for response actions; reconnection is required.
Signing out sends a private-cache deletion request before submitting the
ordinary sign-out form. An expired server session cannot notify a disconnected
browser, so operators should treat saved incident snapshots like any other
explicitly downloaded sensitive material on that device.
The Badging API receives only the current open-incident count when supported.
## Optional Web Push
Web Push follows [RFC 8291](https://www.rfc-editor.org/rfc/rfc8291.html) message
encryption and [RFC 8292](https://www.rfc-editor.org/rfc/rfc8292.html) VAPID
authentication. It is disabled unless the server configuration names a VAPID
private-key file, contact subject, bounded queue, and request timeout. Create a
new private key without exposing it in command arguments or output:
```sh
observatory admin web-push generate-key \
--output-file /etc/gamertan-observatory/web-push.json
```
The output is created exclusively as a mode-`0600` regular file. The installed
systemd unit copies that root-owned source into its private credential
directory as `web-push.json`, and the non-root server configuration references
only that runtime copy. Do not place the key value in configuration, process
arguments, deployment manifests, or source control:
```json
"web_push": {
"private_key_file": "/run/credentials/gamertan-observatory.service/web-push.json",
"subject": "mailto:security@sandwichhime.com",
"queue_capacity": 64,
"request_timeout": "10s"
}
```
The source key remains `/etc/gamertan-observatory/web-push.json`, owned by
root with mode `0600`. `LoadCredential=` makes the service-specific runtime
copy readable without granting the static service account access to `/etc` or
weakening the original file. A differently named service must update both the
unit and the credential-directory path explicitly; Observatory does not search
for secrets.
An authorized incident reader must press the browser control before
Observatory requests notification permission or creates a subscription.
One browser endpoint is owned by one user and may be mapped to several of that
user's organizations. Removing one organization keeps the browser subscribed
until its final mapping is removed. Authorization is checked again for every
delivery; revoked access retires only that organization's mapping.
Endpoints are accepted only as bounded HTTPS push-service URLs and delivery
uses a redirect-free client that rejects DNS results containing non-public IP
addresses.
Only a transition into `firing` enqueues a notification. The bounded queue is
best effort and never blocks alert evaluation or incident persistence. The
encrypted payload is always exactly:
> Gamertan Observatory needs your attention.
The service worker ignores incoming payload content and renders that same
fixed sentence. It includes no organization, host, service, severity, rule,
incident identifier, count, or telemetry text. Activating it opens `/app/`,
where the user must have a valid authenticated session before seeing details.
Browser-vendor push relays remain an explicit metadata boundary: they can
observe delivery timing, endpoint identity, and the fixed payload size even
though they cannot read its encrypted content.
+130
View File
@@ -0,0 +1,130 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Query execution
Observatory's text editor and assisted visual builder produce the same
versioned typed AST. The builder serializes its bounded controls to reviewable
query text and submits that text to the ordinary parser; it does not create a
parallel query language or bypass validation. Query text never selects or
overrides an organization: the HTTP server and local CLI authorize the
requested resource scope separately before planning or opening its projection.
```text
logs
| where service == "eql"
| where status >= 500
```
Use one `where` stage per comparison in the current preview:
```text
logs
| where service == "eql"
| where status >= 500
| window 24h
| summarize count(), p95(duration) by route, window(5m)
| sort count desc
| limit 50
```
`window 24h` limits the lookback range. `window(5m)` creates five-minute
summary buckets; these are separate AST fields. Filters are typed from reviewed
field descriptors. Regular expressions use Go's bounded RE2 implementation,
not a backtracking engine. Arbitrary SQL is never accepted.
The first assisted builder covers one optional comparison, one lookback, one
optional aggregate, one optional grouping field, one optional time bucket, and
a fixed row limit. Values are quoted before serialization and a literal
pipeline character is escaped before parsing, so form values cannot introduce
new stages. Multi-filter and multi-aggregate work remains in the text editor
until a richer builder can preserve the same explicit AST contract.
Reviewed custom fields use the active per-organization descriptor registry.
An exact or range filter on an activated indexed field is correlated through
that version's typed index instead of casting arbitrary raw JSON. Values that
did not satisfy the reviewed type during the index build remain in raw truth
but do not silently become zero or another valid indexed value.
Unknown fields remain raw-queryable only to principals with the separate
sensitive-telemetry permission. Results contain fixed safe identity columns
plus fields explicitly referenced by the query; sensitive bodies are never a
default result column.
Every execution has independent duration, row, projected-byte, and memory
limits. `explain` reports the authorized projection, descriptors, index policy,
conservative scan estimate, cache eligibility, permissions, and budgets before
execution.
## Storage scale is not query cost
Observatory deliberately separates admission of evidence from execution of a
query. A large organization store, historical import, or forensic archive is
not itself a reason to reject new data or a small recent query. Ingestion and
import use their own explicit storage quotas, bounded batches, backpressure,
durable progress, and capacity checks. Query limits never act as an implicit
organization-size quota.
Planning considers the authorized signal, resource scope, time window,
available indexes or rollups, and result limit. A projection file's total size
alone must not make an indexed, bounded recent-record query unavailable. The
executor still enforces actual duration, rows, logical bytes read, and memory;
summaries, alternate sorts, regular-expression filters, and cold forensic
reads retain conservative preflight because they may need to examine more of
the selected evidence. `explain` should make that distinction visible rather
than promising that a cheap result follows from a small output alone.
A log summary with one canonical `status >= N` threshold, `count()`, a route
group, and either no bucket or a multiple-of-five-minute bucket uses an exact
five-minute projection. Its explain source ends in
`/rollup:http-status-route:5m`. The server still injects the organization and
optional project, environment, and service scope; the same duration, scan,
memory, and result limits apply. Missing routes remain distinct from explicitly
empty routes, and malformed stored statuses are excluded rather than cast to
zero. A lower time boundary inside a bucket reads only that raw partial bucket
and merges it with the complete projected buckets. Queries outside that exact
shape remain on the general executor instead of receiving a different
interpretation merely to reach a faster plan.
Metric summaries with no per-sample value filter and a bucket of at least five
minutes can use the retained aggregate projection. Its explain source ends in
`/rollup:5m`. Counts, sums, minima, maxima, and averages remain exact;
percentiles use the bounded rollup histogram and set
`statistics.approximate=true`. Unknown, sensitive, high-cardinality, and
raw-only fields make the query use raw samples instead of silently reading an
incomplete rollup.
Hot projection expiry does not make older evidence disappear. A query whose
lookback overlaps cold segments includes their catalogued uncompressed size in
the explain estimate, verifies and decompresses each exact zstd object, and
applies the same organization scope, sensitive-field permission, typed
filters, and execution budgets. This path deliberately accepts more latency
for forensic detail. If matching cold metric segments exist, Observatory uses
the exact raw path rather than combining them with an incomplete rollup.
The explain source adds `/cold:raw` when that tier participates.
## Local authorized query
The local command reads query text from standard input so values do not need to
appear in process arguments. Local operating-system access does not grant
telemetry access: `--actor-user-id` must still hold the scoped query grant.
```sh
printf '%s\n' 'logs | where status >= 500 | window 1h | limit 50' |
observatory query \
--actor-user-id USER_ID \
--organization-id ORGANIZATION_ID
```
Use the optional project, environment, and service flags to narrow the
authorized scope. Output is a stable versioned JSON table: column descriptors
are ordered once and each row contains positional nullable string values in the
column's declared type and unit.
## HTTP endpoints
- `POST /api/v1/query/parse` validates text or builder AST input.
- `POST /api/v1/query/explain` requires a scoped query grant.
- `POST /api/v1/query` executes the same authorized plan.
Session-backed endpoints require the canonical same origin. Error responses do
not echo query values or telemetry.
+110
View File
@@ -0,0 +1,110 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Recovery and projection rebuild
Observatory treats immutable, checksummed raw segments as the replayable
telemetry truth. Per-organization SQLite projections, custom indexes, query
caches, and rollups are disposable products of that truth.
## Ordinary startup recovery
All three commands reconcile raw segments that reached durable storage before
their control record. `observatory server` then opens its listener and drains
catalogued but unprojected segments through the bounded background projector.
`observatory check` and `observatory migrate` wait for that projection work as
part of their offline verification. This closes both crash windows without
making source acknowledgement or server readiness depend on disposable query
state. Already projected segments are not rewritten.
Discovery walks only private raw-object metadata: organization, source,
stream, sequence, path, encoded size, and the content digest carried in the
immutable filename. Observatory compares already catalogued objects with the
control database without reading their telemetry. Only an object missing from
the catalog is checksum-verified, decompressed, decoded, validated, and
admitted. Pending projections are replayed in bounded, organization-local
groups. This keeps recovery memory proportional to one fixed directory batch,
one bounded segment group, and one small projection page rather than to the
entire retained archive.
That bounded startup path is not a substitute for forensic verification.
Checksums are still verified when an orphan is admitted, a segment is queried,
moved to cold storage, deleted, exported, or used for an explicit projection
rebuild. Operators should schedule those evidence checks and backups rather
than forcing every accepted raw object through memory before the listener can
open.
When an explicit policy enables cold deletion, startup recovery also completes
a segment retirement that was interrupted
after its durable control-state transition. It removes any remaining raw
projection rows, verifies and removes the exact checksummed segment, and only
then clears its control record. A missing retired file is an idempotent state;
a changed file or path is a hard failure.
Cold archival has an earlier independent recovery boundary. Observatory first
records the exact cold path, then atomically renames the verified zstd object,
then advances its catalog tier. Startup safely completes either a pending move
or a move that reached disk before the catalog update. It will not follow a
symlink, accept another path, or rebuild altered bytes.
The shipped policy never starts the retirement transition. Cold raw evidence
therefore remains available until an organization or server operator has
deliberately enabled `delete_cold_raw`; projection expiry and compaction do not
silently imply evidence deletion.
To run retention and SQLite compaction explicitly while the server is stopped:
```sh
observatory migrate \
--config /etc/gamertan-observatory/server.json \
--apply-retention
```
The long-running server and ordinary local commands hold a shared lock on the
data directory. Offline migration and projection replacement require an
exclusive lock, so they fail closed while any participating Observatory
process is using that directory.
## Rebuild one organization
Stop the Observatory server, retain a filesystem-level backup, and run:
```sh
observatory migrate \
--config /etc/gamertan-observatory/server.json \
--rebuild-organization organization-id \
--approve-rebuild-organization organization-id
```
The two organization values must match exactly. The command:
1. acquires exclusive ownership of the data directory;
2. refuses unknown organizations, symlinked projections, and unsafe SQLite
sidecars;
3. reads every registered **hot** raw segment for the organization through the
checksum-verifying segment store; cold evidence remains outside the fast
projection and available through the budgeted cold query path;
4. rebuilds the base projection and the organization's activated descriptor
version beside the live projection;
5. finalizes the replacement as a private standalone SQLite file; and
6. atomically replaces only that organization's projection and synchronizes
its directory.
Validation or reconstruction failures before activation remove the temporary
files and preserve the existing projection. Other organizations are not
opened or rewritten. The JSON report contains the organization, raw segment
and observation counts, active projection version, and indexed-row count; it
contains no telemetry values.
## Evidence boundary
The rebuild proves that the currently registered checksummed hot segments can
recreate the fast disposable projection. Cold segments remain independently
checksummed forensic truth and are not silently promoted back into hot SQLite.
Neither mechanism replaces backups of the control database, raw/cold segments,
server configuration, identity state, or encryption keys. A missing or corrupt
segment is a hard failure, not a reason to silently accept partial history.
No public Observatory preview exists yet, so there is not yet a supported
cross-preview migration promise. Every future public schema must add an
explicit migration fixture and rebuild campaign before its release can be
called compatible.
+148
View File
@@ -0,0 +1,148 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Retention and metric rollups
Observatory enforces the server policy in `server.json` after startup recovery
and once per hour:
- hot log projections: 30 days;
- hot trace projections: 30 days;
- hot raw metric projections: 14 days;
- immutable cold raw segments: preserved indefinitely by default;
- five-minute metric rollups: 400 days; and
- deployment events, resolved incidents, and security audit evidence: 400 days.
All values are explicit configuration. The list above is the shipped example,
not a hidden fallback. `cold_raw_days` becomes a final raw-evidence cutoff only
when `delete_cold_raw` is explicitly enabled. It is not an additional window
after the hot cutoff.
## Hot and cold evidence
Raw batches are already independently Zstandard-compressed and addressed by
their SHA-256 digest. Observatory does not wrap them in a gzip tarball: that
would make selective verification and opening slower while usually saving
little space over already-compressed input. When the newest observation in a
segment leaves its hot window, Observatory atomically moves the exact object
from `raw/` to `cold/` and advances its catalog tier. No telemetry is decoded,
rewritten, or recompressed during that move.
Cold queries are intentionally allowed to take longer. Their explain estimate
includes each selected segment's catalogued uncompressed size. Execution
validates the catalog path and time range, verifies the compressed checksum,
decodes a bounded segment, and applies the same tenant scope, sensitive-field
authorization, typed filters, scan limit, memory limit, row limit, and timeout
as a hot query. Matching cold metric segments force an exact raw query instead
of mixing incomplete history with aggregate rollups.
The explain plan adds `/cold:raw` whenever this tier participates.
The default therefore preserves forensic raw detail without an automatic
destruction date. Projections and rollups still expire on schedule, so ordinary
queries stay compact while a deliberate cold query can recover exact older
evidence at an accepted additional cost. Full-disk encryption, protected
backups, quota planning, and filesystem capacity remain operator
responsibilities in the first preview.
Forensic retention applies only **after** Observatory's collection boundary.
It does not mean collect everything: request and response bodies remain off by
default, known credential and header deny rules run before spooling, source
adapters use allowlists, and unknown fields remain sensitive and unindexed.
An operator must still choose lawful inputs and retention appropriate to the
people and systems represented by the evidence.
Observatory does not currently combine cold objects into `tar.gz` archives.
Each raw batch is already zstd-compressed and content-addressed, so another
compression layer would usually save little while making selective reads and
independent checksum verification harder. A future high-inode-volume backend
may pack many unchanged zstd objects into an immutable checksummed container
with a separate bounded index. Such a pack must be completely written,
verified, and catalogued before its source objects can be retired; packing must
never change their logical digests or tenant boundaries.
## What a rollup retains
Every metric ingest updates its five-minute aggregate in the same SQLite
transaction as the raw projection. Each aggregate retains exact count, sum,
minimum, maximum, and the last sample value/timestamp plus a bounded deterministic
histogram. `p50`, `p95`, and `p99` over rollups are approximations and the
query result sets `statistics.approximate` to `true`. Count, sum, minimum,
maximum, and average remain exact for the retained samples.
Longer retention never silently widens the data boundary. A dimension enters
a rollup only when its descriptor is:
- reviewed or an Observatory built-in;
- marked with the `metric` retention class;
- public or internal, never sensitive; and
- low or medium cardinality.
Unknown, sensitive, and high-cardinality attributes remain raw-only. The
explain plan names `/rollup:5m` whenever the aggregate projection is selected.
Queries that filter individual values, request sub-five-minute buckets, or
need fields unavailable in the aggregate continue to use raw samples.
Metric values are bounded to an absolute value of `1e25`. This is far beyond
ordinary duration, byte, counter, and host measurements while keeping sums
and the fixed histogram domain finite under hostile input.
## Organization policy
An organization owner can shorten a policy:
```sh
sudo observatory admin retention set \
--config /etc/gamertan-observatory/server.json \
--actor-user-id USER_ID \
--organization-id ORGANIZATION_ID \
--raw-logs-days 14 \
--raw-traces-days 14 \
--raw-metrics-days 7 \
--cold-raw-days 180 \
--delete-cold-raw \
--metric-rollups-days 180 \
--evidence-days 180
```
`cold_raw_days` cannot be shorter than any hot raw/evidence window. Omit
`--delete-cold-raw` to preserve cold evidence indefinitely. Enabling deletion
is an explicit shortening policy. Extending any server default—including
turning off deletion when the server default enables it—additionally requires
the exact organization ID and a positive byte quota larger than the
organization's current stored data:
```sh
--approve-extension ORGANIZATION_ID \
--quota-bytes 10737418240
```
The policy change and actor are recorded without telemetry values. A quota is
checked before accepting another raw segment, using current raw/projection
storage plus a conservative allowance for the new projection. Secret values
never enter the policy, audit summary, command output, or process arguments.
## Deletion and recovery boundary
Projected observations expire at their individual hot timestamps. Raw
segments are immutable, so a segment becomes cold only when its newest
observation crosses that signal's hot cutoff. A batch spanning multiple
timestamps can therefore keep its older members hot until the newest member
expires; agents should keep batches time-local. The pending archive path is
recorded first, the exact segment is verified and atomically moved, both
directory entries are synchronized, and the tier is advanced. Startup recovery
safely completes an interruption before or after the rename.
Only when `delete_cold_raw` is true does the final cold cutoff separately mark
the segment retiring. Its
remaining projection and per-segment rollup ledger rows are removed, its
checksum/path are revalidated, its file and directory entry are synchronized,
and finally its control record is deleted. A missing file is accepted only for
the recorded interrupted-retirement state; changed bytes or another path stop
recovery.
Metric rollups are disposable projections. Their expiration and SQLite
compaction do not alter hot or cold raw evidence. Projection rebuilds use only
hot segments so they do not turn the fast database back into an archive; the
query engine opens cold evidence directly when requested. Once the final cold
window expires under that explicit policy, rebuilding intentionally cannot
recreate those deleted samples. Backups must follow the same published
retention and deletion policy.
+47
View File
@@ -0,0 +1,47 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Preview roadmap
`v0.1.0-preview.1` remains blocked until all of these work together:
- [x] Web Foundations organizations and scoped access are published and
integrated for generated one-time bootstrap, forced password rotation,
session revocation, and bounded query explanation.
- [x] Complete tail-cursor recovery and enrollment around the implemented
native collector adapters and durable 72-hour/5-GiB spool.
- [x] Caddy, requestlog, and Tend event file adapters plus authenticated,
bounded OTLP/HTTP protobuf ingestion for logs, metrics, and traces.
- [x] Linux host, cgroup v2, filesystem, network, and explicitly selected
process metrics in the durable unprivileged agent pipeline.
- [x] Logs, metrics, traces, and deployment events projected and queryable.
- [x] Add execution to the implemented unified builder/text AST, explain plan,
sensitive-field permission, and hard planning budgets.
- [x] Idempotent descriptive schema proposal persistence with organization-
scoped review permission and no observed values in proposal metadata.
- [x] Reviewed descriptor activation and atomic beside-current projection/index switching.
- [x] Sandwich Hime dashboards, accessible alternatives, SSE, durable alert
rules, an online incident inbox, installable shell, badge state, and an
explicit opt-in read-only offline incident snapshot.
- [x] Generic privacy-preserving Web Push with explicit browser opt-in,
fixed encrypted content, reauthorization at delivery, and a bounded
non-blocking queue.
- [x] Strict Tend activation and rollback annotations whose identity, event-file,
agent, network, or Observatory failures cannot control a release.
- [x] Enforced hot/cold raw and evidence retention, approved organization
overrides, serialized storage quotas, crash-recoverable archival and
indefinite forensic preservation by default, explicitly enabled final
retirement, budgeted forensic queries, projection compaction, and
five-minute metric rollups with privacy-safe dimensions.
- [ ] Security, corruption recovery, migration, and projection rebuild campaigns.
- [ ] 4-vCPU/8-GiB capacity campaign and medium-fleet soak.
- [ ] Sanitized public root snapshot, reproducible package, SBOM, and signed checksums.
## Post-preview direction
- [ ] Public-safe status dashboards backed by separately approved aggregate
projections, coarse buckets, minimum group sizes, publication delay, and
no unauthenticated path to internal or sensitive evidence.
- [ ] An additive structured-frame source path for byte-faithful preservation
of permitted producer records while retaining bounded framing,
compression, authentication, tenant scope, and asynchronous parsing.
Existing typed metrics and OTLP ingestion remain typed.
+127
View File
@@ -0,0 +1,127 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Descriptive field schema
Every reviewed Observatory field descriptor records its signal, type, unit,
meaning, sensitivity, cardinality budget, index policy, retention class, and
projection version. Built-in fields such as normalized HTTP route and status
already have explicit descriptors.
Unknown attribute keys remain queryable only with the sensitive-telemetry
permission. They default to:
- sensitive;
- high cardinality;
- no index;
- raw retention.
This includes client addresses, raw queries, referrers, user agents, and
anonymous session identifiers selected through an agent source's explicit
`sensitive_fields` policy. Collection and classification are separate review
steps: opting a value into durable raw evidence does not make it public,
low-cardinality, or indexed.
The reviewed sensitivity classes are deliberately small:
- `public`: eligible for an explicitly approved public-safe aggregate;
- `internal`: ordinary authenticated organization telemetry; and
- `sensitive`: separately authorized evidence such as client addresses,
queries, referrers, user agents, session correlations, or unreviewed fields.
`public` is an eligibility label, not an automatic publication instruction.
A future unauthenticated status view must compile a separate allowlisted
aggregate projection with coarse buckets, minimum group sizes, a publication
delay, and explicit organization approval. It must never expose the
authenticated dashboard, raw records, identifiers, small groups, or query
text. This public-safe projection is roadmap work rather than a capability of
the current private preview.
`raw`, `metric`, and `evidence` are distinct lifecycle classes. `raw` survives
the hot projection cutoff in the checksummed cold archive indefinitely by
default. An organization can opt into an explicit final raw deletion window.
Only reviewed,
non-sensitive, bounded-cardinality metric dimensions marked `metric` enter the
five-minute rollup projection. Selecting `metric` is therefore a retention
decision as well as a query optimization; see
[`RETENTION.md`](RETENTION.md).
After a raw segment is committed, Observatory records one aggregate proposal
summary per unknown field in that segment. The segment digest, organization,
and field form an idempotency key, so ingestion recovery cannot double count
proposal evidence. The proposal contains occurrence count, estimated encoded
bytes, an inferred type, first/last seen times, and a generic query using the
field name. It never stores an observed value or telemetry body.
The batch validator rejects more than 1,024 distinct attribute keys before raw
segment commit so source-controlled field names cannot create unbounded schema
work.
Organization owners can inspect pending proposals locally:
```sh
observatory admin descriptors list \
--actor-user-id USER_ID \
--organization-id ORGANIZATION_ID
```
Operating the host or holding the platform-operator role does not grant this
permission. Descriptor review uses the organization-scoped `schema.manage`
grant.
## Review and activation
The list output supplies the inferred descriptor, occurrence count, estimated
encoded bytes, first/last observation time, and generic example query. Review
those values and create a complete descriptor JSON file. The file is an
administrative input, so production requires an absolute, root-owned,
mode-`0600`, regular non-symlink file; JSON is capped at 64 KiB and unknown
properties fail closed.
```json
{
"version": 1,
"signal": "metrics",
"field": "workshop.queue_depth",
"type": "integer",
"unit": "items",
"meaning": "Number of work items waiting in the selected service queue.",
"sensitivity": "internal",
"cardinality": "low",
"index": "range",
"retention": "raw",
"projection_version": 1
}
```
The input projection version is a placeholder; Observatory assigns the next
organization-local version during activation.
```sh
observatory admin descriptors activate \
--actor-user-id USER_ID \
--organization-id ORGANIZATION_ID \
--descriptor-file /root/reviews/workshop.queue_depth.json
```
Activation copies every currently active descriptor into a new immutable
version, builds the complete typed custom-field index beside the current one,
and changes the active version inside the same organization-database
transaction. Invalid historical values stay in raw evidence but are not
coerced into the index. New ingestion writes to the active version. Old index
tables remain available for recovery, and retry repairs an interrupted
control-database acknowledgement without rebuilding an already active,
identical descriptor.
A proposal that should not become part of the reviewed schema can be rejected
idempotently:
```sh
observatory admin descriptors reject \
--actor-user-id USER_ID \
--organization-id ORGANIZATION_ID \
--signal metrics \
--field workshop.queue_depth
```
An active descriptor cannot be rejected. Revision of an already active
descriptor requires a future explicit review-proposal workflow; the current
command will not silently reinterpret an active field.
+147
View File
@@ -0,0 +1,147 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Security and recovery campaign
This document maps the current maintainer self-assessment to executable
evidence. It is not an independent audit or a claim that the public preview is
ready. The release commit, packaged binary, browser campaign, capacity run,
and fleet soak must receive separate evidence before the preview tag.
## Current executable evidence
| Boundary | Executable evidence |
| --- | --- |
| Organization isolation and scoped queries | `TestBootstrapSeparatesPlatformAndOrganizationAccess`, `TestTeamsInvitationsRevocationAndBreakGlassRemainOrganizationScoped`, `TestPlanRejectsCrossTenantScopeAndScanBudget`, `TestCredentialScopeCannotBeOverridden` |
| Invitations, teams, revocation, and break-glass audit/expiry | `TestTeamsInvitationsRevocationAndBreakGlassRemainOrganizationScoped` plus the pinned Web Foundations package tests |
| Generated bootstrap credential, forced first-login rotation, and local recovery | `TestAdminBootstrapGeneratesExclusiveOneTimeCredential`, `TestAdminBootstrapSupportsConfinedSystemdCredentials`, `TestAdminHierarchyAndEnrollmentSupportConfinedSystemdCredentials`, `TestAdminUserResetPasswordGeneratesPrivateCredentialAndRevokesSessions`, `TestTemporaryOperatorMustRotatePasswordBeforeUsingApplication`, `TestAPITemporaryOperatorReceivesScopedRotationToken`, plus pinned Web Foundations password-change and atomic recovery tests |
| Token-bound HTML forms with privacy-browser compatibility and cross-site rejection | `TestHTMLLoginUsesTokenWhenBrowserOmitsOrObscuresOriginMetadata`, `TestHTMLLoginFailsClosed`, `TestTemporaryOperatorMustRotatePasswordBeforeUsingApplication`, `TestDashboardManagementIsScopedCSRFProtectedAndExportable`, `TestIncidentRulesEvaluationInboxAndResponseAreScoped` |
| Replay, exact logical-batch acknowledgement, duplicate batches, sequence gaps, enrollment, and source revocation | `TestScopedIngestionDeduplicationAndReplay`, `TestNativeEnvelopeReplayUsesBatchIdentityAndAllowsOverlappingTime`, `TestFramedNativeIngestAcknowledgesExactReplayAndOverlappingTime`, `TestSendAcceptsRealServerBatchDigestRatherThanPrivateSegmentDigest`, `TestRunnerPreservesSpoolOnMismatchedAcknowledgement`, `TestEnrollmentIsScopedExpiringAndSingleUse`, `TestAgentEnrollmentIsSingleUseAndCredentialCanSelfRevoke` |
| Native envelope and compressed or malformed OTLP framing | `TestEnvelopeHeadersRoundTripAndRejectAmbiguity`, `FuzzParseEnvelopeHeaders`, `TestOTLPHTTPIngestionIsAuthenticatedBoundedAndCompressed`, `TestDecodeRejectsMalformedAndNonFiniteData`, `FuzzDecode` |
| Cardinality, timestamp, field, query, scan, memory, and result bounds | `TestBatchRejectsDistinctFieldCardinalityAbuse`, `TestBatchClockSkewAndRetentionWindowsFailClosed`, `TestQueryEnforcesSensitiveAndExecutionBudgets`, `FuzzParse` |
| Secret minimization and safe error output | `TestCaddyCollectorDropsSecretsAndQuery`, `TestRequestLogCollectorUsesWhitelist`, `TestDecodeLogsDropsCredentialsAndPreservesTelemetry`, `TestIngestDoesNotExposeValuesInErrors` |
| Filesystem and interrupted-write boundaries | `TestStorageRejectsSymlinkedSQLiteFilesAndProjectionDirectories`, `TestStateAtomicRoundTripAndSymlinkRefusal`, `TestSpoolRejectsQuotaAndSymlink`, `TestTailerPreservesPartialLineAndRecoversRotation`, `TestInterruptedTemporarySegmentIsIgnoredUntilAtomicCommit` |
| Raw corruption and crash recovery | `TestCommitReadAndCorruption`, `TestRecoveryIndexesRawSegmentMissingFromControlDatabase`, `TestProjectionRebuildFailurePreservesLiveProjection` |
| Complete projection reconstruction | `TestProjectionRebuildRestoresRawTruthAndActivatedDescriptorsAtomically`, `TestProjectionRebuildRejectsUnknownOrganization`, `TestProjectionRebuildRefusesSymlinkProjectionOrSidecar` |
| Migration locking and schema fixtures | `TestProcessLockSeparatesLiveServerFromOfflineMigration`, `TestOfflineMigrationRefusesLiveDataDirectory`, `TestControlSchemaFourMigratesToIncidentSchema`, `TestControlSchemaFiveMigratesToPushSchema` |
| PWA, SSE, incident scope, and generic push content | `TestManifestAndServiceWorkerUseExactContentAddressedShell`, `TestLiveRefreshStreamIsAuthorizedAndCarriesNoTelemetry`, `TestIncidentRulesEvaluationInboxAndResponseAreScoped`, `TestSenderUsesEncryptedGenericPayloadAndValidVAPID` |
| Tend input and non-authoritative deployment evidence | `TestTendCollectorIsStrict`, `FuzzTendCollector`; producer activation/rollback failure injection remains authoritative in Tend's own repository |
The migration fixtures cover every internal control schema that predates this
candidate and can reach its current schema. Observatory has not published a
preview, so no public-version migration claim exists yet. Each future public
preview must retain a fixture and a raw-projection rebuild path.
## Reproduction
The ordinary verifier pins Go and Hime-san, checks generated-source freshness
and no-op determinism, then runs tests, the race detector, vet, a trimmed
build, and the production dependency boundary:
```sh
GOCACHE=/tmp/observatory-go-cache ./scripts/verify.sh
```
The bounded adversarial campaign adds query, OTLP, and Tend-event fuzzing and
reruns the security-critical packages under the race detector:
```sh
OBSERVATORY_FUZZ_TIME=30s \
GOCACHE=/tmp/observatory-go-cache \
./scripts/security-campaign.sh
```
On August 17, 2026, a 10-second-per-target development run completed without
an invariant failure: approximately 2.45 million query-parser cases, 670,000
OTLP cases, and 166,000 strict Tend-event cases, followed by the uncached race
matrix. Counts are observations from one run, not minimum performance claims.
Trusted Gitea assurance run 232 then exercised source commit
`14125387d13947eb4a523e95c2e441ff89abcc1a` (tree
`f378872450054e7ff6f5499c61a5db0e4a3d3da7`) with the pinned Go 1.26.6
toolchain and `govulncheck` v1.6.0. It completed 1,092,559 query-parser,
398,595 OTLP-decoder, and 324,020 Tend-event fuzz executions in three separate
30-second targets, then passed the uncached security-package race matrix and
the ordinary deterministic verifier. The checkout remained unchanged.
The same scan reported zero reachable vulnerabilities and zero
vulnerabilities in imported packages. It also reported GO-2026-5932 in the
required `golang.org/x/crypto` module because its legacy `openpgp` package is
unmaintained. Observatory and its Web Foundations dependency do not import
that package, and the advisory has no fixed module version. This is a recorded
dependency boundary, not a claim that the module-only advisory was repaired.
The resource-limited ingestion, query, outage-replay, and retention gate is
defined separately in [`CAPACITY.md`](CAPACITY.md). Its short development mode
is suitable for implementation feedback; only the exact one-hour release mode
can close the capacity item below.
## Open release evidence
- Exercise one granted browser-vendor Web Push delivery and OS notification
activation in a headed supported browser. The networkless Chromium campaign
below proves the application and worker boundaries without contacting a push
relay or depending on a desktop notification service.
- Complete the specified 4-vCPU/8-GiB capacity campaign, outage replay,
retention, compaction, and concurrent-organization workloads. The
August 17 constrained run passed its one-hour 2,000-observation/second
sustain boundary but missed the 10,000-observation/second burst boundary;
[`CAPACITY.md`](CAPACITY.md) records the measured result and remaining work.
- Complete the medium-fleet dogfood soak. Observatory's first real Tend
activation, rollback, and identical-artifact redeployment passed on
August 17; [`DEPLOYMENT.md`](DEPLOYMENT.md) records that bounded result.
- Re-run this campaign against the exact packaged release commit and record
its immutable artifact digest, SBOM, checksum, and signature.
## Real-browser campaign
`scripts/browser-campaign.sh` builds a build-tagged, disposable HTTPS fixture
and drives Chromium through pinned Playwright 1.62.1. The approved Linux image
is `mcr.microsoft.com/playwright@sha256:dcc5531e97840b9b5e794f2814476b21571c5124a3fca2267d73041f56e7580e`.
The fixture and browser use loopback only. The campaign rejects every HTTP
request to another origin and verifies manifest installability, the public
offline shell, explicit private-inbox caching and sign-out deletion, SSE
reconnection, app badging, generic notification content and activation,
keyboard entry, landmarks, forced colors, reduced motion, and 320-pixel
overflow.
On August 17, 2026, the campaign completed twice in pinned headless Chromium
inside a disposable, networkless Linux container limited to four CPUs and
8 GiB. Both runs reported every evidence field true and zero external HTTP
requests. They exercised a real service worker, cache storage, EventSource,
session, incident inbox, application badge, and the production push and
notification-click handlers. Headless Chromium denied the intentional
user-triggered notification permission request, so the worker's fixed-shape
push event and activation path were invoked directly; the prohibited OS focus
side effect was replaced with an in-worker client test double. This proves the
payload and activation contract, not end-to-end browser-vendor delivery. The
exact npm lockfile audit reported zero known vulnerabilities at all severities.
The disposable fixture uses a one-hour self-signed `localhost` certificate and
passes only its ephemeral SHA-256 subject-public-key fingerprint to Chromium's
SPKI allowlist. Chromium serializes `Origin: null` on form submissions under
that synthetic certificate while Fetch Metadata still reports `same-origin`.
The fixture does not rewrite those headers: the campaign exercises the same
token-bound HTML form policy used in production and asserts the observed
metadata. The token remains mandatory, and explicit cross-site metadata still
fails closed. This is not a general TLS-origin acceptance test.
To test native EventSource recovery deterministically, the build-tagged
fixture cancels the real authenticated `/app/events` request after 1.25
seconds. The browser must reconnect and receive a later generic refresh event.
The production handler, authorization, event format, and connection lifetime
are not changed.
Install the exact development dependency without downloading a browser when a
pinned Playwright container supplies Chromium:
```sh
cd test/browser
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm ci --ignore-scripts
cd ../..
./scripts/browser-campaign.sh
```
The resulting JSON contains pass/fail booleans and no machine, user, token,
organization, incident, path, or telemetry identifiers. A development pass is
not release evidence until repeated against the packaged release commit and
the pinned container digest is recorded.
+76
View File
@@ -0,0 +1,76 @@
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
# Tend deployment evidence
Observatory consumes Tend's bounded version-1 deployment-event JSONL as an
unprivileged, read-only file source. Tend does not call Observatory and never
waits for an Observatory acknowledgement. Identity, entropy, event-file, agent,
network, and server failures therefore cannot decide whether Tend activates or
rolls back an application.
Each accepted record has exactly these fields:
- a cryptographically random operation ID;
- service, approved artifact SHA-256, source commit, and release version;
- phase, optional slot, elapsed milliseconds, outcome, and UTC observation
time.
The adapter rejects unknown fields, trailing JSON, negative durations,
malformed identifiers, unsafe values, invalid timestamps, and records larger
than Tend's 4-KiB producer limit. It discards the source line after converting
only this fixed field set into a deployment observation. No environment value,
secret path, HTTP body, command output, or arbitrary process output belongs to
the contract.
## Agent configuration
Grant the dedicated Observatory agent account read access only to the selected
service's event file, then configure an explicit local source:
```json
{
"kind": "tend_events_jsonl",
"path": "/opt/example/deployment-events.jsonl",
"stream_id": "tend-deployments"
}
```
The source's organization, project, environment, and service scope comes from
its server-side enrollment. Neither the file nor a deployment event may choose
tenant scope. The normal durable cursor and spool rules apply during rotation,
agent restarts, or an Observatory outage.
## Querying
Activation and rollback attempts share the `tend.deployment` observation name
and correlate through `deployment.operation_id`:
```text
deployments
| where service.name == "example-site"
| sort deployment.duration_ms desc
| limit 50
```
Keep candidate, activation, and rollback phases together when reconstructing a
release operation. A missing event means evidence was unavailable; it must not
be interpreted as proof that a deployment did not occur. Tend's own state and
the application's active release remain authoritative for deployment control.
The producer contract is maintained by [Gamertan Tend](https://gitea.speelman.ca/gamertan/tend).
## Production dogfood observation
On August 18, 2026, one checksum-approved Tend candidate exercised candidate
validation, activation, explicit rollback, and reactivation for Gamertan,
Sandwich Hime, and Observatory. The production agent then projected all three
bounded event files through separate streams: ten Gamertan events and six for
each of the two singleton services. Gamertan's stream intentionally includes
two failed pre-activation candidates that never received public traffic; those
records helped identify a hardened-umask extraction defect before the corrected
candidate completed all three service cycles.
This observation demonstrates the producer-to-agent-to-projection path and its
failure evidence. It is not a substitute for Tend state, active-release
inspection, public health checks, or the remaining Observatory fleet and
capacity release gates.
+43
View File
@@ -0,0 +1,43 @@
# SPDX-License-Identifier: 0BSD
#
# Explicit richer-evidence example. Replace the origin, upstream, paths, and
# query-key deny list only after reviewing the application's privacy policy.
example.com {
log application_sensitive_access {
output file /var/log/caddy/example-sensitive-access.jsonl {
mode 0640
roll_size 100mb
roll_keep 10
roll_keep_for 720h
}
format filter {
request>uri query {
delete access_token
delete api_key
delete authorization
delete code
delete credential
delete key
delete password
delete secret
delete session
delete session_id
delete token
}
client_ip ip_mask 24 56
request>remote_ip delete
request>remote_port delete
request>client_ip delete
request>headers delete
resp_headers delete
user_id delete
wrap json
}
}
log_append request_id {http.response.header.X-Request-ID}
log_append client_ip {http.request.client_ip}
log_append referrer {http.request.header.Referer}
log_append user_agent {http.request.header.User-Agent}
reverse_proxy 127.0.0.1:8080
}
+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.
+23
View File
@@ -0,0 +1,23 @@
<!-- SPDX-License-Identifier: 0BSD -->
# Examples
Copy these files into your own deployment repository and adapt them. Production configuration belongs at `/etc/gamertan-observatory/`, must be root-owned mode `0600`, and should reference secrets stored in separate root-owned files. The example systemd unit uses `LoadCredential=` so the agent can consume runtime copies while remaining an unprivileged service.
The optional `web_push` block expects a private key created on the server with
`observatory admin web-push generate-key --output-file /etc/gamertan-observatory/web-push.json`.
Remove the block when browser notifications are not wanted. Never commit the
generated file.
`agent.json` demonstrates the privacy-minimized collection default. If an
application's privacy policy and operating purpose permit collection of client
addresses, queries, referrers, user agents, or anonymous session identifiers,
select those names explicitly in that source's `sensitive_fields` array. The
agent will not retain them merely because they exist in the producer log.
`Caddyfile.sensitive-access-log` is an intentionally richer edge-log example.
It still deletes request and response header maps, filters common credential
query keys, masks client addresses, and keeps the application request ID as a
correlation field. Its deny list cannot know an application's vocabulary:
review and extend it before use. Treat the resulting file as sensitive source
evidence with narrow read permissions and a documented retention period.
+4
View File
@@ -0,0 +1,4 @@
{
"credential": "replace-with-the-single-enrollment-result"
}
+1
View File
@@ -0,0 +1 @@
SPDX-License-Identifier: 0BSD
+3
View File
@@ -0,0 +1,3 @@
{
"enrollment_token": "replace-with-the-single-use-enrollment-token"
}
+1
View File
@@ -0,0 +1 @@
SPDX-License-Identifier: 0BSD
+42
View File
@@ -0,0 +1,42 @@
{
"schema": 1,
"server_url": "https://observatory.example.com",
"credential_file": "/etc/gamertan-observatory/agent-credential.json",
"spool_dir": "/var/lib/gamertan-observatory-agent",
"state_file": "/var/lib/gamertan-observatory-agent/state.json",
"max_spool_bytes": 5368709120,
"max_spool_age": "72h",
"batch_records": 5000,
"flush_interval": "1s",
"sources": [
{
"kind": "caddy_json",
"path": "/var/log/caddy/example-access.jsonl",
"stream_id": "caddy-access"
},
{
"kind": "requestlog_jsonl",
"path": "/var/log/example/request.jsonl",
"stream_id": "application-request"
},
{
"kind": "tend_events_jsonl",
"path": "/opt/example/deployment-events.jsonl",
"stream_id": "tend-deployments"
},
{
"kind": "linux_metrics",
"stream_id": "host-metrics",
"linux_metrics": {
"proc_root": "/proc",
"cgroup_root": "/sys/fs/cgroup",
"filesystems": [
{ "name": "root", "path": "/" }
],
"cgroups": [
{ "name": "example-service", "path": "system.slice/example.service" }
]
}
}
]
}
+1
View File
@@ -0,0 +1 @@
SPDX-License-Identifier: 0BSD
+31
View File
@@ -0,0 +1,31 @@
# SPDX-License-Identifier: 0BSD
[Unit]
Description=Gamertan Observatory agent
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=observatory-agent
Group=observatory-agent
LoadCredential=agent.json:/etc/gamertan-observatory/agent.json
LoadCredential=agent-credential.json:/etc/gamertan-observatory/agent-credential.json
ExecStart=/usr/local/bin/observatory agent --systemd-credentials --config %d/agent.json --credential-file %d/agent-credential.json
Restart=on-failure
RestartSec=5s
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictSUIDSGID=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
ReadWritePaths=/var/lib/gamertan-observatory-agent
[Install]
WantedBy=multi-user.target
+30
View File
@@ -0,0 +1,30 @@
{
"schema": 1,
"listen": "127.0.0.1:9010",
"public_url": "https://observatory.example.com",
"data_dir": "/var/lib/gamertan-observatory",
"max_body_bytes": 33554432,
"max_concurrent_ingest": 8,
"session_lifetime": "12h",
"query": {
"max_duration": "5s",
"max_rows": 10000,
"max_scanned_bytes": 268435456,
"max_memory_bytes": 134217728
},
"retention": {
"raw_logs_days": 30,
"raw_traces_days": 30,
"raw_metrics_days": 14,
"cold_raw_days": 400,
"delete_cold_raw": false,
"metric_rollups_days": 400,
"evidence_days": 400
},
"web_push": {
"private_key_file": "/etc/gamertan-observatory/web-push.json",
"subject": "mailto:security@example.com",
"queue_capacity": 64,
"request_timeout": "10s"
}
}
+1
View File
@@ -0,0 +1 @@
SPDX-License-Identifier: 0BSD
+31
View File
@@ -0,0 +1,31 @@
// SPDX-License-Identifier: AGPL-3.0-only
module gamertan.com/observatory
go 1.26
require (
gamertan.com/sandwich-hime/sando v1.0.0-beta.1
gamertan.com/web v0.1.0-preview.4
github.com/klauspost/compress v1.18.7
go.opentelemetry.io/proto/otlp v1.11.0
google.golang.org/protobuf v1.36.11
modernc.org/sqlite v1.56.0
)
require (
gamertan.com/tend v0.2.0-preview.2 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/crypto v0.54.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
modernc.org/libc v1.74.4 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
)
tool gamertan.com/tend/cmd/tend
+66
View File
@@ -0,0 +1,66 @@
gamertan.com/sandwich-hime/sando v1.0.0-beta.1 h1:WHe6LnVKvOz7CQr9OIWI78pCzIFIAGgoXlGfjYVAVoU=
gamertan.com/sandwich-hime/sando v1.0.0-beta.1/go.mod h1:awOXo4t2zNxxgH60qkTpMOdhYnultm9AfpjlN9gOEis=
gamertan.com/tend v0.2.0-preview.2 h1:1bcu+0cHEtbw3aqnBX0PaS0WWQf3v88Mw3wwrZZwXVA=
gamertan.com/tend v0.2.0-preview.2/go.mod h1:JEzonyOsZsG+jcPDCE6LkTw6E8rHg+Vp5TFgBz5sEVE=
gamertan.com/web v0.1.0-preview.4 h1:n5s0njTVgBe+5jlWIv6u2wnKZGU/hN/UfgBrJU9MpJM=
gamertan.com/web v0.1.0-preview.4/go.mod h1:KOxki9zGWgNb9+1H6OsvnShBijLvw+ZjurBR8D8FZW0=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI=
modernc.org/cc/v4 v4.29.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k=
modernc.org/libc v1.74.4/go.mod h1:eeQAS9W3sZeKYMFubydxJpII9ybHWshk+7or7bLG9co=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.56.0 h1:/D8e2RfFqoy/Zc6PuC76U28zFwmI/sYx1Kjm4yEn9e0=
modernc.org/sqlite v1.56.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
+303
View File
@@ -0,0 +1,303 @@
// SPDX-License-Identifier: AGPL-3.0-only
package agent
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
"gamertan.com/observatory/internal/agentclient"
"gamertan.com/observatory/internal/agentstate"
"gamertan.com/observatory/internal/config"
"gamertan.com/observatory/internal/edgealert"
"gamertan.com/observatory/internal/hostmetrics"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/spool"
"gamertan.com/observatory/internal/storage"
"gamertan.com/observatory/internal/tailer"
)
type Sender interface {
Send(context.Context, model.Batch) (storage.Ack, error)
SendAlertTransition(context.Context, model.AlertTransition) (storage.SourceAlertTransitionAck, error)
}
type Runner struct {
configuration config.Agent
sourceID string
stateStore *agentstate.Store
state agentstate.State
spool *spool.Spool
sender Sender
agentEpoch string
}
func Open(configuration config.Agent, credential string, transport http.RoundTripper) (*Runner, error) {
sourceID, err := sourceIDFromCredential(credential)
if err != nil {
return nil, err
}
stateStore, state, err := agentstate.Open(configuration.StateFile)
if err != nil {
return nil, err
}
queue, err := spool.Open(configuration.SpoolDir, configuration.MaxSpoolBytes, configuration.MaxSpoolAge)
if err != nil {
return nil, err
}
client, err := agentclient.New(configuration.ServerURL, credential, transport)
if err != nil {
return nil, err
}
return newRunner(configuration, sourceID, stateStore, state, queue, client, agentEpoch(credential))
}
func New(configuration config.Agent, sourceID string, stateStore *agentstate.Store, state agentstate.State, queue *spool.Spool, sender Sender) (*Runner, error) {
return newRunner(configuration, sourceID, stateStore, state, queue, sender, agentEpoch(sourceID))
}
func newRunner(configuration config.Agent, sourceID string, stateStore *agentstate.Store, state agentstate.State, queue *spool.Spool, sender Sender, epoch string) (*Runner, error) {
if err := model.ValidateSourceID(sourceID); err != nil || stateStore == nil || queue == nil || sender == nil {
return nil, errors.New("agent runtime dependencies are invalid")
}
if err := state.Validate(); err != nil {
return nil, err
}
if len(epoch) != 32 {
return nil, errors.New("agent epoch is invalid")
}
return &Runner{configuration: configuration, sourceID: sourceID, stateStore: stateStore, state: state, spool: queue, sender: sender, agentEpoch: epoch}, nil
}
func (runner *Runner) RunOnce(ctx context.Context, now time.Time) error {
if now.IsZero() {
return errors.New("agent cycle time is required")
}
var cycleErrors []error
if err := runner.recoverCheckpoints(now); err != nil {
return err
}
deliveryFailed := false
if err := runner.deliver(ctx, now); err != nil {
cycleErrors = append(cycleErrors, err)
deliveryFailed = true
}
for _, source := range runner.configuration.Sources {
cursor := runner.state.Streams[source.StreamID]
if source.Kind == "linux_metrics" {
observations, collectErr := hostmetrics.Collect(*source.LinuxMetrics, now)
if len(observations) == 0 {
if collectErr != nil {
cycleErrors = append(cycleErrors, fmt.Errorf("collect stream %s: %w", source.StreamID, collectErr))
}
continue
}
for start := 0; start < len(observations); start += runner.configuration.BatchRecords {
end := min(start+runner.configuration.BatchRecords, len(observations))
cursor.Sequence++
spooled, err := runner.spoolObservations(source.StreamID, cursor, model.SignalMetrics, observations[start:end], now)
if err != nil {
if spooled {
return err
}
cycleErrors = append(cycleErrors, fmt.Errorf("spool stream %s: %w", source.StreamID, err))
break
}
}
if collectErr != nil {
cycleErrors = append(cycleErrors, fmt.Errorf("collect stream %s: %w", source.StreamID, collectErr))
}
continue
}
result, err := tailer.Read(source, cursor, runner.configuration.BatchRecords, now)
if err != nil {
cycleErrors = append(cycleErrors, fmt.Errorf("collect stream %s: %w", source.StreamID, err))
continue
}
if len(result.Observations) == 0 {
if result.Cursor != cursor {
runner.state.Streams[source.StreamID] = result.Cursor
if err = runner.stateStore.Save(runner.state); err != nil {
return err
}
}
continue
}
result.Cursor.Sequence = cursor.Sequence + 1
spooled, err := runner.spoolObservations(source.StreamID, result.Cursor, result.Signal, result.Observations, now)
if err != nil {
if spooled {
return err
}
cycleErrors = append(cycleErrors, fmt.Errorf("spool stream %s: %w", source.StreamID, err))
continue
}
}
if !deliveryFailed {
if err := runner.deliver(ctx, now); err != nil {
cycleErrors = append(cycleErrors, err)
}
}
return errors.Join(cycleErrors...)
}
func (runner *Runner) spoolObservations(streamID string, cursor agentstate.Cursor, signal model.Signal, observations []model.Observation, now time.Time) (bool, error) {
batch := model.Batch{Version: model.BatchVersion, SourceID: runner.sourceID, StreamID: streamID, Sequence: cursor.Sequence, ObservedAt: now.UTC(), Signal: signal, Records: observations}
checkpoint, err := json.Marshal(cursor)
if err != nil {
return false, err
}
if _, err = runner.spool.PutWithCheckpoint(batch, checkpoint, now); err != nil {
return false, err
}
runner.state.Streams[streamID] = cursor
return true, runner.stateStore.Save(runner.state)
}
func (runner *Runner) recoverCheckpoints(now time.Time) error {
entries, err := runner.spool.List(now)
if err != nil {
return err
}
changed := false
for _, entry := range entries {
_, checkpoint, err := runner.spool.ReadWithCheckpoint(entry)
if err != nil {
return err
}
if len(checkpoint) == 0 {
return errors.New("pending spool batch lacks a cursor checkpoint")
}
cursor, err := decodeCursor(checkpoint)
if err != nil || cursor.Sequence != entry.Sequence {
return errors.New("pending spool checkpoint is invalid")
}
current := runner.state.Streams[entry.StreamID]
if cursor.Sequence < current.Sequence {
continue
}
if cursor.Sequence == current.Sequence {
if cursor != current {
return errors.New("pending spool checkpoint conflicts with agent state")
}
continue
}
if cursor.Sequence != current.Sequence+1 {
return errors.New("pending spool checkpoint has a sequence gap")
}
runner.state.Streams[entry.StreamID] = cursor
changed = true
}
if changed {
return runner.stateStore.Save(runner.state)
}
return nil
}
func (runner *Runner) deliver(ctx context.Context, now time.Time) error {
entries, err := runner.spool.List(now)
if err != nil {
return err
}
blocked := map[string]bool{}
var deliveryErrors []error
for _, entry := range entries {
if blocked[entry.StreamID] {
continue
}
batch, _, err := runner.spool.ReadWithCheckpoint(entry)
if err != nil {
return err
}
ack, sendErr := runner.sender.Send(ctx, batch)
if sendErr != nil {
blocked[entry.StreamID] = true
deliveryErrors = append(deliveryErrors, fmt.Errorf("deliver stream %s sequence %d: %w", entry.StreamID, entry.Sequence, sendErr))
continue
}
batchDigest, digestErr := batch.Digest()
if digestErr != nil || ack.SourceID != batch.SourceID || ack.StreamID != batch.StreamID || ack.Sequence != batch.Sequence || ack.BatchDigest != batchDigest {
blocked[entry.StreamID] = true
deliveryErrors = append(deliveryErrors, fmt.Errorf("deliver stream %s sequence %d: acknowledgement does not match exact batch", entry.StreamID, entry.Sequence))
continue
}
transitionFailed := false
for _, rule := range runner.configuration.AlertRules {
if rule.StreamID != batch.StreamID {
continue
}
evaluation, evaluationErr := edgealert.Evaluate(rule, batch)
if evaluationErr != nil {
blocked[entry.StreamID] = true
deliveryErrors = append(deliveryErrors, fmt.Errorf("evaluate alert rule %s for stream %s sequence %d: %w", rule.ID, entry.StreamID, entry.Sequence, evaluationErr))
transitionFailed = true
break
}
transition := model.AlertTransition{Version: model.AlertTransitionVersion, RuleID: rule.ID, RuleRevision: rule.Revision, AgentEpoch: runner.agentEpoch, Sequence: batch.Sequence, StreamID: batch.StreamID, BatchSequence: batch.Sequence, SegmentDigest: ack.Digest, WindowStart: evaluation.WindowStart, WindowEnd: evaluation.WindowEnd, State: evaluation.State, ObservedAt: evaluation.ObservedAt}
transitionAck, transitionErr := runner.sender.SendAlertTransition(ctx, transition)
expectedDigest, digestErr := transition.Digest()
if transitionErr != nil || digestErr != nil || transitionAck.SourceID != batch.SourceID || transitionAck.RuleID != transition.RuleID || transitionAck.RuleRevision != transition.RuleRevision || transitionAck.AgentEpoch != transition.AgentEpoch || transitionAck.Sequence != transition.Sequence || transitionAck.Digest != expectedDigest {
blocked[entry.StreamID] = true
if transitionErr == nil {
transitionErr = errors.New("acknowledgement does not match exact transition")
}
deliveryErrors = append(deliveryErrors, fmt.Errorf("deliver alert rule %s for stream %s sequence %d: %w", rule.ID, entry.StreamID, entry.Sequence, transitionErr))
transitionFailed = true
break
}
}
if transitionFailed {
continue
}
if err = runner.spool.Acknowledge(entry, entry.Digest); err != nil {
return err
}
}
return errors.Join(deliveryErrors...)
}
func agentEpoch(sourceID string) string {
digest := sha256.Sum256([]byte("observatory-agent-epoch-v1\x00" + sourceID))
return hex.EncodeToString(digest[:16])
}
func decodeCursor(body []byte) (agentstate.Cursor, error) {
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
var cursor agentstate.Cursor
if err := decoder.Decode(&cursor); err != nil {
return agentstate.Cursor{}, err
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return agentstate.Cursor{}, errors.New("cursor checkpoint has trailing data")
}
if cursor.Offset < 0 || (cursor.Device == 0) != (cursor.Inode == 0) || cursor.Sequence == 0 {
return agentstate.Cursor{}, errors.New("cursor checkpoint is invalid")
}
return cursor, nil
}
func sourceIDFromCredential(credential string) (string, error) {
if !strings.HasPrefix(credential, "obs1.") || strings.ContainsAny(credential, " \t\r\n") {
return "", errors.New("source credential is invalid")
}
remainder := strings.TrimPrefix(credential, "obs1.")
separator := strings.LastIndexByte(remainder, '.')
if separator < 1 || separator == len(remainder)-1 {
return "", errors.New("source credential is invalid")
}
sourceID := remainder[:separator]
if err := model.ValidateSourceID(sourceID); err != nil {
return "", errors.New("source credential is invalid")
}
return sourceID, nil
}
+306
View File
@@ -0,0 +1,306 @@
// SPDX-License-Identifier: AGPL-3.0-only
package agent
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gamertan.com/observatory/internal/agentstate"
"gamertan.com/observatory/internal/config"
"gamertan.com/observatory/internal/hostmetrics"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/query"
"gamertan.com/observatory/internal/spool"
"gamertan.com/observatory/internal/storage"
)
type fakeSender struct {
fail bool
failAlerts bool
batchDigests map[uint64]string
sent []uint64
alerts []model.AlertTransition
}
func (sender *fakeSender) SendAlertTransition(_ context.Context, transition model.AlertTransition) (storage.SourceAlertTransitionAck, error) {
if sender.failAlerts {
return storage.SourceAlertTransitionAck{}, errors.New("alert endpoint unavailable")
}
sender.alerts = append(sender.alerts, transition)
digest, err := transition.Digest()
if err != nil {
return storage.SourceAlertTransitionAck{}, err
}
return storage.SourceAlertTransitionAck{SourceID: "source", RuleID: transition.RuleID, RuleRevision: transition.RuleRevision, AgentEpoch: transition.AgentEpoch, Sequence: transition.Sequence, Digest: digest}, nil
}
func (sender *fakeSender) Send(_ context.Context, batch model.Batch) (storage.Ack, error) {
if sender.fail {
return storage.Ack{}, errors.New("server unavailable")
}
sender.sent = append(sender.sent, batch.Sequence)
batchDigest, err := batch.Digest()
if err != nil {
return storage.Ack{}, err
}
if override := sender.batchDigests[batch.Sequence]; override != "" {
batchDigest = override
}
return storage.Ack{SourceID: batch.SourceID, StreamID: batch.StreamID, Sequence: batch.Sequence, Digest: strings.Repeat("d", 64), BatchDigest: batchDigest}, nil
}
func TestRunnerCollectsWhileOfflineAndRecoversCheckpoint(t *testing.T) {
root := t.TempDir()
logPath := filepath.Join(root, "request.jsonl")
if err := os.WriteFile(logPath, []byte(requestLine("one")+"\n"), 0o640); err != nil {
t.Fatal(err)
}
spoolRoot := filepath.Join(root, "spool")
configuration := config.Agent{BatchRecords: 1, MaxSpoolBytes: 1 << 20, MaxSpoolAge: 72 * time.Hour, SpoolDir: spoolRoot, StateFile: filepath.Join(spoolRoot, "state.json"), Sources: []config.AgentSource{{Kind: "requestlog_jsonl", Path: logPath, StreamID: "request"}}}
stateStore, state, err := agentstate.Open(configuration.StateFile)
if err != nil {
t.Fatal(err)
}
queue, err := spool.Open(spoolRoot, configuration.MaxSpoolBytes, configuration.MaxSpoolAge)
if err != nil {
t.Fatal(err)
}
sender := &fakeSender{fail: true}
runner, err := New(configuration, "source", stateStore, state, queue, sender)
if err != nil {
t.Fatal(err)
}
now := time.Date(2026, 8, 17, 1, 2, 4, 0, time.UTC)
if err = runner.RunOnce(context.Background(), now); err == nil {
t.Fatal("offline delivery unexpectedly succeeded")
}
file, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
if _, err = file.WriteString(requestLine("two") + "\n"); err != nil {
t.Fatal(err)
}
file.Close()
if err = runner.RunOnce(context.Background(), now.Add(time.Second)); err == nil {
t.Fatal("offline delivery unexpectedly succeeded")
}
entries, err := queue.List(now.Add(time.Second))
if err != nil || len(entries) != 2 || entries[0].Sequence != 1 || entries[1].Sequence != 2 {
t.Fatalf("entries=%+v err=%v", entries, err)
}
// Simulate a crash after both durable spool commits but before either cursor
// checkpoint reached the state file. Recovery must advance state from the
// spool envelopes before it reads the source again.
empty := agentstate.State{Version: agentstate.Version, Streams: map[string]agentstate.Cursor{}}
if err = stateStore.Save(empty); err != nil {
t.Fatal(err)
}
_, recoveredState, err := agentstate.Open(configuration.StateFile)
if err != nil {
t.Fatal(err)
}
sender.fail = false
restarted, err := New(configuration, "source", stateStore, recoveredState, queue, sender)
if err != nil {
t.Fatal(err)
}
if err = restarted.RunOnce(context.Background(), now.Add(2*time.Second)); err != nil {
t.Fatal(err)
}
if len(sender.sent) != 2 || sender.sent[0] != 1 || sender.sent[1] != 2 {
t.Fatalf("sent=%v", sender.sent)
}
if entries, err = queue.List(now.Add(2 * time.Second)); err != nil || len(entries) != 0 {
t.Fatalf("remaining=%+v err=%v", entries, err)
}
_, finalState, err := agentstate.Open(configuration.StateFile)
if err != nil || finalState.Streams["request"].Sequence != 2 {
t.Fatalf("state=%+v err=%v", finalState, err)
}
}
func TestRunnerPreservesSpoolOnMismatchedAcknowledgement(t *testing.T) {
root := t.TempDir()
logPath := filepath.Join(root, "request.jsonl")
if err := os.WriteFile(logPath, []byte(requestLine("one")+"\n"), 0o640); err != nil {
t.Fatal(err)
}
spoolRoot := filepath.Join(root, "spool")
configuration := config.Agent{BatchRecords: 1, MaxSpoolBytes: 1 << 20, MaxSpoolAge: 72 * time.Hour, SpoolDir: spoolRoot, StateFile: filepath.Join(spoolRoot, "state.json"), Sources: []config.AgentSource{{Kind: "requestlog_jsonl", Path: logPath, StreamID: "request"}}}
stateStore, state, err := agentstate.Open(configuration.StateFile)
if err != nil {
t.Fatal(err)
}
queue, err := spool.Open(spoolRoot, configuration.MaxSpoolBytes, configuration.MaxSpoolAge)
if err != nil {
t.Fatal(err)
}
sender := &fakeSender{batchDigests: map[uint64]string{1: strings.Repeat("a", 64)}}
runner, err := New(configuration, "source", stateStore, state, queue, sender)
if err != nil {
t.Fatal(err)
}
now := time.Date(2026, 8, 17, 1, 2, 4, 0, time.UTC)
if err = runner.RunOnce(context.Background(), now); err == nil || !strings.Contains(err.Error(), "acknowledgement does not match exact batch") {
t.Fatalf("expected exact acknowledgement rejection, got %v", err)
}
entries, err := queue.List(now)
if err != nil || len(entries) != 1 {
t.Fatalf("entries=%+v err=%v", entries, err)
}
}
func TestRunnerDeliversLocallyEvaluatedAlertAfterRawBatchAcknowledgement(t *testing.T) {
root := t.TempDir()
logPath := filepath.Join(root, "request.jsonl")
if err := os.WriteFile(logPath, []byte(requestLineWithStatus("failed", 503)+"\n"), 0o640); err != nil {
t.Fatal(err)
}
spoolRoot := filepath.Join(root, "spool")
ast, err := query.Parse("logs | where status >= 500 | limit 10", model.MaxRecords)
if err != nil {
t.Fatal(err)
}
configuration := config.Agent{BatchRecords: 10, MaxSpoolBytes: 1 << 20, MaxSpoolAge: time.Hour, SpoolDir: spoolRoot, StateFile: filepath.Join(spoolRoot, "state.json"), Sources: []config.AgentSource{{Kind: "requestlog_jsonl", Path: logPath, StreamID: "request"}}, AlertRules: []config.AgentAlertRule{{Version: 1, ID: "http-failures", Revision: 1, StreamID: "request", Query: "logs | where status >= 500 | limit 10", MinimumMatches: 1, AST: ast}}}
stateStore, state, err := agentstate.Open(configuration.StateFile)
if err != nil {
t.Fatal(err)
}
queue, err := spool.Open(spoolRoot, configuration.MaxSpoolBytes, configuration.MaxSpoolAge)
if err != nil {
t.Fatal(err)
}
sender := &fakeSender{}
runner, err := New(configuration, "source", stateStore, state, queue, sender)
if err != nil {
t.Fatal(err)
}
now := time.Date(2026, 8, 17, 1, 2, 4, 0, time.UTC)
if err = runner.RunOnce(context.Background(), now); err != nil {
t.Fatal(err)
}
if len(sender.sent) != 1 || len(sender.alerts) != 1 || sender.alerts[0].State != "matched" || sender.alerts[0].Sequence != 1 || sender.alerts[0].SegmentDigest != strings.Repeat("d", 64) || len(sender.alerts[0].AgentEpoch) != 32 {
t.Fatalf("sent=%v alerts=%+v", sender.sent, sender.alerts)
}
if entries, listErr := queue.List(now); listErr != nil || len(entries) != 0 {
t.Fatalf("entries=%+v err=%v", entries, listErr)
}
}
func TestRunnerRetainsRawBatchUntilAlertTransitionIsAcknowledged(t *testing.T) {
root := t.TempDir()
logPath := filepath.Join(root, "request.jsonl")
if err := os.WriteFile(logPath, []byte(requestLineWithStatus("failed", 503)+"\n"), 0o640); err != nil {
t.Fatal(err)
}
spoolRoot := filepath.Join(root, "spool")
ast, err := query.Parse("logs | where status >= 500 | limit 10", model.MaxRecords)
if err != nil {
t.Fatal(err)
}
configuration := config.Agent{BatchRecords: 10, MaxSpoolBytes: 1 << 20, MaxSpoolAge: time.Hour, SpoolDir: spoolRoot, StateFile: filepath.Join(spoolRoot, "state.json"), Sources: []config.AgentSource{{Kind: "requestlog_jsonl", Path: logPath, StreamID: "request"}}, AlertRules: []config.AgentAlertRule{{Version: 1, ID: "http-failures", Revision: 1, StreamID: "request", Query: "logs | where status >= 500 | limit 10", MinimumMatches: 1, AST: ast}}}
stateStore, state, err := agentstate.Open(configuration.StateFile)
if err != nil {
t.Fatal(err)
}
queue, err := spool.Open(spoolRoot, configuration.MaxSpoolBytes, configuration.MaxSpoolAge)
if err != nil {
t.Fatal(err)
}
sender := &fakeSender{failAlerts: true}
runner, err := New(configuration, "source", stateStore, state, queue, sender)
if err != nil {
t.Fatal(err)
}
now := time.Date(2026, 8, 17, 1, 2, 4, 0, time.UTC)
if err = runner.RunOnce(context.Background(), now); err == nil || !strings.Contains(err.Error(), "alert endpoint unavailable") {
t.Fatalf("err=%v", err)
}
if entries, listErr := queue.List(now); listErr != nil || len(entries) != 1 {
t.Fatalf("entries=%+v err=%v", entries, listErr)
}
sender.failAlerts = false
if err = runner.RunOnce(context.Background(), now.Add(time.Second)); err != nil {
t.Fatal(err)
}
if len(sender.sent) != 2 || len(sender.alerts) != 1 {
t.Fatalf("sent=%v alerts=%+v", sender.sent, sender.alerts)
}
}
func TestSourceIDParsingKeepsDotsInsideIdentifier(t *testing.T) {
id, err := sourceIDFromCredential("obs1.node.example.abcdef")
if err != nil || id != "node.example" {
t.Fatalf("id=%q err=%v", id, err)
}
for _, invalid := range []string{"token", "obs1..secret", "obs1.bad value.secret"} {
if _, err = sourceIDFromCredential(invalid); err == nil {
t.Fatalf("accepted %q", invalid)
}
}
}
func TestRunnerSpoolsLinuxMetricsWhileServerIsOffline(t *testing.T) {
root := t.TempDir()
proc := filepath.Join(root, "proc")
if err := os.MkdirAll(filepath.Join(proc, "net"), 0o700); err != nil {
t.Fatal(err)
}
files := map[string]string{
"stat": "cpu 1 2 3 4\n", "uptime": "10 5\n",
"meminfo": "MemTotal: 10 kB\nMemAvailable: 8 kB\nSwapTotal: 2 kB\nSwapFree: 1 kB\n",
"loadavg": "0.1 0.2 0.3 1/1 1\n", filepath.Join("net", "dev"): "Inter-| Receive | Transmit\n",
}
for name, body := range files {
if err := os.WriteFile(filepath.Join(proc, name), []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
spoolRoot := filepath.Join(root, "spool")
configuration := config.Agent{BatchRecords: 3, MaxSpoolBytes: 1 << 20, MaxSpoolAge: time.Hour, SpoolDir: spoolRoot, StateFile: filepath.Join(spoolRoot, "state.json"), Sources: []config.AgentSource{{Kind: "linux_metrics", StreamID: "host-metrics", LinuxMetrics: &hostmetrics.Config{ProcRoot: proc}}}}
stateStore, state, err := agentstate.Open(configuration.StateFile)
if err != nil {
t.Fatal(err)
}
queue, err := spool.Open(spoolRoot, configuration.MaxSpoolBytes, configuration.MaxSpoolAge)
if err != nil {
t.Fatal(err)
}
runner, err := New(configuration, "source", stateStore, state, queue, &fakeSender{fail: true})
if err != nil {
t.Fatal(err)
}
now := time.Date(2026, 8, 17, 6, 0, 0, 0, time.UTC)
if err = runner.RunOnce(context.Background(), now); err == nil {
t.Fatal("offline delivery unexpectedly succeeded")
}
entries, err := queue.List(now)
if err != nil || len(entries) < 2 {
t.Fatalf("entries=%+v err=%v", entries, err)
}
for index, entry := range entries {
batch, _, readErr := queue.ReadWithCheckpoint(entry)
if readErr != nil {
t.Fatal(readErr)
}
if batch.Signal != model.SignalMetrics || batch.StreamID != "host-metrics" || len(batch.Records) == 0 || len(batch.Records) > configuration.BatchRecords || batch.Sequence != uint64(index+1) {
t.Fatalf("batch=%+v", batch)
}
}
}
func requestLine(route string) string {
return `{"timestamp":"2026-08-17T01:02:03Z","method":"GET","route":"/` + route + `","status":200,"bytes":12,"duration_ns":1000,"request_id":"request-1"}`
}
func requestLineWithStatus(route string, status int) string {
return fmt.Sprintf(`{"timestamp":"2026-08-17T01:02:03Z","method":"GET","route":"/%s","status":%d,"bytes":12,"duration_ns":1000,"request_id":"request-1"}`, route, status)
}
+229
View File
@@ -0,0 +1,229 @@
// SPDX-License-Identifier: AGPL-3.0-only
package agentclient
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/nativeprotocol"
"gamertan.com/observatory/internal/storage"
)
type Client struct {
endpoint string
alertEndpoint string
credential string
sourceID string
http *http.Client
}
type EnrollmentResult struct {
SourceID string `json:"source_id"`
Credential string `json:"credential"`
}
func Enroll(ctx context.Context, serverURL, enrollmentToken string, transport http.RoundTripper) (EnrollmentResult, error) {
u, err := url.Parse(serverURL)
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" {
return EnrollmentResult{}, errors.New("server URL must be an absolute HTTPS origin")
}
if len(enrollmentToken) != len("obse1.")+64 || !strings.HasPrefix(enrollmentToken, "obse1.") || strings.ContainsAny(enrollmentToken, " \t\r\n") {
return EnrollmentResult{}, errors.New("invalid enrollment token")
}
if transport == nil {
transport = http.DefaultTransport
}
client := &http.Client{Transport: transport, Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimSuffix(serverURL, "/")+"/api/v1/agent/enroll", http.NoBody)
if err != nil {
return EnrollmentResult{}, errors.New("create enrollment request")
}
request.Header.Set("Authorization", "Bearer "+enrollmentToken)
request.Header.Set("Accept", "application/json")
response, err := client.Do(request)
if err != nil {
return EnrollmentResult{}, errors.New("enrollment request failed")
}
defer response.Body.Close()
if response.StatusCode != http.StatusCreated {
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 64<<10))
return EnrollmentResult{}, fmt.Errorf("enrollment returned HTTP %d", response.StatusCode)
}
decoder := json.NewDecoder(io.LimitReader(response.Body, 64<<10))
decoder.DisallowUnknownFields()
var result EnrollmentResult
if err = decoder.Decode(&result); err != nil {
return EnrollmentResult{}, errors.New("invalid enrollment response")
}
if err = decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return EnrollmentResult{}, errors.New("enrollment response has trailing data")
}
if err = validateCredential(result.SourceID, result.Credential); err != nil {
return EnrollmentResult{}, err
}
return result, nil
}
func RevokeSource(ctx context.Context, serverURL, credential string, transport http.RoundTripper) error {
u, err := url.Parse(serverURL)
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" {
return errors.New("server URL must be an absolute HTTPS origin")
}
if len(credential) < 48 || len(credential) > 512 || !strings.HasPrefix(credential, "obs1.") || strings.ContainsAny(credential, " \t\r\n") {
return errors.New("invalid source credential")
}
if transport == nil {
transport = http.DefaultTransport
}
client := &http.Client{Transport: transport, Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }}
request, err := http.NewRequestWithContext(ctx, http.MethodDelete, strings.TrimSuffix(serverURL, "/")+"/api/v1/agent/source", http.NoBody)
if err != nil {
return errors.New("create source revocation request")
}
request.Header.Set("Authorization", "Bearer "+credential)
response, err := client.Do(request)
if err != nil {
return errors.New("source revocation request failed")
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 64<<10))
if response.StatusCode != http.StatusNoContent {
return fmt.Errorf("source revocation returned HTTP %d", response.StatusCode)
}
return nil
}
func New(serverURL, credential string, transport http.RoundTripper) (*Client, error) {
u, err := url.Parse(serverURL)
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" {
return nil, errors.New("server URL must be an absolute HTTPS origin")
}
sourceID, credentialErr := credentialSourceID(credential)
if credentialErr != nil {
return nil, errors.New("invalid source credential")
}
if transport == nil {
transport = http.DefaultTransport
}
httpClient := &http.Client{Transport: transport, Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }}
base := strings.TrimSuffix(serverURL, "/")
return &Client{endpoint: base + "/api/v2/ingest/native", alertEndpoint: base + "/api/v1/agent/alert-transition", credential: credential, sourceID: sourceID, http: httpClient}, nil
}
func (c *Client) SendAlertTransition(ctx context.Context, transition model.AlertTransition) (storage.SourceAlertTransitionAck, error) {
b, err := json.Marshal(transition)
if err != nil {
return storage.SourceAlertTransitionAck{}, errors.New("encode source alert transition")
}
expectedDigest, err := transition.Digest()
if err != nil {
return storage.SourceAlertTransitionAck{}, err
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.alertEndpoint, bytes.NewReader(b))
if err != nil {
return storage.SourceAlertTransitionAck{}, errors.New("create source alert transition request")
}
request.Header.Set("Authorization", "Bearer "+c.credential)
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
response, err := c.http.Do(request)
if err != nil {
return storage.SourceAlertTransitionAck{}, errors.New("source alert transition request failed")
}
defer response.Body.Close()
if response.StatusCode != http.StatusAccepted {
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 64<<10))
return storage.SourceAlertTransitionAck{}, fmt.Errorf("source alert transition returned HTTP %d", response.StatusCode)
}
decoder := json.NewDecoder(io.LimitReader(response.Body, 64<<10))
decoder.DisallowUnknownFields()
var ack storage.SourceAlertTransitionAck
if err = decoder.Decode(&ack); err != nil {
return storage.SourceAlertTransitionAck{}, errors.New("invalid source alert transition acknowledgement")
}
if err = decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return storage.SourceAlertTransitionAck{}, errors.New("source alert transition acknowledgement has trailing data")
}
if ack.SourceID != c.sourceID || ack.RuleID != transition.RuleID || ack.RuleRevision != transition.RuleRevision || ack.AgentEpoch != transition.AgentEpoch || ack.Sequence != transition.Sequence || ack.Digest != expectedDigest {
return storage.SourceAlertTransitionAck{}, errors.New("source alert transition acknowledgement does not match transition")
}
return ack, nil
}
func credentialSourceID(credential string) (string, error) {
if len(credential) < 48 || len(credential) > 512 || !strings.HasPrefix(credential, "obs1.") || strings.ContainsAny(credential, " \t\r\n") {
return "", errors.New("invalid source credential")
}
remainder := strings.TrimPrefix(credential, "obs1.")
separator := strings.LastIndexByte(remainder, '.')
if separator < 1 || separator == len(remainder)-1 {
return "", errors.New("invalid source credential")
}
sourceID := remainder[:separator]
if model.ValidateSourceID(sourceID) != nil {
return "", errors.New("invalid source credential")
}
return sourceID, nil
}
func validateCredential(sourceID, credential string) error {
if model.ValidateSourceID(sourceID) != nil || len(credential) < 48 || len(credential) > 512 || !strings.HasPrefix(credential, "obs1."+sourceID+".") || strings.ContainsAny(credential, " \t\r\n") {
return errors.New("invalid source credential")
}
return nil
}
func (c *Client) Send(ctx context.Context, batch model.Batch) (storage.Ack, error) {
b, err := json.Marshal(batch)
if err != nil {
return storage.Ack{}, errors.New("encode native batch")
}
envelope, err := batch.Envelope(b)
if err != nil {
return storage.Ack{}, errors.New("encode native batch envelope")
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, bytes.NewReader(b))
if err != nil {
return storage.Ack{}, errors.New("create ingestion request")
}
request.Header.Set("Authorization", "Bearer "+c.credential)
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
nativeprotocol.SetHeaders(request.Header, envelope)
response, err := c.http.Do(request)
if err != nil {
return storage.Ack{}, errors.New("ingestion request failed")
}
defer response.Body.Close()
if response.StatusCode != http.StatusAccepted {
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 64<<10))
return storage.Ack{}, fmt.Errorf("ingestion returned HTTP %d", response.StatusCode)
}
decoder := json.NewDecoder(io.LimitReader(response.Body, 64<<10))
decoder.DisallowUnknownFields()
var ack storage.Ack
if err := decoder.Decode(&ack); err != nil {
return storage.Ack{}, errors.New("invalid ingestion acknowledgement")
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return storage.Ack{}, errors.New("ingestion acknowledgement has trailing data")
}
decodedDigest, digestErr := hex.DecodeString(ack.Digest)
decodedBatchDigest, batchDigestErr := hex.DecodeString(ack.BatchDigest)
if ack.SourceID != batch.SourceID || ack.StreamID != batch.StreamID || ack.Sequence != batch.Sequence || digestErr != nil || len(decodedDigest) != sha256.Size || batchDigestErr != nil || len(decodedBatchDigest) != sha256.Size || ack.BatchDigest != envelope.BatchDigest {
return storage.Ack{}, errors.New("ingestion acknowledgement does not match batch")
}
return ack, nil
}
+206
View File
@@ -0,0 +1,206 @@
// SPDX-License-Identifier: AGPL-3.0-only
package agentclient
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gamertan.com/observatory/internal/httpserver"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/nativeprotocol"
"gamertan.com/observatory/internal/query"
"gamertan.com/observatory/internal/storage"
)
type transportFunc func(*http.Request) (*http.Response, error)
func (f transportFunc) RoundTrip(request *http.Request) (*http.Response, error) { return f(request) }
func TestSendRequiresMatchingAcknowledgementAndDoesNotRedirect(t *testing.T) {
credential := "obs1.source." + strings.Repeat("a", 64)
var authorization, path string
client, err := New("https://observatory.example", credential, transportFunc(func(request *http.Request) (*http.Response, error) {
authorization = request.Header.Get("Authorization")
path = request.URL.Path
body, readErr := io.ReadAll(request.Body)
if readErr != nil {
t.Fatal(readErr)
}
digest := sha256.Sum256(body)
if request.Header.Get(nativeprotocol.WireDigestHeader) != hex.EncodeToString(digest[:]) || request.Header.Get(nativeprotocol.StreamHeader) != "access" || request.Header.Get(nativeprotocol.SequenceHeader) != "1" {
t.Fatalf("missing framed batch metadata: %v", request.Header)
}
response := fmt.Sprintf(`{"source_id":"source","stream_id":"access","sequence":1,"digest":"%s","batch_digest":"%s","duplicate":false}`, strings.Repeat("a", 64), hex.EncodeToString(digest[:]))
return &http.Response{StatusCode: http.StatusAccepted, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(response))}, nil
}))
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
batch := model.Batch{Version: 1, SourceID: "source", StreamID: "access", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "request"}}}
if _, err := client.Send(context.Background(), batch); err != nil {
t.Fatal(err)
}
if authorization != "Bearer "+credential || path != "/api/v2/ingest/native" {
t.Fatalf("authorization=%q path=%q", authorization, path)
}
}
func TestSendAcceptsRealServerBatchDigestRatherThanPrivateSegmentDigest(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
t.Fatal(err)
}
defer store.Close()
identities, err := identity.Open(root)
if err != nil {
t.Fatal(err)
}
defer identities.Close()
token, err := store.CreateSource(context.Background(), "source", model.Scope{OrganizationID: "organization", ProjectID: "project", EnvironmentID: "production", ServiceID: "service"})
if err != nil {
t.Fatal(err)
}
server, err := httpserver.New(store, identities, httpserver.Options{
PublicOrigin: "https://observatory.example", MaxBodyBytes: 1 << 20, MaxQueryRows: 100,
QueryBudget: query.Budget{MaxDuration: time.Second, MaxRows: 100, MaxScannedBytes: 1 << 20, MaxMemoryBytes: 1 << 20}, SessionLifetime: time.Hour,
})
if err != nil {
t.Fatal(err)
}
client, err := New("https://observatory.example", token, transportFunc(func(request *http.Request) (*http.Response, error) {
request.RemoteAddr = "127.0.0.1:40000"
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
return response.Result(), nil
}))
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
batch := model.Batch{Version: 1, SourceID: "source", StreamID: "access", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "request"}}}
ack, err := client.Send(context.Background(), batch)
if err != nil {
t.Fatal(err)
}
expected, err := batch.Digest()
if err != nil {
t.Fatal(err)
}
if ack.BatchDigest != expected || ack.Digest == ack.BatchDigest {
t.Fatalf("ack=%+v expected batch digest=%s", ack, expected)
}
}
func TestSendRejectsMismatchedAcknowledgementWithoutEchoingBody(t *testing.T) {
credential := "obs1.source." + strings.Repeat("a", 64)
client, err := New("https://observatory.example", credential, transportFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusAccepted, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"source_id":"source","stream_id":"access","sequence":1,"digest":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","batch_digest":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}`))}, nil
}))
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
batch := model.Batch{Version: 1, SourceID: "source", StreamID: "access", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "request", Body: "do-not-echo"}}}
_, err = client.Send(context.Background(), batch)
if err == nil || strings.Contains(err.Error(), "do-not-echo") {
t.Fatalf("unexpected error: %v", err)
}
}
func TestSendAlertTransitionUsesExactEndpointAndRejectsMismatchedAcknowledgement(t *testing.T) {
credential := "obs1.source." + strings.Repeat("a", 64)
now := time.Date(2026, 8, 18, 23, 50, 0, 0, time.UTC)
transition := model.AlertTransition{Version: model.AlertTransitionVersion, RuleID: "rule-a", RuleRevision: 2, AgentEpoch: strings.Repeat("b", 32), Sequence: 3, StreamID: "requests", BatchSequence: 8, SegmentDigest: strings.Repeat("c", 64), WindowStart: now.Add(-time.Minute), WindowEnd: now, State: "matched", ObservedAt: now}
digest, err := transition.Digest()
if err != nil {
t.Fatal(err)
}
var path, authorization string
client, err := New("https://observatory.example", credential, transportFunc(func(request *http.Request) (*http.Response, error) {
path = request.URL.Path
authorization = request.Header.Get("Authorization")
body, readErr := io.ReadAll(request.Body)
if readErr != nil || !strings.Contains(string(body), `"segment_digest":"`+transition.SegmentDigest+`"`) {
t.Fatalf("body=%q err=%v", string(body), readErr)
}
response := fmt.Sprintf(`{"source_id":"source","rule_id":"rule-a","rule_revision":2,"agent_epoch":"%s","sequence":3,"digest":"%s","duplicate":false}`, transition.AgentEpoch, digest)
return &http.Response{StatusCode: http.StatusAccepted, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(response))}, nil
}))
if err != nil {
t.Fatal(err)
}
ack, err := client.SendAlertTransition(context.Background(), transition)
if err != nil || ack.Digest != digest || path != "/api/v1/agent/alert-transition" || authorization != "Bearer "+credential {
t.Fatalf("ack=%+v path=%q authorization=%q err=%v", ack, path, authorization, err)
}
mismatch, err := New("https://observatory.example", credential, transportFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusAccepted, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(fmt.Sprintf(`{"source_id":"source","rule_id":"rule-a","rule_revision":2,"agent_epoch":"%s","sequence":4,"digest":"%s","duplicate":false}`, transition.AgentEpoch, digest)))}, nil
}))
if err != nil {
t.Fatal(err)
}
if _, err = mismatch.SendAlertTransition(context.Background(), transition); err == nil || !strings.Contains(err.Error(), "does not match") {
t.Fatalf("mismatch err=%v", err)
}
wrongSource, err := New("https://observatory.example", credential, transportFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusAccepted, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(fmt.Sprintf(`{"source_id":"other","rule_id":"rule-a","rule_revision":2,"agent_epoch":"%s","sequence":3,"digest":"%s","duplicate":false}`, transition.AgentEpoch, digest)))}, nil
}))
if err != nil {
t.Fatal(err)
}
if _, err = wrongSource.SendAlertTransition(context.Background(), transition); err == nil || !strings.Contains(err.Error(), "does not match") {
t.Fatalf("wrong source err=%v", err)
}
}
func TestEnrollAndRevokeUseExactHTTPSEndpoints(t *testing.T) {
enrollment := "obse1." + strings.Repeat("e", 64)
credential := "obs1.source." + strings.Repeat("a", 64)
var methods []string
transport := transportFunc(func(request *http.Request) (*http.Response, error) {
methods = append(methods, request.Method+" "+request.URL.Path)
switch request.URL.Path {
case "/api/v1/agent/enroll":
if request.Header.Get("Authorization") != "Bearer "+enrollment {
t.Fatal("enrollment authorization missing")
}
return &http.Response{StatusCode: http.StatusCreated, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"source_id":"source","credential":"` + credential + `"}`))}, nil
case "/api/v1/agent/source":
if request.Header.Get("Authorization") != "Bearer "+credential {
t.Fatal("source authorization missing")
}
return &http.Response{StatusCode: http.StatusNoContent, Header: make(http.Header), Body: http.NoBody}, nil
default:
t.Fatalf("unexpected endpoint %s", request.URL.Path)
return nil, nil
}
})
result, err := Enroll(context.Background(), "https://observatory.example", enrollment, transport)
if err != nil || result.SourceID != "source" || result.Credential != credential {
t.Fatalf("result=%+v err=%v", result, err)
}
if err = RevokeSource(context.Background(), "https://observatory.example", credential, transport); err != nil {
t.Fatal(err)
}
if len(methods) != 2 || methods[0] != "POST /api/v1/agent/enroll" || methods[1] != "DELETE /api/v1/agent/source" {
t.Fatalf("methods=%v", methods)
}
}
+149
View File
@@ -0,0 +1,149 @@
// SPDX-License-Identifier: AGPL-3.0-only
package agentstate
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
const Version = 1
type Cursor struct {
Device uint64 `json:"device"`
Inode uint64 `json:"inode"`
Offset int64 `json:"offset"`
Sequence uint64 `json:"sequence"`
DiscardingLine bool `json:"discarding_line"`
DroppedRecords uint64 `json:"dropped_records"`
Discontinuities uint64 `json:"discontinuities"`
}
type State struct {
Version int `json:"version"`
Streams map[string]Cursor `json:"streams"`
}
type Store struct{ path string }
func Open(path string) (*Store, State, error) {
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
return nil, State{}, errors.New("agent state path must be absolute and clean")
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return nil, State{}, fmt.Errorf("create agent state directory: %w", err)
}
parent, err := os.Lstat(filepath.Dir(path))
if err != nil || !parent.IsDir() || parent.Mode()&os.ModeSymlink != 0 || parent.Mode().Perm()&0o077 != 0 {
return nil, State{}, errors.New("agent state directory must be private and must not be a symlink")
}
store := &Store{path: path}
state, err := store.Load()
return store, state, err
}
func (store *Store) Load() (State, error) {
info, err := os.Lstat(store.path)
if errors.Is(err, os.ErrNotExist) {
return State{Version: Version, Streams: map[string]Cursor{}}, nil
}
if err != nil {
return State{}, fmt.Errorf("inspect agent state: %w", err)
}
if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Mode().Perm() != 0o600 {
return State{}, errors.New("agent state must be a mode-0600 regular non-symlink file")
}
body, err := os.ReadFile(store.path)
if err != nil {
return State{}, fmt.Errorf("read agent state: %w", err)
}
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
var state State
if err = decoder.Decode(&state); err != nil {
return State{}, errors.New("decode agent state")
}
if err = decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return State{}, errors.New("agent state contains trailing data")
}
if err = state.Validate(); err != nil {
return State{}, err
}
return state, nil
}
func (store *Store) Save(state State) error {
if err := state.Validate(); err != nil {
return err
}
body, err := json.Marshal(state)
if err != nil {
return err
}
body = append(body, '\n')
dir := filepath.Dir(store.path)
temporary, err := os.CreateTemp(dir, ".state-*")
if err != nil {
return err
}
name := temporary.Name()
defer os.Remove(name)
if err = temporary.Chmod(0o600); err == nil {
_, err = temporary.Write(body)
}
if err == nil {
err = temporary.Sync()
}
if closeErr := temporary.Close(); err == nil {
err = closeErr
}
if err != nil {
return fmt.Errorf("write agent state: %w", err)
}
if existing, inspectErr := os.Lstat(store.path); inspectErr == nil {
if !existing.Mode().IsRegular() || existing.Mode()&os.ModeSymlink != 0 {
return errors.New("agent state destination is not a regular file")
}
} else if !errors.Is(inspectErr, os.ErrNotExist) {
return inspectErr
}
if err = os.Rename(name, store.path); err != nil {
return err
}
directory, err := os.Open(dir)
if err != nil {
return err
}
defer directory.Close()
return directory.Sync()
}
func (state State) Validate() error {
if state.Version != Version || state.Streams == nil || len(state.Streams) > 64 {
return errors.New("agent state identity is invalid")
}
for stream, cursor := range state.Streams {
if !safeID(stream) || cursor.Offset < 0 || (cursor.Device == 0) != (cursor.Inode == 0) {
return errors.New("agent state cursor is invalid")
}
}
return nil
}
func safeID(value string) bool {
if value == "" || len(value) > 128 {
return false
}
for _, character := range value {
if !(character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' || character >= '0' && character <= '9' || strings.ContainsRune("._-", character)) {
return false
}
}
return true
}
+43
View File
@@ -0,0 +1,43 @@
// SPDX-License-Identifier: AGPL-3.0-only
package agentstate
import (
"os"
"path/filepath"
"testing"
)
func TestStateAtomicRoundTripAndSymlinkRefusal(t *testing.T) {
root := filepath.Join(t.TempDir(), "state")
path := filepath.Join(root, "state.json")
store, state, err := Open(path)
if err != nil {
t.Fatal(err)
}
state.Streams["access"] = Cursor{Device: 1, Inode: 2, Offset: 99, Sequence: 3, DroppedRecords: 4}
if err = store.Save(state); err != nil {
t.Fatal(err)
}
_, loaded, err := Open(path)
if err != nil || loaded.Streams["access"] != state.Streams["access"] {
t.Fatalf("loaded=%+v err=%v", loaded, err)
}
info, err := os.Stat(path)
if err != nil || info.Mode().Perm() != 0o600 {
t.Fatalf("state info=%v err=%v", info, err)
}
if err = os.Remove(path); err != nil {
t.Fatal(err)
}
outside := filepath.Join(t.TempDir(), "outside")
if err = os.WriteFile(outside, []byte(`{"version":1,"streams":{}}`), 0o600); err != nil {
t.Fatal(err)
}
if err = os.Symlink(outside, path); err != nil {
t.Skip(err)
}
if _, _, err = Open(path); err == nil {
t.Fatal("symlinked state accepted")
}
}
+253
View File
@@ -0,0 +1,253 @@
//go:build observatory_browser_fixture
// SPDX-License-Identifier: AGPL-3.0-only
// Command browsertest serves a disposable HTTPS Observatory instance for the
// real-browser verification campaign. It is excluded from ordinary builds.
package main
import (
"bytes"
"context"
"crypto/ecdh"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"math/big"
"net"
"net/http"
"net/http/httptest"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"gamertan.com/observatory/internal/httpserver"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/query"
"gamertan.com/observatory/internal/storage"
)
const (
fixtureUsername = "browser-operator"
fixturePassword = "browser-fixture-password"
)
type pushDispatcher struct{}
func (pushDispatcher) Enqueue(string) bool { return true }
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "browser fixture failed:", err)
os.Exit(1)
}
}
func run() error {
root, err := os.MkdirTemp("", "observatory-browser-fixture-")
if err != nil {
return errors.New("create browser fixture root")
}
defer os.RemoveAll(root)
if err = os.Chmod(root, 0o700); err != nil {
return errors.New("protect browser fixture root")
}
certificate, spki, err := localCertificate()
if err != nil {
return err
}
listener, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{Certificates: []tls.Certificate{certificate}, MinVersion: tls.VersionTLS13})
if err != nil {
return errors.New("listen for browser fixture")
}
defer listener.Close()
_, port, err := net.SplitHostPort(listener.Addr().String())
if err != nil {
return errors.New("read browser fixture listener")
}
origin := "https://localhost:" + port
store, err := storage.Open(filepath.Join(root, "data"))
if err != nil {
return err
}
defer store.Close()
identities, err := identity.Open(filepath.Join(root, "data"))
if err != nil {
return err
}
defer identities.Close()
bootstrap, err := identities.Bootstrap(context.Background(), identity.BootstrapInput{
Username: fixtureUsername, Email: "browser@example.test", DisplayName: "Browser Operator", Password: fixturePassword,
})
if err != nil {
return err
}
now := time.Now().UTC()
scope := model.Scope{OrganizationID: bootstrap.Organization.ID, ProjectID: "browser-project", EnvironmentID: "test", ServiceID: "browser-service"}
token, err := store.CreateSource(context.Background(), "browser-source", scope)
if err != nil {
return err
}
if _, err = store.Ingest(context.Background(), token, logBatch(1, now), now); err != nil {
return err
}
if err = store.Recover(context.Background()); err != nil {
return err
}
saved, err := store.SaveQuery(context.Background(), storage.SavedQueryInput{
OrganizationID: scope.OrganizationID, Name: "Browser fixture evidence", Description: "Exact browser-campaign evidence.",
Query: "logs | window 1h | limit 10", ActorUserID: bootstrap.User.ID, MaxRows: 100,
}, now)
if err != nil {
return err
}
if _, err = store.SaveAlertRule(context.Background(), storage.AlertRuleInput{
OrganizationID: scope.OrganizationID, Name: "Browser fixture incident", Description: "Exercises the private offline incident boundary.",
SavedQueryID: saved.ID, Severity: "critical", MinimumMatches: 1, RequiredConsecutive: 1,
EvaluationInterval: 15 * time.Second, Enabled: true, ActorUserID: bootstrap.User.ID,
}, now); err != nil {
return err
}
vapid, err := ecdh.P256().GenerateKey(rand.Reader)
if err != nil {
return errors.New("create browser fixture Web Push key")
}
server, err := httpserver.New(store, identities, httpserver.Options{
PublicOrigin: origin, MaxBodyBytes: 1 << 20, MaxQueryRows: 100,
QueryBudget: query.Budget{MaxDuration: 2 * time.Second, MaxRows: 100, MaxScannedBytes: 32 << 20, MaxMemoryBytes: 16 << 20},
SessionLifetime: time.Hour, PushPublicKey: base64.RawURLEncoding.EncodeToString(vapid.PublicKey().Bytes()), PushDispatcher: pushDispatcher{},
})
if err != nil {
return err
}
if _, err = server.EvaluateAlerts(context.Background()); err != nil {
return err
}
handler := browserFixture(server.Handler())
httpServer := &http.Server{Handler: handler, ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 30 * time.Second}
serveErrors := make(chan error, 1)
go func() { serveErrors <- httpServer.Serve(listener) }()
updatesDone := make(chan struct{})
defer close(updatesDone)
go publishUpdates(handler, origin, token, updatesDone)
fmt.Println(origin)
fmt.Println(spki)
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(signals)
select {
case <-signals:
shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return httpServer.Shutdown(shutdown)
case serveErr := <-serveErrors:
if errors.Is(serveErr, http.ErrServerClosed) {
return nil
}
return serveErr
}
}
// browserFixture bounds the fixture EventSource connection so the browser
// campaign can prove native reconnection. It does not alter request origin
// metadata; form submissions exercise the production token-bound policy.
func browserFixture(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/app/events" {
ctx, cancel := context.WithTimeout(r.Context(), 1250*time.Millisecond)
defer cancel()
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
})
}
func logBatch(sequence uint64, observed time.Time) model.Batch {
return model.Batch{Version: model.BatchVersion, SourceID: "browser-source", StreamID: "browser-stream", Sequence: sequence, ObservedAt: observed, Signal: model.SignalLogs, Records: []model.Observation{{
Timestamp: observed, Name: "browser.fixture", Severity: "information", Body: "bounded browser fixture observation",
Attributes: map[string]string{"http.route": "/browser-fixture", "http.status_code": "200"},
}}}
}
func publishUpdates(handler http.Handler, origin, token string, done <-chan struct{}) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
sequence := uint64(2)
for {
select {
case <-done:
return
case observed := <-ticker.C:
body, err := json.Marshal(logBatch(sequence, observed.UTC()))
if err != nil {
return
}
request := httptest.NewRequest(http.MethodPost, origin+"/api/v1/ingest/native", bytes.NewReader(body))
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code == http.StatusAccepted {
sequence++
}
}
}
}
func localCertificate() (tls.Certificate, string, error) {
private, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return tls.Certificate{}, "", errors.New("create local TLS key")
}
maximum := new(big.Int).Lsh(big.NewInt(1), 128)
serial, err := rand.Int(rand.Reader, maximum)
if err != nil {
return tls.Certificate{}, "", errors.New("create local TLS serial")
}
now := time.Now().UTC()
template := x509.Certificate{
SerialNumber: serial, Subject: pkix.Name{CommonName: "Observatory browser fixture"},
NotBefore: now.Add(-time.Minute), NotAfter: now.Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
DNSNames: []string{"localhost"}, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
}
der, err := x509.CreateCertificate(rand.Reader, &template, &template, &private.PublicKey, private)
if err != nil {
return tls.Certificate{}, "", errors.New("create local TLS certificate")
}
encodedKey, err := x509.MarshalPKCS8PrivateKey(private)
if err != nil {
return tls.Certificate{}, "", errors.New("encode local TLS key")
}
encodedPublic, err := x509.MarshalPKIXPublicKey(&private.PublicKey)
if err != nil {
return tls.Certificate{}, "", errors.New("encode local TLS public key")
}
digest := sha256.Sum256(encodedPublic)
certificate, err := tls.X509KeyPair(
pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}),
pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: encodedKey}),
)
if err != nil {
return tls.Certificate{}, "", err
}
return certificate, base64.StdEncoding.EncodeToString(digest[:]), nil
}
+920
View File
@@ -0,0 +1,920 @@
//go:build observatory_capacity_fixture && linux
// SPDX-License-Identifier: AGPL-3.0-only
// Command capacitytest runs the bounded Observatory capacity and recovery
// campaign. It is excluded from ordinary builds and emits only aggregate,
// synthetic evidence.
package main
import (
"context"
"database/sql"
"encoding/json"
"errors"
"flag"
"fmt"
"math"
"net/url"
"os"
"os/signal"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/query"
"gamertan.com/observatory/internal/spool"
"gamertan.com/observatory/internal/storage"
)
const (
reportVersion = 2
visibilityObservationTimeout = 30 * time.Second
)
type settings struct {
sustainRate int
sustainDuration time.Duration
burstRate int
burstDuration time.Duration
minimumPrimary int64
queryIterations int
organizations int
primaryWeight int
batchInterval time.Duration
requireCgroup bool
expectedCPUs int
expectedMemory int64
}
type phaseReport struct {
TargetRate int `json:"target_rate_per_second"`
DurationSeconds float64 `json:"target_duration_seconds"`
Observations int64 `json:"observations"`
ElapsedSeconds float64 `json:"elapsed_seconds"`
AchievedRate float64 `json:"achieved_rate_per_second"`
IngestP50Milliseconds float64 `json:"ingest_p50_milliseconds"`
IngestP95Milliseconds float64 `json:"ingest_p95_milliseconds"`
IngestP99Milliseconds float64 `json:"ingest_p99_milliseconds"`
VisibleP50Milliseconds float64 `json:"visible_p50_milliseconds"`
VisibleP95Milliseconds float64 `json:"visible_p95_milliseconds"`
VisibleP99Milliseconds float64 `json:"visible_p99_milliseconds"`
}
type queryReport struct {
Name string `json:"name"`
Iterations int `json:"iterations"`
P50Milliseconds float64 `json:"p50_milliseconds"`
P95Milliseconds float64 `json:"p95_milliseconds"`
P99Milliseconds float64 `json:"p99_milliseconds"`
MaximumScannedRows int64 `json:"maximum_scanned_rows"`
MaximumScannedBytes int64 `json:"maximum_scanned_bytes"`
}
type spoolReport struct {
Batches int `json:"batches"`
Observations int64 `json:"observations"`
OldestAgeHours float64 `json:"oldest_age_hours"`
Replayed int64 `json:"replayed_observations"`
RemainingAfterAck int `json:"remaining_after_ack"`
DuplicateRecognized bool `json:"duplicate_recognized"`
}
type retentionEvidence struct {
ArchivedSegments int `json:"archived_segments"`
ArchivedBytes int64 `json:"archived_bytes"`
RemovedSegments int `json:"removed_segments"`
RemovedBytes int64 `json:"removed_bytes"`
ProjectionRowsRemoved int64 `json:"projection_rows_removed"`
ColdQueryRows int `json:"cold_query_rows"`
}
type resourceReport struct {
GOMAXPROCS int `json:"gomaxprocs"`
CPUQuota float64 `json:"cpu_quota"`
MemoryLimitBytes int64 `json:"memory_limit_bytes"`
MaximumRSSBytes int64 `json:"maximum_rss_bytes"`
DatasetBytes int64 `json:"dataset_bytes"`
}
type projectionDrainReport struct {
PendingSegments int `json:"pending_segments_at_start"`
PendingBytes int64 `json:"pending_bytes_at_start"`
OldestLagSeconds float64 `json:"oldest_pending_lag_seconds_at_start"`
ElapsedSeconds float64 `json:"elapsed_seconds"`
}
type storageClass struct {
Files int `json:"files"`
Bytes int64 `json:"bytes"`
}
type storageBreakdown struct {
Raw storageClass `json:"raw_segments"`
Projection storageClass `json:"projection_sqlite"`
Control storageClass `json:"control_sqlite"`
Other storageClass `json:"other"`
Total storageClass `json:"total"`
SQLitePageClasses sqlitePageBreakdown `json:"primary_projection_sqlite_page_classes"`
SQLiteBytes map[string]int64 `json:"primary_projection_sqlite_objects"`
}
type sqlitePageBreakdown struct {
Tables int64 `json:"tables_bytes"`
Indexes int64 `json:"indexes_bytes"`
Internal int64 `json:"internal_bytes"`
Total int64 `json:"total_bytes"`
}
type campaignReport struct {
Version int `json:"version"`
StartedAt time.Time `json:"started_at"`
CompletedAt time.Time `json:"completed_at"`
Organizations int `json:"organizations"`
PrimaryPhaseWeight int `json:"primary_phase_weight"`
TotalObservations int64 `json:"total_observations"`
PrimaryObservations int64 `json:"primary_observations"`
Sustain phaseReport `json:"sustain"`
Burst phaseReport `json:"burst"`
FillSeconds float64 `json:"fill_seconds"`
ProjectionDrain projectionDrainReport `json:"projection_drain"`
PrimaryStorage storageBreakdown `json:"primary_storage"`
Queries []queryReport `json:"queries"`
Spool spoolReport `json:"spool"`
Retention retentionEvidence `json:"retention"`
Resources resourceReport `json:"resources"`
Pass bool `json:"pass"`
}
type sourceState struct {
index int
weight int64
organizationID string
sourceID string
token string
sequences map[model.Signal]uint64
count atomic.Int64
}
type measurements struct {
mu sync.Mutex
ingest []time.Duration
visibility []time.Duration
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "capacity campaign failed:", err)
os.Exit(1)
}
}
func run() error {
configuration := settings{}
flag.IntVar(&configuration.sustainRate, "sustain-rate", 2_000, "sustained mixed observations per second")
flag.DurationVar(&configuration.sustainDuration, "sustain-duration", time.Hour, "sustained campaign duration")
flag.IntVar(&configuration.burstRate, "burst-rate", 10_000, "burst observations per second")
flag.DurationVar(&configuration.burstDuration, "burst-duration", time.Minute, "burst campaign duration")
flag.Int64Var(&configuration.minimumPrimary, "minimum-primary-observations", 10_000_000, "minimum observations in the primary organization")
flag.IntVar(&configuration.queryIterations, "query-iterations", 20, "iterations per common query")
flag.IntVar(&configuration.organizations, "organizations", 4, "concurrent organizations")
flag.IntVar(&configuration.primaryWeight, "primary-phase-weight", 1, "relative phase weight of the primary organization")
flag.DurationVar(&configuration.batchInterval, "batch-interval", 500*time.Millisecond, "batch scheduling interval")
flag.BoolVar(&configuration.requireCgroup, "require-cgroup", false, "require exact CPU and memory cgroup limits")
flag.IntVar(&configuration.expectedCPUs, "expected-cpus", 4, "required CPU quota")
flag.Int64Var(&configuration.expectedMemory, "expected-memory-bytes", 8<<30, "required memory limit")
flag.Parse()
if flag.NArg() != 0 {
return errors.New("capacity campaign accepts no positional arguments")
}
if err := configuration.validate(); err != nil {
return err
}
cpuQuota, memoryLimit, err := cgroupLimits()
if err != nil && configuration.requireCgroup {
return err
}
if configuration.requireCgroup && (math.Abs(cpuQuota-float64(configuration.expectedCPUs)) > 0.001 || memoryLimit != configuration.expectedMemory || runtime.GOMAXPROCS(0) != configuration.expectedCPUs) {
return fmt.Errorf("resource boundary differs: cpu=%.3f memory=%d gomaxprocs=%d", cpuQuota, memoryLimit, runtime.GOMAXPROCS(0))
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
root, err := os.MkdirTemp("", "observatory-capacity-")
if err != nil {
return errors.New("create capacity workspace")
}
defer os.RemoveAll(root)
if err = os.Chmod(root, 0o700); err != nil {
return errors.New("protect capacity workspace")
}
store, err := storage.Open(filepath.Join(root, "dataset"))
if err != nil {
return err
}
defer store.Close()
projectorContext, stopProjector := context.WithCancel(ctx)
projectorDone := make(chan struct{})
projectorErrors := make(chan error, 1)
go func() {
defer close(projectorDone)
store.RunProjector(projectorContext, 100*time.Millisecond, func(projectErr error) {
select {
case projectorErrors <- projectErr:
default:
}
})
}()
defer func() {
stopProjector()
<-projectorDone
}()
states, err := createSources(ctx, store, configuration.organizations, configuration.primaryWeight)
if err != nil {
return err
}
report := campaignReport{Version: reportVersion, StartedAt: time.Now().UTC(), Organizations: len(states), PrimaryPhaseWeight: configuration.primaryWeight}
seed := &atomic.Uint64{}
fmt.Fprintln(os.Stderr, "stage=sustain")
report.Sustain, err = runPhase(ctx, store, states, seed, configuration.sustainRate, configuration.sustainDuration, configuration.batchInterval)
if err != nil {
return err
}
fmt.Fprintln(os.Stderr, "stage=burst")
report.Burst, err = runPhase(ctx, store, states, seed, configuration.burstRate, configuration.burstDuration, configuration.batchInterval)
if err != nil {
return err
}
fmt.Fprintln(os.Stderr, "stage=fill")
fillStarted := time.Now()
if err = fillPrimary(ctx, store, states[0], seed, configuration.minimumPrimary); err != nil {
return err
}
report.FillSeconds = time.Since(fillStarted).Seconds()
report.PrimaryObservations = states[0].count.Load()
for _, state := range states {
report.TotalObservations += state.count.Load()
}
if report.PrimaryObservations < configuration.minimumPrimary {
return errors.New("primary dataset did not reach the required observation count")
}
drainStarted := time.Now()
drainStart, statusErr := store.ProjectionStatus(ctx, drainStarted.UTC())
if statusErr != nil {
return statusErr
}
report.ProjectionDrain = projectionDrainReport{
PendingSegments: drainStart.PendingSegments,
PendingBytes: drainStart.PendingBytes,
OldestLagSeconds: drainStart.OldestPendingLag.Seconds(),
}
if err = waitForProjection(ctx, store, projectorErrors, 10*time.Minute); err != nil {
return err
}
report.ProjectionDrain.ElapsedSeconds = time.Since(drainStarted).Seconds()
fmt.Fprintln(os.Stderr, "stage=queries")
report.Queries, err = runQueries(ctx, store, states[0].organizationID, configuration.queryIterations)
if err != nil {
return err
}
report.PrimaryStorage, err = measureStorage(filepath.Join(root, "dataset"), states[0].organizationID)
if err != nil {
return err
}
fmt.Fprintln(os.Stderr, "stage=spool")
report.Spool, err = runSpoolReplay(ctx, filepath.Join(root, "outage"))
if err != nil {
return err
}
fmt.Fprintln(os.Stderr, "stage=retention")
report.Retention, err = runRetention(ctx, filepath.Join(root, "retention"))
if err != nil {
return err
}
report.Resources = resourceReport{GOMAXPROCS: runtime.GOMAXPROCS(0), CPUQuota: cpuQuota, MemoryLimitBytes: memoryLimit}
report.Resources.MaximumRSSBytes = maximumRSS()
report.Resources.DatasetBytes, err = directoryBytes(root)
if err != nil {
return err
}
var campaignErrors []error
if report.Sustain.AchievedRate < float64(configuration.sustainRate)*0.99 || report.Burst.AchievedRate < float64(configuration.burstRate)*0.99 {
campaignErrors = append(campaignErrors, errors.New("target observation rate was not sustained"))
}
if report.Sustain.VisibleP95Milliseconds >= 2_000 || report.Burst.VisibleP95Milliseconds >= 2_000 {
campaignErrors = append(campaignErrors, errors.New("p95 ingestion-to-query visibility exceeded two seconds"))
}
for _, result := range report.Queries {
if result.P95Milliseconds >= 3_000 {
campaignErrors = append(campaignErrors, fmt.Errorf("query %s exceeded the three-second p95 boundary", result.Name))
}
}
if configuration.requireCgroup && report.Resources.MaximumRSSBytes >= configuration.expectedMemory {
campaignErrors = append(campaignErrors, errors.New("maximum RSS reached the cgroup memory boundary"))
}
report.CompletedAt = time.Now().UTC()
report.Pass = len(campaignErrors) == 0
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
if err = encoder.Encode(report); err != nil {
campaignErrors = append(campaignErrors, fmt.Errorf("encode capacity report: %w", err))
}
return errors.Join(campaignErrors...)
}
func (configuration settings) validate() error {
if configuration.sustainRate < 1 || configuration.burstRate < configuration.sustainRate || configuration.sustainDuration < time.Second || configuration.burstDuration < time.Second || configuration.minimumPrimary < 1 || configuration.queryIterations < 1 || configuration.queryIterations > 100 || configuration.organizations != 4 || configuration.primaryWeight < 1 || configuration.primaryWeight > 32 || configuration.batchInterval < 100*time.Millisecond || configuration.batchInterval > time.Second || configuration.expectedCPUs < 1 || configuration.expectedMemory < 1<<30 {
return errors.New("capacity campaign settings are invalid")
}
primaryShare := float64(configuration.primaryWeight) / float64(configuration.primaryWeight+configuration.organizations-1)
for _, rate := range []int{configuration.sustainRate, configuration.burstRate} {
if int(math.Ceil(float64(rate)*configuration.batchInterval.Seconds()*primaryShare)) > model.MaxRecords {
return errors.New("weighted batch would exceed the model record limit")
}
}
return nil
}
func createSources(ctx context.Context, store *storage.Store, count, primaryWeight int) ([]*sourceState, error) {
states := make([]*sourceState, 0, count)
for index := 0; index < count; index++ {
state := &sourceState{index: index, weight: 1, organizationID: fmt.Sprintf("capacity-org-%d", index+1), sourceID: fmt.Sprintf("capacity-source-%d", index+1), sequences: map[model.Signal]uint64{}}
if index == 0 {
state.weight = int64(primaryWeight)
}
var err error
state.token, err = store.CreateSource(ctx, state.sourceID, model.Scope{OrganizationID: state.organizationID, ProjectID: "observatory", EnvironmentID: "capacity", ServiceID: "server"})
if err != nil {
return nil, err
}
states = append(states, state)
}
return states, nil
}
func runPhase(ctx context.Context, store *storage.Store, states []*sourceState, seed *atomic.Uint64, rate int, duration, interval time.Duration) (phaseReport, error) {
target := int64(math.Round(float64(rate) * duration.Seconds()))
batches := int(math.Ceil(float64(duration) / float64(interval)))
started := time.Now()
measure := &measurements{}
errorsChannel := make(chan error, len(states))
visibilityExpected := make(chan time.Time, batches)
visibilityErrors := make(chan error, 1)
visibilityDone := make(chan struct{})
go func() {
defer close(visibilityDone)
for expected := range visibilityExpected {
visible, err := latestVisibility(ctx, store, states[0].organizationID, expected)
if err != nil {
select {
case visibilityErrors <- err:
default:
}
return
}
measure.mu.Lock()
measure.visibility = append(measure.visibility, visible)
measure.mu.Unlock()
}
}()
var wait sync.WaitGroup
remaining := target
weightTotal := int64(0)
for _, state := range states {
weightTotal += state.weight
}
for index, state := range states {
stateTarget := target * state.weight / weightTotal
if index == 0 {
allocated := int64(0)
for _, candidate := range states {
allocated += target * candidate.weight / weightTotal
}
stateTarget += target - allocated
}
remaining -= stateTarget
wait.Add(1)
go func(current *sourceState, count int64) {
defer wait.Done()
if err := runScheduledSource(ctx, store, current, seed, count, batches, interval, started, measure, visibilityExpected); err != nil {
errorsChannel <- err
}
}(state, stateTarget)
}
if remaining != 0 {
return phaseReport{}, errors.New("phase allocation did not preserve target")
}
wait.Wait()
elapsed := time.Since(started)
close(visibilityExpected)
<-visibilityDone
close(errorsChannel)
for phaseErr := range errorsChannel {
if phaseErr != nil {
return phaseReport{}, phaseErr
}
}
select {
case visibilityErr := <-visibilityErrors:
return phaseReport{}, visibilityErr
default:
}
measure.mu.Lock()
ingest := append([]time.Duration(nil), measure.ingest...)
visibility := append([]time.Duration(nil), measure.visibility...)
measure.mu.Unlock()
if len(ingest) == 0 || len(visibility) == 0 {
return phaseReport{}, errors.New("phase produced no latency evidence")
}
return phaseReport{
TargetRate: rate, DurationSeconds: duration.Seconds(), Observations: target, ElapsedSeconds: elapsed.Seconds(), AchievedRate: float64(target) / elapsed.Seconds(),
IngestP50Milliseconds: milliseconds(percentile(ingest, 0.50)), IngestP95Milliseconds: milliseconds(percentile(ingest, 0.95)), IngestP99Milliseconds: milliseconds(percentile(ingest, 0.99)),
VisibleP50Milliseconds: milliseconds(percentile(visibility, 0.50)), VisibleP95Milliseconds: milliseconds(percentile(visibility, 0.95)), VisibleP99Milliseconds: milliseconds(percentile(visibility, 0.99)),
}, nil
}
func runScheduledSource(ctx context.Context, store *storage.Store, state *sourceState, seed *atomic.Uint64, target int64, batches int, interval time.Duration, phaseStart time.Time, measurements *measurements, visibilityExpected chan<- time.Time) error {
base, remainder := target/int64(batches), target%int64(batches)
for batchIndex := 0; batchIndex < batches; batchIndex++ {
planned := phaseStart.Add(time.Duration(batchIndex) * interval)
if delay := time.Until(planned); delay > 0 {
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
}
count := base
if int64(batchIndex) < remainder {
count++
}
if count == 0 {
continue
}
signal := []model.Signal{model.SignalLogs, model.SignalMetrics, model.SignalTraces}[batchIndex%3]
observed := time.Now().UTC()
records := syntheticRecords(int(count), signal, observed, seed)
state.sequences[signal]++
batch := model.Batch{Version: model.BatchVersion, SourceID: state.sourceID, StreamID: string(signal), Sequence: state.sequences[signal], ObservedAt: observed, Signal: signal, Records: records}
ingestStarted := time.Now()
ack, err := store.Ingest(ctx, state.token, batch, observed)
latency := time.Since(ingestStarted)
if err != nil {
return err
}
expected, err := batch.Digest()
if err != nil || ack.BatchDigest != expected || ack.Duplicate {
return errors.New("ingestion acknowledgement did not bind the scheduled batch")
}
state.count.Add(count)
measurements.mu.Lock()
measurements.ingest = append(measurements.ingest, latency)
measurements.mu.Unlock()
if state.index == 0 && signal == model.SignalLogs {
visibilityExpected <- observed
}
}
return nil
}
func syntheticRecords(count int, signal model.Signal, observed time.Time, seed *atomic.Uint64) []model.Observation {
records := make([]model.Observation, count)
routes := []string{"/", "/items", "/search", "/healthz"}
for index := range records {
id := seed.Add(1)
timestamp := observed.Add(time.Duration(index) * time.Nanosecond)
switch signal {
case model.SignalLogs:
status := "200"
if id%50 == 0 {
status = "503"
}
records[index] = model.Observation{Timestamp: timestamp, Name: "http.server.request", Severity: "information", CorrelationID: fmt.Sprintf("capacity-%d", id), Attributes: map[string]string{"http.route": routes[id%uint64(len(routes))], "http.status_code": status, "duration_ns": strconv.FormatUint(100_000+id%5_000_000, 10)}}
case model.SignalMetrics:
value := float64(id%10_000) / 100
records[index] = model.Observation{Timestamp: timestamp, Name: "system.cpu.utilization", Value: &value}
case model.SignalTraces:
records[index] = model.Observation{Timestamp: timestamp, Name: "http.server", TraceID: fmt.Sprintf("%032x", id), SpanID: fmt.Sprintf("%016x", id), Attributes: map[string]string{"http.route": routes[id%uint64(len(routes))]}}
}
}
return records
}
func latestVisibility(ctx context.Context, store *storage.Store, organizationID string, expected time.Time) (time.Duration, error) {
ast, err := query.Parse("logs | sort timestamp desc | limit 1", 10)
if err != nil {
return 0, err
}
// The release boundary is the aggregate p95 below two seconds, not a
// zero-outlier maximum. Keep observing a slow sample long enough to retain
// the phase evidence; the report gate below still fails an excessive p95.
deadline := time.Now().Add(visibilityObservationTimeout)
for {
result, queryErr := store.Query(ctx, ast, query.Scope{OrganizationID: organizationID}, capacityBudget(10), time.Now().UTC())
if queryErr == nil && len(result.Rows) == 1 {
var timestamp string
for index, column := range result.Columns {
if column.Field == "timestamp" && result.Rows[0].Values[index] != nil {
timestamp = *result.Rows[0].Values[index]
}
}
visibleAt, parseErr := time.Parse(time.RFC3339Nano, timestamp)
if parseErr == nil && !visibleAt.Before(expected) {
return time.Since(expected), nil
}
}
if time.Now().After(deadline) {
return 0, fmt.Errorf("latest visibility query remained stale for %s", visibilityObservationTimeout)
}
timer := time.NewTimer(10 * time.Millisecond)
select {
case <-ctx.Done():
timer.Stop()
return 0, ctx.Err()
case <-timer.C:
}
}
}
func waitForProjection(ctx context.Context, store *storage.Store, projectorErrors <-chan error, maximum time.Duration) error {
deadline := time.Now().Add(maximum)
for {
select {
case err := <-projectorErrors:
return fmt.Errorf("background projection failed: %w", err)
default:
}
status, err := store.ProjectionStatus(ctx, time.Now().UTC())
if err != nil {
return err
}
if status.PendingSegments == 0 {
return nil
}
if time.Now().After(deadline) {
return fmt.Errorf("projection backlog remained after %s: segments=%d bytes=%d lag=%s", maximum, status.PendingSegments, status.PendingBytes, status.OldestPendingLag)
}
timer := time.NewTimer(100 * time.Millisecond)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
}
}
func fillPrimary(ctx context.Context, store *storage.Store, state *sourceState, seed *atomic.Uint64, minimum int64) error {
batchIndex := 0
for state.count.Load() < minimum {
remaining := minimum - state.count.Load()
count := int64(model.MaxRecords)
if remaining < count {
count = remaining
}
signal := []model.Signal{model.SignalLogs, model.SignalMetrics, model.SignalTraces}[batchIndex%3]
observed := time.Now().UTC()
state.sequences[signal]++
batch := model.Batch{Version: model.BatchVersion, SourceID: state.sourceID, StreamID: string(signal), Sequence: state.sequences[signal], ObservedAt: observed, Signal: signal, Records: syntheticRecords(int(count), signal, observed, seed)}
ack, err := store.Ingest(ctx, state.token, batch, observed)
if err != nil {
return err
}
expected, _ := batch.Digest()
if ack.BatchDigest != expected || ack.Duplicate {
return errors.New("fill acknowledgement did not bind the batch")
}
state.count.Add(count)
batchIndex++
if batchIndex%100 == 0 {
fmt.Fprintf(os.Stderr, "stage=fill observations=%d\n", state.count.Load())
}
}
return nil
}
func runQueries(ctx context.Context, store *storage.Store, organizationID string, iterations int) ([]queryReport, error) {
definitions := []struct{ name, text string }{
{"recent-errors-by-route", `logs | where status >= 500 | window 24h | summarize count() by route, window(5m) | sort count desc | limit 50`},
{"recent-items", `logs | where route == "/items" | window 24h | sort timestamp desc | limit 50`},
{"metric-rollup", `metrics | window 24h | summarize count(), p95(value) by name, window(5m) | sort count desc | limit 50`},
}
reports := make([]queryReport, 0, len(definitions))
for _, definition := range definitions {
ast, err := query.Parse(definition.text, 50)
if err != nil {
return nil, err
}
var samples []time.Duration
var maximumRows, maximumBytes int64
for iteration := 0; iteration < iterations; iteration++ {
started := time.Now()
result, queryErr := store.Query(ctx, ast, query.Scope{OrganizationID: organizationID}, capacityBudget(50), time.Now().UTC())
samples = append(samples, time.Since(started))
if queryErr != nil {
return nil, fmt.Errorf("capacity query %s failed: %w", definition.name, queryErr)
}
if len(result.Rows) == 0 {
return nil, fmt.Errorf("capacity query %s returned no rows", definition.name)
}
maximumRows = max(maximumRows, int64(result.Stats.ScannedRows))
maximumBytes = max(maximumBytes, result.Stats.ScannedBytes)
}
reports = append(reports, queryReport{Name: definition.name, Iterations: iterations, P50Milliseconds: milliseconds(percentile(samples, 0.50)), P95Milliseconds: milliseconds(percentile(samples, 0.95)), P99Milliseconds: milliseconds(percentile(samples, 0.99)), MaximumScannedRows: maximumRows, MaximumScannedBytes: maximumBytes})
}
return reports, nil
}
func runSpoolReplay(ctx context.Context, root string) (spoolReport, error) {
now := time.Now().UTC()
queue, err := spool.Open(filepath.Join(root, "spool"), 1<<30, 72*time.Hour)
if err != nil {
return spoolReport{}, err
}
store, err := storage.Open(filepath.Join(root, "server"))
if err != nil {
return spoolReport{}, err
}
defer store.Close()
token, err := store.CreateSource(ctx, "outage-source", model.Scope{OrganizationID: "outage-org", ProjectID: "observatory", EnvironmentID: "capacity", ServiceID: "agent"})
if err != nil {
return spoolReport{}, err
}
const batches, recordsPerBatch = 72, 100
for index := 0; index < batches; index++ {
observed := now.Add(-time.Duration(batches-index) * time.Hour).Add(time.Minute)
batch := model.Batch{Version: model.BatchVersion, SourceID: "outage-source", StreamID: "logs", Sequence: uint64(index + 1), ObservedAt: observed, Signal: model.SignalLogs, Records: syntheticRecords(recordsPerBatch, model.SignalLogs, observed, &atomic.Uint64{})}
entry, putErr := queue.Put(batch, observed)
if putErr != nil {
return spoolReport{}, putErr
}
if err = os.Chtimes(entry.Path, observed, observed); err != nil {
return spoolReport{}, err
}
}
entries, err := queue.List(now)
if err != nil || len(entries) != batches {
return spoolReport{}, errors.New("72-hour spool did not preserve every batch")
}
report := spoolReport{Batches: len(entries), Observations: batches * recordsPerBatch, OldestAgeHours: now.Sub(entries[0].ModTime).Hours()}
for index, entry := range entries {
batch, readErr := queue.Read(entry)
if readErr != nil {
return spoolReport{}, readErr
}
ack, ingestErr := store.Ingest(ctx, token, batch, now)
if ingestErr != nil {
return spoolReport{}, ingestErr
}
expected, _ := batch.Digest()
if ack.BatchDigest != expected {
return spoolReport{}, errors.New("outage replay acknowledgement mismatch")
}
if index == 0 {
duplicate, duplicateErr := store.Ingest(ctx, token, batch, now)
if duplicateErr != nil || !duplicate.Duplicate || duplicate.BatchDigest != expected {
return spoolReport{}, errors.New("outage replay duplicate was not recognized")
}
report.DuplicateRecognized = true
}
if err = queue.Acknowledge(entry, entry.Digest); err != nil {
return spoolReport{}, err
}
report.Replayed += int64(len(batch.Records))
}
remaining, err := queue.List(now)
if err != nil {
return spoolReport{}, err
}
report.RemainingAfterAck = len(remaining)
if report.Replayed != report.Observations || report.RemainingAfterAck != 0 || report.OldestAgeHours < 71.9 {
return spoolReport{}, errors.New("outage replay evidence is incomplete")
}
return report, nil
}
func runRetention(ctx context.Context, root string) (retentionEvidence, error) {
now := time.Now().UTC()
store, err := storage.Open(root)
if err != nil {
return retentionEvidence{}, err
}
defer store.Close()
token, err := store.CreateSource(ctx, "retention-source", model.Scope{OrganizationID: "retention-org", ProjectID: "observatory", EnvironmentID: "capacity", ServiceID: "server"})
if err != nil {
return retentionEvidence{}, err
}
tests := []struct {
signal model.Signal
age time.Duration
}{
{model.SignalLogs, 31 * 24 * time.Hour},
{model.SignalTraces, 31 * 24 * time.Hour},
{model.SignalMetrics, 15 * 24 * time.Hour},
{model.SignalDeployments, 399 * 24 * time.Hour},
}
for index, item := range tests {
observed := now.Add(-item.age)
batch := model.Batch{Version: model.BatchVersion, SourceID: "retention-source", StreamID: string(item.signal), Sequence: 1, ObservedAt: now, Signal: item.signal, Records: syntheticRecords(1, item.signal, observed, &atomic.Uint64{})}
if item.signal == model.SignalDeployments {
batch.Records[0] = model.Observation{Timestamp: observed, Name: "deployment", Attributes: map[string]string{"outcome": "success"}}
}
if _, err = store.Ingest(ctx, token, batch, now); err != nil {
return retentionEvidence{}, fmt.Errorf("retention fixture %d: %w", index, err)
}
}
if err = store.Recover(ctx); err != nil {
return retentionEvidence{}, err
}
policy := storage.RetentionPolicy{RawLogsDays: 30, RawTracesDays: 30, RawMetricsDays: 14, ColdRawDays: 400, DeleteColdRaw: true, MetricRollupsDays: 400, EvidenceDays: 400}
report, err := store.ApplyRetention(ctx, policy, now.Add(2*24*time.Hour))
if err != nil {
return retentionEvidence{}, err
}
ast, err := query.Parse("logs | window 960h | limit 10", 10)
if err != nil {
return retentionEvidence{}, err
}
result, err := store.Query(ctx, ast, query.Scope{OrganizationID: "retention-org", Sensitive: true}, capacityBudget(10), now.Add(2*24*time.Hour))
if err != nil {
return retentionEvidence{}, err
}
evidence := retentionEvidence{ArchivedSegments: report.RawSegmentsArchived, ArchivedBytes: report.RawBytesArchived, RemovedSegments: report.RawSegmentsRemoved, RemovedBytes: report.RawBytesRemoved, ProjectionRowsRemoved: report.ProjectedObservationsRemoved, ColdQueryRows: len(result.Rows)}
if evidence.ArchivedSegments != 4 || evidence.RemovedSegments != 1 || evidence.ProjectionRowsRemoved != 4 || evidence.ColdQueryRows != 1 {
return retentionEvidence{}, fmt.Errorf("retention lifecycle mismatch: %+v", evidence)
}
return evidence, nil
}
func capacityBudget(rows int) query.Budget {
return query.Budget{MaxDuration: 10 * time.Second, MaxRows: rows, MaxScannedBytes: 64 << 30, MaxMemoryBytes: 1 << 30}
}
func percentile(values []time.Duration, fraction float64) time.Duration {
copyOfValues := append([]time.Duration(nil), values...)
sort.Slice(copyOfValues, func(left, right int) bool { return copyOfValues[left] < copyOfValues[right] })
index := int(math.Ceil(float64(len(copyOfValues))*fraction)) - 1
if index < 0 {
index = 0
}
return copyOfValues[index]
}
func milliseconds(value time.Duration) float64 { return float64(value) / float64(time.Millisecond) }
func cgroupLimits() (float64, int64, error) {
cpuBody, err := os.ReadFile("/sys/fs/cgroup/cpu.max")
if err != nil {
return 0, 0, errors.New("read cgroup CPU limit")
}
parts := strings.Fields(string(cpuBody))
if len(parts) != 2 || parts[0] == "max" {
return 0, 0, errors.New("cgroup CPU quota is not finite")
}
quota, quotaErr := strconv.ParseFloat(parts[0], 64)
period, periodErr := strconv.ParseFloat(parts[1], 64)
memoryBody, memoryErr := os.ReadFile("/sys/fs/cgroup/memory.max")
memory, parseMemoryErr := strconv.ParseInt(strings.TrimSpace(string(memoryBody)), 10, 64)
if quotaErr != nil || periodErr != nil || period <= 0 || memoryErr != nil || parseMemoryErr != nil {
return 0, 0, errors.New("cgroup resource limit is invalid")
}
return quota / period, memory, nil
}
func maximumRSS() int64 {
var usage syscall.Rusage
if syscall.Getrusage(syscall.RUSAGE_SELF, &usage) != nil {
return 0
}
return usage.Maxrss * 1024
}
func directoryBytes(root string) (int64, error) {
var total int64
err := filepath.WalkDir(root, func(path string, entry os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.Type()&os.ModeSymlink != 0 {
return errors.New("capacity workspace contains a symlink")
}
if entry.IsDir() {
return nil
}
info, err := entry.Info()
if err != nil || !info.Mode().IsRegular() {
return errors.New("capacity workspace contains a non-regular file")
}
if info.Size() > math.MaxInt64-total {
return errors.New("capacity workspace size overflow")
}
total += info.Size()
return nil
})
return total, err
}
func measureStorage(root, primaryOrganizationID string) (storageBreakdown, error) {
var report storageBreakdown
err := filepath.WalkDir(root, func(path string, entry os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.Type()&os.ModeSymlink != 0 {
return errors.New("capacity dataset contains a symlink")
}
if entry.IsDir() {
return nil
}
info, err := entry.Info()
if err != nil || !info.Mode().IsRegular() {
return errors.New("capacity dataset contains a non-regular file")
}
relative, err := filepath.Rel(root, path)
if err != nil || relative == "." || strings.HasPrefix(relative, ".."+string(os.PathSeparator)) {
return errors.New("capacity dataset path is invalid")
}
class := &report.Other
switch {
case relative == "control.sqlite" || strings.HasPrefix(relative, "control.sqlite-"):
class = &report.Control
case strings.HasPrefix(relative, "raw"+string(os.PathSeparator)) || strings.HasPrefix(relative, "cold"+string(os.PathSeparator)):
class = &report.Raw
case strings.HasPrefix(relative, "organizations"+string(os.PathSeparator)):
class = &report.Projection
}
if info.Size() > math.MaxInt64-class.Bytes || info.Size() > math.MaxInt64-report.Total.Bytes {
return errors.New("capacity storage class size overflow")
}
class.Files++
class.Bytes += info.Size()
report.Total.Files++
report.Total.Bytes += info.Size()
return nil
})
if err != nil {
return storageBreakdown{}, err
}
projectionPath := filepath.Join(root, "organizations", primaryOrganizationID, "projection.sqlite")
report.SQLiteBytes, report.SQLitePageClasses, err = sqliteObjectBytes(projectionPath)
if err != nil {
return storageBreakdown{}, err
}
return report, nil
}
func sqliteObjectBytes(path string) (map[string]int64, sqlitePageBreakdown, error) {
dsn := (&url.URL{Scheme: "file", Path: path, RawQuery: "mode=ro"}).String()
db, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, sqlitePageBreakdown{}, errors.New("open capacity projection diagnostics")
}
defer db.Close()
db.SetMaxOpenConns(1)
rows, err := db.Query(`SELECT d.name,COALESCE(m.type,'internal'),COALESCE(SUM(d.pgsize),0) FROM dbstat AS d LEFT JOIN sqlite_schema AS m ON m.name=d.name GROUP BY d.name,m.type ORDER BY d.name`)
if err != nil {
return nil, sqlitePageBreakdown{}, errors.New("read capacity projection page accounting")
}
defer rows.Close()
report := map[string]int64{}
var classes sqlitePageBreakdown
for rows.Next() {
var name, objectType string
var bytes int64
if err = rows.Scan(&name, &objectType, &bytes); err != nil || name == "" || bytes < 0 {
return nil, sqlitePageBreakdown{}, errors.New("read capacity projection page accounting")
}
report[name] = bytes
if bytes > math.MaxInt64-classes.Total {
return nil, sqlitePageBreakdown{}, errors.New("capacity projection page accounting overflow")
}
classes.Total += bytes
switch objectType {
case "table":
classes.Tables += bytes
case "index":
classes.Indexes += bytes
default:
classes.Internal += bytes
}
}
if err = rows.Err(); err != nil {
return nil, sqlitePageBreakdown{}, errors.New("read capacity projection page accounting")
}
if len(report) == 0 {
return nil, sqlitePageBreakdown{}, errors.New("capacity projection page accounting is empty")
}
if classes.Total != classes.Tables+classes.Indexes+classes.Internal {
return nil, sqlitePageBreakdown{}, errors.New("capacity projection page accounting total mismatch")
}
return report, classes, nil
}
+80
View File
@@ -0,0 +1,80 @@
//go:build observatory_capacity_fixture && linux
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"context"
"os"
"path/filepath"
"sync/atomic"
"testing"
"time"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/storage"
)
func TestMeasureStorageClassifiesFilesAndSQLiteObjects(t *testing.T) {
root := filepath.Join(t.TempDir(), "dataset")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
scope := model.Scope{OrganizationID: "capacity-org-1", ProjectID: "observatory", EnvironmentID: "capacity", ServiceID: "server"}
token, err := store.CreateSource(t.Context(), "capacity-source-1", scope)
if err != nil {
store.Close()
t.Fatal(err)
}
batch := model.Batch{Version: model.BatchVersion, SourceID: "capacity-source-1", StreamID: "logs", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: syntheticRecords(2, model.SignalLogs, now, new(atomic.Uint64))}
if _, err = store.Ingest(context.Background(), token, batch, now); err != nil {
store.Close()
t.Fatal(err)
}
if _, err = store.ProjectPending(t.Context()); err != nil {
store.Close()
t.Fatal(err)
}
report, err := measureStorage(root, scope.OrganizationID)
if closeErr := store.Close(); err == nil && closeErr != nil {
err = closeErr
}
if err != nil {
t.Fatal(err)
}
if report.Raw.Files == 0 || report.Raw.Bytes == 0 || report.Projection.Files == 0 || report.Projection.Bytes == 0 || report.Control.Files == 0 || report.Control.Bytes == 0 {
t.Fatalf("incomplete breakdown: %+v", report)
}
if report.Total.Files != report.Raw.Files+report.Projection.Files+report.Control.Files+report.Other.Files {
t.Fatalf("file total mismatch: %+v", report)
}
if report.Total.Bytes != report.Raw.Bytes+report.Projection.Bytes+report.Control.Bytes+report.Other.Bytes {
t.Fatalf("byte total mismatch: %+v", report)
}
if report.SQLiteBytes["observations"] == 0 || report.SQLiteBytes["observations_signal_time"] == 0 {
t.Fatalf("SQLite object accounting missing: %+v", report.SQLiteBytes)
}
if report.SQLitePageClasses.Tables == 0 || report.SQLitePageClasses.Indexes == 0 || report.SQLitePageClasses.Total != report.SQLitePageClasses.Tables+report.SQLitePageClasses.Indexes+report.SQLitePageClasses.Internal {
t.Fatalf("SQLite page classes incomplete: %+v", report.SQLitePageClasses)
}
}
func TestMeasureStorageRejectsSymlink(t *testing.T) {
root := t.TempDir()
target := filepath.Join(t.TempDir(), "target")
if err := os.WriteFile(target, []byte("unsafe"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(target, filepath.Join(root, "linked")); err != nil {
t.Skipf("symlink unavailable: %v", err)
}
if _, err := measureStorage(root, "capacity-org-1"); err == nil {
t.Fatal("symlinked capacity evidence was accepted")
}
}
+303
View File
@@ -0,0 +1,303 @@
// SPDX-License-Identifier: AGPL-3.0-only
package collector
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/netip"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"gamertan.com/observatory/internal/model"
)
const MaxLineBytes = 1 << 20
var tendSafeValue = regexp.MustCompile(`^[A-Za-z0-9._:/@+-]{1,256}$`)
var tendOperationID = regexp.MustCompile(`^[0-9a-f]{32}$`)
var tendArtifactDigest = regexp.MustCompile(`^[0-9a-f]{64}$`)
var tendCommit = regexp.MustCompile(`^[0-9a-f]{40}$`)
func Parse(kind string, line []byte, fallback time.Time, sensitiveFields ...string) (model.Signal, model.Observation, error) {
if len(line) == 0 || len(line) > MaxLineBytes || !utf8.Valid(line) || bytes.IndexByte(line, 0) >= 0 {
return "", model.Observation{}, errors.New("collector line is outside accepted bounds")
}
switch kind {
case "caddy_json":
observation, err := parseCaddy(line, fallback, sensitiveFields)
return model.SignalLogs, observation, err
case "requestlog_jsonl":
observation, err := parseRequestLog(line, fallback, sensitiveFields)
return model.SignalLogs, observation, err
case "tend_events_jsonl":
observation, err := parseTend(line, fallback)
return model.SignalDeployments, observation, err
default:
return "", model.Observation{}, errors.New("unsupported collector kind")
}
}
func parseCaddy(line []byte, fallback time.Time, sensitiveFields []string) (model.Observation, error) {
var record struct {
Timestamp float64 `json:"ts"`
Status int `json:"status"`
Size int64 `json:"size"`
Duration float64 `json:"duration"`
RequestID string `json:"request_id"`
ClientIP string `json:"client_ip"`
Referrer string `json:"referrer"`
UserAgent string `json:"user_agent"`
Request struct {
Method string `json:"method"`
URI string `json:"uri"`
Headers map[string][]string `json:"headers"`
} `json:"request"`
}
if err := json.Unmarshal(line, &record); err != nil {
return model.Observation{}, errors.New("invalid Caddy JSON record")
}
timestamp := fallback
if record.Timestamp > 0 {
seconds, fraction := mathModf(record.Timestamp)
timestamp = time.Unix(seconds, int64(fraction*1e9)).UTC()
}
path := "/"
parsed, parseErr := url.ParseRequestURI(record.Request.URI)
if parseErr == nil && parsed.Path != "" {
path = parsed.EscapedPath()
}
attributes := map[string]string{
"http.method": bounded(record.Request.Method, 32),
"http.path": bounded(path, 4096),
"http.status_code": strconv.Itoa(record.Status),
"http.response_bytes": strconv.FormatInt(record.Size, 10),
"duration_ns": strconv.FormatInt(int64(record.Duration*1e9), 10),
}
requestID := record.RequestID
if !safeIdentifier(requestID) {
requestID = firstHeader(record.Request.Headers, "X-Request-Id", "X-Request-ID")
}
if safeIdentifier(requestID) {
attributes["request.id"] = requestID
}
selected := sensitiveFieldSet(sensitiveFields)
if selected["client_ip"] {
if address, err := netip.ParseAddr(record.ClientIP); err == nil && address.IsValid() && address.Zone() == "" {
attributes["client.address"] = address.String()
}
}
if selected["query"] && parseErr == nil && parsed.RawQuery != "" {
attributes["url.query"] = bounded(parsed.RawQuery, 4096)
}
if selected["referrer"] {
if value := boundedSensitive(record.Referrer, 4096); value != "" {
attributes["http.request.referrer"] = value
}
}
if selected["user_agent"] {
if value := boundedSensitive(record.UserAgent, 1024); value != "" {
attributes["user_agent.original"] = value
}
}
return model.Observation{Timestamp: timestamp, Name: "caddy.http.request", CorrelationID: attributes["request.id"], Attributes: attributes}, nil
}
func parseRequestLog(line []byte, fallback time.Time, sensitiveFields []string) (model.Observation, error) {
var raw map[string]json.RawMessage
if err := json.Unmarshal(line, &raw); err != nil {
return model.Observation{}, errors.New("invalid requestlog JSON record")
}
timestamp := parseTimeFields(raw, fallback, "observed_at", "timestamp", "time")
attributes := map[string]string{}
copyString(raw, attributes, "method", "http.method", 32)
copyString(raw, attributes, "route", "http.route", 4096)
copyNumber(raw, attributes, "status", "http.status_code")
copyNumber(raw, attributes, "bytes", "http.response_bytes")
copyNumber(raw, attributes, "duration_ns", "duration_ns")
copyString(raw, attributes, "authorization_outcome", "auth.outcome", 128)
requestID := rawString(raw["request_id"], 128)
if safeIdentifier(requestID) {
attributes["request.id"] = requestID
}
selected := sensitiveFieldSet(sensitiveFields)
if selected["client_ip"] {
if address, err := netip.ParseAddr(rawString(raw["client_ip"], 64)); err == nil && address.IsValid() && address.Zone() == "" {
attributes["client.address"] = address.String()
}
}
if selected["query"] {
copyString(raw, attributes, "query", "url.query", 4096)
}
if selected["referrer"] {
copyString(raw, attributes, "referer", "http.request.referrer", 2048)
}
if selected["user_agent"] {
copyString(raw, attributes, "user_agent", "user_agent.original", 1024)
}
if selected["session_id"] {
copyString(raw, attributes, "session_id", "session.id", 256)
}
return model.Observation{Timestamp: timestamp, Name: "application.http.request", CorrelationID: requestID, Attributes: attributes}, nil
}
func sensitiveFieldSet(fields []string) map[string]bool {
selected := make(map[string]bool, len(fields))
for _, field := range fields {
selected[field] = true
}
return selected
}
func boundedSensitive(value string, maximum int) string {
if value == "" || len(value) > maximum || !utf8.ValidString(value) || strings.ContainsAny(value, "\x00\r\n") {
return ""
}
return value
}
func parseTend(line []byte, _ time.Time) (model.Observation, error) {
if len(line) > 4096 {
return model.Observation{}, errors.New("invalid Tend deployment event")
}
var record tendEvent
decoder := json.NewDecoder(bytes.NewReader(line))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&record); err != nil || record.validate() != nil {
return model.Observation{}, errors.New("invalid Tend deployment event")
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return model.Observation{}, errors.New("invalid Tend deployment event")
}
timestamp, _ := time.Parse(time.RFC3339Nano, record.ObservedAt)
attributes := map[string]string{
"deployment.operation_id": record.OperationID,
"service.name": record.Service,
"deployment.artifact": record.ArtifactDigest,
"deployment.commit": record.Commit,
"deployment.version": record.ReleaseVersion,
"deployment.phase": record.Phase,
"deployment.duration_ms": strconv.FormatInt(record.DurationMillis, 10),
"deployment.outcome": record.Outcome,
}
if record.Slot != "" {
attributes["deployment.slot"] = record.Slot
}
return model.Observation{Timestamp: timestamp.UTC(), Name: "tend.deployment", CorrelationID: record.OperationID, Attributes: attributes}, nil
}
type tendEvent struct {
Version int `json:"version"`
OperationID string `json:"operation_id"`
Service string `json:"service"`
ArtifactDigest string `json:"artifact_digest"`
Commit string `json:"commit"`
ReleaseVersion string `json:"release_version"`
Phase string `json:"phase"`
Slot string `json:"slot"`
DurationMillis int64 `json:"duration_ms"`
Outcome string `json:"outcome"`
ObservedAt string `json:"observed_at"`
}
func (event tendEvent) validate() error {
if event.Version != 1 || !tendOperationID.MatchString(event.OperationID) || !tendArtifactDigest.MatchString(event.ArtifactDigest) || !tendCommit.MatchString(event.Commit) {
return errors.New("identity or provenance is invalid")
}
for _, value := range []string{event.Service, event.ArtifactDigest, event.Commit, event.ReleaseVersion, event.Phase, event.Outcome} {
if !tendSafeValue.MatchString(value) || strings.ContainsRune(value, '\x00') {
return errors.New("value is invalid")
}
}
if event.Slot != "" && !tendSafeValue.MatchString(event.Slot) {
return errors.New("slot is invalid")
}
if event.DurationMillis < 0 {
return errors.New("duration is invalid")
}
if _, err := time.Parse(time.RFC3339Nano, event.ObservedAt); err != nil {
return errors.New("timestamp is invalid")
}
return nil
}
func copyString(raw map[string]json.RawMessage, attributes map[string]string, source, target string, maximum int) {
if value := rawString(raw[source], maximum); value != "" {
attributes[target] = value
}
}
func copyNumber(raw map[string]json.RawMessage, attributes map[string]string, source, target string) {
value := strings.TrimSpace(string(raw[source]))
if value == "" || len(value) > 64 {
return
}
if _, err := strconv.ParseFloat(value, 64); err == nil {
attributes[target] = value
}
}
func rawString(raw json.RawMessage, maximum int) string {
var value string
if len(raw) == 0 || json.Unmarshal(raw, &value) != nil || len(value) > maximum || !utf8.ValidString(value) || strings.ContainsAny(value, "\x00\r\n") {
return ""
}
return value
}
func parseTimeFields(raw map[string]json.RawMessage, fallback time.Time, names ...string) time.Time {
for _, name := range names {
value := rawString(raw[name], 128)
if value == "" {
continue
}
if parsed, err := time.Parse(time.RFC3339Nano, value); err == nil {
return parsed.UTC()
}
}
return fallback.UTC()
}
func firstHeader(headers map[string][]string, names ...string) string {
for _, name := range names {
for key, values := range headers {
if strings.EqualFold(key, name) && len(values) == 1 {
return values[0]
}
}
}
return ""
}
func safeIdentifier(value string) bool {
if len(value) < 1 || len(value) > 128 {
return false
}
for _, r := range value {
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("._:-", r)) {
return false
}
}
return true
}
func bounded(value string, maximum int) string {
if len(value) > maximum {
for maximum > 0 && !utf8.ValidString(value[:maximum]) {
maximum--
}
return value[:maximum]
}
return value
}
func mathModf(value float64) (int64, float64) {
seconds := int64(value)
return seconds, value - float64(seconds)
}
+125
View File
@@ -0,0 +1,125 @@
// SPDX-License-Identifier: AGPL-3.0-only
package collector
import (
"encoding/json"
"strings"
"testing"
"time"
)
func TestCaddyCollectorDropsSecretsAndQuery(t *testing.T) {
line := []byte(`{"ts":1720000000.25,"request":{"method":"GET","uri":"/search?q=secret","remote_ip":"192.0.2.10","headers":{"Cookie":["session=secret"],"Authorization":["Bearer secret"],"X-Request-Id":["req-123"]}},"status":200,"size":42,"duration":0.001}`)
_, observation, err := Parse("caddy_json", line, time.Unix(1, 0))
if err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(observation)
for _, forbidden := range []string{"q=secret", "session=secret", "Bearer secret", "192.0.2.10", "Authorization", "Cookie"} {
if strings.Contains(string(b), forbidden) {
t.Fatalf("secret escaped into observation: %s", b)
}
}
if observation.Attributes["http.path"] != "/search" || observation.CorrelationID != "req-123" {
t.Fatalf("observation=%+v", observation)
}
}
func TestCaddyCollectorUsesFilteredTopLevelRequestID(t *testing.T) {
line := []byte(`{"ts":1720000000.25,"request_id":"response-request-123","client_ip":"192.0.2.45","referrer":"https://example.test/start?private=yes","user_agent":"example-agent","request":{"method":"GET","uri":"/items?view=private"},"status":200,"size":42,"duration":0.001}`)
_, observation, err := Parse("caddy_json", line, time.Unix(1, 0))
if err != nil {
t.Fatal(err)
}
if observation.CorrelationID != "response-request-123" || observation.Attributes["request.id"] != "response-request-123" || observation.Attributes["http.path"] != "/items" {
t.Fatalf("observation=%+v", observation)
}
for _, forbidden := range []string{"client.address", "url.query", "http.request.referrer", "user_agent.original"} {
if _, ok := observation.Attributes[forbidden]; ok {
t.Fatalf("default collection retained sensitive field %q", forbidden)
}
}
_, observation, err = Parse("caddy_json", line, time.Unix(1, 0), "client_ip", "query", "referrer", "user_agent")
if err != nil || observation.Attributes["client.address"] != "192.0.2.45" || observation.Attributes["url.query"] != "view=private" || observation.Attributes["http.request.referrer"] != "https://example.test/start?private=yes" || observation.Attributes["user_agent.original"] != "example-agent" {
t.Fatalf("sensitive observation=%+v err=%v", observation, err)
}
line = []byte(`{"request_id":"invalid request id","request":{"method":"GET","uri":"/items","headers":{"X-Request-ID":["compatible-header-id"]}},"status":200}`)
_, observation, err = Parse("caddy_json", line, time.Unix(1, 0))
if err != nil || observation.CorrelationID != "compatible-header-id" {
t.Fatalf("fallback observation=%+v err=%v", observation, err)
}
}
func TestRequestLogCollectorUsesWhitelist(t *testing.T) {
line := []byte(`{"timestamp":"2026-08-17T01:02:03Z","method":"GET","route":"/items/{id}","status":200,"request_id":"request-1","query":"view=full","client_ip":"192.0.2.2","referer":"https://example.test/start","user_agent":"example-agent","session_id":"anonymous-session","extra_secret":"nope"}`)
_, observation, err := Parse("requestlog_jsonl", line, time.Unix(1, 0))
if err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(observation)
if strings.Contains(string(b), "192.0.2.2") || strings.Contains(string(b), "view=full") || strings.Contains(string(b), "anonymous-session") || observation.Attributes["http.route"] != "/items/{id}" {
t.Fatalf("observation=%s", b)
}
_, observation, err = Parse("requestlog_jsonl", line, time.Unix(1, 0), "client_ip", "query", "referrer", "user_agent", "session_id")
if err != nil || observation.Attributes["client.address"] != "192.0.2.2" || observation.Attributes["url.query"] != "view=full" || observation.Attributes["http.request.referrer"] != "https://example.test/start" || observation.Attributes["user_agent.original"] != "example-agent" || observation.Attributes["session.id"] != "anonymous-session" {
t.Fatalf("sensitive requestlog observation=%+v err=%v", observation, err)
}
}
func TestTendCollectorIsStrict(t *testing.T) {
line := []byte(`{"version":1,"operation_id":"0123456789abcdef0123456789abcdef","service":"site","artifact_digest":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","commit":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","release_version":"v0.2.0-preview.1","phase":"activation","slot":"green","duration_ms":25,"outcome":"succeeded","observed_at":"2026-08-17T01:02:03Z"}`)
signal, observation, err := Parse("tend_events_jsonl", line, time.Unix(1, 0))
if err != nil {
t.Fatal(err)
}
if signal != "deployments" || observation.Attributes["deployment.outcome"] != "succeeded" || observation.CorrelationID != "0123456789abcdef0123456789abcdef" || len(observation.Attributes) != 9 {
t.Fatalf("signal=%s observation=%+v", signal, observation)
}
if _, _, err := Parse("tend_events_jsonl", append(line[:len(line)-1], []byte(`,"secret":"x"}`)...), time.Unix(1, 0)); err == nil {
t.Fatal("expected unknown field rejection")
}
rollback := []byte(`{"version":1,"operation_id":"fedcba9876543210fedcba9876543210","service":"site","artifact_digest":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc","commit":"dddddddddddddddddddddddddddddddddddddddd","release_version":"v0.2.0-preview.1","phase":"rollback","slot":"blue","duration_ms":12,"outcome":"succeeded","observed_at":"2026-08-17T01:03:04.123Z"}`)
_, observation, err = Parse("tend_events_jsonl", rollback, time.Unix(1, 0))
if err != nil || observation.Attributes["deployment.phase"] != "rollback" || observation.Attributes["deployment.artifact"] != strings.Repeat("c", 64) {
t.Fatalf("rollback observation=%+v err=%v", observation, err)
}
invalid := [][]byte{
[]byte(strings.Replace(string(line), `"version":1`, `"version":2`, 1)),
[]byte(strings.Replace(string(line), "0123456789abcdef0123456789abcdef", "short", 1)),
[]byte(strings.Replace(string(line), strings.Repeat("a", 64), strings.Repeat("A", 64), 1)),
[]byte(strings.Replace(string(line), strings.Repeat("b", 40), strings.Repeat("b", 39), 1)),
[]byte(strings.Replace(string(line), `"service":"site"`, `"service":"unsafe service"`, 1)),
[]byte(strings.Replace(string(line), `"duration_ms":25`, `"duration_ms":-1`, 1)),
[]byte(strings.Replace(string(line), "2026-08-17T01:02:03Z", "not-a-time", 1)),
append(append([]byte{}, line...), []byte(` {}`)...),
[]byte(strings.Repeat(" ", 4097)),
}
for index, candidate := range invalid {
if _, _, err := Parse("tend_events_jsonl", candidate, time.Unix(1, 0)); err == nil {
t.Fatalf("invalid Tend event %d was accepted", index)
}
}
}
func FuzzTendCollector(f *testing.F) {
f.Add([]byte(`{"version":1,"operation_id":"0123456789abcdef0123456789abcdef","service":"site","artifact_digest":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","commit":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","release_version":"v0.2.0-preview.1","phase":"activation","slot":"green","duration_ms":25,"outcome":"succeeded","observed_at":"2026-08-17T01:02:03Z"}`))
f.Add([]byte(`{"version":1}`))
f.Add([]byte{0, 1, 2, 3})
f.Fuzz(func(t *testing.T, line []byte) {
signal, observation, err := Parse("tend_events_jsonl", line, time.Unix(1, 0))
if err != nil {
return
}
if signal != "deployments" || observation.Name != "tend.deployment" || observation.CorrelationID == "" || len(observation.Attributes) < 8 || len(observation.Attributes) > 9 {
t.Fatalf("accepted event violated invariants: signal=%q observation=%+v", signal, observation)
}
allowed := map[string]bool{"deployment.operation_id": true, "service.name": true, "deployment.artifact": true, "deployment.commit": true, "deployment.version": true, "deployment.phase": true, "deployment.slot": true, "deployment.duration_ms": true, "deployment.outcome": true}
for name := range observation.Attributes {
if !allowed[name] {
t.Fatalf("accepted unexpected attribute %q", name)
}
}
})
}
+506
View File
@@ -0,0 +1,506 @@
// SPDX-License-Identifier: AGPL-3.0-only
package config
import (
"bytes"
"crypto/ecdh"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"runtime"
"strings"
"syscall"
"time"
"gamertan.com/observatory/internal/hostmetrics"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/query"
)
const SchemaVersion = 1
type Server struct {
Schema int `json:"schema"`
Listen string `json:"listen"`
PublicURL string `json:"public_url"`
DataDir string `json:"data_dir"`
MaxBodyBytes int64 `json:"max_body_bytes"`
MaxConcurrentIngest int `json:"max_concurrent_ingest,omitempty"`
SessionLifetimeText string `json:"session_lifetime"`
SessionLifetime time.Duration `json:"-"`
Query QueryLimits `json:"query"`
Retention Retention `json:"retention"`
WebPush *WebPush `json:"web_push,omitempty"`
}
type WebPush struct {
PrivateKeyFile string `json:"private_key_file"`
Subject string `json:"subject"`
QueueCapacity int `json:"queue_capacity"`
RequestTimeout string `json:"request_timeout"`
Timeout time.Duration `json:"-"`
PrivateKey []byte `json:"-"`
}
type QueryLimits struct {
MaxDuration time.Duration `json:"-"`
MaxDurationText string `json:"max_duration"`
MaxRows int `json:"max_rows"`
MaxScannedBytes int64 `json:"max_scanned_bytes"`
MaxMemoryBytes int64 `json:"max_memory_bytes"`
}
type Retention struct {
RawLogsDays int `json:"raw_logs_days"`
RawTracesDays int `json:"raw_traces_days"`
RawMetricsDays int `json:"raw_metrics_days"`
ColdRawDays int `json:"cold_raw_days"`
DeleteColdRaw bool `json:"delete_cold_raw"`
MetricRollupsDays int `json:"metric_rollups_days"`
EvidenceDays int `json:"evidence_days"`
}
type FilePolicy struct {
RequireRoot bool
SystemdCredentialDirectory string
}
func SystemdCredentialPolicy() (FilePolicy, error) {
directory := os.Getenv("CREDENTIALS_DIRECTORY")
if directory == "" {
return FilePolicy{}, errors.New("CREDENTIALS_DIRECTORY is not set")
}
if !filepath.IsAbs(directory) || filepath.Clean(directory) != directory {
return FilePolicy{}, errors.New("CREDENTIALS_DIRECTORY must be an absolute clean path")
}
info, err := os.Lstat(directory)
if err != nil {
return FilePolicy{}, fmt.Errorf("inspect CREDENTIALS_DIRECTORY: %w", err)
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return FilePolicy{}, errors.New("CREDENTIALS_DIRECTORY must be a non-symlink directory")
}
return FilePolicy{SystemdCredentialDirectory: directory}, nil
}
type Agent struct {
Schema int `json:"schema"`
ServerURL string `json:"server_url"`
CredentialFile string `json:"credential_file"`
SpoolDir string `json:"spool_dir"`
StateFile string `json:"state_file"`
MaxSpoolBytes int64 `json:"max_spool_bytes"`
MaxSpoolAgeText string `json:"max_spool_age"`
MaxSpoolAge time.Duration `json:"-"`
BatchRecords int `json:"batch_records"`
FlushInterval string `json:"flush_interval"`
FlushEvery time.Duration `json:"-"`
Sources []AgentSource `json:"sources"`
AlertRules []AgentAlertRule `json:"alert_rules,omitempty"`
}
type AgentSource struct {
Kind string `json:"kind"`
Path string `json:"path,omitempty"`
StreamID string `json:"stream_id"`
SensitiveFields []string `json:"sensitive_fields,omitempty"`
LinuxMetrics *hostmetrics.Config `json:"linux_metrics,omitempty"`
}
type AgentAlertRule struct {
Version int `json:"version"`
ID string `json:"id"`
Revision int `json:"revision"`
StreamID string `json:"stream_id"`
Query string `json:"query"`
MinimumMatches int `json:"minimum_matches"`
AST query.AST `json:"-"`
}
func LoadServer(path string, policy FilePolicy) (Server, error) {
var cfg Server
if err := loadStrict(path, policy, &cfg); err != nil {
return Server{}, err
}
if cfg.Schema != SchemaVersion {
return Server{}, fmt.Errorf("unsupported server configuration schema %d", cfg.Schema)
}
if cfg.Listen == "" {
return Server{}, errors.New("listen is required")
}
u, err := url.Parse(cfg.PublicURL)
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" {
return Server{}, errors.New("public_url must be an absolute HTTPS origin")
}
if !filepath.IsAbs(cfg.DataDir) || filepath.Clean(cfg.DataDir) != cfg.DataDir {
return Server{}, errors.New("data_dir must be an absolute clean path")
}
if cfg.MaxBodyBytes < 1024 || cfg.MaxBodyBytes > 64<<20 {
return Server{}, errors.New("max_body_bytes must be between 1024 and 67108864")
}
if cfg.MaxConcurrentIngest == 0 {
cfg.MaxConcurrentIngest = 8
}
if cfg.MaxConcurrentIngest < 1 || cfg.MaxConcurrentIngest > 64 {
return Server{}, errors.New("max_concurrent_ingest must be between 1 and 64")
}
sessionLifetime, err := time.ParseDuration(cfg.SessionLifetimeText)
if err != nil || sessionLifetime < 5*time.Minute || sessionLifetime > 30*24*time.Hour {
return Server{}, errors.New("session_lifetime must be between 5m and 720h")
}
cfg.SessionLifetime = sessionLifetime
if cfg.Query.MaxRows < 1 || cfg.Query.MaxRows > 100_000 {
return Server{}, errors.New("query.max_rows must be between 1 and 100000")
}
if cfg.Query.MaxScannedBytes < 1 || cfg.Query.MaxMemoryBytes < 1 {
return Server{}, errors.New("query byte limits must be positive")
}
d, err := time.ParseDuration(cfg.Query.MaxDurationText)
if err != nil || d < time.Millisecond || d > time.Minute {
return Server{}, errors.New("query.max_duration must be between 1ms and 1m")
}
cfg.Query.MaxDuration = d
if err := cfg.Retention.validate(); err != nil {
return Server{}, err
}
if cfg.WebPush != nil {
if !filepath.IsAbs(cfg.WebPush.PrivateKeyFile) || filepath.Clean(cfg.WebPush.PrivateKeyFile) != cfg.WebPush.PrivateKeyFile {
return Server{}, errors.New("web_push.private_key_file must be an absolute clean path")
}
if err = validateWebPushSubject(cfg.WebPush.Subject); err != nil {
return Server{}, err
}
if cfg.WebPush.QueueCapacity < 1 || cfg.WebPush.QueueCapacity > 1024 {
return Server{}, errors.New("web_push.queue_capacity must be between 1 and 1024")
}
cfg.WebPush.Timeout, err = time.ParseDuration(cfg.WebPush.RequestTimeout)
if err != nil || cfg.WebPush.Timeout < time.Second || cfg.WebPush.Timeout > 30*time.Second {
return Server{}, errors.New("web_push.request_timeout must be between 1s and 30s")
}
cfg.WebPush.PrivateKey, err = LoadWebPushPrivateKey(cfg.WebPush.PrivateKeyFile, policy)
if err != nil {
return Server{}, err
}
}
return cfg, nil
}
func LoadAgent(path string, policy FilePolicy) (Agent, error) {
var cfg Agent
if err := loadStrict(path, policy, &cfg); err != nil {
return Agent{}, err
}
if cfg.Schema != SchemaVersion {
return Agent{}, fmt.Errorf("unsupported agent configuration schema %d", cfg.Schema)
}
u, err := url.Parse(cfg.ServerURL)
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" {
return Agent{}, errors.New("server_url must be an absolute HTTPS origin")
}
for label, path := range map[string]string{"credential_file": cfg.CredentialFile, "spool_dir": cfg.SpoolDir, "state_file": cfg.StateFile} {
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
return Agent{}, fmt.Errorf("%s must be an absolute clean path", label)
}
}
if cfg.SpoolDir == cfg.StateFile || !strings.HasPrefix(cfg.StateFile, cfg.SpoolDir+string(os.PathSeparator)) {
return Agent{}, errors.New("state_file must be below spool_dir")
}
if cfg.MaxSpoolBytes < 1<<20 || cfg.MaxSpoolBytes > 5<<30 {
return Agent{}, errors.New("max_spool_bytes must be between 1 MiB and 5 GiB")
}
age, err := time.ParseDuration(cfg.MaxSpoolAgeText)
if err != nil || age < time.Hour || age > 72*time.Hour {
return Agent{}, errors.New("max_spool_age must be between 1h and 72h")
}
cfg.MaxSpoolAge = age
flush, err := time.ParseDuration(cfg.FlushInterval)
if err != nil || flush < 100*time.Millisecond || flush > time.Minute {
return Agent{}, errors.New("flush_interval must be between 100ms and 1m")
}
cfg.FlushEvery = flush
if cfg.BatchRecords < 1 || cfg.BatchRecords > model.MaxRecords {
return Agent{}, fmt.Errorf("batch_records must be between 1 and %d", model.MaxRecords)
}
if len(cfg.Sources) < 1 || len(cfg.Sources) > 64 {
return Agent{}, errors.New("sources must contain between 1 and 64 entries")
}
streams := map[string]bool{}
for index, source := range cfg.Sources {
switch source.Kind {
case "caddy_json", "requestlog_jsonl", "tend_events_jsonl":
if source.LinuxMetrics != nil {
return Agent{}, fmt.Errorf("sources[%d].linux_metrics is only valid for linux_metrics", index)
}
if !filepath.IsAbs(source.Path) || filepath.Clean(source.Path) != source.Path {
return Agent{}, fmt.Errorf("sources[%d].path must be absolute and clean", index)
}
case "linux_metrics":
if source.Path != "" || source.LinuxMetrics == nil {
return Agent{}, fmt.Errorf("sources[%d] requires linux_metrics and no path", index)
}
if err := source.LinuxMetrics.Validate(); err != nil {
return Agent{}, fmt.Errorf("sources[%d]: %w", index, err)
}
default:
return Agent{}, fmt.Errorf("sources[%d].kind is unsupported", index)
}
allowedSensitive := map[string]bool{}
switch source.Kind {
case "caddy_json":
for _, name := range []string{"client_ip", "query", "referrer", "user_agent"} {
allowedSensitive[name] = true
}
case "requestlog_jsonl":
for _, name := range []string{"client_ip", "query", "referrer", "session_id", "user_agent"} {
allowedSensitive[name] = true
}
}
selectedSensitive := map[string]bool{}
for _, name := range source.SensitiveFields {
if !allowedSensitive[name] {
return Agent{}, fmt.Errorf("sources[%d].sensitive_fields contains unsupported field %q", index, name)
}
if selectedSensitive[name] {
return Agent{}, fmt.Errorf("sources[%d].sensitive_fields duplicates %q", index, name)
}
selectedSensitive[name] = true
}
if err := model.ValidateStreamID(source.StreamID); err != nil {
return Agent{}, fmt.Errorf("sources[%d]: %w", index, err)
}
if streams[source.StreamID] {
return Agent{}, fmt.Errorf("sources[%d].stream_id is duplicated", index)
}
streams[source.StreamID] = true
}
rules := map[string]bool{}
for index := range cfg.AlertRules {
rule := &cfg.AlertRules[index]
if rule.Version != 1 || model.ValidateSourceID(rule.ID) != nil || rule.Revision < 1 || rule.Revision > 1_000_000 || !streams[rule.StreamID] || rule.MinimumMatches < 1 || rule.MinimumMatches > model.MaxRecords || rules[rule.ID] {
return Agent{}, fmt.Errorf("alert_rules[%d] identity is invalid", index)
}
var sourceKind string
for _, source := range cfg.Sources {
if source.StreamID == rule.StreamID {
sourceKind = source.Kind
break
}
}
if sourceKind != "caddy_json" && sourceKind != "requestlog_jsonl" {
return Agent{}, fmt.Errorf("alert_rules[%d] requires a log stream", index)
}
rule.AST, err = query.Parse(rule.Query, model.MaxRecords)
if err != nil || rule.AST.Signal != model.SignalLogs || len(rule.AST.Filters) == 0 || rule.AST.Summary != nil || rule.AST.Sort != nil || rule.AST.Window != 0 || rule.AST.Limit < rule.MinimumMatches {
return Agent{}, fmt.Errorf("alert_rules[%d] query must be a bounded logs filter without sort, summary, or window", index)
}
for _, filter := range rule.AST.Filters {
switch query.CanonicalField(filter.Field) {
case "project.id", "environment.id", "service.id", "source.id", "stream.id":
return Agent{}, fmt.Errorf("alert_rules[%d] cannot filter server-derived scope", index)
}
}
rules[rule.ID] = true
}
return cfg, nil
}
func LoadCredential(path string, policy FilePolicy) (string, error) {
var holder struct {
Credential string `json:"credential"`
}
if err := loadStrict(path, policy, &holder); err != nil {
return "", err
}
if len(holder.Credential) < 48 || len(holder.Credential) > 512 || !strings.HasPrefix(holder.Credential, "obs1.") || strings.ContainsAny(holder.Credential, " \t\r\n") {
return "", errors.New("credential file contains an invalid source credential")
}
return holder.Credential, nil
}
func LoadEnrollmentToken(path string, policy FilePolicy) (string, error) {
var holder struct {
EnrollmentToken string `json:"enrollment_token"`
}
if err := loadStrict(path, policy, &holder); err != nil {
return "", err
}
if len(holder.EnrollmentToken) != len("obse1.")+64 || !strings.HasPrefix(holder.EnrollmentToken, "obse1.") || strings.ContainsAny(holder.EnrollmentToken, " \t\r\n") {
return "", errors.New("enrollment file contains an invalid token")
}
return holder.EnrollmentToken, nil
}
func WriteEnrollmentToken(path, token string) error {
if len(token) != len("obse1.")+64 || !strings.HasPrefix(token, "obse1.") || strings.ContainsAny(token, " \t\r\n") {
return errors.New("invalid enrollment token")
}
return writePrivateJSON(path, struct {
EnrollmentToken string `json:"enrollment_token"`
}{token})
}
func WriteCredential(path, credential string) error {
if len(credential) < 48 || len(credential) > 512 || !strings.HasPrefix(credential, "obs1.") || strings.ContainsAny(credential, " \t\r\n") {
return errors.New("invalid source credential")
}
return writePrivateJSON(path, struct {
Credential string `json:"credential"`
}{credential})
}
func LoadWebPushPrivateKey(path string, policy FilePolicy) ([]byte, error) {
var holder struct {
PrivateKey string `json:"private_key"`
}
if err := loadStrict(path, policy, &holder); err != nil {
return nil, err
}
key, err := base64.RawURLEncoding.DecodeString(holder.PrivateKey)
if err != nil || len(key) != 32 {
return nil, errors.New("web push private key file is invalid")
}
if _, err = ecdh.P256().NewPrivateKey(key); err != nil {
return nil, errors.New("web push private key file is invalid")
}
return key, nil
}
func WriteWebPushPrivateKey(path string, key []byte) error {
if len(key) != 32 {
return errors.New("invalid web push private key")
}
if _, err := ecdh.P256().NewPrivateKey(key); err != nil {
return errors.New("invalid web push private key")
}
return writePrivateJSON(path, struct {
PrivateKey string `json:"private_key"`
}{base64.RawURLEncoding.EncodeToString(key)})
}
func writePrivateJSON(path string, value any) error {
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
return errors.New("secret output path must be absolute and clean")
}
parent := filepath.Dir(path)
info, err := os.Lstat(parent)
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("secret output directory must be an existing non-symlink directory")
}
file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY|syscall.O_NOFOLLOW, 0o600)
if err != nil {
return fmt.Errorf("create secret output: %w", err)
}
body, marshalErr := json.Marshal(value)
if marshalErr == nil {
body = append(body, '\n')
_, marshalErr = file.Write(body)
}
if marshalErr == nil {
marshalErr = file.Sync()
}
if closeErr := file.Close(); marshalErr == nil {
marshalErr = closeErr
}
if marshalErr != nil {
_ = os.Remove(path)
return fmt.Errorf("write secret output: %w", marshalErr)
}
directory, err := os.Open(parent)
if err != nil {
return err
}
defer directory.Close()
return directory.Sync()
}
func (r Retention) validate() error {
values := []int{r.RawLogsDays, r.RawTracesDays, r.RawMetricsDays, r.ColdRawDays, r.MetricRollupsDays, r.EvidenceDays}
for _, days := range values {
if days < 1 || days > 3650 {
return errors.New("retention values must be between 1 and 3650 days")
}
}
if r.MetricRollupsDays < r.RawMetricsDays {
return errors.New("metric rollup retention cannot be shorter than raw metric retention")
}
if r.ColdRawDays < r.RawLogsDays || r.ColdRawDays < r.RawTracesDays || r.ColdRawDays < r.RawMetricsDays || r.ColdRawDays < r.EvidenceDays {
return errors.New("cold raw retention cannot be shorter than a hot raw or evidence retention window")
}
return nil
}
func validateWebPushSubject(subject string) error {
if len(subject) < 8 || len(subject) > 512 || strings.ContainsAny(subject, " \t\r\n") {
return errors.New("web_push.subject is invalid")
}
parsed, err := url.Parse(subject)
if err != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
return errors.New("web_push.subject is invalid")
}
if parsed.Scheme == "mailto" && parsed.Opaque != "" && strings.Contains(parsed.Opaque, "@") {
return nil
}
if parsed.Scheme == "https" && parsed.Host != "" && parsed.User == nil {
return nil
}
return errors.New("web_push.subject must be a mailto address or HTTPS URL")
}
func loadStrict(path string, policy FilePolicy, out any) error {
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
return errors.New("configuration path must be absolute and clean")
}
info, err := os.Lstat(path)
if err != nil {
return fmt.Errorf("inspect configuration: %w", err)
}
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
return errors.New("configuration must be a regular non-symlink file")
}
if policy.SystemdCredentialDirectory != "" {
if filepath.Dir(path) != policy.SystemdCredentialDirectory {
return errors.New("runtime credential must be a direct child of CREDENTIALS_DIRECTORY")
}
mode := info.Mode().Perm()
if mode != 0o400 && mode != 0o440 && mode != 0o600 {
return fmt.Errorf("runtime credential mode must be 0400, 0440, or 0600, got %04o", mode)
}
if runtime.GOOS != "linux" {
return errors.New("systemd credential validation is supported only on Linux")
}
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok || (stat.Uid != 0 && stat.Uid != uint32(os.Geteuid())) {
return errors.New("runtime credential must be owned by root or the service user")
}
} else if info.Mode().Perm() != 0o600 {
return fmt.Errorf("configuration mode must be 0600, got %04o", info.Mode().Perm())
}
if policy.RequireRoot {
if runtime.GOOS != "linux" {
return errors.New("root ownership validation is supported only on Linux")
}
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok || stat.Uid != 0 {
return errors.New("configuration must be owned by root")
}
}
b, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("read configuration: %w", err)
}
dec := json.NewDecoder(bytes.NewReader(b))
dec.DisallowUnknownFields()
if err := dec.Decode(out); err != nil {
return fmt.Errorf("decode configuration: %w", err)
}
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return errors.New("configuration must contain exactly one JSON value")
}
return nil
}
+349
View File
@@ -0,0 +1,349 @@
// SPDX-License-Identifier: AGPL-3.0-only
package config
import (
"crypto/ecdh"
"crypto/rand"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestLoadServerStrictAndValidated(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "server.json")
body := `{"schema":1,"listen":"127.0.0.1:9010","public_url":"https://observatory.example","data_dir":"` + filepath.Join(dir, "data") + `","max_body_bytes":1048576,"session_lifetime":"12h","query":{"max_duration":"2s","max_rows":1000,"max_scanned_bytes":10485760,"max_memory_bytes":8388608},"retention":{"raw_logs_days":30,"raw_traces_days":30,"raw_metrics_days":14,"cold_raw_days":400,"metric_rollups_days":400,"evidence_days":400}}`
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := LoadServer(path, FilePolicy{})
if err != nil {
t.Fatal(err)
}
if cfg.Query.MaxDuration.String() != "2s" || cfg.MaxConcurrentIngest != 8 || cfg.Retention.EvidenceDays != 400 || cfg.Retention.DeleteColdRaw {
t.Fatalf("unexpected config: %#v", cfg)
}
deleting := strings.Replace(body, `"cold_raw_days":400`, `"cold_raw_days":400,"delete_cold_raw":true`, 1)
if err = os.WriteFile(path, []byte(deleting), 0o600); err != nil {
t.Fatal(err)
}
if cfg, err = LoadServer(path, FilePolicy{}); err != nil || !cfg.Retention.DeleteColdRaw {
t.Fatalf("explicit cold deletion config=%#v err=%v", cfg.Retention, err)
}
bad := strings.Replace(body, `"schema":1`, `"schema":1,"surprise":true`, 1)
if err := os.WriteFile(path, []byte(bad), 0o600); err != nil {
t.Fatal(err)
}
if _, err := LoadServer(path, FilePolicy{}); err == nil || !strings.Contains(err.Error(), "unknown field") {
t.Fatalf("expected unknown-field rejection, got %v", err)
}
bad = strings.Replace(body, `"max_body_bytes":1048576`, `"max_body_bytes":1048576,"max_concurrent_ingest":65`, 1)
if err = os.WriteFile(path, []byte(bad), 0o600); err != nil {
t.Fatal(err)
}
if _, err = LoadServer(path, FilePolicy{}); err == nil || !strings.Contains(err.Error(), "max_concurrent_ingest") {
t.Fatalf("expected ingestion concurrency rejection, got %v", err)
}
}
func TestDogfoodServerConfigurationMatchesTheDeploymentBoundary(t *testing.T) {
body, err := os.ReadFile(filepath.Join("..", "..", "release", "server.json"))
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
keyPath := filepath.Join(dir, "web-push.json")
key, err := ecdh.P256().GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
if err = WriteWebPushPrivateKey(keyPath, key.Bytes()); err != nil {
t.Fatal(err)
}
const runtimeKey = "/run/credentials/gamertan-observatory.service/web-push.json"
rewritten := strings.Replace(string(body), runtimeKey, keyPath, 1)
if rewritten == string(body) || strings.Contains(rewritten, runtimeKey) {
t.Fatal("dogfood Web Push credential path was not replaced exactly once")
}
path := filepath.Join(dir, "server.json")
if err = os.WriteFile(path, []byte(rewritten), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := LoadServer(path, FilePolicy{})
if err != nil {
t.Fatal(err)
}
if cfg.Listen != "127.0.0.1:8093" || cfg.PublicURL != "https://observatory.gamertan.com" || cfg.DataDir != "/var/lib/gamertan-observatory" || cfg.MaxBodyBytes != 32<<20 || cfg.MaxConcurrentIngest != 8 || cfg.Retention.DeleteColdRaw || cfg.WebPush == nil || cfg.WebPush.Subject != "mailto:security@sandwichhime.com" || cfg.WebPush.QueueCapacity != 64 || cfg.WebPush.Timeout != 10*time.Second || string(cfg.WebPush.PrivateKey) != string(key.Bytes()) {
t.Fatalf("unexpected dogfood config: %#v", cfg)
}
}
func TestLoadServerRejectsRollupsShorterThanRawMetrics(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "server.json")
body := `{"schema":1,"listen":"127.0.0.1:9010","public_url":"https://observatory.example","data_dir":"` + filepath.Join(dir, "data") + `","max_body_bytes":1048576,"session_lifetime":"12h","query":{"max_duration":"2s","max_rows":1000,"max_scanned_bytes":10485760,"max_memory_bytes":8388608},"retention":{"raw_logs_days":30,"raw_traces_days":30,"raw_metrics_days":14,"cold_raw_days":400,"metric_rollups_days":7,"evidence_days":400}}`
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
if _, err := LoadServer(path, FilePolicy{}); err == nil || !strings.Contains(err.Error(), "cannot be shorter") {
t.Fatalf("short metric rollup retention err=%v", err)
}
}
func TestLoadServerRejectsColdWindowShorterThanHotEvidence(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "server.json")
body := `{"schema":1,"listen":"127.0.0.1:9010","public_url":"https://observatory.example","data_dir":"` + filepath.Join(dir, "data") + `","max_body_bytes":1048576,"session_lifetime":"12h","query":{"max_duration":"2s","max_rows":1000,"max_scanned_bytes":10485760,"max_memory_bytes":8388608},"retention":{"raw_logs_days":30,"raw_traces_days":30,"raw_metrics_days":14,"cold_raw_days":399,"metric_rollups_days":400,"evidence_days":400}}`
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
if _, err := LoadServer(path, FilePolicy{}); err == nil || !strings.Contains(err.Error(), "cold raw retention") {
t.Fatalf("short cold retention err=%v", err)
}
}
func TestLoadServerWebPushUsesSeparatePrivateKeyFile(t *testing.T) {
dir := t.TempDir()
keyPath := filepath.Join(dir, "web-push.json")
key, err := ecdh.P256().GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
if err = WriteWebPushPrivateKey(keyPath, key.Bytes()); err != nil {
t.Fatal(err)
}
path := filepath.Join(dir, "server.json")
body := `{"schema":1,"listen":"127.0.0.1:9010","public_url":"https://observatory.example","data_dir":"` + filepath.Join(dir, "data") + `","max_body_bytes":1048576,"session_lifetime":"12h","query":{"max_duration":"2s","max_rows":1000,"max_scanned_bytes":10485760,"max_memory_bytes":8388608},"retention":{"raw_logs_days":30,"raw_traces_days":30,"raw_metrics_days":14,"cold_raw_days":400,"metric_rollups_days":400,"evidence_days":400},"web_push":{"private_key_file":"` + keyPath + `","subject":"mailto:security@sandwichhime.com","queue_capacity":16,"request_timeout":"5s"}}`
if err = os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := LoadServer(path, FilePolicy{})
if err != nil {
t.Fatal(err)
}
if cfg.WebPush == nil || cfg.WebPush.Timeout != 5*time.Second || cfg.WebPush.QueueCapacity != 16 || string(cfg.WebPush.PrivateKey) != string(key.Bytes()) {
t.Fatalf("web push=%+v", cfg.WebPush)
}
if err = os.WriteFile(keyPath, []byte(`{"private_key":"not-a-key"}`), 0o600); err != nil {
t.Fatal(err)
}
if _, err = LoadServer(path, FilePolicy{}); err == nil {
t.Fatal("invalid Web Push private key accepted")
}
}
func TestLoadServerRejectsModeAndSymlink(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "server.json")
if err := os.WriteFile(path, []byte(`{}`), 0o644); err != nil {
t.Fatal(err)
}
if _, err := LoadServer(path, FilePolicy{}); err == nil || !strings.Contains(err.Error(), "0600") {
t.Fatalf("expected mode rejection, got %v", err)
}
link := filepath.Join(dir, "link.json")
if err := os.Symlink(path, link); err != nil {
t.Skipf("symlink unavailable: %v", err)
}
if _, err := LoadServer(link, FilePolicy{}); err == nil || !strings.Contains(err.Error(), "non-symlink") {
t.Fatalf("expected symlink rejection, got %v", err)
}
}
func TestLoadAgentKeepsSourcesLocalAndBounded(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "agent.json")
body := `{"schema":1,"server_url":"https://observatory.example","credential_file":"` + filepath.Join(dir, "credential.json") + `","spool_dir":"` + filepath.Join(dir, "spool") + `","state_file":"` + filepath.Join(dir, "spool", "state.json") + `","max_spool_bytes":5368709120,"max_spool_age":"72h","batch_records":500,"flush_interval":"1s","sources":[{"kind":"caddy_json","path":"/var/log/caddy/access.jsonl","stream_id":"caddy","sensitive_fields":["client_ip","query","referrer","user_agent"]}]}`
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := LoadAgent(path, FilePolicy{})
if err != nil {
t.Fatal(err)
}
if cfg.MaxSpoolAge != 72*time.Hour || cfg.FlushEvery != time.Second || cfg.Sources[0].Path != "/var/log/caddy/access.jsonl" || len(cfg.Sources[0].SensitiveFields) != 4 {
t.Fatalf("agent=%+v", cfg)
}
bad := strings.Replace(body, `"kind":"caddy_json"`, `"kind":"shell"`, 1)
if err := os.WriteFile(path, []byte(bad), 0o600); err != nil {
t.Fatal(err)
}
if _, err := LoadAgent(path, FilePolicy{}); err == nil {
t.Fatal("expected collector-kind rejection")
}
for _, change := range [][2]string{
{`"sensitive_fields":["client_ip","query","referrer","user_agent"]`, `"sensitive_fields":["client_ip","client_ip"]`},
{`"sensitive_fields":["client_ip","query","referrer","user_agent"]`, `"sensitive_fields":["cookie"]`},
{`"kind":"caddy_json"`, `"kind":"tend_events_jsonl"`},
} {
candidate := strings.Replace(body, change[0], change[1], 1)
if err := os.WriteFile(path, []byte(candidate), 0o600); err != nil {
t.Fatal(err)
}
if _, err := LoadAgent(path, FilePolicy{}); err == nil {
t.Fatalf("invalid sensitive-field configuration accepted: %s", change[1])
}
}
}
func TestLoadAgentAcceptsExplicitLinuxMetricSelectors(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "agent.json")
body := `{"schema":1,"server_url":"https://observatory.example","credential_file":"` + filepath.Join(dir, "credential.json") + `","spool_dir":"` + filepath.Join(dir, "spool") + `","state_file":"` + filepath.Join(dir, "spool", "state.json") + `","max_spool_bytes":1048576,"max_spool_age":"1h","batch_records":500,"flush_interval":"1s","sources":[{"kind":"linux_metrics","stream_id":"host-metrics","linux_metrics":{"proc_root":"/proc","cgroup_root":"/sys/fs/cgroup","filesystems":[{"name":"root","path":"/"}],"processes":[{"name":"caddy","pid_file":"/run/caddy.pid"}],"cgroups":[{"name":"caddy-service","path":"system.slice/caddy.service"}]}}]}`
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := LoadAgent(path, FilePolicy{})
if err != nil {
t.Fatal(err)
}
if cfg.Sources[0].LinuxMetrics == nil || cfg.Sources[0].LinuxMetrics.Filesystems[0].Name != "root" {
t.Fatalf("agent=%+v", cfg)
}
bad := strings.Replace(body, `"path":"system.slice/caddy.service"`, `"path":"../escape"`, 1)
if err = os.WriteFile(path, []byte(bad), 0o600); err != nil {
t.Fatal(err)
}
if _, err = LoadAgent(path, FilePolicy{}); err == nil {
t.Fatal("escaping cgroup selector accepted")
}
}
func TestLoadAgentAcceptsOnlyLocalBoundedLogAlertRules(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "agent.json")
body := `{"schema":1,"server_url":"https://observatory.example","credential_file":"` + filepath.Join(dir, "credential.json") + `","spool_dir":"` + filepath.Join(dir, "spool") + `","state_file":"` + filepath.Join(dir, "spool", "state.json") + `","max_spool_bytes":1048576,"max_spool_age":"1h","batch_records":500,"flush_interval":"1s","sources":[{"kind":"requestlog_jsonl","path":"/var/log/example/request.jsonl","stream_id":"requests"}],"alert_rules":[{"version":1,"id":"http-failures","revision":2,"stream_id":"requests","query":"logs | where status >= 500 | limit 10","minimum_matches":1}]}`
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := LoadAgent(path, FilePolicy{})
if err != nil || len(cfg.AlertRules) != 1 || cfg.AlertRules[0].AST.Signal != "logs" || len(cfg.AlertRules[0].AST.Filters) != 1 {
t.Fatalf("agent=%+v err=%v", cfg, err)
}
for _, replacement := range []string{
`"stream_id":"missing"`,
`"query":"metrics | where value > 0 | limit 10"`,
`"query":"logs | summarize count() | limit 10"`,
`"query":"logs | where service == other | limit 10"`,
`"minimum_matches":11`,
} {
candidate := body
switch {
case strings.Contains(replacement, "missing"):
candidate = strings.Replace(candidate, `"stream_id":"requests","query"`, replacement+`,"query"`, 1)
case strings.HasPrefix(replacement, `"query"`):
candidate = strings.Replace(candidate, `"query":"logs | where status >= 500 | limit 10"`, replacement, 1)
default:
candidate = strings.Replace(candidate, `"minimum_matches":1`, replacement, 1)
}
if err = os.WriteFile(path, []byte(candidate), 0o600); err != nil {
t.Fatal(err)
}
if _, err = LoadAgent(path, FilePolicy{}); err == nil {
t.Fatalf("invalid alert rule accepted: %s", replacement)
}
}
}
func TestLoadCredentialDoesNotAcceptWhitespaceOrExtraFields(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "credential.json")
valid := `{"credential":"obs1.source.` + strings.Repeat("a", 64) + `"}`
if err := os.WriteFile(path, []byte(valid), 0o600); err != nil {
t.Fatal(err)
}
if credential, err := LoadCredential(path, FilePolicy{}); err != nil || !strings.HasPrefix(credential, "obs1.source.") {
t.Fatalf("credential=%q err=%v", credential, err)
}
if err := os.WriteFile(path, []byte(`{"credential":"obs1.source.bad value"}`), 0o600); err != nil {
t.Fatal(err)
}
if _, err := LoadCredential(path, FilePolicy{}); err == nil {
t.Fatal("expected whitespace rejection")
}
}
func TestEnrollmentAndCredentialOutputsArePrivateAndExclusive(t *testing.T) {
dir := t.TempDir()
enrollmentPath := filepath.Join(dir, "enrollment.json")
enrollment := "obse1." + strings.Repeat("e", 64)
if err := WriteEnrollmentToken(enrollmentPath, enrollment); err != nil {
t.Fatal(err)
}
if got, err := LoadEnrollmentToken(enrollmentPath, FilePolicy{}); err != nil || got != enrollment {
t.Fatalf("token=%q err=%v", got, err)
}
if err := WriteEnrollmentToken(enrollmentPath, enrollment); err == nil {
t.Fatal("enrollment output overwritten")
}
credentialPath := filepath.Join(dir, "credential.json")
credential := "obs1.source." + strings.Repeat("a", 64)
if err := WriteCredential(credentialPath, credential); err != nil {
t.Fatal(err)
}
if got, err := LoadCredential(credentialPath, FilePolicy{}); err != nil || got != credential {
t.Fatalf("credential=%q err=%v", got, err)
}
for _, path := range []string{enrollmentPath, credentialPath} {
info, err := os.Stat(path)
if err != nil || info.Mode().Perm() != 0o600 {
t.Fatalf("path=%s info=%v err=%v", path, info, err)
}
}
}
func TestSystemdCredentialPolicyIsExplicitAndConfined(t *testing.T) {
dir := t.TempDir()
t.Setenv("CREDENTIALS_DIRECTORY", dir)
policy, err := SystemdCredentialPolicy()
if err != nil {
t.Fatal(err)
}
path := filepath.Join(dir, "credential.json")
credential := `{"credential":"obs1.source.` + strings.Repeat("a", 64) + `"}`
if err := os.WriteFile(path, []byte(credential), 0o400); err != nil {
t.Fatal(err)
}
if _, err := LoadCredential(path, policy); err != nil {
t.Fatalf("load systemd credential: %v", err)
}
if err := os.Chmod(path, 0o440); err != nil {
t.Fatal(err)
}
if _, err := LoadCredential(path, policy); err != nil {
t.Fatalf("load systemd mode-0440 credential: %v", err)
}
if err := os.Chmod(path, 0o444); err != nil {
t.Fatal(err)
}
if _, err := LoadCredential(path, policy); err == nil || !strings.Contains(err.Error(), "0400, 0440, or 0600") {
t.Fatalf("expected public credential mode rejection, got %v", err)
}
if err := os.Chmod(path, 0o400); err != nil {
t.Fatal(err)
}
outside := filepath.Join(t.TempDir(), "credential.json")
if err := os.WriteFile(outside, []byte(credential), 0o400); err != nil {
t.Fatal(err)
}
if _, err := LoadCredential(outside, policy); err == nil || !strings.Contains(err.Error(), "direct child") {
t.Fatalf("expected confinement rejection, got %v", err)
}
nested := filepath.Join(dir, "nested")
if err := os.Mkdir(nested, 0o700); err != nil {
t.Fatal(err)
}
nestedPath := filepath.Join(nested, "credential.json")
if err := os.WriteFile(nestedPath, []byte(credential), 0o400); err != nil {
t.Fatal(err)
}
if _, err := LoadCredential(nestedPath, policy); err == nil || !strings.Contains(err.Error(), "direct child") {
t.Fatalf("expected nested-path rejection, got %v", err)
}
}
+59
View File
@@ -0,0 +1,59 @@
// SPDX-License-Identifier: AGPL-3.0-only
package edgealert
import (
"errors"
"time"
"gamertan.com/observatory/internal/config"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/query"
)
type Evaluation struct {
State string
Matches int
WindowStart time.Time
WindowEnd time.Time
ObservedAt time.Time
}
// Evaluate applies one locally configured, filter-only log rule to one exact
// durable batch. It does not perform I/O, mutate incident state, or retain
// telemetry beyond the caller-owned batch.
func Evaluate(rule config.AgentAlertRule, batch model.Batch) (Evaluation, error) {
if rule.AST.Signal != model.SignalLogs || batch.Signal != model.SignalLogs || rule.StreamID != batch.StreamID || len(batch.Records) == 0 {
return Evaluation{}, errors.New("edge alert rule and batch are incompatible")
}
first, last := batch.Records[0].Timestamp.UTC(), batch.Records[0].Timestamp.UTC()
matches := 0
state := "clear"
for _, observation := range batch.Records {
timestamp := observation.Timestamp.UTC()
if timestamp.Before(first) {
first = timestamp
}
if timestamp.After(last) {
last = timestamp
}
matched, err := query.MatchObservation(observation, rule.AST, nil)
if err != nil {
return Evaluation{State: "error", Matches: matches, WindowStart: first, WindowEnd: last, ObservedAt: maxTime(batch.ObservedAt.UTC(), last)}, nil
}
if matched {
matches++
if matches >= rule.MinimumMatches {
state = "matched"
}
}
}
return Evaluation{State: state, Matches: matches, WindowStart: first, WindowEnd: last, ObservedAt: maxTime(batch.ObservedAt.UTC(), last)}, nil
}
func maxTime(left, right time.Time) time.Time {
if left.After(right) {
return left
}
return right
}
+105
View File
@@ -0,0 +1,105 @@
// SPDX-License-Identifier: AGPL-3.0-only
package edgealert
import (
"context"
"os"
"path/filepath"
"testing"
"time"
"gamertan.com/observatory/internal/config"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/query"
"gamertan.com/observatory/internal/storage"
)
func TestEvaluateMatchesBoundedBatchWithoutIO(t *testing.T) {
now := time.Date(2026, 8, 19, 0, 0, 0, 0, time.UTC)
ast, err := query.Parse("logs | where status >= 500 | limit 10", model.MaxRecords)
if err != nil {
t.Fatal(err)
}
rule := config.AgentAlertRule{Version: 1, ID: "rule-a", Revision: 1, StreamID: "requests", Query: "logs | where status >= 500 | limit 10", MinimumMatches: 2, AST: ast}
batch := model.Batch{Version: model.BatchVersion, SourceID: "source-a", StreamID: "requests", Sequence: 4, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{
{Timestamp: now.Add(-time.Second), Name: "request", Attributes: map[string]string{"http.status_code": "503"}},
{Timestamp: now, Name: "request", Attributes: map[string]string{"http.status_code": "502"}},
}}
evaluation, err := Evaluate(rule, batch)
if err != nil || evaluation.State != "matched" || evaluation.Matches != 2 || !evaluation.WindowStart.Equal(now.Add(-time.Second)) || !evaluation.WindowEnd.Equal(now) || !evaluation.ObservedAt.Equal(now) {
t.Fatalf("evaluation=%+v err=%v", evaluation, err)
}
batch.Records[1].Attributes["http.status_code"] = "200"
evaluation, err = Evaluate(rule, batch)
if err != nil || evaluation.State != "clear" || evaluation.Matches != 1 {
t.Fatalf("evaluation=%+v err=%v", evaluation, err)
}
}
func TestEdgeEvaluationMatchesCentralOracleForExactBatch(t *testing.T) {
ctx := context.Background()
root := filepath.Join(t.TempDir(), "data")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
t.Fatal(err)
}
defer store.Close()
now := time.Date(2026, 8, 19, 0, 5, 0, 0, time.UTC)
scope := model.Scope{OrganizationID: "organization-a", ProjectID: "project-a", EnvironmentID: "production", ServiceID: "service-a"}
token, err := store.CreateSource(ctx, "source-a", scope)
if err != nil {
t.Fatal(err)
}
queryText := "logs | where status >= 500 | limit 10"
ast, err := query.Parse(queryText, model.MaxRecords)
if err != nil {
t.Fatal(err)
}
saved, err := store.SaveQuery(ctx, storage.SavedQueryInput{OrganizationID: scope.OrganizationID, ActorUserID: "operator-a", MaxRows: 100, Name: "Failures", Query: queryText, Scope: storage.ResourceScope{ProjectID: scope.ProjectID, EnvironmentID: scope.EnvironmentID, ServiceID: scope.ServiceID}}, now)
if err != nil {
t.Fatal(err)
}
_, err = store.SaveAlertRule(ctx, storage.AlertRuleInput{OrganizationID: scope.OrganizationID, ActorUserID: "operator-a", SavedQueryID: saved.ID, Name: "Failures", Severity: "warning", MinimumMatches: 1, RequiredConsecutive: 1, EvaluationInterval: 15 * time.Second, Enabled: true}, now)
if err != nil {
t.Fatal(err)
}
batch := model.Batch{Version: model.BatchVersion, SourceID: "source-a", StreamID: "requests", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "request", Attributes: map[string]string{"http.status_code": "503"}}, {Timestamp: now, Name: "request", Attributes: map[string]string{"http.status_code": "200"}}}}
if _, err = store.Ingest(ctx, token, batch, now); err != nil {
t.Fatal(err)
}
for {
report, projectErr := store.ProjectPending(ctx)
if projectErr != nil {
t.Fatal(projectErr)
}
if report.ProjectedSegments == 0 {
break
}
}
edge, err := Evaluate(config.AgentAlertRule{Version: 1, ID: "rule-a", Revision: 1, StreamID: "requests", Query: queryText, MinimumMatches: 1, AST: ast}, batch)
if err != nil {
t.Fatal(err)
}
central, err := store.EvaluateDueAlertRules(ctx, query.Budget{MaxDuration: time.Second, MaxRows: 100, MaxScannedBytes: 16 << 20, MaxMemoryBytes: 8 << 20}, now)
if err != nil || len(central) != 1 || (edge.State == "matched") != central[0].Matched || edge.Matches != central[0].Rows {
t.Fatalf("edge=%+v central=%+v err=%v", edge, central, err)
}
}
func TestEvaluateReturnsBoundedErrorStateForTypedMismatch(t *testing.T) {
now := time.Now().UTC()
ast, err := query.Parse("logs | where status >= nope | limit 10", model.MaxRecords)
if err != nil {
t.Fatal(err)
}
rule := config.AgentAlertRule{Version: 1, ID: "rule-a", Revision: 1, StreamID: "requests", Query: "logs | where status >= nope | limit 10", MinimumMatches: 1, AST: ast}
batch := model.Batch{Version: model.BatchVersion, SourceID: "source-a", StreamID: "requests", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "request", Attributes: map[string]string{"http.status_code": "503"}}}}
evaluation, err := Evaluate(rule, batch)
if err != nil || evaluation.State != "error" || evaluation.Matches != 0 {
t.Fatalf("evaluation=%+v err=%v", evaluation, err)
}
}
+487
View File
@@ -0,0 +1,487 @@
// SPDX-License-Identifier: AGPL-3.0-only
package hostmetrics
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"unicode/utf8"
"gamertan.com/observatory/internal/model"
)
const maxSourceBytes = 1 << 20
type Config struct {
ProcRoot string `json:"proc_root"`
CgroupRoot string `json:"cgroup_root,omitempty"`
Filesystems []Filesystem `json:"filesystems,omitempty"`
Processes []Process `json:"processes,omitempty"`
ControlGroups []Cgroup `json:"cgroups,omitempty"`
}
type Filesystem struct {
Name string `json:"name"`
Path string `json:"path"`
}
type Process struct {
Name string `json:"name"`
PIDFile string `json:"pid_file"`
}
type Cgroup struct {
Name string `json:"name"`
Path string `json:"path"`
}
func (configuration Config) Validate() error {
if runtime.GOOS != "linux" {
return errors.New("Linux metrics require Linux")
}
if err := absoluteClean("proc_root", configuration.ProcRoot); err != nil {
return err
}
if configuration.CgroupRoot != "" {
if err := absoluteClean("cgroup_root", configuration.CgroupRoot); err != nil {
return err
}
}
if len(configuration.Filesystems) > 32 || len(configuration.Processes) > 32 || len(configuration.ControlGroups) > 32 {
return errors.New("Linux metric selector limit exceeded")
}
names := map[string]bool{}
for _, filesystem := range configuration.Filesystems {
if err := selectorName(filesystem.Name, names); err != nil {
return fmt.Errorf("filesystem: %w", err)
}
if err := absoluteClean("filesystem path", filesystem.Path); err != nil {
return err
}
}
for _, process := range configuration.Processes {
if err := selectorName(process.Name, names); err != nil {
return fmt.Errorf("process: %w", err)
}
if err := absoluteClean("pid_file", process.PIDFile); err != nil {
return err
}
}
for _, group := range configuration.ControlGroups {
if err := selectorName(group.Name, names); err != nil {
return fmt.Errorf("cgroup: %w", err)
}
if configuration.CgroupRoot == "" {
return errors.New("cgroup_root is required when cgroups are selected")
}
if group.Path == "" || filepath.IsAbs(group.Path) || filepath.Clean(group.Path) != group.Path || group.Path == "." || strings.HasPrefix(group.Path, ".."+string(os.PathSeparator)) {
return errors.New("cgroup path must be a clean relative path below cgroup_root")
}
}
return nil
}
func Collect(configuration Config, now time.Time) ([]model.Observation, error) {
if err := configuration.Validate(); err != nil {
return nil, err
}
if now.IsZero() {
return nil, errors.New("collection time is required")
}
if err := secureDirectory(configuration.ProcRoot); err != nil {
return nil, errors.New("proc_root is unavailable")
}
var observations []model.Observation
var problems []error
appendResult := func(result []model.Observation, err error) {
observations = append(observations, result...)
if err != nil {
problems = append(problems, err)
}
}
result, err := collectStat(configuration.ProcRoot, now)
appendResult(result, err)
result, err = collectMemory(configuration.ProcRoot, now)
appendResult(result, err)
result, err = collectLoad(configuration.ProcRoot, now)
appendResult(result, err)
result, err = collectNetwork(configuration.ProcRoot, now)
appendResult(result, err)
for _, filesystem := range configuration.Filesystems {
result, err = collectFilesystem(filesystem, now)
appendResult(result, err)
}
for _, process := range configuration.Processes {
result, err = collectProcess(configuration.ProcRoot, process, now)
appendResult(result, err)
}
for _, group := range configuration.ControlGroups {
result, err = collectCgroup(configuration.CgroupRoot, group, now)
appendResult(result, err)
}
if len(observations) > model.MaxRecords {
return nil, errors.New("Linux metric record limit exceeded")
}
return observations, errors.Join(problems...)
}
func collectStat(root string, now time.Time) ([]model.Observation, error) {
body, err := readBounded(filepath.Join(root, "stat"))
if err != nil {
return nil, errors.New("read proc stat")
}
var observations []model.Observation
for _, line := range strings.Split(string(body), "\n") {
fields := strings.Fields(line)
if len(fields) < 5 || fields[0] != "cpu" {
continue
}
states := []string{"user", "nice", "system", "idle", "iowait", "irq", "softirq", "steal", "guest", "guest_nice"}
for index := 1; index < len(fields) && index <= len(states); index++ {
value, parseErr := strconv.ParseFloat(fields[index], 64)
if parseErr != nil {
return nil, errors.New("proc stat contains an invalid CPU counter")
}
observations = append(observations, metric(now, "system.cpu.time_ticks", value, "ticks", map[string]string{"state": states[index-1]}))
}
break
}
uptime, err := readBounded(filepath.Join(root, "uptime"))
if err == nil {
fields := strings.Fields(string(uptime))
if len(fields) > 0 {
if value, parseErr := strconv.ParseFloat(fields[0], 64); parseErr == nil {
observations = append(observations, metric(now, "system.uptime", value, "seconds", nil))
}
}
}
if len(observations) == 0 {
return nil, errors.New("proc stat contains no aggregate CPU record")
}
return observations, nil
}
func collectMemory(root string, now time.Time) ([]model.Observation, error) {
body, err := readBounded(filepath.Join(root, "meminfo"))
if err != nil {
return nil, errors.New("read proc meminfo")
}
wanted := map[string]string{"MemTotal": "total", "MemAvailable": "available", "SwapTotal": "swap_total", "SwapFree": "swap_free"}
var observations []model.Observation
for _, line := range strings.Split(string(body), "\n") {
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
state, ok := wanted[strings.TrimSuffix(fields[0], ":")]
if !ok {
continue
}
value, parseErr := strconv.ParseFloat(fields[1], 64)
if parseErr != nil {
return nil, errors.New("proc meminfo contains an invalid value")
}
if len(fields) > 2 && fields[2] == "kB" {
value *= 1024
}
observations = append(observations, metric(now, "system.memory", value, "bytes", map[string]string{"state": state}))
}
if len(observations) != len(wanted) {
return observations, errors.New("proc meminfo is missing required values")
}
return observations, nil
}
func collectLoad(root string, now time.Time) ([]model.Observation, error) {
body, err := readBounded(filepath.Join(root, "loadavg"))
if err != nil {
return nil, errors.New("read proc loadavg")
}
fields := strings.Fields(string(body))
if len(fields) < 3 {
return nil, errors.New("proc loadavg is incomplete")
}
periods := []string{"1m", "5m", "15m"}
observations := make([]model.Observation, 0, 3)
for index := range periods {
value, parseErr := strconv.ParseFloat(fields[index], 64)
if parseErr != nil {
return nil, errors.New("proc loadavg contains an invalid value")
}
observations = append(observations, metric(now, "system.load.average", value, "1", map[string]string{"period": periods[index]}))
}
return observations, nil
}
func collectNetwork(root string, now time.Time) ([]model.Observation, error) {
body, err := readBounded(filepath.Join(root, "net", "dev"))
if err != nil {
return nil, errors.New("read proc network counters")
}
var observations []model.Observation
for _, line := range strings.Split(string(body), "\n") {
separator := strings.IndexByte(line, ':')
if separator < 0 {
continue
}
name := strings.TrimSpace(line[:separator])
if !safeLabel(name) {
return nil, errors.New("proc network interface name is invalid")
}
fields := strings.Fields(line[separator+1:])
if len(fields) != 16 {
return nil, errors.New("proc network counter record is invalid")
}
indexes := []struct {
field int
name string
dir string
}{{0, "system.network.bytes", "receive"}, {1, "system.network.packets", "receive"}, {3, "system.network.dropped_packets", "receive"}, {8, "system.network.bytes", "transmit"}, {9, "system.network.packets", "transmit"}, {11, "system.network.dropped_packets", "transmit"}}
for _, selected := range indexes {
value, parseErr := strconv.ParseFloat(fields[selected.field], 64)
if parseErr != nil {
return nil, errors.New("proc network counter is invalid")
}
unit := "1"
if selected.name == "system.network.bytes" {
unit = "bytes"
}
observations = append(observations, metric(now, selected.name, value, unit, map[string]string{"interface": name, "direction": selected.dir}))
}
if len(observations) > 128*6 {
return nil, errors.New("proc network interface limit exceeded")
}
}
return observations, nil
}
func collectFilesystem(selected Filesystem, now time.Time) ([]model.Observation, error) {
info, err := os.Lstat(selected.Path)
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return nil, fmt.Errorf("filesystem %s is unavailable", selected.Name)
}
var status syscall.Statfs_t
if err = syscall.Statfs(selected.Path, &status); err != nil {
return nil, fmt.Errorf("inspect filesystem %s", selected.Name)
}
blockSize := float64(status.Bsize)
attributes := map[string]string{"filesystem": selected.Name}
return []model.Observation{
metric(now, "system.filesystem.bytes", float64(status.Blocks)*blockSize, "bytes", with(attributes, "state", "total")),
metric(now, "system.filesystem.bytes", float64(status.Bavail)*blockSize, "bytes", with(attributes, "state", "available")),
metric(now, "system.filesystem.inodes", float64(status.Files), "1", with(attributes, "state", "total")),
metric(now, "system.filesystem.inodes", float64(status.Ffree), "1", with(attributes, "state", "free")),
}, nil
}
func collectProcess(procRoot string, selected Process, now time.Time) ([]model.Observation, error) {
pidBody, err := readBounded(selected.PIDFile)
if err != nil {
return []model.Observation{metric(now, "process.up", 0, "1", map[string]string{"process": selected.Name})}, fmt.Errorf("process %s PID is unavailable", selected.Name)
}
pidText := strings.TrimSpace(string(pidBody))
pid, err := strconv.ParseUint(pidText, 10, 31)
if err != nil || pid == 0 {
return []model.Observation{metric(now, "process.up", 0, "1", map[string]string{"process": selected.Name})}, fmt.Errorf("process %s PID is invalid", selected.Name)
}
stat, err := readBounded(filepath.Join(procRoot, pidText, "stat"))
if err != nil {
return []model.Observation{metric(now, "process.up", 0, "1", map[string]string{"process": selected.Name})}, fmt.Errorf("process %s is unavailable", selected.Name)
}
closing := strings.LastIndexByte(string(stat), ')')
if closing < 2 {
return nil, fmt.Errorf("process %s stat is invalid", selected.Name)
}
fields := strings.Fields(string(stat)[closing+1:])
// fields begin with state (field 3); utime, stime, starttime, vsize, rss
// are therefore indexes 11, 12, 19, 20, and 21 in this slice.
if len(fields) < 22 {
return nil, fmt.Errorf("process %s stat is incomplete", selected.Name)
}
values := make([]float64, 5)
for index, field := range []int{11, 12, 19, 20, 21} {
values[index], err = strconv.ParseFloat(fields[field], 64)
if err != nil {
return nil, fmt.Errorf("process %s stat contains an invalid counter", selected.Name)
}
}
pageSize := float64(os.Getpagesize())
base := map[string]string{"process": selected.Name}
observations := []model.Observation{
metric(now, "process.up", 1, "1", base),
metric(now, "process.start_time_ticks", values[2], "ticks", base),
metric(now, "process.cpu.time_ticks", values[0], "ticks", with(base, "state", "user")),
metric(now, "process.cpu.time_ticks", values[1], "ticks", with(base, "state", "system")),
metric(now, "process.memory.virtual", values[3], "bytes", base),
metric(now, "process.memory.resident", values[4]*pageSize, "bytes", base),
}
if ioBody, ioErr := readBounded(filepath.Join(procRoot, pidText, "io")); ioErr == nil {
for _, line := range strings.Split(string(ioBody), "\n") {
fields := strings.Fields(line)
if len(fields) != 2 || fields[0] != "read_bytes:" && fields[0] != "write_bytes:" {
continue
}
value, parseErr := strconv.ParseFloat(fields[1], 64)
if parseErr != nil {
continue
}
direction := strings.TrimSuffix(fields[0], "_bytes:")
observations = append(observations, metric(now, "process.io.bytes", value, "bytes", with(base, "direction", direction)))
}
}
return observations, nil
}
func collectCgroup(root string, selected Cgroup, now time.Time) ([]model.Observation, error) {
directory, err := secureRelativeDirectory(root, selected.Path)
if err != nil {
return []model.Observation{metric(now, "cgroup.up", 0, "1", map[string]string{"cgroup": selected.Name})}, fmt.Errorf("cgroup %s is unavailable", selected.Name)
}
base := map[string]string{"cgroup": selected.Name}
observations := []model.Observation{metric(now, "cgroup.up", 1, "1", base)}
for _, scalar := range []struct {
file, name, unit, state string
}{{"memory.current", "cgroup.memory", "bytes", "current"}, {"memory.peak", "cgroup.memory", "bytes", "peak"}, {"memory.swap.current", "cgroup.memory", "bytes", "swap"}, {"pids.current", "cgroup.pids", "1", "current"}} {
body, readErr := readBounded(filepath.Join(directory, scalar.file))
if readErr != nil {
continue
}
value, parseErr := strconv.ParseFloat(strings.TrimSpace(string(body)), 64)
if parseErr == nil {
observations = append(observations, metric(now, scalar.name, value, scalar.unit, with(base, "state", scalar.state)))
}
}
if body, readErr := readBounded(filepath.Join(directory, "cpu.stat")); readErr == nil {
for _, line := range strings.Split(string(body), "\n") {
fields := strings.Fields(line)
if len(fields) != 2 || fields[0] != "usage_usec" && fields[0] != "user_usec" && fields[0] != "system_usec" {
continue
}
value, parseErr := strconv.ParseFloat(fields[1], 64)
if parseErr == nil {
observations = append(observations, metric(now, "cgroup.cpu.time", value, "microseconds", with(base, "state", strings.TrimSuffix(fields[0], "_usec"))))
}
}
}
if body, readErr := readBounded(filepath.Join(directory, "io.stat")); readErr == nil {
var readBytes, writeBytes float64
for _, line := range strings.Split(string(body), "\n") {
for _, field := range strings.Fields(line) {
key, text, found := strings.Cut(field, "=")
if !found || key != "rbytes" && key != "wbytes" {
continue
}
value, parseErr := strconv.ParseFloat(text, 64)
if parseErr != nil {
continue
}
if key == "rbytes" {
readBytes += value
} else {
writeBytes += value
}
}
}
observations = append(observations,
metric(now, "cgroup.io.bytes", readBytes, "bytes", with(base, "direction", "read")),
metric(now, "cgroup.io.bytes", writeBytes, "bytes", with(base, "direction", "write")),
)
}
return observations, nil
}
func metric(now time.Time, name string, value float64, unit string, attributes map[string]string) model.Observation {
copied := with(attributes, "unit", unit)
return model.Observation{Timestamp: now.UTC(), Name: name, Value: &value, Attributes: copied}
}
func with(source map[string]string, key, value string) map[string]string {
result := make(map[string]string, len(source)+1)
for existingKey, existingValue := range source {
result[existingKey] = existingValue
}
result[key] = value
return result
}
func readBounded(path string) ([]byte, error) {
before, err := os.Lstat(path)
if err != nil || !before.Mode().IsRegular() || before.Mode()&os.ModeSymlink != 0 || before.Size() > maxSourceBytes {
return nil, errors.New("metric source is not a bounded regular file")
}
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
after, err := file.Stat()
if err != nil || !after.Mode().IsRegular() || !os.SameFile(before, after) {
return nil, errors.New("metric source changed during open")
}
body, err := io.ReadAll(io.LimitReader(bufio.NewReader(file), maxSourceBytes+1))
if err != nil || len(body) > maxSourceBytes || !utf8.Valid(body) || strings.IndexByte(string(body), 0) >= 0 {
return nil, errors.New("metric source exceeds accepted bounds")
}
return body, nil
}
func secureDirectory(path string) error {
info, err := os.Lstat(path)
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("path is not a non-symlink directory")
}
return nil
}
func secureRelativeDirectory(root, relative string) (string, error) {
if err := secureDirectory(root); err != nil {
return "", err
}
current := root
for _, part := range strings.Split(filepath.ToSlash(relative), "/") {
current = filepath.Join(current, part)
if err := secureDirectory(current); err != nil {
return "", err
}
}
return current, nil
}
func absoluteClean(label, value string) error {
if !filepath.IsAbs(value) || filepath.Clean(value) != value {
return fmt.Errorf("%s must be absolute and clean", label)
}
return nil
}
func selectorName(value string, names map[string]bool) error {
if !safeLabel(value) {
return errors.New("selector name is invalid")
}
if names[value] {
return errors.New("selector name is duplicated")
}
names[value] = true
return nil
}
func safeLabel(value string) bool {
if value == "" || len(value) > 128 {
return false
}
for _, character := range value {
if !(character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' || character >= '0' && character <= '9' || strings.ContainsRune("._-", character)) {
return false
}
}
return true
}
+158
View File
@@ -0,0 +1,158 @@
// SPDX-License-Identifier: AGPL-3.0-only
package hostmetrics
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
"gamertan.com/observatory/internal/model"
)
func TestCollectReadsOnlyConfiguredLinuxEvidence(t *testing.T) {
root := t.TempDir()
proc := filepath.Join(root, "proc")
cgroup := filepath.Join(root, "cgroup")
filesystem := filepath.Join(root, "filesystem")
pidFile := filepath.Join(root, "service.pid")
for _, directory := range []string{filepath.Join(proc, "net"), filepath.Join(proc, "123"), filepath.Join(cgroup, "system.slice", "example.service"), filesystem} {
if err := os.MkdirAll(directory, 0o700); err != nil {
t.Fatal(err)
}
}
write := func(path, body string) {
t.Helper()
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
write(filepath.Join(proc, "stat"), "cpu 100 2 30 400 5 6 7 8 9 10\n")
write(filepath.Join(proc, "uptime"), "99.5 80.0\n")
write(filepath.Join(proc, "meminfo"), "MemTotal: 1000 kB\nMemAvailable: 750 kB\nSwapTotal: 200 kB\nSwapFree: 150 kB\n")
write(filepath.Join(proc, "loadavg"), "0.10 0.20 0.30 1/100 123\n")
write(filepath.Join(proc, "net", "dev"), "Inter-| Receive | Transmit\nlo: 100 2 0 1 0 0 0 0 200 3 0 2 0 0 0 0\n")
write(pidFile, "123\n")
write(filepath.Join(proc, "123", "stat"), "123 (example worker) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23\n")
write(filepath.Join(proc, "123", "io"), "read_bytes: 4096\nwrite_bytes: 8192\n")
group := filepath.Join(cgroup, "system.slice", "example.service")
write(filepath.Join(group, "memory.current"), "1024\n")
write(filepath.Join(group, "memory.peak"), "2048\n")
write(filepath.Join(group, "memory.swap.current"), "0\n")
write(filepath.Join(group, "pids.current"), "3\n")
write(filepath.Join(group, "cpu.stat"), "usage_usec 300\nuser_usec 200\nsystem_usec 100\n")
write(filepath.Join(group, "io.stat"), "8:0 rbytes=100 wbytes=200 rios=1 wios=2\n8:1 rbytes=300 wbytes=400 rios=3 wios=4\n")
configuration := Config{
ProcRoot: proc, CgroupRoot: cgroup,
Filesystems: []Filesystem{{Name: "data", Path: filesystem}},
Processes: []Process{{Name: "web", PIDFile: pidFile}},
ControlGroups: []Cgroup{{Name: "web-service", Path: filepath.Join("system.slice", "example.service")}},
}
now := time.Date(2026, 8, 17, 6, 0, 0, 0, time.UTC)
observations, err := Collect(configuration, now)
if err != nil {
t.Fatal(err)
}
wanted := map[string]bool{
"system.cpu.time_ticks": false, "system.memory": false, "system.load.average": false,
"system.network.bytes": false, "system.filesystem.bytes": false, "process.up": false,
"process.start_time_ticks": false, "process.io.bytes": false, "cgroup.up": false, "cgroup.io.bytes": false,
}
for _, observation := range observations {
if _, ok := wanted[observation.Name]; ok {
wanted[observation.Name] = true
}
for _, value := range observation.Attributes {
if strings.Contains(value, root) {
t.Fatalf("local path leaked in attributes: %+v", observation)
}
}
if _, found := observation.Attributes["start_ticks"]; found {
t.Fatalf("dynamic process identity leaked into metric attributes: %+v", observation)
}
}
for name, found := range wanted {
if !found {
t.Errorf("missing %s", name)
}
}
batch := model.Batch{Version: model.BatchVersion, SourceID: "source", StreamID: "host-metrics", Sequence: 1, ObservedAt: now, Signal: model.SignalMetrics, Records: observations}
if err = batch.Validate(now); err != nil {
t.Fatalf("collected batch: %v", err)
}
}
func TestCollectRejectsSymlinkMetricSource(t *testing.T) {
proc := createMinimalProc(t)
target := filepath.Join(t.TempDir(), "pid")
if err := os.WriteFile(target, []byte("123\n"), 0o600); err != nil {
t.Fatal(err)
}
link := filepath.Join(t.TempDir(), "selected.pid")
if err := os.Symlink(target, link); err != nil {
t.Fatal(err)
}
observations, err := Collect(Config{ProcRoot: proc, Processes: []Process{{Name: "selected", PIDFile: link}}}, time.Date(2026, 8, 17, 6, 0, 0, 0, time.UTC))
if err == nil {
t.Fatal("symlink PID source accepted without a collection warning")
}
for _, observation := range observations {
if observation.Name == "process.up" && observation.Value != nil && *observation.Value == 0 {
return
}
}
t.Fatal("rejected symlink source did not retain process.up=0 evidence")
}
func TestCollectReportsMissingSelectedProcessWithoutDroppingHostMetrics(t *testing.T) {
proc := createMinimalProc(t)
now := time.Date(2026, 8, 17, 6, 0, 0, 0, time.UTC)
observations, err := Collect(Config{ProcRoot: proc, Processes: []Process{{Name: "missing", PIDFile: filepath.Join(t.TempDir(), "missing.pid")}}}, now)
if err == nil || len(observations) == 0 {
t.Fatalf("observations=%d err=%v", len(observations), err)
}
foundDown := false
for _, observation := range observations {
if observation.Name == "process.up" && observation.Value != nil && *observation.Value == 0 {
foundDown = true
}
}
if !foundDown {
t.Fatal("missing process did not emit process.up=0")
}
}
func TestValidationRejectsEscapingAndDuplicateSelectors(t *testing.T) {
root := t.TempDir()
for _, configuration := range []Config{
{ProcRoot: "relative"},
{ProcRoot: root, CgroupRoot: root, ControlGroups: []Cgroup{{Name: "bad", Path: "../escape"}}},
{ProcRoot: root, Filesystems: []Filesystem{{Name: "same", Path: root}}, Processes: []Process{{Name: "same", PIDFile: filepath.Join(root, "pid")}}},
} {
if err := configuration.Validate(); err == nil {
t.Fatalf("invalid configuration accepted: %+v", configuration)
}
}
}
func createMinimalProc(t *testing.T) string {
t.Helper()
proc := filepath.Join(t.TempDir(), "proc")
if err := os.MkdirAll(filepath.Join(proc, "net"), 0o700); err != nil {
t.Fatal(err)
}
files := map[string]string{
"stat": "cpu 1 1 1 1\n", "uptime": "1 1\n",
"meminfo": "MemTotal: 1 kB\nMemAvailable: 1 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n",
"loadavg": "0 0 0 1/1 1\n", filepath.Join("net", "dev"): "Inter-| Receive | Transmit\n",
}
for name, body := range files {
if err := os.WriteFile(filepath.Join(proc, name), []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
return proc
}
+182
View File
@@ -0,0 +1,182 @@
// SPDX-License-Identifier: AGPL-3.0-only
package httpserver
import (
"errors"
"fmt"
"net/http"
"net/url"
"time"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/query"
"gamertan.com/observatory/internal/site"
"gamertan.com/web/access"
"gamertan.com/web/auth"
"gamertan.com/web/authhttp"
)
const defaultExploreQuery = "logs | window 1h | limit 50"
func (s *Server) explorePage(w http.ResponseWriter, r *http.Request) {
view, _, ok := s.exploreView(w, r, defaultExploreQuery)
if !ok {
return
}
s.renderHTML(w, r, http.StatusOK, site.Explore(view))
}
func (s *Server) exploreForm(w http.ResponseWriter, r *http.Request) {
values, err := readForm(w, r, 20<<10, "csrf_token", "query")
queryText := defaultExploreQuery
if err == nil {
queryText = values.Get("query")
}
view, token, ok := s.exploreView(w, r, queryText)
if !ok {
return
}
csrfOK := err == nil && authhttp.VerifyCSRF(token, "query:execute", values.Get("csrf_token"))
if !tokenBoundFormRequest(r, s.options.PublicOrigin, csrfOK) {
view.ErrorMessage = "This query form expired or could not be verified. Please try again."
s.renderHTML(w, r, http.StatusForbidden, site.Explore(view))
return
}
if err != nil {
view.ErrorMessage = "The query form was not accepted."
s.renderHTML(w, r, http.StatusBadRequest, site.Explore(view))
return
}
ast, err := query.Parse(queryText, s.options.MaxQueryRows)
if err != nil {
view.ErrorMessage = "The query could not be parsed. Check its stages, values, window, and limit."
s.renderHTML(w, r, http.StatusUnprocessableEntity, site.Explore(view))
return
}
principal, _ := auth.PrincipalFromContext(r.Context())
scope := access.Scope{OrganizationID: view.Organization.ID}
sensitive, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, scope, identity.PermissionTelemetryReadSensitive)
if err != nil {
view.ErrorMessage = "Authorization is temporarily unavailable."
s.renderHTML(w, r, http.StatusServiceUnavailable, site.Explore(view))
return
}
result, err := s.store.Query(r.Context(), ast, query.Scope{OrganizationID: view.Organization.ID, Sensitive: sensitive.Allowed}, s.options.QueryBudget, s.now())
switch {
case errors.Is(err, query.ErrSensitivePermissionRequired):
view.ErrorMessage = "This query requires permission to read sensitive fields."
s.renderHTML(w, r, http.StatusForbidden, site.Explore(view))
return
case errors.Is(err, query.ErrBudgetExceeded):
view.ErrorMessage = "This query exceeded its execution budget. Narrow the time window, fields, or result limit."
s.renderHTML(w, r, http.StatusUnprocessableEntity, site.Explore(view))
return
case errors.Is(err, query.ErrTypeMismatch):
view.ErrorMessage = "A query value did not match the selected field type."
s.renderHTML(w, r, http.StatusUnprocessableEntity, site.Explore(view))
return
case err != nil:
view.ErrorMessage = "The bounded query is temporarily unavailable. Your query text remains here to retry."
s.renderHTML(w, r, http.StatusServiceUnavailable, site.Explore(view))
return
}
view.Executed = true
view.Table = resultTable("Authorized query results", result)
view.Table.Empty = "No observations matched this query."
view.Stats = site.QueryStatsView{
ScannedRows: result.Stats.ScannedRows, MatchedRows: result.Stats.MatchedRows,
ScannedBytes: formatQueryBytes(result.Stats.ScannedBytes),
Duration: formatQueryDuration(result.Stats.DurationNS),
Truncated: result.Stats.Truncated, Approximate: result.Stats.Approximate,
}
s.renderHTML(w, r, http.StatusOK, site.Explore(view))
}
func (s *Server) exploreView(w http.ResponseWriter, r *http.Request, queryText string) (site.ExploreView, string, bool) {
principal, ok := auth.PrincipalFromContext(r.Context())
if !ok {
http.Redirect(w, r, "/login/", http.StatusSeeOther)
return site.ExploreView{}, "", false
}
values := r.URL.Query()
organizationID := values.Get("organization")
if len(values) != 1 || len(values["organization"]) != 1 || organizationID == "" {
writeProblem(w, http.StatusBadRequest, "organization is required")
return site.ExploreView{}, "", false
}
organizations, err := s.identity.OrganizationsForUser(r.Context(), principal.User.ID)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "organization list unavailable")
return site.ExploreView{}, "", false
}
organizationName := ""
for _, organization := range organizations {
if organization.ID == organizationID {
organizationName = organization.Name
break
}
}
if organizationName == "" {
writeProblem(w, http.StatusForbidden, "organization access denied")
return site.ExploreView{}, "", false
}
scope := access.Scope{OrganizationID: organizationID}
decision, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, scope, identity.PermissionTelemetryQuery)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "authorization unavailable")
return site.ExploreView{}, "", false
}
if !decision.Allowed {
writeProblem(w, http.StatusForbidden, "telemetry query access denied")
return site.ExploreView{}, "", false
}
if err = s.identity.ValidateResourceScope(r.Context(), scope); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid organization")
return site.ExploreView{}, "", false
}
token, ok := authhttp.SessionToken(r, s.cookie)
if !ok {
writeProblem(w, http.StatusUnauthorized, "authentication required")
return site.ExploreView{}, "", false
}
csrf, err := authhttp.CSRFToken(token, "query:execute")
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return site.ExploreView{}, "", false
}
view := site.ExploreView{
Head: s.head("Explore — Gamertan Observatory", "Run an authorized, bounded query against organization evidence.", "/app/explore/"),
DisplayName: principal.User.DisplayName,
Organization: site.OrganizationOption{ID: organizationID, Name: organizationName, Selected: true},
Query: queryText, CSRFToken: csrf,
EventsURL: "/app/events?organization=" + url.QueryEscape(organizationID),
}
return view, token, true
}
func formatQueryBytes(value int64) string {
if value < 1024 {
return fmt.Sprintf("%d B", value)
}
units := []string{"KiB", "MiB", "GiB", "TiB"}
amount := float64(value)
for _, unit := range units {
amount /= 1024
if amount < 1024 || unit == units[len(units)-1] {
return fmt.Sprintf("%.1f %s", amount, unit)
}
}
return fmt.Sprintf("%d B", value)
}
func formatQueryDuration(nanoseconds int64) string {
duration := time.Duration(nanoseconds)
if duration < time.Microsecond {
return duration.String()
}
if duration < time.Millisecond {
return duration.Round(time.Microsecond).String()
}
return duration.Round(time.Millisecond).String()
}
+281
View File
@@ -0,0 +1,281 @@
// SPDX-License-Identifier: AGPL-3.0-only
package httpserver
import (
"context"
"net/http"
"net/url"
"strconv"
"time"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/site"
"gamertan.com/observatory/internal/storage"
"gamertan.com/web/access"
"gamertan.com/web/auth"
"gamertan.com/web/authhttp"
)
// EvaluateAlerts performs one bounded due-rule pass. It publishes only a
// generic organization invalidation signal when an incident changed;
// telemetry and incident details never enter the SSE stream.
func (s *Server) EvaluateAlerts(ctx context.Context) (int, error) {
evaluations, err := s.store.EvaluateDueAlertRules(ctx, s.options.QueryBudget, s.now())
if err != nil {
return 0, err
}
organizations := map[string]struct{}{}
for _, evaluation := range evaluations {
if evaluation.IncidentChanged {
organizations[evaluation.OrganizationID] = struct{}{}
}
if evaluation.IncidentChanged && evaluation.IncidentState == "firing" && s.options.PushDispatcher != nil {
s.options.PushDispatcher.Enqueue(evaluation.OrganizationID)
}
}
for organizationID := range organizations {
s.refresh.publish(organizationID)
}
return len(evaluations), nil
}
func (s *Server) incidentInbox(w http.ResponseWriter, r *http.Request) {
principal, organizationID, organizationName, ok := s.authorizeIncidentRead(w, r)
if !ok {
return
}
scope := access.Scope{OrganizationID: organizationID}
incidents, err := s.store.Incidents(r.Context(), organizationID, true, 100)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "incidents unavailable")
return
}
rules, err := s.store.AlertRules(r.Context(), organizationID)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "alert rules unavailable")
return
}
saved, err := s.store.SavedQueries(r.Context(), organizationID)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "saved queries unavailable")
return
}
view := site.IncidentInboxView{
Head: s.head("Incident inbox — Gamertan Observatory", "Authorized incident response and bounded alert rules.", "/app/incidents/"),
DisplayName: principal.User.DisplayName,
Organization: site.OrganizationOption{ID: organizationID, Name: organizationName, Selected: true},
EventsURL: "/app/events?organization=" + url.QueryEscape(organizationID),
OfflineURL: "/app/incidents/offline/?organization=" + url.QueryEscape(organizationID),
CacheKey: "/app/incidents/?organization=" + url.QueryEscape(organizationID),
}
if s.options.PushDispatcher != nil {
token, sessionOK := authhttp.SessionToken(r, s.cookie)
if !sessionOK {
writeProblem(w, http.StatusUnauthorized, "authentication required")
return
}
view.PushPublicKey = s.options.PushPublicKey
view.PushCSRF, err = authhttp.CSRFToken(token, "push:manage")
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
}
for _, incident := range incidents {
item := site.IncidentSummary{ID: incident.ID, Title: incident.Title, State: incident.State, Severity: incident.Severity, StartedAt: incident.StartedAt.Format("2006-01-02 15:04:05 UTC"), UpdatedAt: incident.UpdatedAt.Format("2006-01-02 15:04:05 UTC")}
if incident.SilencedUntil != nil {
item.SilencedUntil = incident.SilencedUntil.Format("2006-01-02 15:04:05 UTC")
}
view.Incidents = append(view.Incidents, item)
if incident.State != "resolved" {
view.OpenCount++
}
}
for _, rule := range rules {
item := site.AlertRuleSummary{Name: rule.Name, Description: rule.Description, Severity: rule.Severity, Enabled: rule.Enabled, Interval: rule.EvaluationInterval.String(), LastError: rule.LastError}
if rule.LastEvaluatedAt != nil {
item.LastEvaluatedAt = rule.LastEvaluatedAt.Format("2006-01-02 15:04:05 UTC")
}
view.Rules = append(view.Rules, item)
}
for _, savedQuery := range saved {
view.SavedQueries = append(view.SavedQueries, site.SavedQuerySummary{ID: savedQuery.ID, Name: savedQuery.Name, Description: savedQuery.Description, Query: savedQuery.Query})
}
manage, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, scope, identity.PermissionIncidentsManage)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "authorization unavailable")
return
}
view.CanManage = manage.Allowed
if view.CanManage {
token, sessionOK := authhttp.SessionToken(r, s.cookie)
if !sessionOK {
writeProblem(w, http.StatusUnauthorized, "authentication required")
return
}
view.ManageCSRF, err = authhttp.CSRFToken(token, "incidents:manage")
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
}
s.renderHTML(w, r, http.StatusOK, site.IncidentInbox(view))
}
func (s *Server) offlineIncidentInbox(w http.ResponseWriter, r *http.Request) {
_, organizationID, organizationName, ok := s.authorizeIncidentRead(w, r)
if !ok {
return
}
incidents, err := s.store.Incidents(r.Context(), organizationID, false, 100)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "incidents unavailable")
return
}
view := site.OfflineIncidentView{
Head: s.head("Saved incident inbox — Gamertan Observatory", "A deliberately saved read-only incident snapshot.", "/app/incidents/"),
Organization: site.OrganizationOption{ID: organizationID, Name: organizationName, Selected: true},
CapturedAt: s.now().Format("2006-01-02 15:04:05 UTC"),
}
for _, incident := range incidents {
item := site.IncidentSummary{Title: incident.Title, State: incident.State, Severity: incident.Severity, StartedAt: incident.StartedAt.Format("2006-01-02 15:04:05 UTC"), UpdatedAt: incident.UpdatedAt.Format("2006-01-02 15:04:05 UTC")}
if incident.SilencedUntil != nil {
item.SilencedUntil = incident.SilencedUntil.Format("2006-01-02 15:04:05 UTC")
}
view.Incidents = append(view.Incidents, item)
}
s.renderHTML(w, r, http.StatusOK, site.OfflineIncidentInbox(view))
}
func (s *Server) authorizeIncidentRead(w http.ResponseWriter, r *http.Request) (auth.Principal, string, string, bool) {
principal, ok := auth.PrincipalFromContext(r.Context())
if !ok {
http.Redirect(w, r, "/login/", http.StatusSeeOther)
return auth.Principal{}, "", "", false
}
values := r.URL.Query()
organizationValues, exists := values["organization"]
if !exists || len(values) != 1 || len(organizationValues) != 1 || organizationValues[0] == "" {
writeProblem(w, http.StatusBadRequest, "incident organization is required")
return auth.Principal{}, "", "", false
}
organizationID := organizationValues[0]
scope := access.Scope{OrganizationID: organizationID}
decision, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, scope, identity.PermissionIncidentsRead)
if err != nil || !decision.Allowed {
writeProblem(w, http.StatusForbidden, "incident access denied")
return auth.Principal{}, "", "", false
}
if err = s.identity.ValidateResourceScope(r.Context(), scope); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid organization")
return auth.Principal{}, "", "", false
}
organizations, err := s.identity.OrganizationsForUser(r.Context(), principal.User.ID)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "organization unavailable")
return auth.Principal{}, "", "", false
}
for _, organization := range organizations {
if organization.ID == organizationID {
return principal, organizationID, organization.Name, true
}
}
writeProblem(w, http.StatusForbidden, "incident access denied")
return auth.Principal{}, "", "", false
}
func (s *Server) createAlertRule(w http.ResponseWriter, r *http.Request) {
values, principal, ok := s.authorizeIncidentForm(w, r, []string{"organization_id", "csrf_token", "name", "description", "saved_query_id", "severity", "minimum_matches", "required_consecutive", "evaluation_interval"}, nil)
if !ok {
return
}
minimumMatches, err := strconv.Atoi(values.Get("minimum_matches"))
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "alert rule rejected")
return
}
requiredConsecutive, err := strconv.Atoi(values.Get("required_consecutive"))
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "alert rule rejected")
return
}
intervals := map[string]time.Duration{"15s": 15 * time.Second, "30s": 30 * time.Second, "1m": time.Minute, "5m": 5 * time.Minute, "15m": 15 * time.Minute}
interval, exists := intervals[values.Get("evaluation_interval")]
if !exists {
writeProblem(w, http.StatusUnprocessableEntity, "alert rule rejected")
return
}
_, err = s.store.SaveAlertRule(r.Context(), storage.AlertRuleInput{
OrganizationID: values.Get("organization_id"), Name: values.Get("name"), Description: values.Get("description"),
SavedQueryID: values.Get("saved_query_id"), Severity: values.Get("severity"), MinimumMatches: minimumMatches,
RequiredConsecutive: requiredConsecutive, EvaluationInterval: interval, Enabled: true, ActorUserID: principal.User.ID,
}, s.now())
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "alert rule rejected")
return
}
http.Redirect(w, r, "/app/incidents/?organization="+url.QueryEscape(values.Get("organization_id")), http.StatusSeeOther)
}
func (s *Server) transitionIncident(w http.ResponseWriter, r *http.Request) {
values, principal, ok := s.authorizeIncidentForm(w, r, []string{"organization_id", "csrf_token", "action"}, []string{"silence_duration"})
if !ok {
return
}
var silenceUntil *time.Time
if values.Get("action") == "silence" {
durations := map[string]time.Duration{"15m": 15 * time.Minute, "1h": time.Hour, "6h": 6 * time.Hour, "24h": 24 * time.Hour, "168h": 7 * 24 * time.Hour}
duration, exists := durations[values.Get("silence_duration")]
if !exists {
writeProblem(w, http.StatusUnprocessableEntity, "incident transition rejected")
return
}
until := s.now().Add(duration)
silenceUntil = &until
} else if values.Get("silence_duration") != "" {
writeProblem(w, http.StatusUnprocessableEntity, "incident transition rejected")
return
}
_, err := s.store.TransitionIncident(r.Context(), values.Get("organization_id"), r.PathValue("id"), values.Get("action"), principal.User.ID, silenceUntil, s.now())
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "incident transition rejected")
return
}
s.refresh.publish(values.Get("organization_id"))
http.Redirect(w, r, "/app/incidents/?organization="+url.QueryEscape(values.Get("organization_id")), http.StatusSeeOther)
}
func (s *Server) authorizeIncidentForm(w http.ResponseWriter, r *http.Request, required, optional []string) (url.Values, auth.Principal, bool) {
principal, ok := auth.PrincipalFromContext(r.Context())
values, err := readFormFields(w, r, 24<<10, required, optional)
token, sessionOK := authhttp.SessionToken(r, s.cookie)
csrfOK := err == nil && sessionOK && authhttp.VerifyCSRF(token, "incidents:manage", values.Get("csrf_token"))
if !tokenBoundFormRequest(r, s.options.PublicOrigin, csrfOK) {
writeProblem(w, http.StatusForbidden, "valid incident form required")
return nil, auth.Principal{}, false
}
if !ok {
writeProblem(w, http.StatusUnauthorized, "authentication required")
return nil, auth.Principal{}, false
}
if err != nil {
writeProblem(w, http.StatusBadRequest, "invalid incident management request")
return nil, auth.Principal{}, false
}
scope := access.Scope{OrganizationID: values.Get("organization_id")}
decision, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, scope, identity.PermissionIncidentsManage)
if err != nil || !decision.Allowed {
writeProblem(w, http.StatusForbidden, "incident management denied")
return nil, auth.Principal{}, false
}
if err = s.identity.ValidateResourceScope(r.Context(), scope); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid organization")
return nil, auth.Principal{}, false
}
if !csrfOK {
writeProblem(w, http.StatusForbidden, "valid incident CSRF token required")
return nil, auth.Principal{}, false
}
return values, principal, true
}
+591
View File
@@ -0,0 +1,591 @@
// SPDX-License-Identifier: AGPL-3.0-only
package httpserver
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math"
"net/http"
"net/url"
"strconv"
"strings"
"unicode/utf8"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/query"
"gamertan.com/observatory/internal/site"
"gamertan.com/observatory/internal/storage"
"gamertan.com/web/access"
"gamertan.com/web/auth"
"gamertan.com/web/authhttp"
)
func (s *Server) createSavedQuery(w http.ResponseWriter, r *http.Request) {
values, principal, ok := s.authorizeManagementForm(w, r, "organization_id", "csrf_token", "name", "description", "query")
if !ok {
return
}
s.saveQuery(w, r, values, principal, values.Get("query"))
}
func (s *Server) createBuiltQuery(w http.ResponseWriter, r *http.Request) {
required := []string{"organization_id", "csrf_token", "name", "description", "signal", "filter_operator", "window", "aggregate", "limit"}
optional := []string{"filter_field", "filter_value", "aggregate_field", "group_by", "bucket"}
values, principal, ok := s.authorizeManagementFormFields(w, r, required, optional)
if !ok {
return
}
text, err := buildAssistedQuery(values, s.options.MaxQueryRows)
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "assisted query rejected")
return
}
s.saveQuery(w, r, values, principal, text)
}
func (s *Server) saveQuery(w http.ResponseWriter, r *http.Request, values url.Values, principal auth.Principal, text string) {
_, err := s.store.SaveQuery(r.Context(), storage.SavedQueryInput{
OrganizationID: values.Get("organization_id"), Name: values.Get("name"),
Description: values.Get("description"), Query: text,
ActorUserID: principal.User.ID, MaxRows: s.options.MaxQueryRows,
}, s.now())
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "saved query rejected")
return
}
http.Redirect(w, r, "/app/?organization="+url.QueryEscape(values.Get("organization_id"))+"#saved-work", http.StatusSeeOther)
}
func buildAssistedQuery(values url.Values, maxRows int) (string, error) {
allowed := func(value string, candidates ...string) bool {
for _, candidate := range candidates {
if value == candidate {
return true
}
}
return false
}
signal := values.Get("signal")
if !allowed(signal, "logs", "metrics", "traces", "deployments") {
return "", fmt.Errorf("unsupported signal")
}
window := values.Get("window")
if !allowed(window, "15m", "1h", "6h", "24h", "168h") {
return "", fmt.Errorf("unsupported window")
}
limit, err := strconv.Atoi(values.Get("limit"))
if err != nil || limit < 1 || limit > maxRows || !allowed(values.Get("limit"), "10", "20", "50", "100", "250") {
return "", fmt.Errorf("unsupported limit")
}
stages := []string{signal}
filterField := values.Get("filter_field")
filterValue := values.Get("filter_value")
filterOperator := values.Get("filter_operator")
if !allowed(filterOperator, "==", "!=", ">=", "<=", ">", "<") {
return "", fmt.Errorf("invalid filter comparison")
}
if filterField == "" {
if filterValue != "" {
return "", fmt.Errorf("filter value requires a field")
}
} else {
if !allowed(filterField, "service", "project", "environment", "route", "status", "duration", "name", "severity", "value", "trace_id", "correlation_id") ||
filterValue == "" || len(filterValue) > 256 || !utf8.ValidString(filterValue) || strings.IndexByte(filterValue, 0) >= 0 {
return "", fmt.Errorf("invalid filter")
}
quoted := strconv.Quote(filterValue)
quoted = strings.ReplaceAll(quoted, "|", `\u007c`)
stages = append(stages, "where "+filterField+" "+filterOperator+" "+quoted)
}
stages = append(stages, "window "+window)
aggregate := values.Get("aggregate")
aggregateField := values.Get("aggregate_field")
groupBy := values.Get("group_by")
bucket := values.Get("bucket")
if aggregate == "none" {
if aggregateField != "" || groupBy != "" || bucket != "" {
return "", fmt.Errorf("summary options require an aggregate")
}
} else {
if !allowed(aggregate, "count", "min", "max", "sum", "avg", "p50", "p95", "p99") ||
!allowed(groupBy, "", "service", "project", "environment", "route", "status", "name", "severity") ||
!allowed(bucket, "", "1m", "5m", "15m", "1h") {
return "", fmt.Errorf("invalid summary")
}
expression := "count()"
if aggregate == "count" {
if aggregateField != "" {
return "", fmt.Errorf("count accepts no field")
}
} else {
if !allowed(aggregateField, "value", "duration", "status") {
return "", fmt.Errorf("numeric aggregate field required")
}
expression = aggregate + "(" + aggregateField + ")"
}
groups := make([]string, 0, 2)
if groupBy != "" {
groups = append(groups, groupBy)
}
if bucket != "" {
groups = append(groups, "window("+bucket+")")
}
stage := "summarize " + expression
if len(groups) > 0 {
stage += " by " + strings.Join(groups, ", ")
}
stages = append(stages, stage)
}
stages = append(stages, "limit "+strconv.Itoa(limit))
text := strings.Join(stages, " | ")
if _, err = query.Parse(text, maxRows); err != nil {
return "", err
}
return text, nil
}
func (s *Server) createDashboard(w http.ResponseWriter, r *http.Request) {
values, principal, ok := s.authorizeManagementForm(w, r, "organization_id", "csrf_token", "slug", "name", "description", "panel_title", "saved_query_id", "visualization")
if !ok {
return
}
organizationID := values.Get("organization_id")
queryValue, err := s.store.SavedQuery(r.Context(), organizationID, values.Get("saved_query_id"))
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "dashboard query rejected")
return
}
visualization := values.Get("visualization")
if !validDashboardPresentation(queryValue, visualization) {
writeProblem(w, http.StatusUnprocessableEntity, "dashboard presentation does not match query")
return
}
_, err = s.store.SaveDashboard(r.Context(), storage.DashboardInput{
OrganizationID: organizationID, Slug: values.Get("slug"), Name: values.Get("name"),
Description: values.Get("description"), ActorUserID: principal.User.ID,
Panels: []storage.DashboardPanel{{Position: 0, Title: values.Get("panel_title"), Visualization: visualization, SavedQueryID: queryValue.ID}},
}, s.now())
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "dashboard rejected")
return
}
http.Redirect(w, r, "/app/dashboards/"+url.PathEscape(values.Get("slug"))+"/?organization="+url.QueryEscape(organizationID), http.StatusSeeOther)
}
func (s *Server) updateDashboard(w http.ResponseWriter, r *http.Request) {
values, principal, ok := s.authorizeManagementForm(w, r, "organization_id", "csrf_token", "dashboard_id", "expected_revision", "slug", "name", "description")
if !ok {
return
}
current, ok := s.dashboardForRevision(w, r, values)
if !ok {
return
}
updated, err := s.store.SaveDashboard(r.Context(), storage.DashboardInput{
ID: current.ID, ExpectedRevision: current.Revision, OrganizationID: current.OrganizationID,
Slug: values.Get("slug"), Name: values.Get("name"), Description: values.Get("description"),
Panels: current.Panels, ActorUserID: principal.User.ID,
}, s.now())
if !writeDashboardRevisionResult(w, err) {
return
}
redirectDashboard(w, r, updated.Slug, current.OrganizationID)
}
func (s *Server) addDashboardPanel(w http.ResponseWriter, r *http.Request) {
values, principal, ok := s.authorizeManagementForm(w, r, "organization_id", "csrf_token", "dashboard_id", "expected_revision", "panel_title", "saved_query_id", "visualization")
if !ok {
return
}
current, ok := s.dashboardForRevision(w, r, values)
if !ok {
return
}
queryValue, err := s.store.SavedQuery(r.Context(), current.OrganizationID, values.Get("saved_query_id"))
if err != nil || !validDashboardPresentation(queryValue, values.Get("visualization")) {
writeProblem(w, http.StatusUnprocessableEntity, "dashboard panel rejected")
return
}
panels := append([]storage.DashboardPanel(nil), current.Panels...)
panels = append(panels, storage.DashboardPanel{Position: len(panels), Title: values.Get("panel_title"), Visualization: values.Get("visualization"), SavedQueryID: queryValue.ID})
updated, err := s.store.SaveDashboard(r.Context(), storage.DashboardInput{
ID: current.ID, ExpectedRevision: current.Revision, OrganizationID: current.OrganizationID,
Slug: current.Slug, Name: current.Name, Description: current.Description,
Panels: panels, ActorUserID: principal.User.ID,
}, s.now())
if !writeDashboardRevisionResult(w, err) {
return
}
redirectDashboard(w, r, updated.Slug, current.OrganizationID)
}
func (s *Server) updateDashboardPanel(w http.ResponseWriter, r *http.Request) {
values, principal, ok := s.authorizeManagementForm(w, r, "organization_id", "csrf_token", "dashboard_id", "expected_revision", "panel_title", "saved_query_id", "visualization")
if !ok {
return
}
current, ok := s.dashboardForRevision(w, r, values)
if !ok {
return
}
queryValue, err := s.store.SavedQuery(r.Context(), current.OrganizationID, values.Get("saved_query_id"))
if err != nil || !validDashboardPresentation(queryValue, values.Get("visualization")) {
writeProblem(w, http.StatusUnprocessableEntity, "dashboard panel rejected")
return
}
panelID := r.PathValue("panel")
panels := append([]storage.DashboardPanel(nil), current.Panels...)
found := false
for index := range panels {
if panels[index].ID != panelID {
continue
}
panels[index].Title = values.Get("panel_title")
panels[index].Visualization = values.Get("visualization")
panels[index].SavedQueryID = queryValue.ID
found = true
break
}
if !found {
writeProblem(w, http.StatusNotFound, "dashboard panel not found")
return
}
updated, err := s.store.SaveDashboard(r.Context(), storage.DashboardInput{
ID: current.ID, ExpectedRevision: current.Revision, OrganizationID: current.OrganizationID,
Slug: current.Slug, Name: current.Name, Description: current.Description,
Panels: panels, ActorUserID: principal.User.ID,
}, s.now())
if !writeDashboardRevisionResult(w, err) {
return
}
redirectDashboard(w, r, updated.Slug, current.OrganizationID)
}
func (s *Server) removeDashboardPanel(w http.ResponseWriter, r *http.Request) {
values, principal, ok := s.authorizeManagementForm(w, r, "organization_id", "csrf_token", "dashboard_id", "expected_revision")
if !ok {
return
}
current, ok := s.dashboardForRevision(w, r, values)
if !ok {
return
}
panelID := r.PathValue("panel")
panels := make([]storage.DashboardPanel, 0, len(current.Panels))
for _, panel := range current.Panels {
if panel.ID != panelID {
panel.Position = len(panels)
panels = append(panels, panel)
}
}
if len(panels) == len(current.Panels) {
writeProblem(w, http.StatusNotFound, "dashboard panel not found")
return
}
updated, err := s.store.SaveDashboard(r.Context(), storage.DashboardInput{
ID: current.ID, ExpectedRevision: current.Revision, OrganizationID: current.OrganizationID,
Slug: current.Slug, Name: current.Name, Description: current.Description,
Panels: panels, ActorUserID: principal.User.ID,
}, s.now())
if !writeDashboardRevisionResult(w, err) {
return
}
redirectDashboard(w, r, updated.Slug, current.OrganizationID)
}
func (s *Server) dashboardForRevision(w http.ResponseWriter, r *http.Request, values url.Values) (storage.Dashboard, bool) {
current, err := s.store.Dashboard(r.Context(), values.Get("organization_id"), r.PathValue("slug"))
if err != nil {
writeProblem(w, http.StatusNotFound, "dashboard not found")
return storage.Dashboard{}, false
}
revision, err := strconv.Atoi(values.Get("expected_revision"))
if err != nil || revision < 1 || values.Get("dashboard_id") != current.ID {
writeProblem(w, http.StatusBadRequest, "dashboard revision is invalid")
return storage.Dashboard{}, false
}
if revision != current.Revision {
writeProblem(w, http.StatusConflict, "dashboard changed; reload before editing")
return storage.Dashboard{}, false
}
return current, true
}
func validDashboardPresentation(saved storage.SavedQuery, visualization string) bool {
switch visualization {
case "table":
return true
case "stat":
return saved.AST.Summary != nil
case "timeseries":
return saved.AST.Summary != nil && saved.AST.Bucket > 0
default:
return false
}
}
func writeDashboardRevisionResult(w http.ResponseWriter, err error) bool {
if err == nil {
return true
}
if errors.Is(err, storage.ErrDashboardRevisionConflict) {
writeProblem(w, http.StatusConflict, "dashboard changed; reload before editing")
} else {
writeProblem(w, http.StatusUnprocessableEntity, "dashboard revision rejected")
}
return false
}
func redirectDashboard(w http.ResponseWriter, r *http.Request, slug, organizationID string) {
http.Redirect(w, r, "/app/dashboards/"+url.PathEscape(slug)+"/?organization="+url.QueryEscape(organizationID), http.StatusSeeOther)
}
func (s *Server) authorizeManagementForm(w http.ResponseWriter, r *http.Request, fields ...string) (url.Values, auth.Principal, bool) {
return s.authorizeManagementFormFields(w, r, fields, nil)
}
func (s *Server) authorizeManagementFormFields(w http.ResponseWriter, r *http.Request, required, optional []string) (url.Values, auth.Principal, bool) {
principal, ok := auth.PrincipalFromContext(r.Context())
values, err := readFormFields(w, r, 24<<10, required, optional)
token, sessionOK := authhttp.SessionToken(r, s.cookie)
csrfOK := err == nil && sessionOK && authhttp.VerifyCSRF(token, "dashboards:manage", values.Get("csrf_token"))
if !tokenBoundFormRequest(r, s.options.PublicOrigin, csrfOK) {
writeProblem(w, http.StatusForbidden, "valid dashboard form required")
return nil, auth.Principal{}, false
}
if !ok {
writeProblem(w, http.StatusUnauthorized, "authentication required")
return nil, auth.Principal{}, false
}
if err != nil {
writeProblem(w, http.StatusBadRequest, "invalid dashboard management request")
return nil, auth.Principal{}, false
}
organizationID := values.Get("organization_id")
scope := access.Scope{OrganizationID: organizationID}
if err = s.identity.ValidateResourceScope(r.Context(), scope); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid organization")
return nil, auth.Principal{}, false
}
decision, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, scope, identity.PermissionDashboardsManage)
if err != nil || !decision.Allowed {
writeProblem(w, http.StatusForbidden, "dashboard management denied")
return nil, auth.Principal{}, false
}
if !csrfOK {
writeProblem(w, http.StatusForbidden, "valid dashboard CSRF token required")
return nil, auth.Principal{}, false
}
return values, principal, true
}
func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) {
organizationID, principal, ok := s.authorizeDashboardRead(w, r)
if !ok {
return
}
dashboard, err := s.store.Dashboard(r.Context(), organizationID, r.PathValue("slug"))
if err != nil {
writeProblem(w, http.StatusNotFound, "dashboard not found")
return
}
organizations, err := s.identity.OrganizationsForUser(r.Context(), principal.User.ID)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "organization unavailable")
return
}
organizationName := "Organization"
for _, organization := range organizations {
if organization.ID == organizationID {
organizationName = organization.Name
break
}
}
view := site.DashboardView{
Head: s.head(dashboard.Name+" — Gamertan Observatory", dashboard.Description, "/app/dashboards/"+url.PathEscape(dashboard.Slug)+"/"),
DisplayName: principal.User.DisplayName, Organization: site.OrganizationOption{ID: organizationID, Name: organizationName, Selected: true},
ID: dashboard.ID, Slug: dashboard.Slug, Revision: dashboard.Revision,
Name: dashboard.Name, Description: dashboard.Description,
ExportURL: "/app/dashboards/" + url.PathEscape(dashboard.Slug) + "/export.json?organization=" + url.QueryEscape(organizationID),
}
manage, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, access.Scope{OrganizationID: organizationID}, identity.PermissionDashboardsManage)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "authorization unavailable")
return
}
view.CanManage = manage.Allowed
if view.CanManage {
token, sessionOK := authhttp.SessionToken(r, s.cookie)
if !sessionOK {
writeProblem(w, http.StatusUnauthorized, "authentication required")
return
}
view.ManageCSRF, err = authhttp.CSRFToken(token, "dashboards:manage")
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
savedQueries, loadErr := s.store.SavedQueries(r.Context(), organizationID)
if loadErr != nil {
writeProblem(w, http.StatusServiceUnavailable, "saved queries unavailable")
return
}
for _, saved := range savedQueries {
view.SavedQueries = append(view.SavedQueries, site.SavedQuerySummary{ID: saved.ID, Name: saved.Name, Description: saved.Description, Query: saved.Query})
}
}
for _, panel := range dashboard.Panels {
view.Panels = append(view.Panels, s.dashboardPanel(r, principal.User.ID, organizationID, panel))
}
s.renderHTML(w, r, http.StatusOK, site.Dashboard(view))
}
func (s *Server) dashboardPanel(r *http.Request, userID, organizationID string, panel storage.DashboardPanel) site.PanelView {
view := site.PanelView{ID: panel.ID, SavedQueryID: panel.SavedQueryID, Title: panel.Title, Visualization: panel.Visualization, Table: site.TableView{Caption: panel.Title, Columns: []site.TableColumn{{Label: "Status"}}, Empty: "Panel data is unavailable."}}
saved, err := s.store.SavedQuery(r.Context(), organizationID, panel.SavedQueryID)
if err != nil {
return view
}
view.Query = saved.Query
scope := access.Scope{OrganizationID: organizationID, ProjectID: saved.Scope.ProjectID, EnvironmentID: saved.Scope.EnvironmentID, ServiceID: saved.Scope.ServiceID}
decision, err := s.identity.Access.Authorize(r.Context(), userID, scope, identity.PermissionTelemetryQuery)
if err != nil || !decision.Allowed || s.identity.ValidateResourceScope(r.Context(), scope) != nil {
return view
}
sensitive, err := s.identity.Access.Authorize(r.Context(), userID, scope, identity.PermissionTelemetryReadSensitive)
if err != nil {
return view
}
result, err := s.store.Query(r.Context(), saved.AST, query.Scope{OrganizationID: organizationID, ProjectID: saved.Scope.ProjectID, EnvironmentID: saved.Scope.EnvironmentID, ServiceID: saved.Scope.ServiceID, Sensitive: sensitive.Allowed}, s.options.QueryBudget, s.now())
if err != nil {
return view
}
view.Table = resultTable(panel.Title, result)
if panel.Visualization == "timeseries" {
view.Chart = resultChart(panel.Title, result)
}
if panel.Visualization == "stat" {
for _, row := range result.Rows {
for _, value := range row.Values {
if value != nil {
view.Stat = boundedCell(*value)
return view
}
}
}
}
return view
}
func resultChart(title string, result query.Result) site.ChartView {
if len(result.Columns) < 2 || len(result.Rows) == 0 {
return site.ChartView{}
}
valueIndex := len(result.Columns) - 1
valueType := result.Columns[valueIndex].Type
if valueType != "integer" && valueType != "float" && valueType != "duration" {
return site.ChartView{}
}
const maxPoints = 48
points := make([]struct {
label, display string
value float64
}, 0, min(len(result.Rows), maxPoints))
maximum := float64(0)
for index, row := range result.Rows {
if index >= maxPoints || valueIndex >= len(row.Values) || row.Values[valueIndex] == nil {
continue
}
value, err := strconv.ParseFloat(*row.Values[valueIndex], 64)
if err != nil || math.IsNaN(value) || math.IsInf(value, 0) || value < 0 {
return site.ChartView{}
}
labels := make([]string, 0, valueIndex)
for column := 0; column < valueIndex && column < len(row.Values); column++ {
if row.Values[column] != nil {
labels = append(labels, boundedCell(*row.Values[column]))
}
}
label := boundedCell(strings.Join(labels, " · "))
if label == "" {
label = fmt.Sprintf("Point %d", index+1)
}
display := boundedCell(*row.Values[valueIndex])
if unit := result.Columns[valueIndex].Unit; unit != "" {
display += " " + boundedCell(unit)
}
points = append(points, struct {
label, display string
value float64
}{label: label, display: display, value: value})
maximum = math.Max(maximum, value)
}
if len(points) == 0 {
return site.ChartView{}
}
if maximum == 0 {
maximum = 1
}
view := site.ChartView{Label: title + " visual summary"}
for _, point := range points {
view.Points = append(view.Points, site.ChartPoint{
Label: point.label, Value: strconv.FormatFloat(point.value, 'g', -1, 64),
Maximum: strconv.FormatFloat(maximum, 'g', -1, 64), Display: point.display,
})
}
return view
}
func (s *Server) exportDashboard(w http.ResponseWriter, r *http.Request) {
organizationID, _, ok := s.authorizeDashboardRead(w, r)
if !ok {
return
}
exported, err := s.store.ExportDashboard(r.Context(), organizationID, r.PathValue("slug"))
if err != nil {
writeProblem(w, http.StatusNotFound, "dashboard not found")
return
}
var body bytes.Buffer
encoder := json.NewEncoder(&body)
encoder.SetIndent("", " ")
if err = encoder.Encode(exported); err != nil {
writeProblem(w, http.StatusInternalServerError, "dashboard export unavailable")
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", "observatory-dashboard-"+r.PathValue("slug")+".json"))
w.Header().Set("Content-Length", fmt.Sprintf("%d", body.Len()))
if r.Method != http.MethodHead {
_, _ = w.Write(body.Bytes())
}
}
func (s *Server) authorizeDashboardRead(w http.ResponseWriter, r *http.Request) (string, auth.Principal, bool) {
principal, ok := auth.PrincipalFromContext(r.Context())
if !ok {
writeProblem(w, http.StatusUnauthorized, "authentication required")
return "", auth.Principal{}, false
}
values := r.URL.Query()
organizationID := values.Get("organization")
if len(values) != 1 || len(values["organization"]) != 1 || organizationID == "" {
writeProblem(w, http.StatusBadRequest, "organization is required")
return "", auth.Principal{}, false
}
scope := access.Scope{OrganizationID: organizationID}
if err := s.identity.ValidateResourceScope(r.Context(), scope); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid organization")
return "", auth.Principal{}, false
}
decision, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, scope, identity.PermissionDashboardsRead)
if err != nil || !decision.Allowed {
writeProblem(w, http.StatusForbidden, "dashboard access denied")
return "", auth.Principal{}, false
}
return organizationID, principal, true
}
@@ -0,0 +1,103 @@
// SPDX-License-Identifier: AGPL-3.0-only
package httpserver
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/nativeprotocol"
"gamertan.com/observatory/internal/storage"
)
func BenchmarkNativeExactReplay(b *testing.B) {
root := filepath.Join(b.TempDir(), "data")
if err := os.Mkdir(root, 0o700); err != nil {
b.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
b.Fatal(err)
}
defer store.Close()
identities, err := identity.Open(root)
if err != nil {
b.Fatal(err)
}
defer identities.Close()
token, err := store.CreateSource(context.Background(), "source", model.Scope{OrganizationID: "org", ProjectID: "project", EnvironmentID: "production", ServiceID: "service"})
if err != nil {
b.Fatal(err)
}
now := time.Date(2026, 8, 18, 20, 0, 0, 0, time.UTC)
server, err := New(store, identities, testOptions())
if err != nil {
b.Fatal(err)
}
server.now = func() time.Time { return now }
handler := server.Handler()
legacy := model.Batch{Version: model.BatchVersion, SourceID: "source", StreamID: "legacy", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: benchmarkRecords(now)}
legacyBody, _ := json.Marshal(legacy)
framed := legacy
framed.StreamID = "framed"
framedBody, _ := json.Marshal(framed)
framedEnvelope, _ := framed.Envelope(framedBody)
seed := func(path string, body []byte, envelope *model.BatchEnvelope) {
request := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body))
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Content-Type", "application/json")
if envelope != nil {
nativeprotocol.SetHeaders(request.Header, *envelope)
}
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != http.StatusAccepted {
b.Fatalf("seed %s: %d %s", path, response.Code, response.Body.String())
}
}
seed("/api/v1/ingest/native", legacyBody, nil)
seed("/api/v2/ingest/native", framedBody, &framedEnvelope)
for _, benchmark := range []struct {
name string
path string
body []byte
envelope *model.BatchEnvelope
}{{"legacy-v1", "/api/v1/ingest/native", legacyBody, nil}, {"framed-v2", "/api/v2/ingest/native", framedBody, &framedEnvelope}} {
b.Run(benchmark.name, func(b *testing.B) {
b.ReportAllocs()
b.SetBytes(int64(len(benchmark.body)))
for range b.N {
request := httptest.NewRequest(http.MethodPost, benchmark.path, bytes.NewReader(benchmark.body))
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Content-Type", "application/json")
if benchmark.envelope != nil {
nativeprotocol.SetHeaders(request.Header, *benchmark.envelope)
}
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != http.StatusAccepted {
b.Fatalf("status=%d body=%s", response.Code, response.Body.String())
}
}
})
}
}
func benchmarkRecords(now time.Time) []model.Observation {
records := make([]model.Observation, 500)
for index := range records {
records[index] = model.Observation{Timestamp: now, Name: "http.request", Attributes: map[string]string{"route": "/items", "status": "200", "method": "GET"}}
}
return records
}
+132
View File
@@ -0,0 +1,132 @@
// SPDX-License-Identifier: AGPL-3.0-only
package httpserver
import (
"crypto/ecdh"
"encoding/base64"
"net/http"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/storage"
"gamertan.com/observatory/internal/webpush"
"gamertan.com/web/access"
"gamertan.com/web/auth"
"gamertan.com/web/authhttp"
"gamertan.com/web/websec"
)
type pushSubscriptionRequest struct {
OrganizationID string `json:"organization_id"`
Endpoint string `json:"endpoint"`
Keys struct {
P256DH string `json:"p256dh"`
Auth string `json:"auth"`
} `json:"keys"`
}
func (s *Server) savePushSubscription(w http.ResponseWriter, r *http.Request) {
request, principal, ok := s.authorizePushRequest(w, r)
if !ok {
return
}
p256dh, p256Err := base64.RawURLEncoding.DecodeString(request.Keys.P256DH)
authSecret, authErr := base64.RawURLEncoding.DecodeString(request.Keys.Auth)
if p256Err != nil || authErr != nil || len(p256dh) != 65 || len(authSecret) != 16 {
writeProblem(w, http.StatusUnprocessableEntity, "push subscription rejected")
return
}
if _, err := ecdh.P256().NewPublicKey(p256dh); err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "push subscription rejected")
return
}
if _, err := webpush.ValidateEndpoint(request.Endpoint); err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "push subscription rejected")
return
}
subscription, err := s.store.SavePushSubscription(r.Context(), storage.PushSubscriptionInput{OrganizationID: request.OrganizationID, UserID: principal.User.ID, Endpoint: request.Endpoint, P256DH: p256dh, Auth: authSecret}, s.now())
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "push subscription rejected")
return
}
writeJSON(w, http.StatusCreated, struct {
ID string `json:"id"`
}{subscription.ID})
}
func (s *Server) deletePushSubscription(w http.ResponseWriter, r *http.Request) {
request, principal, ok := s.authorizePushRequest(w, r)
if !ok {
return
}
if _, err := webpush.ValidateEndpoint(request.Endpoint); err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "push subscription rejected")
return
}
remaining, err := s.store.DeletePushSubscription(r.Context(), request.OrganizationID, principal.User.ID, request.Endpoint)
if err != nil {
writeProblem(w, http.StatusNotFound, "push subscription not found")
return
}
writeJSON(w, http.StatusOK, struct {
Remaining bool `json:"remaining"`
}{remaining})
}
func (s *Server) pushSubscriptionStatus(w http.ResponseWriter, r *http.Request) {
request, principal, ok := s.authorizePushRequest(w, r)
if !ok {
return
}
if _, err := webpush.ValidateEndpoint(request.Endpoint); err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "push subscription rejected")
return
}
subscribed, err := s.store.HasPushSubscription(r.Context(), request.OrganizationID, principal.User.ID, request.Endpoint)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "push subscription status unavailable")
return
}
writeJSON(w, http.StatusOK, struct {
Subscribed bool `json:"subscribed"`
}{subscribed})
}
func (s *Server) authorizePushRequest(w http.ResponseWriter, r *http.Request) (pushSubscriptionRequest, auth.Principal, bool) {
if s.options.PushDispatcher == nil {
writeProblem(w, http.StatusNotFound, "Web Push is not configured")
return pushSubscriptionRequest{}, auth.Principal{}, false
}
if !websec.SameOrigin(r, s.options.PublicOrigin) {
writeProblem(w, http.StatusForbidden, "same-origin request required")
return pushSubscriptionRequest{}, auth.Principal{}, false
}
principal, ok := auth.PrincipalFromContext(r.Context())
if !ok {
writeProblem(w, http.StatusUnauthorized, "authentication required")
return pushSubscriptionRequest{}, auth.Principal{}, false
}
body := http.MaxBytesReader(w, r.Body, 8<<10)
defer body.Close()
var request pushSubscriptionRequest
if err := decodeOne(body, &request); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid push subscription request")
return pushSubscriptionRequest{}, auth.Principal{}, false
}
scope := access.Scope{OrganizationID: request.OrganizationID}
decision, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, scope, identity.PermissionIncidentsRead)
if err != nil || !decision.Allowed {
writeProblem(w, http.StatusForbidden, "incident access denied")
return pushSubscriptionRequest{}, auth.Principal{}, false
}
if err = s.identity.ValidateResourceScope(r.Context(), scope); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid organization")
return pushSubscriptionRequest{}, auth.Principal{}, false
}
token, sessionOK := authhttp.SessionToken(r, s.cookie)
if !sessionOK || !authhttp.VerifyCSRF(token, "push:manage", r.Header.Get("X-CSRF-Token")) {
writeProblem(w, http.StatusForbidden, "valid push CSRF token required")
return pushSubscriptionRequest{}, auth.Principal{}, false
}
return request, principal, true
}
+32
View File
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: AGPL-3.0-only
package httpserver
import (
"fmt"
"net/http"
"gamertan.com/observatory/internal/site"
)
func (s *Server) webManifest(w http.ResponseWriter, r *http.Request) {
serveFixedBody(w, r, site.WebManifest(), "application/manifest+json")
}
func (s *Server) serviceWorker(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Service-Worker-Allowed", "/")
serveFixedBody(w, r, site.ServiceWorker(), "text/javascript; charset=utf-8")
}
func (s *Server) offlineShell(w http.ResponseWriter, r *http.Request) {
s.renderHTML(w, r, http.StatusOK, site.Offline(site.OfflineView{Head: s.head("Offline — Gamertan Observatory", "Observatory is temporarily unreachable.", "/offline/")}))
}
func serveFixedBody(w http.ResponseWriter, r *http.Request, body []byte, contentType string) {
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body)))
if r.Method != http.MethodHead {
_, _ = w.Write(body)
}
}
+71
View File
@@ -0,0 +1,71 @@
// SPDX-License-Identifier: AGPL-3.0-only
package httpserver
import (
"errors"
"sync"
)
var errRefreshCapacity = errors.New("live refresh capacity reached")
// refreshHub carries only a coalescible invalidation signal. It never carries
// telemetry, resource names, incident details, or credentials.
type refreshHub struct {
mu sync.Mutex
next uint64
total int
maxTotal int
maxPerOrganization int
subscribers map[string]map[uint64]chan struct{}
}
func newRefreshHub(maxTotal, maxPerOrganization int) *refreshHub {
return &refreshHub{maxTotal: maxTotal, maxPerOrganization: maxPerOrganization, subscribers: make(map[string]map[uint64]chan struct{})}
}
func (hub *refreshHub) subscribe(organizationID string) (<-chan struct{}, func(), error) {
hub.mu.Lock()
defer hub.mu.Unlock()
group := hub.subscribers[organizationID]
if hub.total >= hub.maxTotal || len(group) >= hub.maxPerOrganization {
return nil, nil, errRefreshCapacity
}
if group == nil {
group = make(map[uint64]chan struct{})
hub.subscribers[organizationID] = group
}
hub.next++
id := hub.next
updates := make(chan struct{}, 1)
group[id] = updates
hub.total++
var once sync.Once
remove := func() {
once.Do(func() {
hub.mu.Lock()
defer hub.mu.Unlock()
if current := hub.subscribers[organizationID]; current != nil {
if _, exists := current[id]; exists {
delete(current, id)
hub.total--
}
if len(current) == 0 {
delete(hub.subscribers, organizationID)
}
}
})
}
return updates, remove, nil
}
func (hub *refreshHub) publish(organizationID string) {
hub.mu.Lock()
defer hub.mu.Unlock()
for _, updates := range hub.subscribers[organizationID] {
select {
case updates <- struct{}{}:
default:
}
}
}
+53
View File
@@ -0,0 +1,53 @@
// SPDX-License-Identifier: AGPL-3.0-only
package httpserver
import (
"errors"
"testing"
)
func TestRefreshHubIsBoundedCoalescedAndOrganizationScoped(t *testing.T) {
hub := newRefreshHub(2, 1)
first, removeFirst, err := hub.subscribe("organization-a")
if err != nil {
t.Fatal(err)
}
defer removeFirst()
if _, _, err = hub.subscribe("organization-a"); !errors.Is(err, errRefreshCapacity) {
t.Fatalf("same-organization capacity err=%v", err)
}
second, removeSecond, err := hub.subscribe("organization-b")
if err != nil {
t.Fatal(err)
}
defer removeSecond()
if _, _, err = hub.subscribe("organization-c"); !errors.Is(err, errRefreshCapacity) {
t.Fatalf("total capacity err=%v", err)
}
hub.publish("organization-a")
hub.publish("organization-a")
select {
case <-first:
default:
t.Fatal("organization A did not receive refresh")
}
select {
case <-first:
t.Fatal("duplicate refresh was not coalesced")
default:
}
select {
case <-second:
t.Fatal("organization B received organization A refresh")
default:
}
removeFirst()
if _, removeReplacement, err := hub.subscribe("organization-a"); err != nil {
t.Fatalf("released capacity was not reusable: %v", err)
} else {
removeReplacement()
}
}
+810
View File
@@ -0,0 +1,810 @@
// SPDX-License-Identifier: AGPL-3.0-only
package httpserver
import (
"bytes"
"compress/gzip"
"crypto/ecdh"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"strings"
"time"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/nativeprotocol"
"gamertan.com/observatory/internal/otlp"
"gamertan.com/observatory/internal/query"
"gamertan.com/observatory/internal/storage"
"gamertan.com/web/access"
"gamertan.com/web/auth"
"gamertan.com/web/authhttp"
"gamertan.com/web/requestmeta"
"gamertan.com/web/websec"
)
type Options struct {
PublicOrigin string
MaxBodyBytes int64
MaxConcurrentIngest int
MaxQueryRows int
QueryBudget query.Budget
SessionLifetime time.Duration
PushPublicKey string
PushDispatcher PushDispatcher
}
type PushDispatcher interface {
Enqueue(organizationID string) bool
}
type Server struct {
store *storage.Store
identity *identity.Services
options Options
cookie authhttp.CookieConfig
now func() time.Time
refresh *refreshHub
requests *requestmeta.Resolver
ingestSlots chan struct{}
}
func New(store *storage.Store, identities *identity.Services, options Options) (*Server, error) {
if store == nil || identities == nil || identities.Auth == nil || identities.Access == nil {
return nil, errors.New("server storage and identity services are required")
}
origin, err := url.Parse(options.PublicOrigin)
if err != nil || origin.Scheme != "https" || origin.Host == "" || origin.User != nil || origin.Path != "" && origin.Path != "/" || origin.RawQuery != "" || origin.Fragment != "" {
return nil, errors.New("server public origin must be an absolute HTTPS origin")
}
options.PublicOrigin = strings.TrimSuffix(options.PublicOrigin, "/")
if options.MaxConcurrentIngest == 0 {
options.MaxConcurrentIngest = 8
}
if options.MaxBodyBytes < 1024 || options.MaxConcurrentIngest < 1 || options.MaxConcurrentIngest > 64 || options.MaxQueryRows < 1 || options.SessionLifetime < 5*time.Minute || options.SessionLifetime > 30*24*time.Hour {
return nil, errors.New("server limits are invalid")
}
if options.QueryBudget.MaxRows != options.MaxQueryRows || options.QueryBudget.MaxDuration < time.Millisecond || options.QueryBudget.MaxScannedBytes < 1 || options.QueryBudget.MaxMemoryBytes < 1 {
return nil, errors.New("server query budget is invalid")
}
if (options.PushPublicKey == "") != (options.PushDispatcher == nil) {
return nil, errors.New("server Web Push key and dispatcher must be configured together")
}
if options.PushPublicKey != "" {
publicKey, decodeErr := base64.RawURLEncoding.DecodeString(options.PushPublicKey)
if decodeErr != nil || len(publicKey) != 65 {
return nil, errors.New("server Web Push public key is invalid")
}
if _, decodeErr = ecdh.P256().NewPublicKey(publicKey); decodeErr != nil {
return nil, errors.New("server Web Push public key is invalid")
}
}
cookie := authhttp.CookieConfig{Name: "__Host-observatory_session", Lifetime: options.SessionLifetime, SameSite: http.SameSiteStrictMode}
if err = cookie.Validate(); err != nil {
return nil, err
}
requests, err := requestmeta.New(requestmeta.Config{})
if err != nil {
return nil, fmt.Errorf("server request metadata: %w", err)
}
return &Server{store: store, identity: identities, options: options, cookie: cookie, now: func() time.Time { return time.Now().UTC() }, refresh: newRefreshHub(256, 8), requests: requests, ingestSlots: make(chan struct{}, options.MaxConcurrentIngest)}, nil
}
func (s *Server) enterIngest(w http.ResponseWriter) (func(), bool) {
select {
case s.ingestSlots <- struct{}{}:
return func() { <-s.ingestSlots }, true
default:
w.Header().Set("Retry-After", "1")
writeProblem(w, http.StatusServiceUnavailable, "ingestion capacity temporarily unavailable")
return nil, false
}
}
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", textOK("ok\n"))
mux.HandleFunc("HEAD /healthz", textOK("ok\n"))
mux.HandleFunc("GET /readyz", textOK("ready\n"))
mux.HandleFunc("HEAD /readyz", textOK("ready\n"))
mux.HandleFunc("GET /{$}", s.landing)
mux.HandleFunc("HEAD /{$}", s.landing)
mux.HandleFunc("GET /manifest.webmanifest", s.webManifest)
mux.HandleFunc("HEAD /manifest.webmanifest", s.webManifest)
mux.HandleFunc("GET /service-worker.js", s.serviceWorker)
mux.HandleFunc("HEAD /service-worker.js", s.serviceWorker)
mux.HandleFunc("GET /offline/{$}", s.offlineShell)
mux.HandleFunc("HEAD /offline/{$}", s.offlineShell)
mux.HandleFunc("GET /login/{$}", s.loginPage)
mux.HandleFunc("HEAD /login/{$}", s.loginPage)
mux.HandleFunc("POST /login/{$}", s.loginForm)
mux.HandleFunc("POST /logout/{$}", s.logoutForm)
mux.HandleFunc("GET /account/password/{$}", s.passwordPage)
mux.HandleFunc("HEAD /account/password/{$}", s.passwordPage)
mux.HandleFunc("POST /account/password/{$}", s.passwordForm)
mux.HandleFunc("GET /app/{$}", s.app)
mux.HandleFunc("HEAD /app/{$}", s.app)
mux.HandleFunc("GET /app/explore/{$}", s.explorePage)
mux.HandleFunc("HEAD /app/explore/{$}", s.explorePage)
mux.HandleFunc("POST /app/explore/{$}", s.exploreForm)
mux.HandleFunc("GET /app/events", s.events)
mux.HandleFunc("POST /app/queries/{$}", s.createSavedQuery)
mux.HandleFunc("POST /app/queries/builder/{$}", s.createBuiltQuery)
mux.HandleFunc("POST /app/dashboards/{$}", s.createDashboard)
mux.HandleFunc("GET /app/dashboards/{slug}/{$}", s.dashboard)
mux.HandleFunc("HEAD /app/dashboards/{slug}/{$}", s.dashboard)
mux.HandleFunc("POST /app/dashboards/{slug}/{$}", s.updateDashboard)
mux.HandleFunc("POST /app/dashboards/{slug}/panels/{$}", s.addDashboardPanel)
mux.HandleFunc("POST /app/dashboards/{slug}/panels/{panel}/{$}", s.updateDashboardPanel)
mux.HandleFunc("POST /app/dashboards/{slug}/panels/{panel}/remove/{$}", s.removeDashboardPanel)
mux.HandleFunc("GET /app/dashboards/{slug}/export.json", s.exportDashboard)
mux.HandleFunc("HEAD /app/dashboards/{slug}/export.json", s.exportDashboard)
mux.HandleFunc("GET /app/incidents/{$}", s.incidentInbox)
mux.HandleFunc("HEAD /app/incidents/{$}", s.incidentInbox)
mux.HandleFunc("GET /app/incidents/offline/{$}", s.offlineIncidentInbox)
mux.HandleFunc("HEAD /app/incidents/offline/{$}", s.offlineIncidentInbox)
mux.HandleFunc("POST /app/alert-rules/{$}", s.createAlertRule)
mux.HandleFunc("POST /app/incidents/{id}/{$}", s.transitionIncident)
mux.HandleFunc("GET /assets/", s.serveAsset)
mux.HandleFunc("HEAD /assets/", s.serveAsset)
mux.HandleFunc("POST /api/v1/ingest/native", s.ingest)
mux.HandleFunc("POST /api/v2/ingest/native", s.ingestFramed)
mux.HandleFunc("POST /v1/logs", s.ingestOTLP(otlp.Logs))
mux.HandleFunc("POST /v1/metrics", s.ingestOTLP(otlp.Metrics))
mux.HandleFunc("POST /v1/traces", s.ingestOTLP(otlp.Traces))
mux.HandleFunc("POST /api/v1/agent/enroll", s.enrollAgent)
mux.HandleFunc("POST /api/v1/agent/alert-transition", s.recordAgentAlertTransition)
mux.HandleFunc("DELETE /api/v1/agent/source", s.revokeAgentSource)
mux.HandleFunc("POST /api/v1/session", s.login)
mux.HandleFunc("DELETE /api/v1/session", s.logout)
mux.HandleFunc("POST /api/v1/account/password", s.changePassword)
mux.HandleFunc("POST /api/v1/query/parse", s.parseQuery)
mux.HandleFunc("POST /api/v1/query/explain", s.explainQuery)
mux.HandleFunc("POST /api/v1/query", s.executeQuery)
mux.HandleFunc("POST /api/v1/push/subscription", s.savePushSubscription)
mux.HandleFunc("POST /api/v1/push/subscription/status", s.pushSubscriptionStatus)
mux.HandleFunc("DELETE /api/v1/push/subscription", s.deletePushSubscription)
return securityHeaders(s.requests.Middleware(authhttp.Optional(s.identity.Auth, s.cookie)(s.requirePasswordChange(mux))))
}
func (s *Server) recordAgentAlertTransition(w http.ResponseWriter, r *http.Request) {
token, ok := bearer(r.Header.Get("Authorization"))
if !ok || !strings.HasPrefix(token, "obs1.") {
writeProblem(w, http.StatusUnauthorized, "source authentication required")
return
}
// Authenticate before decoding. RecordSourceAlertTransition authenticates
// again while binding scope and raw evidence to the credential.
if _, err := s.store.Authenticate(r.Context(), token); err != nil {
writeProblem(w, http.StatusUnauthorized, "source authentication required")
return
}
leave, ok := s.enterIngest(w)
if !ok {
return
}
defer leave()
body := http.MaxBytesReader(w, r.Body, 64<<10)
defer body.Close()
var transition model.AlertTransition
if err := decodeOne(body, &transition); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid source alert transition")
return
}
ack, err := s.store.RecordSourceAlertTransition(r.Context(), token, transition, s.now())
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "source alert transition rejected")
return
}
writeJSON(w, http.StatusAccepted, ack)
}
func (s *Server) requirePasswordChange(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
principal, ok := auth.PrincipalFromContext(r.Context())
if !ok || !principal.User.PasswordChangeRequired || passwordChangeAllowed(r) {
next.ServeHTTP(w, r)
return
}
if r.Method == http.MethodGet || r.Method == http.MethodHead {
http.Redirect(w, r, "/account/password/", http.StatusSeeOther)
return
}
writeProblem(w, http.StatusForbidden, "password change required")
})
}
func passwordChangeAllowed(r *http.Request) bool {
switch r.URL.Path {
case "/healthz", "/readyz", "/manifest.webmanifest", "/service-worker.js", "/offline/", "/account/password/", "/logout/", "/api/v1/account/password", "/api/v1/session":
return true
}
return strings.HasPrefix(r.URL.Path, "/assets/")
}
func (s *Server) revokeAgentSource(w http.ResponseWriter, r *http.Request) {
token, ok := bearer(r.Header.Get("Authorization"))
if !ok || !strings.HasPrefix(token, "obs1.") {
writeProblem(w, http.StatusUnauthorized, "source authentication required")
return
}
source, err := s.store.Authenticate(r.Context(), token)
if err != nil {
writeProblem(w, http.StatusUnauthorized, "source authentication required")
return
}
if err = s.store.RevokeSource(r.Context(), source.ID); err != nil {
writeProblem(w, http.StatusServiceUnavailable, "source revocation unavailable")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) enrollAgent(w http.ResponseWriter, r *http.Request) {
token, ok := bearer(r.Header.Get("Authorization"))
if !ok || !strings.HasPrefix(token, "obse1.") {
writeProblem(w, http.StatusUnauthorized, "valid enrollment required")
return
}
body := http.MaxBytesReader(w, r.Body, 1)
defer body.Close()
payload, bodyErr := io.ReadAll(body)
if bodyErr != nil || len(payload) != 0 {
writeProblem(w, http.StatusBadRequest, "enrollment request body must be empty")
return
}
enrollment, credential, err := s.store.RedeemEnrollment(r.Context(), token, s.now())
if err != nil {
writeProblem(w, http.StatusUnauthorized, "valid enrollment required")
return
}
writeJSON(w, http.StatusCreated, struct {
SourceID string `json:"source_id"`
Credential string `json:"credential"`
}{enrollment.SourceID, credential})
}
func (s *Server) ingest(w http.ResponseWriter, r *http.Request) {
token, ok := bearer(r.Header.Get("Authorization"))
if !ok {
writeProblem(w, http.StatusUnauthorized, "source authentication required")
return
}
source, err := s.store.Authenticate(r.Context(), token)
if err != nil {
writeProblem(w, http.StatusUnauthorized, "source authentication required")
return
}
leave, ok := s.enterIngest(w)
if !ok {
return
}
defer leave()
body := http.MaxBytesReader(w, r.Body, s.options.MaxBodyBytes)
defer body.Close()
var batch model.Batch
if err := decodeOne(body, &batch); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid native batch")
return
}
ack, err := s.store.Ingest(r.Context(), token, batch, s.now())
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "batch rejected")
return
}
s.refresh.publish(source.Scope.OrganizationID)
writeJSON(w, http.StatusAccepted, ack)
}
func (s *Server) ingestFramed(w http.ResponseWriter, r *http.Request) {
token, ok := bearer(r.Header.Get("Authorization"))
if !ok {
writeProblem(w, http.StatusUnauthorized, "source authentication required")
return
}
source, err := s.store.Authenticate(r.Context(), token)
if err != nil {
writeProblem(w, http.StatusUnauthorized, "source authentication required")
return
}
leave, ok := s.enterIngest(w)
if !ok {
return
}
defer leave()
mediaType, parameters, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" || len(parameters) != 0 {
writeProblem(w, http.StatusUnsupportedMediaType, "native JSON content type required")
return
}
envelope, err := nativeprotocol.ParseHeaders(r.Header, s.options.MaxBodyBytes)
if err != nil {
writeProblem(w, http.StatusBadRequest, "invalid native batch envelope")
return
}
body := http.MaxBytesReader(w, r.Body, s.options.MaxBodyBytes)
defer body.Close()
if _, exact, checkErr := s.store.CheckNativeReplay(r.Context(), token, envelope); checkErr != nil {
writeProblem(w, http.StatusUnprocessableEntity, "batch rejected")
return
} else if exact {
if err = verifyNativeReplayBody(body, envelope); err != nil {
writeProblem(w, http.StatusBadRequest, "native batch body does not match envelope")
return
}
ack, confirmErr := s.store.ConfirmNativeReplay(r.Context(), token, envelope)
if confirmErr != nil {
writeProblem(w, http.StatusUnprocessableEntity, "batch rejected")
return
}
writeJSON(w, http.StatusAccepted, ack)
return
}
encoded, err := io.ReadAll(body)
if err != nil {
writeProblem(w, http.StatusBadRequest, "invalid native batch")
return
}
var batch model.Batch
if err = decodeOne(bytes.NewReader(encoded), &batch); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid native batch")
return
}
ack, err := s.store.IngestNative(r.Context(), token, batch, envelope, encoded, s.now())
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "batch rejected")
return
}
if !ack.Duplicate {
s.refresh.publish(source.Scope.OrganizationID)
}
writeJSON(w, http.StatusAccepted, ack)
}
func verifyNativeReplayBody(body io.Reader, envelope model.BatchEnvelope) error {
digest := sha256.New()
written, err := io.Copy(digest, body)
if err != nil || written != envelope.EncodedBytes || hex.EncodeToString(digest.Sum(nil)) != envelope.WireDigest {
return errors.New("native batch body does not match envelope")
}
return nil
}
func (s *Server) ingestOTLP(signal otlp.Signal) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token, ok := bearer(r.Header.Get("Authorization"))
if !ok || !strings.HasPrefix(token, "obs1.") {
writeProblem(w, http.StatusUnauthorized, "source authentication required")
return
}
// Authenticate before parsing attacker-controlled protobuf. IngestAuto
// authenticates again while assigning the next sequence under its source
// lock so revocation cannot race into an acknowledged write.
source, err := s.store.Authenticate(r.Context(), token)
if err != nil {
writeProblem(w, http.StatusUnauthorized, "source authentication required")
return
}
leave, ok := s.enterIngest(w)
if !ok {
return
}
defer leave()
mediaType, parameters, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/x-protobuf" || len(parameters) != 0 {
writeProblem(w, http.StatusUnsupportedMediaType, "OTLP protobuf content type required")
return
}
body, status, err := readOTLPBody(w, r, s.options.MaxBodyBytes)
if err != nil {
title := "invalid OTLP request body"
if status == http.StatusRequestEntityTooLarge {
title = "OTLP request body exceeds limit"
} else if status == http.StatusUnsupportedMediaType {
title = "unsupported OTLP content encoding"
}
writeProblem(w, status, title)
return
}
now := s.now()
records, err := otlp.Decode(signal, body, now)
if err != nil {
writeProblem(w, http.StatusBadRequest, "invalid OTLP protobuf payload")
return
}
if _, err = s.store.IngestAuto(r.Context(), token, signal.StreamID(), signal.ModelSignal(), records, now); err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "OTLP batch rejected")
return
}
s.refresh.publish(source.Scope.OrganizationID)
response, err := otlp.SuccessResponse(signal)
if err != nil {
writeProblem(w, http.StatusInternalServerError, "OTLP response unavailable")
return
}
w.Header().Set("Content-Type", "application/x-protobuf")
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(response)))
w.WriteHeader(http.StatusOK)
if len(response) > 0 {
_, _ = w.Write(response)
}
}
}
func readOTLPBody(w http.ResponseWriter, r *http.Request, limit int64) ([]byte, int, error) {
compressed := http.MaxBytesReader(w, r.Body, limit)
defer compressed.Close()
encoding := strings.TrimSpace(strings.ToLower(r.Header.Get("Content-Encoding")))
var reader io.Reader = compressed
var zipped *gzip.Reader
switch encoding {
case "", "identity":
case "gzip":
var err error
zipped, err = gzip.NewReader(compressed)
if err != nil {
return nil, http.StatusBadRequest, err
}
defer zipped.Close()
reader = io.LimitReader(zipped, limit+1)
default:
return nil, http.StatusUnsupportedMediaType, errors.New("unsupported content encoding")
}
body, err := io.ReadAll(reader)
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return nil, http.StatusRequestEntityTooLarge, err
}
return nil, http.StatusBadRequest, err
}
if int64(len(body)) > limit {
return nil, http.StatusRequestEntityTooLarge, errors.New("decoded body exceeds limit")
}
return body, http.StatusOK, nil
}
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
if !websec.SameOrigin(r, s.options.PublicOrigin) {
writeProblem(w, http.StatusForbidden, "same-origin request required")
return
}
body := http.MaxBytesReader(w, r.Body, 16<<10)
defer body.Close()
var input struct {
Identifier string `json:"identifier"`
Password string `json:"password"`
}
if err := decodeOne(body, &input); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid session request")
return
}
token, principal, err := s.identity.Auth.Authenticate(r.Context(), input.Identifier, input.Password, s.options.SessionLifetime)
if err != nil {
writeProblem(w, http.StatusUnauthorized, "invalid credentials")
return
}
if err = authhttp.SetSession(w, s.cookie, token, s.now()); err != nil {
_ = s.identity.Auth.RevokeSession(r.Context(), token)
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
csrf, err := authhttp.CSRFToken(token, "session:delete")
if err != nil {
_ = s.identity.Auth.RevokeSession(r.Context(), token)
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
passwordCSRF := ""
if principal.User.PasswordChangeRequired {
passwordCSRF, err = authhttp.CSRFToken(token, "account:password:change")
if err != nil {
_ = s.identity.Auth.RevokeSession(r.Context(), token)
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
}
writeJSON(w, http.StatusOK, struct {
UserID string `json:"user_id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CSRFToken string `json:"csrf_token"`
PasswordChangeCSRF string `json:"password_change_csrf,omitempty"`
PasswordChangeRequired bool `json:"password_change_required"`
}{principal.User.ID, principal.User.Username, principal.User.DisplayName, csrf, passwordCSRF, principal.User.PasswordChangeRequired})
}
func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
if !websec.SameOrigin(r, s.options.PublicOrigin) {
writeProblem(w, http.StatusForbidden, "same-origin request required")
return
}
principal, ok := auth.PrincipalFromContext(r.Context())
token, tokenOK := authhttp.SessionToken(r, s.cookie)
if !ok || !tokenOK || !principal.User.PasswordChangeRequired || !authhttp.VerifyCSRF(token, "account:password:change", r.Header.Get("X-CSRF-Token")) {
writeProblem(w, http.StatusForbidden, "password change authorization required")
return
}
body := http.MaxBytesReader(w, r.Body, 8<<10)
defer body.Close()
var input struct {
CurrentPassword string `json:"current_password"`
NewPassword string `json:"new_password"`
}
if err := decodeOne(body, &input); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid password change request")
return
}
if err := s.identity.Auth.ChangePassword(r.Context(), principal.User.ID, input.CurrentPassword, input.NewPassword); err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "password change rejected")
return
}
if err := authhttp.ClearSession(w, s.cookie); err != nil {
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
if !websec.SameOrigin(r, s.options.PublicOrigin) {
writeProblem(w, http.StatusForbidden, "same-origin request required")
return
}
token, ok := authhttp.SessionToken(r, s.cookie)
if !ok || !authhttp.VerifyCSRF(token, "session:delete", r.Header.Get("X-CSRF-Token")) {
writeProblem(w, http.StatusForbidden, "valid session CSRF token required")
return
}
if err := s.identity.Auth.RevokeSession(r.Context(), token); err != nil && !errors.Is(err, auth.ErrSessionNotFound) {
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
if err := authhttp.ClearSession(w, s.cookie); err != nil {
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
w.WriteHeader(http.StatusNoContent)
}
type queryRequest struct {
Query string `json:"query,omitempty"`
AST *query.AST `json:"ast,omitempty"`
OrganizationID string `json:"organization_id,omitempty"`
ProjectID string `json:"project_id,omitempty"`
EnvironmentID string `json:"environment_id,omitempty"`
ServiceID string `json:"service_id,omitempty"`
}
func (s *Server) parseQuery(w http.ResponseWriter, r *http.Request) {
body := http.MaxBytesReader(w, r.Body, 16<<10)
defer body.Close()
var input queryRequest
if err := decodeOne(body, &input); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid query request")
return
}
ast, err := parseAST(input, s.options.MaxQueryRows)
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "query rejected")
return
}
writeJSON(w, http.StatusOK, ast)
}
func (s *Server) explainQuery(w http.ResponseWriter, r *http.Request) {
if !websec.SameOrigin(r, s.options.PublicOrigin) {
writeProblem(w, http.StatusForbidden, "same-origin request required")
return
}
principal, ok := auth.PrincipalFromContext(r.Context())
if !ok {
writeProblem(w, http.StatusUnauthorized, "authentication required")
return
}
body := http.MaxBytesReader(w, r.Body, 16<<10)
defer body.Close()
var input queryRequest
if err := decodeOne(body, &input); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid query request")
return
}
ast, err := parseAST(input, s.options.MaxQueryRows)
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "query rejected")
return
}
requested := access.Scope{OrganizationID: input.OrganizationID, ProjectID: input.ProjectID, EnvironmentID: input.EnvironmentID, ServiceID: input.ServiceID}
decision, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, requested, identity.PermissionTelemetryQuery)
if err != nil {
writeProblem(w, http.StatusBadRequest, "invalid resource scope")
return
}
if !decision.Allowed {
writeProblem(w, http.StatusForbidden, "resource access denied")
return
}
if err := s.identity.ValidateResourceScope(r.Context(), requested); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid resource scope")
return
}
sensitive, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, requested, identity.PermissionTelemetryReadSensitive)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "authorization unavailable")
return
}
estimated, err := s.store.EstimateOrganizationBytes(input.OrganizationID)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "query planning unavailable")
return
}
registry, _, err := s.store.ActiveDescriptors(r.Context(), input.OrganizationID)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "query planning unavailable")
return
}
explain, err := query.Plan(ast, query.Scope{
OrganizationID: input.OrganizationID, ProjectID: input.ProjectID,
EnvironmentID: input.EnvironmentID, ServiceID: input.ServiceID,
Sensitive: sensitive.Allowed,
}, registry, estimated, s.options.QueryBudget)
if errors.Is(err, query.ErrSensitivePermissionRequired) {
writeProblem(w, http.StatusForbidden, "sensitive-field permission required")
return
}
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "query plan rejected")
return
}
writeJSON(w, http.StatusOK, explain)
}
func (s *Server) executeQuery(w http.ResponseWriter, r *http.Request) {
if !websec.SameOrigin(r, s.options.PublicOrigin) {
writeProblem(w, http.StatusForbidden, "same-origin request required")
return
}
principal, ok := auth.PrincipalFromContext(r.Context())
if !ok {
writeProblem(w, http.StatusUnauthorized, "authentication required")
return
}
body := http.MaxBytesReader(w, r.Body, 16<<10)
defer body.Close()
var input queryRequest
if err := decodeOne(body, &input); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid query request")
return
}
ast, err := parseAST(input, s.options.MaxQueryRows)
if err != nil {
writeProblem(w, http.StatusUnprocessableEntity, "query rejected")
return
}
requested := access.Scope{OrganizationID: input.OrganizationID, ProjectID: input.ProjectID, EnvironmentID: input.EnvironmentID, ServiceID: input.ServiceID}
decision, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, requested, identity.PermissionTelemetryQuery)
if err != nil {
writeProblem(w, http.StatusBadRequest, "invalid resource scope")
return
}
if !decision.Allowed {
writeProblem(w, http.StatusForbidden, "resource access denied")
return
}
if err = s.identity.ValidateResourceScope(r.Context(), requested); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid resource scope")
return
}
sensitive, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, requested, identity.PermissionTelemetryReadSensitive)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "authorization unavailable")
return
}
result, err := s.store.Query(r.Context(), ast, query.Scope{
OrganizationID: input.OrganizationID, ProjectID: input.ProjectID,
EnvironmentID: input.EnvironmentID, ServiceID: input.ServiceID,
Sensitive: sensitive.Allowed,
}, s.options.QueryBudget, s.now())
switch {
case errors.Is(err, query.ErrSensitivePermissionRequired):
writeProblem(w, http.StatusForbidden, "sensitive-field permission required")
return
case errors.Is(err, query.ErrBudgetExceeded):
writeProblem(w, http.StatusUnprocessableEntity, "query execution budget exceeded")
return
case errors.Is(err, query.ErrTypeMismatch):
writeProblem(w, http.StatusUnprocessableEntity, "query field type mismatch")
return
case err != nil:
writeProblem(w, http.StatusServiceUnavailable, "query execution unavailable")
return
}
writeJSON(w, http.StatusOK, result)
}
func parseAST(input queryRequest, maxRows int) (query.AST, error) {
if (input.Query == "") == (input.AST == nil) {
return query.AST{}, errors.New("provide exactly one query or AST")
}
if input.AST == nil {
return query.Parse(input.Query, maxRows)
}
ast := *input.AST
var err error
if ast.WindowText != "" {
ast.Window, err = time.ParseDuration(ast.WindowText)
}
if err == nil && ast.BucketText != "" {
ast.Bucket, err = time.ParseDuration(ast.BucketText)
}
if err == nil {
err = query.Validate(ast, maxRows)
}
return ast, err
}
func decodeOne(reader io.Reader, value any) error {
decoder := json.NewDecoder(reader)
decoder.DisallowUnknownFields()
if err := decoder.Decode(value); err != nil {
return err
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return errors.New("request must contain exactly one JSON value")
}
return nil
}
func bearer(value string) (string, bool) {
const prefix = "Bearer "
if !strings.HasPrefix(value, prefix) || strings.ContainsAny(value[len(prefix):], " \t\r\n") {
return "", false
}
return value[len(prefix):], value[len(prefix):] != ""
}
func textOK(body string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body)))
if r.Method != http.MethodHead {
_, _ = io.WriteString(w, body)
}
}
}
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Security-Policy", "default-src 'none'; base-uri 'none'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; img-src 'self'; manifest-src 'self'; script-src 'self'; style-src 'self'; worker-src 'self'")
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
w.Header().Set("Permissions-Policy", "camera=(), geolocation=(), microphone=()")
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("X-Content-Type-Options", "nosniff")
next.ServeHTTP(w, r)
})
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeProblem(w http.ResponseWriter, status int, title string) {
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(struct {
Title string `json:"title"`
Status int `json:"status"`
}{Title: title, Status: status})
}
+496
View File
@@ -0,0 +1,496 @@
// SPDX-License-Identifier: AGPL-3.0-only
package httpserver
import (
"bytes"
"compress/gzip"
"context"
"crypto/ecdh"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/nativeprotocol"
"gamertan.com/observatory/internal/query"
"gamertan.com/observatory/internal/schema"
"gamertan.com/observatory/internal/storage"
commonpb "go.opentelemetry.io/proto/otlp/common/v1"
logspb "go.opentelemetry.io/proto/otlp/logs/v1"
"google.golang.org/protobuf/proto"
)
func TestIngestionConcurrencyIsBoundedAndReusable(t *testing.T) {
server, store, identities, _ := newUITestServer(t)
defer store.Close()
defer identities.Close()
server.ingestSlots = make(chan struct{}, 1)
first := httptest.NewRecorder()
leave, ok := server.enterIngest(first)
if !ok || leave == nil {
t.Fatal("first ingestion slot was unavailable")
}
second := httptest.NewRecorder()
if secondLeave, admitted := server.enterIngest(second); admitted || secondLeave != nil || second.Code != http.StatusServiceUnavailable || second.Header().Get("Retry-After") != "1" || !strings.Contains(second.Body.String(), "ingestion capacity temporarily unavailable") {
t.Fatalf("second admission admitted=%t status=%d retry=%q body=%s", admitted, second.Code, second.Header().Get("Retry-After"), second.Body.String())
}
leave()
third := httptest.NewRecorder()
thirdLeave, admitted := server.enterIngest(third)
if !admitted || thirdLeave == nil {
t.Fatal("released ingestion capacity was not reusable")
}
thirdLeave()
}
func TestServerWebPushConfigurationIsAllOrNothing(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
t.Fatal(err)
}
defer store.Close()
identities, err := identity.Open(root)
if err != nil {
t.Fatal(err)
}
defer identities.Close()
dispatcher := &recordingPushDispatcher{}
options := testOptions()
options.PushDispatcher = dispatcher
if _, err = New(store, identities, options); err == nil {
t.Fatal("dispatcher without public key accepted")
}
options.PushPublicKey = "invalid"
if _, err = New(store, identities, options); err == nil {
t.Fatal("invalid public key accepted")
}
private, err := ecdh.P256().GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
options.PushPublicKey = base64.RawURLEncoding.EncodeToString(private.PublicKey().Bytes())
if _, err = New(store, identities, options); err != nil {
t.Fatalf("valid Web Push configuration: %v", err)
}
}
func TestIngestDoesNotExposeValuesInErrors(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
t.Fatal(err)
}
defer store.Close()
token, err := store.CreateSource(context.Background(), "source", model.Scope{OrganizationID: "org", ProjectID: "p", EnvironmentID: "prod", ServiceID: "s"})
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
identities, err := identity.Open(root)
if err != nil {
t.Fatal(err)
}
defer identities.Close()
server, err := New(store, identities, testOptions())
if err != nil {
t.Fatal(err)
}
server.now = func() time.Time { return now }
batch := model.Batch{Version: 1, SourceID: "source", StreamID: "logs", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "request", Body: "credential=do-not-echo"}}}
body, _ := json.Marshal(batch)
req := httptest.NewRequest(http.MethodPost, "/api/v1/ingest/native", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
rec := httptest.NewRecorder()
server.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusAccepted {
t.Fatalf("expected 202, got %d: %s", rec.Code, rec.Body.String())
}
req = httptest.NewRequest(http.MethodPost, "/api/v1/ingest/native", bytes.NewBufferString(`{"secret":"do-not-echo"}`))
req.Header.Set("Authorization", "Bearer "+token)
rec = httptest.NewRecorder()
server.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest || bytes.Contains(rec.Body.Bytes(), []byte("do-not-echo")) {
t.Fatalf("unsafe error response %d: %s", rec.Code, rec.Body.String())
}
}
func TestFramedNativeIngestAcknowledgesExactReplayAndOverlappingTime(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
t.Fatal(err)
}
defer store.Close()
token, err := store.CreateSource(context.Background(), "source", model.Scope{OrganizationID: "org", ProjectID: "p", EnvironmentID: "prod", ServiceID: "s"})
if err != nil {
t.Fatal(err)
}
identities, err := identity.Open(root)
if err != nil {
t.Fatal(err)
}
defer identities.Close()
now := time.Date(2026, 8, 18, 20, 0, 0, 0, time.UTC)
server, err := New(store, identities, testOptions())
if err != nil {
t.Fatal(err)
}
server.now = func() time.Time { return now }
handler := server.Handler()
send := func(batch model.Batch, body []byte, envelope model.BatchEnvelope) *httptest.ResponseRecorder {
t.Helper()
request := httptest.NewRequest(http.MethodPost, "https://observatory.example/api/v2/ingest/native", bytes.NewReader(body))
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Content-Type", "application/json")
nativeprotocol.SetHeaders(request.Header, envelope)
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
return response
}
batch := model.Batch{Version: model.BatchVersion, SourceID: "source", StreamID: "logs", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "first"}}}
body, _ := json.Marshal(batch)
envelope, _ := batch.Envelope(body)
first := send(batch, body, envelope)
if first.Code != http.StatusAccepted || strings.Contains(first.Body.String(), `"duplicate":true`) {
t.Fatalf("first status=%d body=%s", first.Code, first.Body.String())
}
replay := send(batch, body, envelope)
if replay.Code != http.StatusAccepted || !strings.Contains(replay.Body.String(), `"duplicate":true`) {
t.Fatalf("replay status=%d body=%s", replay.Code, replay.Body.String())
}
tampered := append(append([]byte(nil), body...), ' ')
bad := send(batch, tampered, envelope)
if bad.Code != http.StatusBadRequest {
t.Fatalf("tampered status=%d body=%s", bad.Code, bad.Body.String())
}
batch.Sequence = 2
batch.ObservedAt = now.Add(time.Second)
// The second batch intentionally overlaps the first batch's observed time.
body, _ = json.Marshal(batch)
envelope, _ = batch.Envelope(body)
overlap := send(batch, body, envelope)
if overlap.Code != http.StatusAccepted {
t.Fatalf("overlap status=%d body=%s", overlap.Code, overlap.Body.String())
}
}
func TestOTLPHTTPIngestionIsAuthenticatedBoundedAndCompressed(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
t.Fatal(err)
}
defer store.Close()
scope := model.Scope{OrganizationID: "organization-a", ProjectID: "project-a", EnvironmentID: "production", ServiceID: "service-a"}
token, err := store.CreateSource(context.Background(), "otlp-source", scope)
if err != nil {
t.Fatal(err)
}
identities, err := identity.Open(root)
if err != nil {
t.Fatal(err)
}
defer identities.Close()
now := time.Date(2026, 8, 17, 3, 0, 0, 0, time.UTC)
server, err := New(store, identities, testOptions())
if err != nil {
t.Fatal(err)
}
server.now = func() time.Time { return now }
handler := server.Handler()
payload, err := proto.Marshal(&logspb.LogsData{ResourceLogs: []*logspb.ResourceLogs{{ScopeLogs: []*logspb.ScopeLogs{{LogRecords: []*logspb.LogRecord{{
TimeUnixNano: uint64(now.UnixNano()), EventName: "http.request", Body: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: "accepted"}},
}}}}}}})
if err != nil {
t.Fatal(err)
}
send := func(body []byte, encoding string) *httptest.ResponseRecorder {
t.Helper()
request := httptest.NewRequest(http.MethodPost, "https://observatory.example/v1/logs", bytes.NewReader(body))
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Content-Type", "application/x-protobuf")
if encoding != "" {
request.Header.Set("Content-Encoding", encoding)
}
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
return response
}
plain := send(payload, "")
if plain.Code != http.StatusOK || plain.Header().Get("Content-Type") != "application/x-protobuf" || plain.Header().Get("Content-Length") != "0" || plain.Body.Len() != 0 {
t.Fatalf("plain status=%d headers=%v body=%q", plain.Code, plain.Header(), plain.Body.String())
}
var compressed bytes.Buffer
zipper := gzip.NewWriter(&compressed)
if _, err = zipper.Write(payload); err != nil {
t.Fatal(err)
}
if err = zipper.Close(); err != nil {
t.Fatal(err)
}
if response := send(compressed.Bytes(), "gzip"); response.Code != http.StatusOK {
t.Fatalf("gzip status=%d body=%s", response.Code, response.Body.String())
}
if err = store.Recover(context.Background()); err != nil {
t.Fatal(err)
}
if bytes, err := store.EstimateOrganizationBytes(scope.OrganizationID); err != nil || bytes == 0 {
t.Fatalf("projection bytes=%d err=%v", bytes, err)
}
unauthorized := httptest.NewRequest(http.MethodPost, "https://observatory.example/v1/logs", bytes.NewReader(payload))
unauthorized.Header.Set("Content-Type", "application/x-protobuf")
unauthorizedResult := httptest.NewRecorder()
handler.ServeHTTP(unauthorizedResult, unauthorized)
if unauthorizedResult.Code != http.StatusUnauthorized {
t.Fatalf("unauthorized status=%d", unauthorizedResult.Code)
}
wrongMedia := httptest.NewRequest(http.MethodPost, "https://observatory.example/v1/logs", bytes.NewReader(payload))
wrongMedia.Header.Set("Authorization", "Bearer "+token)
wrongMedia.Header.Set("Content-Type", "application/json")
wrongMediaResult := httptest.NewRecorder()
handler.ServeHTTP(wrongMediaResult, wrongMedia)
if wrongMediaResult.Code != http.StatusUnsupportedMediaType {
t.Fatalf("media status=%d", wrongMediaResult.Code)
}
compressed.Reset()
zipper = gzip.NewWriter(&compressed)
if _, err = zipper.Write(bytes.Repeat([]byte{'x'}, int(testOptions().MaxBodyBytes)+1)); err != nil {
t.Fatal(err)
}
if err = zipper.Close(); err != nil {
t.Fatal(err)
}
tooLarge := send(compressed.Bytes(), "gzip")
if tooLarge.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("oversized status=%d body=%s", tooLarge.Code, tooLarge.Body.String())
}
}
func TestSessionAndScopedExplain(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
t.Fatal(err)
}
defer store.Close()
identities, err := identity.Open(root)
if err != nil {
t.Fatal(err)
}
defer identities.Close()
bootstrap, err := identities.Bootstrap(context.Background(), identity.BootstrapInput{Username: "operator", Email: "operator@example.test", DisplayName: "Operator", Password: "correct horse battery staple"})
if err != nil {
t.Fatal(err)
}
server, err := New(store, identities, testOptions())
if err != nil {
t.Fatal(err)
}
handler := server.Handler()
login := httptest.NewRequest(http.MethodPost, "https://observatory.example/api/v1/session", strings.NewReader(`{"identifier":"operator","password":"correct horse battery staple"}`))
login.Header.Set("Origin", "https://observatory.example")
loginResult := httptest.NewRecorder()
handler.ServeHTTP(loginResult, login)
if loginResult.Code != http.StatusOK || strings.Contains(loginResult.Body.String(), "correct horse") {
t.Fatalf("login status=%d body=%s", loginResult.Code, loginResult.Body.String())
}
var session struct {
CSRFToken string `json:"csrf_token"`
}
if err = json.Unmarshal(loginResult.Body.Bytes(), &session); err != nil || session.CSRFToken == "" {
t.Fatalf("session=%+v err=%v", session, err)
}
cookies := loginResult.Result().Cookies()
if len(cookies) != 1 || cookies[0].Name != "__Host-observatory_session" || !cookies[0].Secure || !cookies[0].HttpOnly {
t.Fatalf("cookies=%+v", cookies)
}
explainBody := fmt.Sprintf(`{"organization_id":%q,"query":"logs | where status >= 500 | limit 10"}`, bootstrap.Organization.ID)
explain := httptest.NewRequest(http.MethodPost, "https://observatory.example/api/v1/query/explain", strings.NewReader(explainBody))
explain.Header.Set("Origin", "https://observatory.example")
explain.AddCookie(cookies[0])
explainResult := httptest.NewRecorder()
handler.ServeHTTP(explainResult, explain)
if explainResult.Code != http.StatusOK || !strings.Contains(explainResult.Body.String(), `"projected_sources"`) {
t.Fatalf("explain status=%d body=%s", explainResult.Code, explainResult.Body.String())
}
now := time.Now().UTC()
sourceToken, err := store.CreateSource(context.Background(), "query-source", model.Scope{OrganizationID: bootstrap.Organization.ID, ProjectID: "project-a", EnvironmentID: "production", ServiceID: "service-a"})
if err != nil {
t.Fatal(err)
}
batch := model.Batch{Version: model.BatchVersion, SourceID: "query-source", StreamID: "requests", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "application.http.request", Attributes: map[string]string{"http.status_code": "503", "http.route": "/failed", "workshop.queue_depth": "12"}}}}
if _, err = store.Ingest(context.Background(), sourceToken, batch, now); err != nil {
t.Fatal(err)
}
if err = store.Recover(context.Background()); err != nil {
t.Fatal(err)
}
execute := httptest.NewRequest(http.MethodPost, "https://observatory.example/api/v1/query", strings.NewReader(explainBody))
execute.Header.Set("Origin", "https://observatory.example")
execute.AddCookie(cookies[0])
executeResult := httptest.NewRecorder()
handler.ServeHTTP(executeResult, execute)
if executeResult.Code != http.StatusOK || !strings.Contains(executeResult.Body.String(), `"http.status_code"`) || !strings.Contains(executeResult.Body.String(), `"503"`) {
t.Fatalf("execute status=%d body=%s", executeResult.Code, executeResult.Body.String())
}
reviewed := schema.Descriptor{Version: schema.DescriptorVersion, Signal: model.SignalLogs, Field: "workshop.queue_depth", Type: schema.TypeInteger, Meaning: "Reviewed queue depth for one application service.", Sensitivity: schema.SensitivityInternal, Cardinality: schema.CardinalityLow, Index: schema.IndexRange, Retention: schema.RetentionRaw, ProjectionVersion: 1}
if _, err = store.ActivateDescriptor(context.Background(), bootstrap.Organization.ID, reviewed, now.Add(time.Second)); err != nil {
t.Fatal(err)
}
customBody := fmt.Sprintf(`{"organization_id":%q,"query":"logs | where workshop.queue_depth >= 10 | limit 10"}`, bootstrap.Organization.ID)
for _, path := range []string{"/api/v1/query/explain", "/api/v1/query"} {
request := httptest.NewRequest(http.MethodPost, "https://observatory.example"+path, strings.NewReader(customBody))
request.Header.Set("Origin", "https://observatory.example")
request.AddCookie(cookies[0])
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"workshop.queue_depth"`) || !strings.Contains(response.Body.String(), `"indexed":true`) {
t.Fatalf("path=%s status=%d body=%s", path, response.Code, response.Body.String())
}
}
for _, path := range []string{"/api/v1/query/explain", "/api/v1/query"} {
denied := httptest.NewRequest(http.MethodPost, "https://observatory.example"+path, strings.NewReader(`{"organization_id":"unowned1","query":"logs | limit 10"}`))
denied.Header.Set("Origin", "https://observatory.example")
denied.AddCookie(cookies[0])
deniedResult := httptest.NewRecorder()
handler.ServeHTTP(deniedResult, denied)
if deniedResult.Code != http.StatusForbidden {
t.Fatalf("path=%s cross-organization status=%d body=%s", path, deniedResult.Code, deniedResult.Body.String())
}
}
logout := httptest.NewRequest(http.MethodDelete, "https://observatory.example/api/v1/session", nil)
logout.Header.Set("Origin", "https://observatory.example")
logout.Header.Set("X-CSRF-Token", session.CSRFToken)
logout.AddCookie(cookies[0])
logoutResult := httptest.NewRecorder()
handler.ServeHTTP(logoutResult, logout)
if logoutResult.Code != http.StatusNoContent {
t.Fatalf("logout status=%d body=%s", logoutResult.Code, logoutResult.Body.String())
}
}
func TestCrossOriginLoginIsRejected(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
t.Fatal(err)
}
defer store.Close()
identities, err := identity.Open(root)
if err != nil {
t.Fatal(err)
}
defer identities.Close()
server, err := New(store, identities, testOptions())
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodPost, "https://observatory.example/api/v1/session", strings.NewReader(`{"identifier":"operator","password":"secret"}`))
request.Header.Set("Origin", "https://attacker.example")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusForbidden {
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
}
}
func TestAgentEnrollmentIsSingleUseAndCredentialCanSelfRevoke(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
t.Fatal(err)
}
defer store.Close()
identities, err := identity.Open(root)
if err != nil {
t.Fatal(err)
}
defer identities.Close()
now := time.Date(2026, 8, 17, 2, 0, 0, 0, time.UTC)
enrollmentToken, _, err := store.CreateEnrollment(context.Background(), "source-a", model.Scope{OrganizationID: "organization-a", ProjectID: "project-a", EnvironmentID: "production", ServiceID: "service-a"}, "operator-a", 15*time.Minute, now)
if err != nil {
t.Fatal(err)
}
server, err := New(store, identities, testOptions())
if err != nil {
t.Fatal(err)
}
server.now = func() time.Time { return now.Add(time.Minute) }
enroll := httptest.NewRequest(http.MethodPost, "https://observatory.example/api/v1/agent/enroll", nil)
enroll.Header.Set("Authorization", "Bearer "+enrollmentToken)
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, enroll)
if response.Code != http.StatusCreated || strings.Contains(response.Body.String(), enrollmentToken) {
t.Fatalf("enroll status=%d body=%s", response.Code, response.Body.String())
}
var enrolled struct {
SourceID string `json:"source_id"`
Credential string `json:"credential"`
}
if err = json.Unmarshal(response.Body.Bytes(), &enrolled); err != nil || enrolled.SourceID != "source-a" || enrolled.Credential == "" {
t.Fatalf("enrolled=%+v err=%v", enrolled, err)
}
replay := httptest.NewRequest(http.MethodPost, "https://observatory.example/api/v1/agent/enroll", nil)
replay.Header.Set("Authorization", "Bearer "+enrollmentToken)
replayResponse := httptest.NewRecorder()
server.Handler().ServeHTTP(replayResponse, replay)
if replayResponse.Code != http.StatusUnauthorized {
t.Fatalf("replay status=%d", replayResponse.Code)
}
revoke := httptest.NewRequest(http.MethodDelete, "https://observatory.example/api/v1/agent/source", nil)
revoke.Header.Set("Authorization", "Bearer "+enrolled.Credential)
revokeResponse := httptest.NewRecorder()
server.Handler().ServeHTTP(revokeResponse, revoke)
if revokeResponse.Code != http.StatusNoContent {
t.Fatalf("revoke status=%d body=%s", revokeResponse.Code, revokeResponse.Body.String())
}
if _, err = store.Authenticate(context.Background(), enrolled.Credential); err == nil {
t.Fatal("revoked source credential remained active")
}
}
func testOptions() Options {
return Options{PublicOrigin: "https://observatory.example", MaxBodyBytes: 1 << 20, MaxQueryRows: 1000, SessionLifetime: time.Hour, QueryBudget: query.Budget{MaxDuration: 2 * time.Second, MaxRows: 1000, MaxScannedBytes: 10 << 20, MaxMemoryBytes: 8 << 20}}
}
+92
View File
@@ -0,0 +1,92 @@
// SPDX-License-Identifier: AGPL-3.0-only
package httpserver
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/storage"
)
func TestAgentAlertTransitionIsAuthenticatedBoundedAndEvidenceBacked(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
t.Fatal(err)
}
defer store.Close()
identities, err := identity.Open(root)
if err != nil {
t.Fatal(err)
}
defer identities.Close()
now := time.Date(2026, 8, 18, 23, 45, 0, 0, time.UTC)
scope := model.Scope{OrganizationID: "organization-a", ProjectID: "project-a", EnvironmentID: "production", ServiceID: "service-a"}
token, err := store.CreateSource(context.Background(), "source-a", scope)
if err != nil {
t.Fatal(err)
}
saved, err := store.SaveQuery(context.Background(), storage.SavedQueryInput{OrganizationID: scope.OrganizationID, ActorUserID: "operator-a", MaxRows: 100, Name: "Logs", Query: "logs | limit 10", Scope: storage.ResourceScope{ProjectID: scope.ProjectID, EnvironmentID: scope.EnvironmentID, ServiceID: scope.ServiceID}}, now)
if err != nil {
t.Fatal(err)
}
rule, err := store.SaveAlertRule(context.Background(), storage.AlertRuleInput{OrganizationID: scope.OrganizationID, ActorUserID: "operator-a", SavedQueryID: saved.ID, Name: "Logs", Severity: "warning", MinimumMatches: 1, RequiredConsecutive: 1, EvaluationInterval: 15 * time.Second, Enabled: true}, now)
if err != nil {
t.Fatal(err)
}
batch := model.Batch{Version: model.BatchVersion, SourceID: "source-a", StreamID: "requests", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "request"}}}
ingested, err := store.Ingest(context.Background(), token, batch, now)
if err != nil {
t.Fatal(err)
}
server, err := New(store, identities, testOptions())
if err != nil {
t.Fatal(err)
}
server.now = func() time.Time { return now }
handler := server.Handler()
transition := model.AlertTransition{Version: model.AlertTransitionVersion, RuleID: rule.ID, RuleRevision: rule.Revision, AgentEpoch: strings.Repeat("a", 32), Sequence: 1, StreamID: batch.StreamID, BatchSequence: batch.Sequence, SegmentDigest: ingested.Digest, WindowStart: now, WindowEnd: now, State: "matched", ObservedAt: now}
payload, err := json.Marshal(transition)
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodPost, "https://observatory.example/api/v1/agent/alert-transition", bytes.NewReader(payload))
request.Header.Set("Authorization", "Bearer "+token)
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != http.StatusAccepted {
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
}
var ack storage.SourceAlertTransitionAck
if err = json.Unmarshal(response.Body.Bytes(), &ack); err != nil || ack.SourceID != "source-a" || ack.RuleID != rule.ID || ack.Duplicate {
t.Fatalf("ack=%+v err=%v", ack, err)
}
unauthorized := httptest.NewRequest(http.MethodPost, "https://observatory.example/api/v1/agent/alert-transition", bytes.NewReader([]byte(`{"state":"do-not-echo"}`)))
unauthorizedResult := httptest.NewRecorder()
handler.ServeHTTP(unauthorizedResult, unauthorized)
if unauthorizedResult.Code != http.StatusUnauthorized || strings.Contains(unauthorizedResult.Body.String(), "do-not-echo") {
t.Fatalf("unauthorized status=%d body=%q", unauthorizedResult.Code, unauthorizedResult.Body.String())
}
oversized := httptest.NewRequest(http.MethodPost, "https://observatory.example/api/v1/agent/alert-transition", strings.NewReader(strings.Repeat("x", (64<<10)+1)))
oversized.Header.Set("Authorization", "Bearer "+token)
oversizedResult := httptest.NewRecorder()
handler.ServeHTTP(oversizedResult, oversized)
if oversizedResult.Code != http.StatusBadRequest {
t.Fatalf("oversized status=%d body=%q", oversizedResult.Code, oversizedResult.Body.String())
}
}
+532
View File
@@ -0,0 +1,532 @@
// SPDX-License-Identifier: AGPL-3.0-only
package httpserver
import (
"bytes"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"strings"
"time"
"unicode/utf8"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/query"
"gamertan.com/observatory/internal/site"
"gamertan.com/sandwich-hime/sando"
"gamertan.com/web/access"
"gamertan.com/web/auth"
"gamertan.com/web/authhttp"
"gamertan.com/web/websec"
)
const loginCSRFCookieName = "__Host-observatory_login_csrf"
const (
loginFormFailure = "This sign-in form expired or could not be verified. Please try again."
loginCredentialFailure = "The username or password was not accepted."
passwordFormFailure = "This password form expired or could not be verified. Please try again."
passwordMatchFailure = "The new passwords did not match. Please enter them again."
passwordChangeFailure = "The password could not be changed. Check the temporary password and choose a different password of at least 12 characters."
)
func (s *Server) landing(w http.ResponseWriter, r *http.Request) {
if _, ok := auth.PrincipalFromContext(r.Context()); ok {
http.Redirect(w, r, "/app/", http.StatusSeeOther)
return
}
view := site.LandingView{Head: s.head("Gamertan Observatory", "A self-hosted observability platform in development for carefully operated Linux systems.", "/")}
s.renderHTML(w, r, http.StatusOK, site.Landing(view))
}
func (s *Server) loginPage(w http.ResponseWriter, r *http.Request) {
if principal, ok := auth.PrincipalFromContext(r.Context()); ok {
if principal.User.PasswordChangeRequired {
http.Redirect(w, r, "/account/password/", http.StatusSeeOther)
return
}
http.Redirect(w, r, "/app/", http.StatusSeeOther)
return
}
s.renderLogin(w, r, http.StatusOK, "")
}
func (s *Server) loginForm(w http.ResponseWriter, r *http.Request) {
values, err := readFormFields(w, r, 16<<10, []string{"identifier", "password"}, []string{"csrf_token"})
csrfOK := err == nil && validLoginCSRF(r, values.Get("csrf_token"))
if !tokenBoundFormRequest(r, s.options.PublicOrigin, csrfOK) {
s.renderLogin(w, r, http.StatusForbidden, loginFormFailure)
return
}
if err != nil {
s.renderLogin(w, r, http.StatusBadRequest, loginFormFailure)
return
}
token, principal, err := s.identity.Auth.Authenticate(r.Context(), values.Get("identifier"), values.Get("password"), s.options.SessionLifetime)
if err != nil {
s.renderLogin(w, r, http.StatusUnauthorized, loginCredentialFailure)
return
}
if err = authhttp.SetSession(w, s.cookie, token, s.now()); err != nil {
_ = s.identity.Auth.RevokeSession(r.Context(), token)
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
if _, cookieErr := r.Cookie(loginCSRFCookieName); cookieErr == nil {
clearLoginCSRF(w)
}
location := "/app/"
if principal.User.PasswordChangeRequired {
location = "/account/password/"
}
http.Redirect(w, r, location, http.StatusSeeOther)
}
// tokenBoundFormRequest makes the purpose-bound form token the primary CSRF
// proof. Browser origin metadata is defense in depth: an explicit cross-site
// or contradictory origin still fails closed, while absent or opaque metadata
// does not break an otherwise valid ordinary HTML form submission.
func tokenBoundFormRequest(r *http.Request, publicOrigin string, validToken bool) bool {
if !validToken {
return false
}
fetchSite := strings.ToLower(strings.TrimSpace(r.Header.Get("Sec-Fetch-Site")))
if fetchSite != "" && fetchSite != "same-origin" && fetchSite != "none" {
return false
}
origin := strings.TrimSpace(r.Header.Get("Origin"))
if origin == "" || origin == "null" {
return true
}
return websec.SameOrigin(r, publicOrigin)
}
func (s *Server) renderLogin(w http.ResponseWriter, r *http.Request, status int, message string) {
csrf, err := s.issueLoginCSRF(w)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "login unavailable")
return
}
view := site.LoginView{Head: s.head("Sign in — Gamertan Observatory", "Sign in to the local Gamertan Observatory workshop.", "/login/"), CSRFToken: csrf, ErrorMessage: message}
s.renderHTML(w, r, status, site.Login(view))
}
func (s *Server) issueLoginCSRF(w http.ResponseWriter) (string, error) {
secret := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, secret); err != nil {
return "", errors.New("generate login CSRF token")
}
token := base64.RawURLEncoding.EncodeToString(secret)
http.SetCookie(w, &http.Cookie{Name: loginCSRFCookieName, Value: token, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, Expires: s.now().Add(10 * time.Minute), MaxAge: 600})
return token, nil
}
func validLoginCSRF(r *http.Request, candidate string) bool {
cookie, err := r.Cookie(loginCSRFCookieName)
if err != nil {
return false
}
want, wantErr := base64.RawURLEncoding.DecodeString(cookie.Value)
got, gotErr := base64.RawURLEncoding.DecodeString(candidate)
return wantErr == nil && gotErr == nil && len(want) == 32 && len(got) == len(want) && subtle.ConstantTimeCompare(want, got) == 1
}
func clearLoginCSRF(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{Name: loginCSRFCookieName, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
}
func (s *Server) passwordPage(w http.ResponseWriter, r *http.Request) {
principal, ok := auth.PrincipalFromContext(r.Context())
if !ok {
http.Redirect(w, r, "/login/", http.StatusSeeOther)
return
}
if !principal.User.PasswordChangeRequired {
http.Redirect(w, r, "/app/", http.StatusSeeOther)
return
}
s.renderPassword(w, r, http.StatusOK, "")
}
func (s *Server) passwordForm(w http.ResponseWriter, r *http.Request) {
principal, ok := auth.PrincipalFromContext(r.Context())
token, tokenOK := authhttp.SessionToken(r, s.cookie)
values, err := readForm(w, r, 8<<10, "csrf_token", "current_password", "new_password", "confirm_password")
csrfOK := err == nil && tokenOK && authhttp.VerifyCSRF(token, "account:password:change", values.Get("csrf_token"))
if !tokenBoundFormRequest(r, s.options.PublicOrigin, csrfOK) {
if ok && tokenOK && principal.User.PasswordChangeRequired {
s.renderPassword(w, r, http.StatusForbidden, passwordFormFailure)
} else {
http.Redirect(w, r, "/login/", http.StatusSeeOther)
}
return
}
if !ok || !tokenOK || !principal.User.PasswordChangeRequired {
writeProblem(w, http.StatusForbidden, "password change authorization required")
return
}
if err != nil || !csrfOK {
s.renderPassword(w, r, http.StatusBadRequest, passwordFormFailure)
return
}
if values.Get("new_password") != values.Get("confirm_password") {
s.renderPassword(w, r, http.StatusUnprocessableEntity, passwordMatchFailure)
return
}
if err = s.identity.Auth.ChangePassword(r.Context(), principal.User.ID, values.Get("current_password"), values.Get("new_password")); err != nil {
s.renderPassword(w, r, http.StatusUnprocessableEntity, passwordChangeFailure)
return
}
if err = authhttp.ClearSession(w, s.cookie); err != nil {
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
http.Redirect(w, r, "/login/?password=changed", http.StatusSeeOther)
}
func (s *Server) renderPassword(w http.ResponseWriter, r *http.Request, status int, message string) {
token, ok := authhttp.SessionToken(r, s.cookie)
if !ok {
writeProblem(w, http.StatusUnauthorized, "authentication required")
return
}
csrf, err := authhttp.CSRFToken(token, "account:password:change")
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
view := site.PasswordView{Head: s.head("Choose your password — Gamertan Observatory", "Replace the one-time Observatory credential before continuing.", "/account/password/"), CSRFToken: csrf, ErrorMessage: message}
s.renderHTML(w, r, status, site.Password(view))
}
func (s *Server) logoutForm(w http.ResponseWriter, r *http.Request) {
values, err := readForm(w, r, 4<<10, "csrf_token")
token, ok := authhttp.SessionToken(r, s.cookie)
csrfOK := err == nil && ok && authhttp.VerifyCSRF(token, "session:delete", values.Get("csrf_token"))
if !tokenBoundFormRequest(r, s.options.PublicOrigin, csrfOK) {
writeProblem(w, http.StatusForbidden, "valid sign-out form required")
return
}
if err != nil {
writeProblem(w, http.StatusBadRequest, "invalid sign-out request")
return
}
if !csrfOK {
writeProblem(w, http.StatusForbidden, "valid session CSRF token required")
return
}
if err = s.identity.Auth.RevokeSession(r.Context(), token); err != nil && !errors.Is(err, auth.ErrSessionNotFound) {
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
if err = authhttp.ClearSession(w, s.cookie); err != nil {
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
http.Redirect(w, r, "/login/", http.StatusSeeOther)
}
func (s *Server) app(w http.ResponseWriter, r *http.Request) {
principal, ok := auth.PrincipalFromContext(r.Context())
if !ok {
http.Redirect(w, r, "/login/", http.StatusSeeOther)
return
}
organizations, err := s.identity.OrganizationsForUser(r.Context(), principal.User.ID)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "organization list unavailable")
return
}
if len(organizations) == 0 {
writeProblem(w, http.StatusForbidden, "organization access required")
return
}
queryValues := r.URL.Query()
requested := queryValues.Get("organization")
if len(queryValues) > 0 {
selectedValues, exists := queryValues["organization"]
if !exists || len(queryValues) != 1 || len(selectedValues) != 1 || selectedValues[0] == "" {
writeProblem(w, http.StatusBadRequest, "invalid organization selection")
return
}
}
selected := organizations[0]
if requested != "" {
found := false
for _, organization := range organizations {
if organization.ID == requested {
selected, found = organization, true
break
}
}
if !found {
writeProblem(w, http.StatusForbidden, "organization access denied")
return
}
}
scope := access.Scope{OrganizationID: selected.ID}
decision, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, scope, identity.PermissionDashboardsRead)
if err != nil || !decision.Allowed {
writeProblem(w, http.StatusForbidden, "dashboard access denied")
return
}
token, ok := authhttp.SessionToken(r, s.cookie)
if !ok {
writeProblem(w, http.StatusUnauthorized, "authentication required")
return
}
csrf, err := authhttp.CSRFToken(token, "session:delete")
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
view := site.AppView{
Head: s.head("Overview — Gamertan Observatory", "Recent authorized telemetry and saved Observatory work.", "/app/"),
DisplayName: principal.User.DisplayName, CSRFToken: csrf,
EventsURL: "/app/events?organization=" + url.QueryEscape(selected.ID),
RefreshedAt: s.now().Format("2006-01-02 15:04:05 UTC"),
Organization: site.OrganizationOption{ID: selected.ID, Name: selected.Name, Selected: true},
IncidentsURL: "/app/incidents/?organization=" + url.QueryEscape(selected.ID),
}
projectionStatus, projectionErr := s.store.OrganizationProjectionStatus(r.Context(), selected.ID, s.now())
if projectionErr == nil && projectionStatus.PendingSegments > 0 {
view.PendingBatches = projectionStatus.PendingSegments
view.ProjectionLag = formatProjectionLag(projectionStatus.OldestPendingLag)
}
incidentDecision, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, scope, identity.PermissionIncidentsRead)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "authorization unavailable")
return
}
if incidentDecision.Allowed {
incidents, incidentErr := s.store.Incidents(r.Context(), selected.ID, false, 100)
if incidentErr != nil {
writeProblem(w, http.StatusServiceUnavailable, "incidents unavailable")
return
}
view.OpenIncidents = len(incidents)
}
manage, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, scope, identity.PermissionDashboardsManage)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "authorization unavailable")
return
}
view.CanManage = manage.Allowed
if view.CanManage {
view.ManageCSRF, err = authhttp.CSRFToken(token, "dashboards:manage")
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "session unavailable")
return
}
}
for _, organization := range organizations {
view.Organizations = append(view.Organizations, site.OrganizationOption{ID: organization.ID, Name: organization.Name, Selected: organization.ID == selected.ID})
}
view.Signals = s.overviewSignals(r, selected.ID)
saved, err := s.store.SavedQueries(r.Context(), selected.ID)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "saved queries unavailable")
return
}
for _, item := range saved {
view.SavedQueries = append(view.SavedQueries, site.SavedQuerySummary{ID: item.ID, Name: item.Name, Description: item.Description, Query: item.Query})
}
dashboards, err := s.store.Dashboards(r.Context(), selected.ID)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "dashboards unavailable")
return
}
for _, item := range dashboards {
view.Dashboards = append(view.Dashboards, site.DashboardSummary{Slug: item.Slug, Name: item.Name, Description: item.Description, PanelCount: len(item.Panels)})
}
s.renderHTML(w, r, http.StatusOK, site.App(view))
}
func formatProjectionLag(lag time.Duration) string {
if lag < time.Second {
return "less than one second"
}
return lag.Round(time.Second).String()
}
func (s *Server) overviewSignals(r *http.Request, organizationID string) []site.SignalView {
definitions := []struct {
signal model.Signal
id, name string
description string
}{
{model.SignalLogs, "logs", "logs", "Recent structured events accepted for this organization."},
{model.SignalMetrics, "metrics", "metrics", "Recent numeric observations with a table alternative."},
{model.SignalTraces, "traces", "traces", "Recent spans and their correlation identities."},
{model.SignalDeployments, "deployments", "deployments", "Recent bounded deployment evidence."},
}
views := make([]site.SignalView, 0, len(definitions))
for _, definition := range definitions {
text := string(definition.signal) + " | window 1h | limit 20"
ast, err := query.Parse(text, s.options.MaxQueryRows)
var result query.Result
if err == nil {
result, err = s.store.Query(r.Context(), ast, query.Scope{OrganizationID: organizationID}, s.options.QueryBudget, s.now())
}
table := site.TableView{Caption: "Recent " + definition.name, Columns: []site.TableColumn{{Label: "Status"}}, Empty: "No observations are available in the last hour."}
if err != nil {
table.Empty = "This bounded query is temporarily unavailable."
} else {
table = resultTable("Recent "+definition.name, result)
}
views = append(views, site.SignalView{ID: definition.id, Name: definition.name, Description: definition.description, Query: text, Table: table})
}
return views
}
func resultTable(caption string, result query.Result) site.TableView {
table := site.TableView{Caption: caption, Empty: "No observations are available in the last hour."}
for _, column := range result.Columns {
table.Columns = append(table.Columns, site.TableColumn{Label: column.Field, Unit: column.Unit})
}
for _, row := range result.Rows {
view := site.TableRow{Values: make([]string, len(result.Columns))}
for index := range view.Values {
view.Values[index] = "—"
if index < len(row.Values) && row.Values[index] != nil {
view.Values[index] = boundedCell(*row.Values[index])
}
}
table.Rows = append(table.Rows, view)
}
return table
}
func boundedCell(value string) string {
const maxRunes = 256
if utf8.RuneCountInString(value) <= maxRunes {
return value
}
runes := []rune(value)
return string(runes[:maxRunes]) + "…"
}
func (s *Server) events(w http.ResponseWriter, r *http.Request) {
principal, ok := auth.PrincipalFromContext(r.Context())
if !ok {
writeProblem(w, http.StatusUnauthorized, "authentication required")
return
}
organizationID := r.URL.Query().Get("organization")
if len(r.URL.Query()) != 1 || len(r.URL.Query()["organization"]) != 1 {
writeProblem(w, http.StatusBadRequest, "organization is required")
return
}
scope := access.Scope{OrganizationID: organizationID}
if err := s.identity.ValidateResourceScope(r.Context(), scope); err != nil {
writeProblem(w, http.StatusBadRequest, "invalid organization")
return
}
decision, err := s.identity.Access.Authorize(r.Context(), principal.User.ID, scope, identity.PermissionDashboardsRead)
if err != nil || !decision.Allowed {
writeProblem(w, http.StatusForbidden, "dashboard access denied")
return
}
updates, remove, err := s.refresh.subscribe(organizationID)
if err != nil {
writeProblem(w, http.StatusServiceUnavailable, "live refresh capacity reached")
return
}
defer remove()
flusher, ok := w.(http.Flusher)
if !ok {
writeProblem(w, http.StatusNotImplemented, "streaming unavailable")
return
}
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Accel-Buffering", "no")
_, _ = io.WriteString(w, "event: ready\ndata: {}\n\n")
flusher.Flush()
heartbeat := time.NewTicker(20 * time.Second)
defer heartbeat.Stop()
for {
select {
case <-r.Context().Done():
return
case <-updates:
_, _ = io.WriteString(w, "event: refresh\ndata: {}\n\n")
flusher.Flush()
case <-heartbeat.C:
_, _ = io.WriteString(w, ": keepalive\n\n")
flusher.Flush()
}
}
}
func (s *Server) serveAsset(w http.ResponseWriter, r *http.Request) {
body, contentType, ok := site.Asset(r.URL.Path)
if !ok {
http.NotFound(w, r)
return
}
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body)))
if r.Method != http.MethodHead {
_, _ = w.Write(body)
}
}
func (s *Server) head(title, description, path string) site.HeadView {
return site.HeadView{Title: title, Description: description, CanonicalURL: s.options.PublicOrigin + path, Assets: site.AssetPaths()}
}
func (s *Server) renderHTML(w http.ResponseWriter, r *http.Request, status int, component sando.Component) {
var body bytes.Buffer
if err := sando.Render(r.Context(), &body, component); err != nil {
writeProblem(w, http.StatusInternalServerError, "interface render unavailable")
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Content-Length", fmt.Sprintf("%d", body.Len()))
w.WriteHeader(status)
if r.Method != http.MethodHead {
_, _ = w.Write(body.Bytes())
}
}
func readForm(w http.ResponseWriter, r *http.Request, limit int64, fields ...string) (url.Values, error) {
return readFormFields(w, r, limit, fields, nil)
}
func readFormFields(w http.ResponseWriter, r *http.Request, limit int64, required, optional []string) (url.Values, error) {
mediaType, parameters, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/x-www-form-urlencoded" || len(parameters) > 1 || len(parameters) == 1 && !strings.EqualFold(parameters["charset"], "utf-8") {
return nil, errors.New("URL-encoded form required")
}
body := http.MaxBytesReader(w, r.Body, limit)
defer body.Close()
encoded, err := io.ReadAll(body)
if err != nil || !utf8.Valid(encoded) {
return nil, errors.New("invalid form body")
}
values, err := url.ParseQuery(string(encoded))
if err != nil || len(values) != len(required)+len(optional) {
return nil, errors.New("invalid form fields")
}
for _, field := range required {
if len(values[field]) != 1 || values.Get(field) == "" {
return nil, errors.New("invalid form field")
}
}
for _, field := range optional {
if len(values[field]) != 1 {
return nil, errors.New("invalid form field")
}
}
return values, nil
}
+1122
View File
@@ -0,0 +1,1122 @@
// SPDX-License-Identifier: AGPL-3.0-only
package httpserver
import (
"bytes"
"context"
"crypto/ecdh"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"html"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"gamertan.com/observatory/internal/identity"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/query"
"gamertan.com/observatory/internal/schema"
"gamertan.com/observatory/internal/site"
"gamertan.com/observatory/internal/storage"
"gamertan.com/web/authhttp"
)
func TestHandlerAssignsFreshBoundedRequestIDs(t *testing.T) {
server, store, identities, _ := newUITestServer(t)
defer store.Close()
defer identities.Close()
handler := server.Handler()
var previous string
for _, test := range []struct {
method string
target string
}{
{http.MethodGet, "https://observatory.example/healthz"},
{http.MethodHead, "https://observatory.example/readyz"},
{http.MethodGet, "https://observatory.example/"},
{http.MethodGet, "https://observatory.example/not-found"},
} {
header := http.Header{"X-Request-ID": []string{"attacker-selected"}}
response := perform(handler, test.method, test.target, nil, nil, header)
requestID := response.Header().Get("X-Request-ID")
decoded, err := hex.DecodeString(requestID)
if err != nil || len(decoded) != 16 || requestID == "attacker-selected" || requestID == previous {
t.Fatalf("%s %s request_id=%q decoded=%d err=%v previous=%q", test.method, test.target, requestID, len(decoded), err, previous)
}
previous = requestID
}
}
func TestHTMLInterfaceAuthenticationAssetsAndOverview(t *testing.T) {
server, store, identities, bootstrap := newUITestServer(t)
defer store.Close()
defer identities.Close()
handler := server.Handler()
landing := perform(handler, http.MethodGet, "https://observatory.example/", nil, nil)
if landing.Code != http.StatusOK || landing.Header().Get("Content-Type") != "text/html; charset=utf-8" || !strings.Contains(landing.Body.String(), "Keep the evidence close.") {
t.Fatalf("landing status=%d body=%s", landing.Code, landing.Body.String())
}
csp := landing.Header().Get("Content-Security-Policy")
if strings.Contains(csp, "unsafe-inline") || !strings.Contains(csp, "script-src 'self'") || !strings.Contains(csp, "style-src 'self'") || !strings.Contains(csp, "manifest-src 'self'") || !strings.Contains(csp, "worker-src 'self'") || strings.Contains(landing.Body.String(), "<style") {
t.Fatalf("CSP=%q body=%s", csp, landing.Body.String())
}
if !strings.Contains(landing.Body.String(), `<link rel="manifest" href="/manifest.webmanifest">`) {
t.Fatalf("landing omitted manifest discovery: %s", landing.Body.String())
}
head := perform(handler, http.MethodHead, "https://observatory.example/", nil, nil)
if head.Code != http.StatusOK || head.Body.Len() != 0 || head.Header().Get("Content-Length") != landing.Header().Get("Content-Length") {
t.Fatalf("HEAD status=%d length=%q body=%d", head.Code, head.Header().Get("Content-Length"), head.Body.Len())
}
for _, path := range []string{site.AssetPaths().StylePath, site.AssetPaths().ScriptPath, site.AssetPaths().IconPath} {
asset := perform(handler, http.MethodGet, "https://observatory.example"+path, nil, nil)
if asset.Code != http.StatusOK || asset.Body.Len() == 0 || asset.Header().Get("Cache-Control") != "public, max-age=31536000, immutable" {
t.Fatalf("asset %s status=%d cache=%q", path, asset.Code, asset.Header().Get("Cache-Control"))
}
assetHead := perform(handler, http.MethodHead, "https://observatory.example"+path, nil, nil)
if assetHead.Code != http.StatusOK || assetHead.Body.Len() != 0 || assetHead.Header().Get("Content-Length") != asset.Header().Get("Content-Length") {
t.Fatalf("asset HEAD %s status=%d", path, assetHead.Code)
}
}
manifest := perform(handler, http.MethodGet, "https://observatory.example/manifest.webmanifest", nil, nil)
if manifest.Code != http.StatusOK || manifest.Header().Get("Content-Type") != "application/manifest+json" || !strings.Contains(manifest.Body.String(), site.AssetPaths().IconPath) {
t.Fatalf("manifest status=%d headers=%v body=%s", manifest.Code, manifest.Header(), manifest.Body.String())
}
manifestHead := perform(handler, http.MethodHead, "https://observatory.example/manifest.webmanifest", nil, nil)
if manifestHead.Code != http.StatusOK || manifestHead.Body.Len() != 0 || manifestHead.Header().Get("Content-Length") != manifest.Header().Get("Content-Length") {
t.Fatalf("manifest HEAD status=%d body=%d", manifestHead.Code, manifestHead.Body.Len())
}
worker := perform(handler, http.MethodGet, "https://observatory.example/service-worker.js", nil, nil)
if worker.Code != http.StatusOK || worker.Header().Get("Content-Type") != "text/javascript; charset=utf-8" || worker.Header().Get("Cache-Control") != "no-cache" || worker.Header().Get("Service-Worker-Allowed") != "/" || !strings.Contains(worker.Body.String(), "cache-inbox") {
t.Fatalf("worker status=%d headers=%v", worker.Code, worker.Header())
}
offline := perform(handler, http.MethodGet, "https://observatory.example/offline/", nil, nil)
if offline.Code != http.StatusOK || !strings.Contains(offline.Body.String(), "The evidence is still safe.") {
t.Fatalf("offline status=%d body=%s", offline.Code, offline.Body.String())
}
disabledPush := perform(handler, http.MethodPost, "https://observatory.example/api/v1/push/subscription", strings.NewReader(`{}`), nil)
if disabledPush.Code != http.StatusNotFound {
t.Fatalf("disabled push status=%d body=%s", disabledPush.Code, disabledPush.Body.String())
}
unauthenticated := perform(handler, http.MethodGet, "https://observatory.example/app/", nil, nil)
if unauthenticated.Code != http.StatusSeeOther || unauthenticated.Header().Get("Location") != "/login/" {
t.Fatalf("unauthenticated status=%d location=%q", unauthenticated.Code, unauthenticated.Header().Get("Location"))
}
extraQuery := perform(handler, http.MethodGet, "https://observatory.example/app/?unexpected=true", nil, []*http.Cookie{loginHTML(t, handler)})
if extraQuery.Code != http.StatusBadRequest {
t.Fatalf("unexpected query status=%d", extraQuery.Code)
}
loginCookie := loginHTML(t, handler)
now := server.now()
token, err := store.CreateSource(context.Background(), "ui-source", model.Scope{OrganizationID: bootstrap.Organization.ID, ProjectID: "project-a", EnvironmentID: "production", ServiceID: "service-a"})
if err != nil {
t.Fatal(err)
}
batch := model.Batch{Version: model.BatchVersion, SourceID: "ui-source", StreamID: "requests", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "application.http.request", Attributes: map[string]string{"http.status_code": "200", "http.route": "/"}}}}
body, _ := json.Marshal(batch)
updates, remove, err := server.refresh.subscribe(bootstrap.Organization.ID)
if err != nil {
t.Fatal(err)
}
defer remove()
ingestHeaders := http.Header{"Authorization": []string{"Bearer " + token}, "Content-Type": []string{"application/json"}}
ingest := perform(handler, http.MethodPost, "https://observatory.example/api/v1/ingest/native", bytes.NewReader(body), nil, ingestHeaders)
if ingest.Code != http.StatusAccepted {
t.Fatalf("ingest status=%d body=%s", ingest.Code, ingest.Body.String())
}
pending := perform(handler, http.MethodGet, "https://observatory.example/app/", nil, []*http.Cookie{loginCookie})
if pending.Code != http.StatusOK || !strings.Contains(pending.Body.String(), "Durable evidence is still being indexed.") || !strings.Contains(pending.Body.String(), "Accepted batches safely stored: 1.") || !strings.Contains(pending.Body.String(), `role="status"`) {
t.Fatalf("pending app status=%d body=%s", pending.Code, pending.Body.String())
}
if err = store.Recover(context.Background()); err != nil {
t.Fatal(err)
}
select {
case <-updates:
default:
t.Fatal("successful ingest did not publish organization refresh")
}
app := perform(handler, http.MethodGet, "https://observatory.example/app/", nil, []*http.Cookie{loginCookie})
if app.Code != http.StatusOK || !strings.Contains(app.Body.String(), bootstrap.Organization.Name) || !strings.Contains(app.Body.String(), "application.http.request") || !strings.Contains(app.Body.String(), "Recent metrics") || !strings.Contains(app.Body.String(), "Recent traces") || !strings.Contains(app.Body.String(), "Recent deployments") || !strings.Contains(app.Body.String(), `action="/app/queries/builder/"`) || !strings.Contains(app.Body.String(), "Build a query") {
t.Fatalf("app status=%d body=%s", app.Code, app.Body.String())
}
if strings.Contains(app.Body.String(), "Durable evidence is still being indexed.") {
t.Fatalf("app retained indexing status after projection completed: %s", app.Body.String())
}
for _, forbidden := range []string{"Render #", "request number", "position:sticky", "unsafe-inline"} {
if strings.Contains(app.Body.String(), forbidden) {
t.Fatalf("app exposed forbidden marker %q", forbidden)
}
}
appHead := perform(handler, http.MethodHead, "https://observatory.example/app/", nil, []*http.Cookie{loginCookie})
if appHead.Code != http.StatusOK || appHead.Body.Len() != 0 || appHead.Header().Get("Content-Length") != app.Header().Get("Content-Length") {
t.Fatalf("app HEAD status=%d body=%d", appHead.Code, appHead.Body.Len())
}
sessionToken := loginCookie.Value
csrf, err := authhttp.CSRFToken(sessionToken, "session:delete")
if err != nil {
t.Fatal(err)
}
logout := url.Values{"csrf_token": []string{csrf}}.Encode()
logoutHeaders := http.Header{"Origin": []string{"null"}, "Content-Type": []string{"application/x-www-form-urlencoded"}}
loggedOut := perform(handler, http.MethodPost, "https://observatory.example/logout/", strings.NewReader(logout), []*http.Cookie{loginCookie}, logoutHeaders)
if loggedOut.Code != http.StatusSeeOther || loggedOut.Header().Get("Location") != "/login/" {
t.Fatalf("logout status=%d location=%q", loggedOut.Code, loggedOut.Header().Get("Location"))
}
}
func TestExploreWorkbenchUsesBoundedServerRenderedQueries(t *testing.T) {
server, store, identities, bootstrap := newUITestServer(t)
defer store.Close()
defer identities.Close()
handler := server.Handler()
unauthenticated := perform(handler, http.MethodGet, "https://observatory.example/app/explore/?organization="+url.QueryEscape(bootstrap.Organization.ID), nil, nil)
if unauthenticated.Code != http.StatusSeeOther || unauthenticated.Header().Get("Location") != "/login/" {
t.Fatalf("unauthenticated status=%d location=%q", unauthenticated.Code, unauthenticated.Header().Get("Location"))
}
cookie := loginHTML(t, handler)
missingOrganization := perform(handler, http.MethodGet, "https://observatory.example/app/explore/", nil, []*http.Cookie{cookie})
if missingOrganization.Code != http.StatusBadRequest {
t.Fatalf("missing organization status=%d body=%s", missingOrganization.Code, missingOrganization.Body.String())
}
target := "https://observatory.example/app/explore/?organization=" + url.QueryEscape(bootstrap.Organization.ID)
page := perform(handler, http.MethodGet, target, nil, []*http.Cookie{cookie})
pageBody := page.Body.String()
currentLink := `<a aria-current="page" href="/app/explore/?organization=` + bootstrap.Organization.ID + `">Explore</a>`
if page.Code != http.StatusOK || !strings.Contains(pageBody, "Follow the evidence.") || !strings.Contains(pageBody, currentLink) || !strings.Contains(pageBody, defaultExploreQuery) || strings.Contains(pageBody, "Authorized query results") {
t.Fatalf("explore status=%d body=%s", page.Code, pageBody)
}
if !strings.Contains(pageBody, `method="post" action="/app/explore/?organization=`+bootstrap.Organization.ID+`"`) || strings.Contains(pageBody, "?query=") {
t.Fatalf("explore form did not keep query in POST body: %s", pageBody)
}
head := perform(handler, http.MethodHead, target, nil, []*http.Cookie{cookie})
if head.Code != http.StatusOK || head.Body.Len() != 0 || head.Header().Get("Content-Length") != page.Header().Get("Content-Length") {
t.Fatalf("explore HEAD status=%d length=%q body=%d", head.Code, head.Header().Get("Content-Length"), head.Body.Len())
}
now := server.now()
sourceToken, err := store.CreateSource(context.Background(), "explore-source", model.Scope{OrganizationID: bootstrap.Organization.ID, ProjectID: "project-a", EnvironmentID: "production", ServiceID: "service-a"})
if err != nil {
t.Fatal(err)
}
batch := model.Batch{Version: model.BatchVersion, SourceID: "explore-source", StreamID: "requests", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "application.http.request", Attributes: map[string]string{"http.status_code": "200", "http.route": "/explore-proof"}}}}
if _, err = store.Ingest(context.Background(), sourceToken, batch, now); err != nil {
t.Fatal(err)
}
if err = store.Recover(context.Background()); err != nil {
t.Fatal(err)
}
csrf, err := authhttp.CSRFToken(cookie.Value, "query:execute")
if err != nil {
t.Fatal(err)
}
queryText := `logs | where route == "/explore-proof" | window 1h | limit 10`
form := url.Values{"csrf_token": []string{csrf}, "query": []string{queryText}}.Encode()
headers := http.Header{"Content-Type": []string{"application/x-www-form-urlencoded"}}
result := perform(handler, http.MethodPost, target, strings.NewReader(form), []*http.Cookie{cookie}, headers)
resultBody := result.Body.String()
for _, required := range []string{"Authorized query results", "/explore-proof", "Scanned rows", "Matched rows", "Scanned bytes", "Execution", html.EscapeString(queryText)} {
if !strings.Contains(resultBody, required) {
t.Fatalf("result omitted %q: status=%d body=%s", required, result.Code, resultBody)
}
}
if result.Code != http.StatusOK || strings.Contains(result.Header().Get("Content-Type"), "application/json") {
t.Fatalf("query status=%d type=%q body=%s", result.Code, result.Header().Get("Content-Type"), resultBody)
}
invalidForm := url.Values{"csrf_token": []string{"invalid"}, "query": []string{"logs | limit 10"}}.Encode()
invalid := perform(handler, http.MethodPost, target, strings.NewReader(invalidForm), []*http.Cookie{cookie}, headers)
if invalid.Code != http.StatusForbidden || !strings.Contains(invalid.Body.String(), "query form expired") || strings.Contains(invalid.Header().Get("Content-Type"), "application/json") {
t.Fatalf("invalid CSRF status=%d body=%s", invalid.Code, invalid.Body.String())
}
badQuery := url.Values{"csrf_token": []string{csrf}, "query": []string{"logs | become unbounded"}}.Encode()
rejected := perform(handler, http.MethodPost, target, strings.NewReader(badQuery), []*http.Cookie{cookie}, headers)
if rejected.Code != http.StatusUnprocessableEntity || !strings.Contains(rejected.Body.String(), "could not be parsed") || !strings.Contains(rejected.Body.String(), "logs | become unbounded") {
t.Fatalf("rejected query status=%d body=%s", rejected.Code, rejected.Body.String())
}
}
func TestHTMLLoginFailsClosed(t *testing.T) {
server, store, identities, _ := newUITestServer(t)
defer store.Close()
defer identities.Close()
handler := server.Handler()
wrongOrigin := http.Header{"Origin": []string{"https://attacker.example"}, "Content-Type": []string{"application/x-www-form-urlencoded"}}
result := perform(handler, http.MethodPost, "https://observatory.example/login/", strings.NewReader("identifier=operator&password=do-not-echo"), nil, wrongOrigin)
if result.Code != http.StatusForbidden || !strings.Contains(result.Body.String(), loginFormFailure) || strings.Contains(result.Body.String(), "do-not-echo") || strings.Contains(result.Header().Get("Content-Type"), "application/json") {
t.Fatalf("wrong origin status=%d body=%s", result.Code, result.Body.String())
}
csrfCookie, csrfToken := loginFormCSRF(t, handler)
extraField := http.Header{"Origin": []string{"https://observatory.example"}, "Content-Type": []string{"application/x-www-form-urlencoded"}}
extraForm := url.Values{"csrf_token": []string{csrfToken}, "identifier": []string{"operator"}, "password": []string{"wrong"}, "next": []string{"https://attacker.example"}}.Encode()
result = perform(handler, http.MethodPost, "https://observatory.example/login/", strings.NewReader(extraForm), []*http.Cookie{csrfCookie}, extraField)
if result.Code != http.StatusForbidden || !strings.Contains(result.Body.String(), loginFormFailure) || strings.Contains(result.Body.String(), "attacker.example") || result.Header().Get("Location") != "" {
t.Fatalf("extra field status=%d location=%q body=%s", result.Code, result.Header().Get("Location"), result.Body.String())
}
}
func TestHTMLLoginUsesTokenWhenBrowserOmitsOrObscuresOriginMetadata(t *testing.T) {
server, store, identities, _ := newUITestServer(t)
defer store.Close()
defer identities.Close()
handler := server.Handler()
page := perform(handler, http.MethodGet, "https://observatory.example/login/", nil, nil)
if page.Code != http.StatusOK {
t.Fatalf("login page status=%d body=%s", page.Code, page.Body.String())
}
var csrfCookie *http.Cookie
for _, cookie := range page.Result().Cookies() {
if cookie.Name == loginCSRFCookieName {
csrfCookie = cookie
}
}
if csrfCookie == nil || !csrfCookie.Secure || !csrfCookie.HttpOnly || csrfCookie.SameSite != http.SameSiteStrictMode || csrfCookie.MaxAge != 600 {
t.Fatalf("login CSRF cookie=%+v", csrfCookie)
}
const marker = `name="csrf_token" value="`
start := strings.Index(page.Body.String(), marker)
if start < 0 {
t.Fatalf("login page omitted CSRF token: %s", page.Body.String())
}
start += len(marker)
end := strings.IndexByte(page.Body.String()[start:], '"')
if end < 0 {
t.Fatal("login page CSRF token is unterminated")
}
token := page.Body.String()[start : start+end]
if token == "" || token != csrfCookie.Value {
t.Fatal("login form and cookie CSRF tokens differ")
}
form := url.Values{"csrf_token": []string{token}, "identifier": []string{"not-a-user"}, "password": []string{"not-a-password"}}.Encode()
contentType := http.Header{"Content-Type": []string{"application/x-www-form-urlencoded"}}
omittedMetadata := perform(handler, http.MethodPost, "https://observatory.example/login/", strings.NewReader(form), []*http.Cookie{csrfCookie}, contentType)
if omittedMetadata.Code != http.StatusUnauthorized || strings.Contains(omittedMetadata.Body.String(), "not-a-password") {
t.Fatalf("origin-metadata fallback status=%d body=%s", omittedMetadata.Code, omittedMetadata.Body.String())
}
opaqueSameOriginHeaders := contentType.Clone()
opaqueSameOriginHeaders.Set("Origin", "null")
opaqueSameOriginHeaders.Set("Sec-Fetch-Site", "same-origin")
opaqueSameOrigin := perform(handler, http.MethodPost, "https://observatory.example/login/", strings.NewReader(form), []*http.Cookie{csrfCookie}, opaqueSameOriginHeaders)
if opaqueSameOrigin.Code != http.StatusUnauthorized || strings.Contains(opaqueSameOrigin.Body.String(), "not-a-password") {
t.Fatalf("opaque same-origin fallback status=%d body=%s", opaqueSameOrigin.Code, opaqueSameOrigin.Body.String())
}
withoutToken := perform(handler, http.MethodPost, "https://observatory.example/login/", strings.NewReader("identifier=not-a-user&password=not-a-password"), nil, contentType)
if withoutToken.Code != http.StatusForbidden {
t.Fatalf("originless tokenless status=%d body=%s", withoutToken.Code, withoutToken.Body.String())
}
opaqueWithoutToken := perform(handler, http.MethodPost, "https://observatory.example/login/", strings.NewReader("identifier=not-a-user&password=not-a-password"), nil, opaqueSameOriginHeaders)
if opaqueWithoutToken.Code != http.StatusForbidden {
t.Fatalf("opaque tokenless status=%d body=%s", opaqueWithoutToken.Code, opaqueWithoutToken.Body.String())
}
opaqueWithoutFetchMetadata := contentType.Clone()
opaqueWithoutFetchMetadata.Set("Origin", "null")
opaqueTokenOnly := perform(handler, http.MethodPost, "https://observatory.example/login/", strings.NewReader(form), []*http.Cookie{csrfCookie}, opaqueWithoutFetchMetadata)
if opaqueTokenOnly.Code != http.StatusUnauthorized || !strings.Contains(opaqueTokenOnly.Body.String(), loginCredentialFailure) {
t.Fatalf("opaque origin without same-origin fetch metadata status=%d body=%s", opaqueTokenOnly.Code, opaqueTokenOnly.Body.String())
}
wrongOrigin := contentType.Clone()
wrongOrigin.Set("Origin", "https://attacker.example")
crossSite := perform(handler, http.MethodPost, "https://observatory.example/login/", strings.NewReader(form), []*http.Cookie{csrfCookie}, wrongOrigin)
if crossSite.Code != http.StatusForbidden {
t.Fatalf("cross-site token replay status=%d body=%s", crossSite.Code, crossSite.Body.String())
}
}
func TestTemporaryOperatorMustRotatePasswordBeforeUsingApplication(t *testing.T) {
server, store, identities, _ := newRotationTestServer(t)
defer store.Close()
defer identities.Close()
handler := server.Handler()
const temporary = "temporary correct horse battery staple"
const replacement = "permanent correct horse battery staple"
headers := http.Header{"Origin": []string{"https://observatory.example"}, "Content-Type": []string{"application/x-www-form-urlencoded"}}
login := loginHTMLResponse(t, handler, "operator", temporary)
if login.Code != http.StatusSeeOther || login.Header().Get("Location") != "/account/password/" || strings.Contains(login.Body.String(), temporary) {
t.Fatalf("login status=%d location=%q body=%s", login.Code, login.Header().Get("Location"), login.Body.String())
}
var cookie *http.Cookie
for _, candidate := range login.Result().Cookies() {
if candidate.Name == "__Host-observatory_session" {
cookie = candidate
break
}
}
if cookie == nil {
t.Fatalf("login cookies=%+v", login.Result().Cookies())
}
blocked := perform(handler, http.MethodGet, "https://observatory.example/app/", nil, []*http.Cookie{cookie})
if blocked.Code != http.StatusSeeOther || blocked.Header().Get("Location") != "/account/password/" {
t.Fatalf("blocked app status=%d location=%q", blocked.Code, blocked.Header().Get("Location"))
}
blockedWrite := perform(handler, http.MethodPost, "https://observatory.example/api/v1/query", strings.NewReader(`{}`), []*http.Cookie{cookie}, headers)
if blockedWrite.Code != http.StatusForbidden {
t.Fatalf("blocked write status=%d body=%s", blockedWrite.Code, blockedWrite.Body.String())
}
page := perform(handler, http.MethodGet, "https://observatory.example/account/password/", nil, []*http.Cookie{cookie})
if page.Code != http.StatusOK || !strings.Contains(page.Body.String(), "Choose your password") || strings.Contains(page.Body.String(), temporary) {
t.Fatalf("password page status=%d body=%s", page.Code, page.Body.String())
}
head := perform(handler, http.MethodHead, "https://observatory.example/account/password/", nil, []*http.Cookie{cookie})
if head.Code != http.StatusOK || head.Body.Len() != 0 || head.Header().Get("Content-Length") != page.Header().Get("Content-Length") {
t.Fatalf("password HEAD status=%d length=%q body=%d", head.Code, head.Header().Get("Content-Length"), head.Body.Len())
}
csrf, err := authhttp.CSRFToken(cookie.Value, "account:password:change")
if err != nil {
t.Fatal(err)
}
crossSiteHeaders := http.Header{"Origin": []string{"https://attacker.example"}, "Sec-Fetch-Site": []string{"cross-site"}, "Content-Type": []string{"application/x-www-form-urlencoded"}}
crossSiteForm := url.Values{"csrf_token": []string{csrf}, "current_password": []string{temporary}, "new_password": []string{replacement}, "confirm_password": []string{replacement}}.Encode()
crossSite := perform(handler, http.MethodPost, "https://observatory.example/account/password/", strings.NewReader(crossSiteForm), []*http.Cookie{cookie}, crossSiteHeaders)
if crossSite.Code != http.StatusForbidden || !strings.Contains(crossSite.Body.String(), passwordFormFailure) || strings.Contains(crossSite.Body.String(), temporary) || strings.Contains(crossSite.Body.String(), replacement) || strings.Contains(crossSite.Header().Get("Content-Type"), "application/json") {
t.Fatalf("cross-site password status=%d body=%s", crossSite.Code, crossSite.Body.String())
}
invalidTokenForm := url.Values{"csrf_token": []string{"invalid"}, "current_password": []string{temporary}, "new_password": []string{replacement}, "confirm_password": []string{replacement}}.Encode()
invalidToken := perform(handler, http.MethodPost, "https://observatory.example/account/password/", strings.NewReader(invalidTokenForm), []*http.Cookie{cookie}, headers)
if invalidToken.Code != http.StatusForbidden || !strings.Contains(invalidToken.Body.String(), passwordFormFailure) || strings.Contains(invalidToken.Body.String(), temporary) || strings.Contains(invalidToken.Body.String(), replacement) || strings.Contains(invalidToken.Header().Get("Content-Type"), "application/json") {
t.Fatalf("invalid-token password status=%d body=%s", invalidToken.Code, invalidToken.Body.String())
}
mismatch := url.Values{"csrf_token": []string{csrf}, "current_password": []string{temporary}, "new_password": []string{replacement}, "confirm_password": []string{"different password value"}}.Encode()
rejected := perform(handler, http.MethodPost, "https://observatory.example/account/password/", strings.NewReader(mismatch), []*http.Cookie{cookie}, headers)
if rejected.Code != http.StatusUnprocessableEntity || !strings.Contains(rejected.Body.String(), passwordMatchFailure) || strings.Contains(rejected.Body.String(), temporary) || strings.Contains(rejected.Body.String(), replacement) {
t.Fatalf("mismatch status=%d body=%s", rejected.Code, rejected.Body.String())
}
change := url.Values{"csrf_token": []string{csrf}, "current_password": []string{temporary}, "new_password": []string{replacement}, "confirm_password": []string{replacement}}.Encode()
privacyHeaders := http.Header{"Origin": []string{"null"}, "Content-Type": []string{"application/x-www-form-urlencoded"}}
changed := perform(handler, http.MethodPost, "https://observatory.example/account/password/", strings.NewReader(change), []*http.Cookie{cookie}, privacyHeaders)
if changed.Code != http.StatusSeeOther || changed.Header().Get("Location") != "/login/?password=changed" {
t.Fatalf("change status=%d location=%q body=%s", changed.Code, changed.Header().Get("Location"), changed.Body.String())
}
oldSession := perform(handler, http.MethodGet, "https://observatory.example/app/", nil, []*http.Cookie{cookie})
if oldSession.Code != http.StatusSeeOther || oldSession.Header().Get("Location") != "/login/" {
t.Fatalf("old session status=%d location=%q", oldSession.Code, oldSession.Header().Get("Location"))
}
if _, _, err = identities.Auth.Authenticate(t.Context(), "operator", temporary, time.Hour); err == nil {
t.Fatal("temporary password remained valid")
}
_, principal, err := identities.Auth.Authenticate(t.Context(), "operator", replacement, time.Hour)
if err != nil || principal.User.PasswordChangeRequired {
t.Fatalf("replacement principal=%+v err=%v", principal, err)
}
newLogin := loginHTMLResponse(t, handler, "operator", replacement)
if newLogin.Code != http.StatusSeeOther || newLogin.Header().Get("Location") != "/app/" {
t.Fatalf("new login status=%d location=%q", newLogin.Code, newLogin.Header().Get("Location"))
}
}
func TestAPITemporaryOperatorReceivesScopedRotationToken(t *testing.T) {
server, store, identities, _ := newRotationTestServer(t)
defer store.Close()
defer identities.Close()
handler := server.Handler()
loginHeaders := http.Header{"Origin": []string{"https://observatory.example"}, "Content-Type": []string{"application/json"}}
login := perform(handler, http.MethodPost, "https://observatory.example/api/v1/session", strings.NewReader(`{"identifier":"operator","password":"temporary correct horse battery staple"}`), nil, loginHeaders)
var session struct {
PasswordChangeRequired bool `json:"password_change_required"`
PasswordChangeCSRF string `json:"password_change_csrf"`
}
if login.Code != http.StatusOK || json.Unmarshal(login.Body.Bytes(), &session) != nil || !session.PasswordChangeRequired || session.PasswordChangeCSRF == "" {
t.Fatalf("login status=%d session=%+v body=%s", login.Code, session, login.Body.String())
}
cookies := login.Result().Cookies()
changeHeaders := http.Header{"Origin": []string{"https://observatory.example"}, "Content-Type": []string{"application/json"}, "X-CSRF-Token": []string{session.PasswordChangeCSRF}}
changed := perform(handler, http.MethodPost, "https://observatory.example/api/v1/account/password", strings.NewReader(`{"current_password":"temporary correct horse battery staple","new_password":"API replacement password value"}`), cookies, changeHeaders)
if changed.Code != http.StatusNoContent || changed.Body.Len() != 0 {
t.Fatalf("change status=%d body=%s", changed.Code, changed.Body.String())
}
_, principal, err := identities.Auth.Authenticate(t.Context(), "operator", "API replacement password value", time.Hour)
if err != nil || principal.User.PasswordChangeRequired {
t.Fatalf("principal=%+v err=%v", principal, err)
}
}
func TestLiveRefreshStreamIsAuthorizedAndCarriesNoTelemetry(t *testing.T) {
server, store, identities, bootstrap := newUITestServer(t)
defer store.Close()
defer identities.Close()
handler := server.Handler()
unauthorized := perform(handler, http.MethodGet, "https://observatory.example/app/events?organization="+url.QueryEscape(bootstrap.Organization.ID), nil, nil)
if unauthorized.Code != http.StatusUnauthorized {
t.Fatalf("unauthorized stream status=%d", unauthorized.Code)
}
cookie := loginHTML(t, handler)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
request := httptest.NewRequest(http.MethodGet, "https://observatory.example/app/events?organization="+url.QueryEscape(bootstrap.Organization.ID), nil).WithContext(ctx)
request.AddCookie(cookie)
stream := newStreamRecorder()
done := make(chan struct{})
go func() {
handler.ServeHTTP(stream, request)
close(done)
}()
waitFlush := func() {
t.Helper()
select {
case <-stream.flushed:
case <-ctx.Done():
t.Fatal("stream did not flush before timeout")
}
}
waitFlush()
if stream.statusCode() != http.StatusOK || stream.Header().Get("Content-Type") != "text/event-stream; charset=utf-8" || stream.Header().Get("X-Accel-Buffering") != "no" || stream.bodyString() != "event: ready\ndata: {}\n\n" {
t.Fatalf("stream status=%d headers=%v body=%q", stream.statusCode(), stream.Header(), stream.bodyString())
}
server.refresh.publish(bootstrap.Organization.ID)
waitFlush()
streamBody := stream.bodyString()
if streamBody != "event: ready\ndata: {}\n\nevent: refresh\ndata: {}\n\n" || strings.Contains(streamBody, bootstrap.Organization.ID) || strings.Contains(streamBody, "service") {
t.Fatalf("stream body=%q", streamBody)
}
cancel()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("stream did not stop after cancellation")
}
}
func TestDashboardManagementIsScopedCSRFProtectedAndExportable(t *testing.T) {
server, store, identities, bootstrap := newUITestServer(t)
defer store.Close()
defer identities.Close()
handler := server.Handler()
cookie := loginHTML(t, handler)
csrf, err := authhttp.CSRFToken(cookie.Value, "dashboards:manage")
if err != nil {
t.Fatal(err)
}
headers := http.Header{"Origin": []string{"https://observatory.example"}, "Content-Type": []string{"application/x-www-form-urlencoded"}}
invalid := url.Values{
"organization_id": []string{bootstrap.Organization.ID}, "csrf_token": []string{"invalid"},
"name": []string{"Recent errors"}, "description": []string{"A bounded recent error view."},
"query": []string{"logs | where status >= 500 | window 1h | limit 50"},
}.Encode()
denied := perform(handler, http.MethodPost, "https://observatory.example/app/queries/", strings.NewReader(invalid), []*http.Cookie{cookie}, headers)
if denied.Code != http.StatusForbidden {
t.Fatalf("invalid CSRF status=%d", denied.Code)
}
queryForm := url.Values{
"organization_id": []string{bootstrap.Organization.ID}, "csrf_token": []string{csrf},
"name": []string{"Recent errors"}, "description": []string{"A bounded recent error view."},
"query": []string{"logs | where status >= 500 | window 1h | limit 50"},
}.Encode()
privacyHeaders := http.Header{"Origin": []string{"null"}, "Content-Type": []string{"application/x-www-form-urlencoded"}}
createdQuery := perform(handler, http.MethodPost, "https://observatory.example/app/queries/", strings.NewReader(queryForm), []*http.Cookie{cookie}, privacyHeaders)
if createdQuery.Code != http.StatusSeeOther || !strings.HasPrefix(createdQuery.Header().Get("Location"), "/app/?organization=") {
t.Fatalf("query status=%d location=%q body=%s", createdQuery.Code, createdQuery.Header().Get("Location"), createdQuery.Body.String())
}
queries, err := store.SavedQueries(context.Background(), bootstrap.Organization.ID)
if err != nil || len(queries) != 1 {
t.Fatalf("queries=%+v err=%v", queries, err)
}
mismatchedDashboard := url.Values{
"organization_id": []string{bootstrap.Organization.ID}, "csrf_token": []string{csrf},
"slug": []string{"invalid-stat"}, "name": []string{"Invalid stat"},
"description": []string{"A non-summary query cannot become a statistic."}, "panel_title": []string{"Invalid"},
"saved_query_id": []string{queries[0].ID}, "visualization": []string{"stat"},
}.Encode()
mismatched := perform(handler, http.MethodPost, "https://observatory.example/app/dashboards/", strings.NewReader(mismatchedDashboard), []*http.Cookie{cookie}, headers)
if mismatched.Code != http.StatusUnprocessableEntity {
t.Fatalf("mismatched presentation status=%d body=%s", mismatched.Code, mismatched.Body.String())
}
dashboardForm := url.Values{
"organization_id": []string{bootstrap.Organization.ID}, "csrf_token": []string{csrf},
"slug": []string{"recent-errors"}, "name": []string{"Recent errors"},
"description": []string{"An accessible bounded error dashboard."}, "panel_title": []string{"Errors"},
"saved_query_id": []string{queries[0].ID}, "visualization": []string{"table"},
}.Encode()
createdDashboard := perform(handler, http.MethodPost, "https://observatory.example/app/dashboards/", strings.NewReader(dashboardForm), []*http.Cookie{cookie}, headers)
if createdDashboard.Code != http.StatusSeeOther || !strings.HasPrefix(createdDashboard.Header().Get("Location"), "/app/dashboards/recent-errors/") {
t.Fatalf("dashboard status=%d location=%q body=%s", createdDashboard.Code, createdDashboard.Header().Get("Location"), createdDashboard.Body.String())
}
target := "https://observatory.example/app/dashboards/recent-errors/?organization=" + url.QueryEscape(bootstrap.Organization.ID)
dashboard := perform(handler, http.MethodGet, target, nil, []*http.Cookie{cookie})
if dashboard.Code != http.StatusOK || !strings.Contains(dashboard.Body.String(), "An accessible bounded error dashboard.") || !strings.Contains(dashboard.Body.String(), "Recent errors") || !strings.Contains(dashboard.Body.String(), ">Errors</h2>") {
t.Fatalf("dashboard status=%d body=%s", dashboard.Code, dashboard.Body.String())
}
dashboardHead := perform(handler, http.MethodHead, target, nil, []*http.Cookie{cookie})
if dashboardHead.Code != http.StatusOK || dashboardHead.Body.Len() != 0 || dashboardHead.Header().Get("Content-Length") != dashboard.Header().Get("Content-Length") {
t.Fatalf("dashboard HEAD status=%d length=%q", dashboardHead.Code, dashboardHead.Header().Get("Content-Length"))
}
storedDashboard, err := store.Dashboard(context.Background(), bootstrap.Organization.ID, "recent-errors")
if err != nil || storedDashboard.Revision != 1 || !strings.Contains(dashboard.Body.String(), "Update dashboard details") || !strings.Contains(dashboard.Body.String(), `name="expected_revision" value="1"`) {
t.Fatalf("stored dashboard=%+v err=%v body=%s", storedDashboard, err, dashboard.Body.String())
}
revisionForm := url.Values{
"organization_id": []string{bootstrap.Organization.ID}, "csrf_token": []string{csrf},
"dashboard_id": []string{storedDashboard.ID}, "expected_revision": []string{strconv.Itoa(storedDashboard.Revision)},
"slug": []string{storedDashboard.Slug}, "name": []string{"Current errors"},
"description": []string{"A revision-safe bounded error dashboard."},
}.Encode()
revised := perform(handler, http.MethodPost, target, strings.NewReader(revisionForm), []*http.Cookie{cookie}, headers)
if revised.Code != http.StatusSeeOther {
t.Fatalf("revision status=%d body=%s", revised.Code, revised.Body.String())
}
stale := perform(handler, http.MethodPost, target, strings.NewReader(revisionForm), []*http.Cookie{cookie}, headers)
if stale.Code != http.StatusConflict {
t.Fatalf("stale revision status=%d body=%s", stale.Code, stale.Body.String())
}
storedDashboard, err = store.Dashboard(context.Background(), bootstrap.Organization.ID, "recent-errors")
if err != nil || storedDashboard.Revision != 2 || storedDashboard.Name != "Current errors" {
t.Fatalf("revised dashboard=%+v err=%v", storedDashboard, err)
}
addPanelForm := url.Values{
"organization_id": []string{bootstrap.Organization.ID}, "csrf_token": []string{csrf},
"dashboard_id": []string{storedDashboard.ID}, "expected_revision": []string{strconv.Itoa(storedDashboard.Revision)},
"panel_title": []string{"Recent failures"}, "saved_query_id": []string{queries[0].ID}, "visualization": []string{"table"},
}.Encode()
addTarget := "https://observatory.example/app/dashboards/recent-errors/panels/?organization=" + url.QueryEscape(bootstrap.Organization.ID)
added := perform(handler, http.MethodPost, addTarget, strings.NewReader(addPanelForm), []*http.Cookie{cookie}, headers)
if added.Code != http.StatusSeeOther {
t.Fatalf("add panel status=%d body=%s", added.Code, added.Body.String())
}
storedDashboard, err = store.Dashboard(context.Background(), bootstrap.Organization.ID, "recent-errors")
if err != nil || storedDashboard.Revision != 3 || len(storedDashboard.Panels) != 2 {
t.Fatalf("dashboard after add=%+v err=%v", storedDashboard, err)
}
addedPanel := storedDashboard.Panels[1]
updatePanelForm := url.Values{
"organization_id": []string{bootstrap.Organization.ID}, "csrf_token": []string{csrf},
"dashboard_id": []string{storedDashboard.ID}, "expected_revision": []string{strconv.Itoa(storedDashboard.Revision)},
"panel_title": []string{"Renamed failures"}, "saved_query_id": []string{queries[0].ID}, "visualization": []string{"table"},
}.Encode()
updatePanelTarget := "https://observatory.example/app/dashboards/recent-errors/panels/" + url.PathEscape(addedPanel.ID) + "/?organization=" + url.QueryEscape(bootstrap.Organization.ID)
updatedPanel := perform(handler, http.MethodPost, updatePanelTarget, strings.NewReader(updatePanelForm), []*http.Cookie{cookie}, headers)
if updatedPanel.Code != http.StatusSeeOther {
t.Fatalf("update panel status=%d body=%s", updatedPanel.Code, updatedPanel.Body.String())
}
storedDashboard, err = store.Dashboard(context.Background(), bootstrap.Organization.ID, "recent-errors")
if err != nil || storedDashboard.Revision != 4 || storedDashboard.Panels[1].Title != "Renamed failures" {
t.Fatalf("dashboard after panel update=%+v err=%v", storedDashboard, err)
}
mismatchedRevision := url.Values{
"organization_id": []string{bootstrap.Organization.ID}, "csrf_token": []string{csrf},
"dashboard_id": []string{storedDashboard.ID}, "expected_revision": []string{strconv.Itoa(storedDashboard.Revision)},
"panel_title": []string{"Invalid chart"}, "saved_query_id": []string{queries[0].ID}, "visualization": []string{"timeseries"},
}.Encode()
mismatchedPanel := perform(handler, http.MethodPost, updatePanelTarget, strings.NewReader(mismatchedRevision), []*http.Cookie{cookie}, headers)
if mismatchedPanel.Code != http.StatusUnprocessableEntity {
t.Fatalf("mismatched panel status=%d body=%s", mismatchedPanel.Code, mismatchedPanel.Body.String())
}
removePanelForm := url.Values{
"organization_id": []string{bootstrap.Organization.ID}, "csrf_token": []string{csrf},
"dashboard_id": []string{storedDashboard.ID}, "expected_revision": []string{strconv.Itoa(storedDashboard.Revision)},
}.Encode()
removeTarget := "https://observatory.example/app/dashboards/recent-errors/panels/" + url.PathEscape(addedPanel.ID) + "/remove/?organization=" + url.QueryEscape(bootstrap.Organization.ID)
removed := perform(handler, http.MethodPost, removeTarget, strings.NewReader(removePanelForm), []*http.Cookie{cookie}, headers)
if removed.Code != http.StatusSeeOther {
t.Fatalf("remove panel status=%d body=%s", removed.Code, removed.Body.String())
}
storedDashboard, err = store.Dashboard(context.Background(), bootstrap.Organization.ID, "recent-errors")
if err != nil || storedDashboard.Revision != 5 || len(storedDashboard.Panels) != 1 {
t.Fatalf("dashboard after remove=%+v err=%v", storedDashboard, err)
}
exportTarget := "https://observatory.example/app/dashboards/recent-errors/export.json?organization=" + url.QueryEscape(bootstrap.Organization.ID)
exported := perform(handler, http.MethodGet, exportTarget, nil, []*http.Cookie{cookie})
if exported.Code != http.StatusOK || exported.Header().Get("Content-Type") != "application/json" || !strings.Contains(exported.Body.String(), `"version": 1`) || strings.Contains(exported.Body.String(), bootstrap.Organization.ID) || strings.Contains(exported.Body.String(), bootstrap.User.ID) {
t.Fatalf("export status=%d headers=%v body=%s", exported.Code, exported.Header(), exported.Body.String())
}
exportedHead := perform(handler, http.MethodHead, exportTarget, nil, []*http.Cookie{cookie})
if exportedHead.Code != http.StatusOK || exportedHead.Body.Len() != 0 || exportedHead.Header().Get("Content-Length") != exported.Header().Get("Content-Length") {
t.Fatalf("export HEAD status=%d length=%q", exportedHead.Code, exportedHead.Header().Get("Content-Length"))
}
unauthorized := perform(handler, http.MethodGet, exportTarget, nil, nil)
if unauthorized.Code != http.StatusUnauthorized || unauthorized.Body.String() == exported.Body.String() {
t.Fatalf("unauthorized export status=%d", unauthorized.Code)
}
}
func TestIncidentRulesEvaluationInboxAndResponseAreScoped(t *testing.T) {
server, store, identities, bootstrap := newUITestServer(t)
defer store.Close()
defer identities.Close()
pushes := &recordingPushDispatcher{}
server.options.PushDispatcher = pushes
server.options.PushPublicKey = base64.RawURLEncoding.EncodeToString(append([]byte{4}, make([]byte, 64)...))
handler := server.Handler()
cookie := loginHTML(t, handler)
now := server.now()
saved, err := store.SaveQuery(context.Background(), storage.SavedQueryInput{
OrganizationID: bootstrap.Organization.ID, ActorUserID: bootstrap.User.ID, MaxRows: 100,
Name: "Recent failures", Description: "Recent HTTP failures.", Query: "logs | where status >= 500 | window 1h | limit 50",
}, now)
if err != nil {
t.Fatal(err)
}
token, err := store.CreateSource(context.Background(), "incident-source", model.Scope{OrganizationID: bootstrap.Organization.ID, ProjectID: "project-a", EnvironmentID: "production", ServiceID: "service-a"})
if err != nil {
t.Fatal(err)
}
batch := model.Batch{Version: model.BatchVersion, SourceID: "incident-source", StreamID: "requests", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "http.request", Attributes: map[string]string{"http.status_code": "503", "http.route": "/failed"}}}}
if _, err = store.Ingest(context.Background(), token, batch, now); err != nil {
t.Fatal(err)
}
if err = store.Recover(context.Background()); err != nil {
t.Fatal(err)
}
csrf, err := authhttp.CSRFToken(cookie.Value, "incidents:manage")
if err != nil {
t.Fatal(err)
}
headers := http.Header{"Origin": []string{"https://observatory.example"}, "Content-Type": []string{"application/x-www-form-urlencoded"}}
form := url.Values{
"organization_id": []string{bootstrap.Organization.ID}, "csrf_token": []string{csrf},
"name": []string{"HTTP failures"}, "description": []string{"Open when a bounded saved query finds a failure."},
"saved_query_id": []string{saved.ID}, "severity": []string{"critical"}, "minimum_matches": []string{"1"},
"required_consecutive": []string{"1"}, "evaluation_interval": []string{"15s"},
}
invalid := cloneValues(form)
invalid.Set("csrf_token", "invalid")
denied := perform(handler, http.MethodPost, "https://observatory.example/app/alert-rules/", strings.NewReader(invalid.Encode()), []*http.Cookie{cookie}, headers)
if denied.Code != http.StatusForbidden {
t.Fatalf("invalid CSRF status=%d body=%s", denied.Code, denied.Body.String())
}
privacyHeaders := http.Header{"Origin": []string{"null"}, "Content-Type": []string{"application/x-www-form-urlencoded"}}
created := perform(handler, http.MethodPost, "https://observatory.example/app/alert-rules/", strings.NewReader(form.Encode()), []*http.Cookie{cookie}, privacyHeaders)
if created.Code != http.StatusSeeOther || !strings.HasPrefix(created.Header().Get("Location"), "/app/incidents/?organization=") {
t.Fatalf("create status=%d location=%q body=%s", created.Code, created.Header().Get("Location"), created.Body.String())
}
updates, remove, err := server.refresh.subscribe(bootstrap.Organization.ID)
if err != nil {
t.Fatal(err)
}
defer remove()
if evaluated, evaluationErr := server.EvaluateAlerts(context.Background()); evaluationErr != nil || evaluated != 1 {
t.Fatalf("evaluated=%d err=%v", evaluated, evaluationErr)
}
if len(pushes.organizations) != 1 || pushes.organizations[0] != bootstrap.Organization.ID {
t.Fatalf("push organizations=%v", pushes.organizations)
}
select {
case <-updates:
default:
t.Fatal("incident change did not publish a generic refresh")
}
incidents, err := store.Incidents(context.Background(), bootstrap.Organization.ID, false, 10)
if err != nil || len(incidents) != 1 || incidents[0].State != "firing" {
t.Fatalf("incidents=%+v err=%v", incidents, err)
}
path := "https://observatory.example/app/incidents/?organization=" + url.QueryEscape(bootstrap.Organization.ID)
inbox := perform(handler, http.MethodGet, path, nil, []*http.Cookie{cookie})
if inbox.Code != http.StatusOK || !strings.Contains(inbox.Body.String(), "What needs attention?") || !strings.Contains(inbox.Body.String(), "HTTP failures") || !strings.Contains(inbox.Body.String(), "critical · firing") || !strings.Contains(inbox.Body.String(), "data-cache-inbox") || !strings.Contains(inbox.Body.String(), "data-push-toggle") || !strings.Contains(inbox.Body.String(), `data-open-incident-count="1"`) || strings.Contains(inbox.Body.String(), "/failed") {
t.Fatalf("inbox status=%d body=%s", inbox.Code, inbox.Body.String())
}
pushCSRF, err := authhttp.CSRFToken(cookie.Value, "push:manage")
if err != nil {
t.Fatal(err)
}
clientKey, err := ecdh.P256().GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
authSecret := make([]byte, 16)
if _, err = rand.Read(authSecret); err != nil {
t.Fatal(err)
}
pushBody, _ := json.Marshal(map[string]any{"organization_id": bootstrap.Organization.ID, "endpoint": "https://push.example.test/send/browser", "keys": map[string]string{"p256dh": base64.RawURLEncoding.EncodeToString(clientKey.PublicKey().Bytes()), "auth": base64.RawURLEncoding.EncodeToString(authSecret)}})
pushHeaders := make(http.Header)
pushHeaders.Set("Origin", "https://observatory.example")
pushHeaders.Set("Content-Type", "application/json")
pushHeaders.Set("X-CSRF-Token", pushCSRF)
invalidPushHeaders := pushHeaders.Clone()
invalidPushHeaders.Set("X-CSRF-Token", "invalid")
invalidPush := perform(handler, http.MethodPost, "https://observatory.example/api/v1/push/subscription", bytes.NewReader(pushBody), []*http.Cookie{cookie}, invalidPushHeaders)
if invalidPush.Code != http.StatusForbidden {
t.Fatalf("invalid push CSRF status=%d body=%s", invalidPush.Code, invalidPush.Body.String())
}
crossOriginPushHeaders := pushHeaders.Clone()
crossOriginPushHeaders.Set("Origin", "https://attacker.example")
crossOriginPush := perform(handler, http.MethodPost, "https://observatory.example/api/v1/push/subscription", bytes.NewReader(pushBody), []*http.Cookie{cookie}, crossOriginPushHeaders)
if crossOriginPush.Code != http.StatusForbidden {
t.Fatalf("cross-origin push status=%d body=%s", crossOriginPush.Code, crossOriginPush.Body.String())
}
registered := perform(handler, http.MethodPost, "https://observatory.example/api/v1/push/subscription", bytes.NewReader(pushBody), []*http.Cookie{cookie}, pushHeaders)
if registered.Code != http.StatusCreated || !strings.Contains(registered.Body.String(), `"id":"push_`) {
t.Fatalf("push registration status=%d body=%s", registered.Code, registered.Body.String())
}
if subscriptions, listErr := store.PushSubscriptions(context.Background(), bootstrap.Organization.ID); listErr != nil || len(subscriptions) != 1 || subscriptions[0].UserID != bootstrap.User.ID {
t.Fatalf("push subscriptions=%+v err=%v", subscriptions, listErr)
}
statusBody, _ := json.Marshal(map[string]any{"organization_id": bootstrap.Organization.ID, "endpoint": "https://push.example.test/send/browser", "keys": map[string]string{"p256dh": "", "auth": ""}})
pushStatus := perform(handler, http.MethodPost, "https://observatory.example/api/v1/push/subscription/status", bytes.NewReader(statusBody), []*http.Cookie{cookie}, pushHeaders)
if pushStatus.Code != http.StatusOK || !strings.Contains(pushStatus.Body.String(), `"subscribed":true`) {
t.Fatalf("push status=%d body=%s", pushStatus.Code, pushStatus.Body.String())
}
privateEndpointBody := bytes.Replace(pushBody, []byte("https://push.example.test/send/browser"), []byte("https://127.0.0.1/send/browser"), 1)
rejected := perform(handler, http.MethodPost, "https://observatory.example/api/v1/push/subscription", bytes.NewReader(privateEndpointBody), []*http.Cookie{cookie}, pushHeaders)
if rejected.Code != http.StatusUnprocessableEntity || strings.Contains(rejected.Body.String(), "127.0.0.1") {
t.Fatalf("private endpoint status=%d body=%s", rejected.Code, rejected.Body.String())
}
invalidCurveBody, _ := json.Marshal(map[string]any{"organization_id": bootstrap.Organization.ID, "endpoint": "https://push.example.test/send/invalid-curve", "keys": map[string]string{"p256dh": base64.RawURLEncoding.EncodeToString(append([]byte{4}, make([]byte, 64)...)), "auth": base64.RawURLEncoding.EncodeToString(authSecret)}})
invalidCurve := perform(handler, http.MethodPost, "https://observatory.example/api/v1/push/subscription", bytes.NewReader(invalidCurveBody), []*http.Cookie{cookie}, pushHeaders)
if invalidCurve.Code != http.StatusUnprocessableEntity {
t.Fatalf("invalid curve status=%d body=%s", invalidCurve.Code, invalidCurve.Body.String())
}
deleteBody, _ := json.Marshal(map[string]any{"organization_id": bootstrap.Organization.ID, "endpoint": "https://push.example.test/send/browser", "keys": map[string]string{"p256dh": "", "auth": ""}})
deleted := perform(handler, http.MethodDelete, "https://observatory.example/api/v1/push/subscription", bytes.NewReader(deleteBody), []*http.Cookie{cookie}, pushHeaders)
if deleted.Code != http.StatusOK || !strings.Contains(deleted.Body.String(), `"remaining":false`) {
t.Fatalf("push deletion status=%d body=%s", deleted.Code, deleted.Body.String())
}
offlineInbox := perform(handler, http.MethodGet, "https://observatory.example/app/incidents/offline/?organization="+url.QueryEscape(bootstrap.Organization.ID), nil, []*http.Cookie{cookie})
if offlineInbox.Code != http.StatusOK || !strings.Contains(offlineInbox.Body.String(), "Saved incident inbox") || !strings.Contains(offlineInbox.Body.String(), "HTTP failures") {
t.Fatalf("offline inbox status=%d body=%s", offlineInbox.Code, offlineInbox.Body.String())
}
for _, forbidden := range []string{incidents[0].ID, saved.Query, bootstrap.User.ID, "csrf_token", "/failed", "Acknowledge", "Resolve"} {
if strings.Contains(offlineInbox.Body.String(), forbidden) {
t.Fatalf("offline inbox exposed %q: %s", forbidden, offlineInbox.Body.String())
}
}
unauthenticatedOffline := perform(handler, http.MethodGet, "https://observatory.example/app/incidents/offline/?organization="+url.QueryEscape(bootstrap.Organization.ID), nil, nil)
if unauthenticatedOffline.Code != http.StatusSeeOther || unauthenticatedOffline.Header().Get("Location") != "/login/" {
t.Fatalf("unauthenticated offline status=%d", unauthenticatedOffline.Code)
}
inboxHead := perform(handler, http.MethodHead, path, nil, []*http.Cookie{cookie})
if inboxHead.Code != http.StatusOK || inboxHead.Body.Len() != 0 || inboxHead.Header().Get("Content-Length") != inbox.Header().Get("Content-Length") {
t.Fatalf("inbox HEAD status=%d length=%q body=%d", inboxHead.Code, inboxHead.Header().Get("Content-Length"), inboxHead.Body.Len())
}
missingOrganization := perform(handler, http.MethodGet, "https://observatory.example/app/incidents/", nil, []*http.Cookie{cookie})
if missingOrganization.Code != http.StatusBadRequest {
t.Fatalf("missing organization status=%d", missingOrganization.Code)
}
action := url.Values{"organization_id": []string{bootstrap.Organization.ID}, "csrf_token": []string{csrf}, "action": []string{"acknowledge"}, "silence_duration": []string{""}}.Encode()
acknowledged := perform(handler, http.MethodPost, "https://observatory.example/app/incidents/"+incidents[0].ID+"/", strings.NewReader(action), []*http.Cookie{cookie}, headers)
if acknowledged.Code != http.StatusSeeOther {
t.Fatalf("acknowledge status=%d body=%s", acknowledged.Code, acknowledged.Body.String())
}
current, err := store.Incidents(context.Background(), bootstrap.Organization.ID, false, 10)
if err != nil || len(current) != 1 || current[0].State != "acknowledged" || current[0].AcknowledgedBy != bootstrap.User.ID {
t.Fatalf("current=%+v err=%v", current, err)
}
}
type recordingPushDispatcher struct{ organizations []string }
func (dispatcher *recordingPushDispatcher) Enqueue(organizationID string) bool {
dispatcher.organizations = append(dispatcher.organizations, organizationID)
return true
}
func cloneValues(input url.Values) url.Values {
result := make(url.Values, len(input))
for key, values := range input {
result[key] = append([]string(nil), values...)
}
return result
}
func TestAssistedQueryBuilderCreatesTypedTimeSeriesWithTableAlternative(t *testing.T) {
server, store, identities, bootstrap := newUITestServer(t)
defer store.Close()
defer identities.Close()
handler := server.Handler()
cookie := loginHTML(t, handler)
csrf, err := authhttp.CSRFToken(cookie.Value, "dashboards:manage")
if err != nil {
t.Fatal(err)
}
now := server.now()
token, err := store.CreateSource(context.Background(), "builder-source", model.Scope{OrganizationID: bootstrap.Organization.ID, ProjectID: "project-a", EnvironmentID: "production", ServiceID: "service-a"})
if err != nil {
t.Fatal(err)
}
batch := model.Batch{Version: model.BatchVersion, SourceID: "builder-source", StreamID: "requests", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{
{Timestamp: now.Add(-6 * time.Minute), Name: "application.http.request", Attributes: map[string]string{"http.status_code": "503", "http.route": "/failed"}},
{Timestamp: now.Add(-1 * time.Minute), Name: "application.http.request", Attributes: map[string]string{"http.status_code": "500", "http.route": "/failed"}},
}}
if _, err = store.Ingest(context.Background(), token, batch, now); err != nil {
t.Fatal(err)
}
if err = store.Recover(context.Background()); err != nil {
t.Fatal(err)
}
headers := http.Header{"Origin": []string{"https://observatory.example"}, "Content-Type": []string{"application/x-www-form-urlencoded"}}
builderForm := url.Values{
"organization_id": []string{bootstrap.Organization.ID}, "csrf_token": []string{csrf},
"name": []string{"Errors over time"}, "description": []string{"Five-minute error counts."},
"signal": []string{"logs"}, "filter_field": []string{"status"}, "filter_operator": []string{">="}, "filter_value": []string{"500"},
"window": []string{"1h"}, "aggregate": []string{"count"}, "aggregate_field": []string{""}, "group_by": []string{"route"}, "bucket": []string{"5m"}, "limit": []string{"50"},
}.Encode()
createdQuery := perform(handler, http.MethodPost, "https://observatory.example/app/queries/builder/", strings.NewReader(builderForm), []*http.Cookie{cookie}, headers)
if createdQuery.Code != http.StatusSeeOther {
t.Fatalf("builder status=%d body=%s", createdQuery.Code, createdQuery.Body.String())
}
queries, err := store.SavedQueries(context.Background(), bootstrap.Organization.ID)
if err != nil || len(queries) != 1 {
t.Fatalf("queries=%+v err=%v", queries, err)
}
expectedText := `logs | where status >= "500" | window 1h | summarize count() by route, window(5m) | limit 50`
if queries[0].Query != expectedText || queries[0].AST.Signal != model.SignalLogs || len(queries[0].AST.Filters) != 1 || queries[0].AST.Filters[0].Value != "500" || queries[0].AST.Summary == nil || queries[0].AST.Bucket != 5*time.Minute {
t.Fatalf("saved query=%+v", queries[0])
}
dashboardForm := url.Values{
"organization_id": []string{bootstrap.Organization.ID}, "csrf_token": []string{csrf},
"slug": []string{"error-rate"}, "name": []string{"Error rate"}, "description": []string{"A bounded error trend."},
"panel_title": []string{"Errors by route"}, "saved_query_id": []string{queries[0].ID}, "visualization": []string{"timeseries"},
}.Encode()
createdDashboard := perform(handler, http.MethodPost, "https://observatory.example/app/dashboards/", strings.NewReader(dashboardForm), []*http.Cookie{cookie}, headers)
if createdDashboard.Code != http.StatusSeeOther {
t.Fatalf("dashboard status=%d body=%s", createdDashboard.Code, createdDashboard.Body.String())
}
target := "https://observatory.example/app/dashboards/error-rate/?organization=" + url.QueryEscape(bootstrap.Organization.ID)
dashboard := perform(handler, http.MethodGet, target, nil, []*http.Cookie{cookie})
body := dashboard.Body.String()
if dashboard.Code != http.StatusOK || !strings.Contains(body, "Errors by route visual summary") || strings.Count(body, "<meter ") != 2 || !strings.Contains(body, "<table>") || !strings.Contains(body, "<caption>Errors by route</caption>") {
t.Fatalf("dashboard status=%d body=%s", dashboard.Code, body)
}
}
func TestAssistedQueryBuilderEscapesStageSeparatorsAndRejectsInvalidCombinations(t *testing.T) {
values := url.Values{
"signal": []string{"logs"}, "filter_field": []string{"name"}, "filter_operator": []string{"=="}, "filter_value": []string{"worker | limit 250"},
"window": []string{"1h"}, "aggregate": []string{"none"}, "aggregate_field": []string{""}, "group_by": []string{""}, "bucket": []string{""}, "limit": []string{"50"},
}
text, err := buildAssistedQuery(values, 1000)
if err != nil || strings.Contains(text, `"worker | limit 250"`) || !strings.Contains(text, `\u007c`) {
t.Fatalf("text=%q err=%v", text, err)
}
ast, err := query.Parse(text, 1000)
if err != nil || len(ast.Filters) != 1 || ast.Filters[0].Value != "worker | limit 250" || ast.Limit != 50 {
t.Fatalf("AST=%+v err=%v", ast, err)
}
values.Set("bucket", "5m")
if _, err = buildAssistedQuery(values, 1000); err == nil {
t.Fatal("time bucket without an aggregate was accepted")
}
}
func TestResultChartIsBoundedAndFailsClosedForNegativeValues(t *testing.T) {
result := query.Result{Columns: []query.Column{{Field: "window_start", Type: schema.TypeTime}, {Field: "count", Type: schema.TypeInteger}}}
for index := range 60 {
label := fmt.Sprintf("2026-08-17T07:%02d:00Z", index)
value := strconv.Itoa(index)
result.Rows = append(result.Rows, query.Row{Values: []*string{&label, &value}})
}
chart := resultChart("Requests", result)
if len(chart.Points) != 48 || chart.Points[47].Maximum != "47" || chart.Points[47].Value != "47" {
t.Fatalf("chart=%+v", chart)
}
negative := "-1"
result.Rows[0].Values[1] = &negative
if chart = resultChart("Requests", result); len(chart.Points) != 0 {
t.Fatalf("negative chart=%+v", chart)
}
}
type streamRecorder struct {
mu sync.Mutex
header http.Header
status int
body bytes.Buffer
flushed chan struct{}
}
func newStreamRecorder() *streamRecorder {
return &streamRecorder{header: make(http.Header), flushed: make(chan struct{}, 4)}
}
func (recorder *streamRecorder) Header() http.Header { return recorder.header }
func (recorder *streamRecorder) WriteHeader(status int) {
recorder.mu.Lock()
defer recorder.mu.Unlock()
if recorder.status == 0 {
recorder.status = status
}
}
func (recorder *streamRecorder) Write(body []byte) (int, error) {
recorder.mu.Lock()
defer recorder.mu.Unlock()
if recorder.status == 0 {
recorder.status = http.StatusOK
}
return recorder.body.Write(body)
}
func (recorder *streamRecorder) Flush() {
select {
case recorder.flushed <- struct{}{}:
default:
}
}
func (recorder *streamRecorder) statusCode() int {
recorder.mu.Lock()
defer recorder.mu.Unlock()
return recorder.status
}
func (recorder *streamRecorder) bodyString() string {
recorder.mu.Lock()
defer recorder.mu.Unlock()
return recorder.body.String()
}
func newUITestServer(t *testing.T) (*Server, *storage.Store, *identity.Services, identity.BootstrapResult) {
t.Helper()
root := filepath.Join(t.TempDir(), "data")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
t.Fatal(err)
}
identities, err := identity.Open(root)
if err != nil {
store.Close()
t.Fatal(err)
}
bootstrap, err := identities.Bootstrap(context.Background(), identity.BootstrapInput{Username: "operator", Email: "operator@example.test", DisplayName: "Operator", Password: "correct horse battery staple"})
if err != nil {
identities.Close()
store.Close()
t.Fatal(err)
}
server, err := New(store, identities, testOptions())
if err != nil {
identities.Close()
store.Close()
t.Fatal(err)
}
server.now = func() time.Time { return time.Date(2026, 8, 17, 7, 30, 0, 0, time.UTC) }
return server, store, identities, bootstrap
}
func newRotationTestServer(t *testing.T) (*Server, *storage.Store, *identity.Services, identity.BootstrapResult) {
t.Helper()
root := filepath.Join(t.TempDir(), "data")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := storage.Open(root)
if err != nil {
t.Fatal(err)
}
identities, err := identity.Open(root)
if err != nil {
store.Close()
t.Fatal(err)
}
bootstrap, err := identities.Bootstrap(t.Context(), identity.BootstrapInput{Username: "operator", Email: "operator@example.test", DisplayName: "Operator", Password: "temporary correct horse battery staple", RequirePasswordChange: true})
if err != nil {
identities.Close()
store.Close()
t.Fatal(err)
}
server, err := New(store, identities, testOptions())
if err != nil {
identities.Close()
store.Close()
t.Fatal(err)
}
server.now = func() time.Time { return time.Date(2026, 8, 18, 5, 30, 0, 0, time.UTC) }
return server, store, identities, bootstrap
}
func loginHTML(t *testing.T, handler http.Handler) *http.Cookie {
t.Helper()
result := loginHTMLResponse(t, handler, "operator", "correct horse battery staple")
if result.Code != http.StatusSeeOther || result.Header().Get("Location") != "/app/" {
t.Fatalf("login status=%d location=%q body=%s", result.Code, result.Header().Get("Location"), result.Body.String())
}
for _, cookie := range result.Result().Cookies() {
if cookie.Name == "__Host-observatory_session" && cookie.Secure && cookie.HttpOnly && cookie.SameSite == http.SameSiteStrictMode {
return cookie
}
}
t.Fatalf("login cookies=%+v", result.Result().Cookies())
return nil
}
func loginHTMLResponse(t *testing.T, handler http.Handler, identifier, password string) *httptest.ResponseRecorder {
t.Helper()
csrfCookie, csrfToken := loginFormCSRF(t, handler)
form := url.Values{"csrf_token": []string{csrfToken}, "identifier": []string{identifier}, "password": []string{password}}.Encode()
headers := http.Header{"Origin": []string{"https://observatory.example"}, "Content-Type": []string{"application/x-www-form-urlencoded; charset=utf-8"}}
return perform(handler, http.MethodPost, "https://observatory.example/login/", strings.NewReader(form), []*http.Cookie{csrfCookie}, headers)
}
func loginFormCSRF(t *testing.T, handler http.Handler) (*http.Cookie, string) {
t.Helper()
page := perform(handler, http.MethodGet, "https://observatory.example/login/", nil, nil)
if page.Code != http.StatusOK {
t.Fatalf("login page status=%d body=%s", page.Code, page.Body.String())
}
var csrfCookie *http.Cookie
for _, cookie := range page.Result().Cookies() {
if cookie.Name == loginCSRFCookieName {
csrfCookie = cookie
break
}
}
if csrfCookie == nil || !csrfCookie.Secure || !csrfCookie.HttpOnly || csrfCookie.SameSite != http.SameSiteStrictMode {
t.Fatalf("login CSRF cookie=%+v", csrfCookie)
}
const marker = `name="csrf_token" value="`
start := strings.Index(page.Body.String(), marker)
if start < 0 {
t.Fatalf("login page omitted CSRF token: %s", page.Body.String())
}
start += len(marker)
end := strings.IndexByte(page.Body.String()[start:], '"')
if end < 0 {
t.Fatal("login page CSRF token is unterminated")
}
token := page.Body.String()[start : start+end]
if token == "" || token != csrfCookie.Value {
t.Fatal("login form and cookie CSRF tokens differ")
}
return csrfCookie, token
}
func perform(handler http.Handler, method, target string, body io.Reader, cookies []*http.Cookie, headerSets ...http.Header) *httptest.ResponseRecorder {
request := httptest.NewRequest(method, target, body)
for _, cookie := range cookies {
request.AddCookie(cookie)
}
for _, headers := range headerSets {
for name, values := range headers {
for _, value := range values {
request.Header.Add(name, value)
}
}
}
result := httptest.NewRecorder()
handler.ServeHTTP(result, request)
return result
}
+431
View File
@@ -0,0 +1,431 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Package identity binds Observatory's application policy to the storage-neutral
// Gamertan Web Foundations authentication, organization, and access packages.
package identity
import (
"context"
"database/sql"
"errors"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"syscall"
"time"
"gamertan.com/web/access"
"gamertan.com/web/auth"
"gamertan.com/web/authsqlite"
"gamertan.com/web/organizations"
_ "modernc.org/sqlite"
)
const (
PlatformOperator = "platform.operator"
OrganizationOwner = "organization.owner"
OrganizationViewer = "organization.viewer"
IncidentResponder = "incident.responder"
PermissionPlatformOperate = "platform.operate"
PermissionTelemetryQuery = "telemetry.query"
PermissionTelemetryReadSensitive = "telemetry.sensitive"
PermissionSourcesManage = "sources.manage"
PermissionSchemaManage = "schema.manage"
PermissionDashboardsRead = "dashboards.read"
PermissionDashboardsManage = "dashboards.manage"
PermissionIncidentsRead = "incidents.read"
PermissionIncidentsManage = "incidents.manage"
PermissionOrganizationAudit = "organization.audit.read"
PermissionOrganizationManage = "organization.manage"
)
var (
ErrAlreadyBootstrapped = errors.New("identity: platform is already bootstrapped")
ErrResourceNotFound = errors.New("identity: resource scope not found")
)
type Services struct {
Store *authsqlite.Store
Auth *auth.Service
Organizations *organizations.Service
Access *access.Service
control *sql.DB
dataDir string
}
func Open(dataDir string) (*Services, error) {
if !filepath.IsAbs(dataDir) || filepath.Clean(dataDir) != dataDir {
return nil, errors.New("identity: data directory must be absolute and clean")
}
info, err := os.Lstat(dataDir)
if err != nil {
return nil, fmt.Errorf("identity: inspect data directory: %w", err)
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 || info.Mode().Perm()&0o077 != 0 {
return nil, errors.New("identity: data directory must be a private non-symlink directory")
}
controlPath := filepath.Join(dataDir, "control.sqlite")
store, err := authsqlite.Open(controlPath)
if err != nil {
return nil, err
}
authService, err := auth.New(store, auth.Options{})
if err != nil {
store.Close()
return nil, err
}
organizationService, err := organizations.New(store, organizations.Options{})
if err != nil {
store.Close()
return nil, err
}
accessService, err := access.New(store, AccessPolicy(), access.Options{})
if err != nil {
store.Close()
return nil, err
}
control, err := sql.Open("sqlite", sqliteDSN(controlPath))
if err != nil {
store.Close()
return nil, err
}
control.SetMaxOpenConns(1)
services := &Services{Store: store, Auth: authService, Organizations: organizationService, Access: accessService, control: control, dataDir: dataDir}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err = services.seed(ctx); err != nil {
services.Close()
return nil, err
}
return services, nil
}
func (services *Services) Close() error {
var errs []error
if services.control != nil {
errs = append(errs, services.control.Close())
}
if services.Store != nil {
errs = append(errs, services.Store.Close())
}
return errors.Join(errs...)
}
func PlatformPolicy() auth.PolicySeed {
return auth.PolicySeed{
Roles: map[string]string{PlatformOperator: "Operate the Observatory service without implicit access to organization telemetry."},
Permissions: map[string]string{PermissionPlatformOperate: "Operate platform-level service and migration controls."},
RolePermissions: map[string][]string{PlatformOperator: {PermissionPlatformOperate}},
}
}
func AccessPolicy() access.Policy {
permissions := map[string]string{
PermissionTelemetryQuery: "Query telemetry in an explicitly authorized resource scope.",
PermissionTelemetryReadSensitive: "Read fields classified as sensitive.",
PermissionSourcesManage: "Enroll, rotate, and revoke ingestion sources.",
PermissionSchemaManage: "Review field descriptors and projection changes.",
PermissionDashboardsRead: "Read saved queries and dashboards.",
PermissionDashboardsManage: "Create and change saved queries and dashboards.",
PermissionIncidentsRead: "Read incidents for an authorized scope.",
PermissionIncidentsManage: "Acknowledge, silence, and resolve incidents.",
PermissionOrganizationAudit: "Read organization-visible security and access audit events.",
PermissionOrganizationManage: "Manage organization membership invitations and teams.",
}
return access.Policy{
Roles: map[string]string{
OrganizationOwner: "Manage an organization and its Observatory resources.",
OrganizationViewer: "Read ordinary telemetry, dashboards, and incidents.",
IncidentResponder: "Read telemetry and respond to incidents without managing sources or access.",
},
Permissions: permissions,
Grants: map[string][]string{
OrganizationOwner: {
PermissionTelemetryQuery, PermissionTelemetryReadSensitive,
PermissionSourcesManage, PermissionSchemaManage, PermissionDashboardsRead,
PermissionDashboardsManage, PermissionIncidentsRead,
PermissionIncidentsManage, PermissionOrganizationAudit,
PermissionOrganizationManage,
},
OrganizationViewer: {PermissionTelemetryQuery, PermissionDashboardsRead, PermissionIncidentsRead},
IncidentResponder: {PermissionTelemetryQuery, PermissionDashboardsRead, PermissionIncidentsRead, PermissionIncidentsManage},
},
}
}
func (services *Services) CancelUnusedInvitation(ctx context.Context, digest [32]byte) error {
result, err := services.control.ExecContext(ctx, `DELETE FROM gwf_organization_invitations WHERE token_hash=? AND used_at IS NULL`, digest[:])
if err != nil {
return errors.New("identity: cancel invitation")
}
if changed, _ := result.RowsAffected(); changed != 1 {
return errors.New("identity: unused invitation was not found")
}
return nil
}
func (services *Services) seed(ctx context.Context) error {
if err := services.Store.SeedPolicy(ctx, PlatformPolicy()); err != nil {
return fmt.Errorf("identity: seed platform policy: %w", err)
}
if err := services.Access.Seed(ctx); err != nil {
return fmt.Errorf("identity: seed organization access policy: %w", err)
}
return nil
}
func (services *Services) ValidateResourceScope(ctx context.Context, scope access.Scope) error {
if err := scope.Validate(); err != nil {
return err
}
queryText := `SELECT COUNT(*) FROM gwf_organizations WHERE id=?`
arguments := []any{scope.OrganizationID}
switch {
case scope.ServiceID != "":
queryText = `SELECT COUNT(*) FROM gwf_application_services WHERE id=? AND environment_id=? AND project_id=? AND organization_id=?`
arguments = []any{scope.ServiceID, scope.EnvironmentID, scope.ProjectID, scope.OrganizationID}
case scope.EnvironmentID != "":
queryText = `SELECT COUNT(*) FROM gwf_environments WHERE id=? AND project_id=? AND organization_id=?`
arguments = []any{scope.EnvironmentID, scope.ProjectID, scope.OrganizationID}
case scope.ProjectID != "":
queryText = `SELECT COUNT(*) FROM gwf_projects WHERE id=? AND organization_id=?`
arguments = []any{scope.ProjectID, scope.OrganizationID}
}
var count int
if err := services.control.QueryRowContext(ctx, queryText, arguments...).Scan(&count); err != nil {
return fmt.Errorf("identity: validate resource scope: %w", err)
}
if count != 1 {
return ErrResourceNotFound
}
return nil
}
// OrganizationsForUser returns only active organizations in which the user
// has a direct membership. Access grants remain the independent authority for
// every operation performed after selection.
func (services *Services) OrganizationsForUser(ctx context.Context, userID string) ([]organizations.Organization, error) {
memberships, err := services.Organizations.Memberships(ctx, userID)
if err != nil {
return nil, fmt.Errorf("identity: list organization memberships: %w", err)
}
result := make([]organizations.Organization, 0, len(memberships))
for _, membership := range memberships {
if membership.Status != "active" {
continue
}
var organization organizations.Organization
var personal int
var createdAt int64
err = services.control.QueryRowContext(ctx, `SELECT id,slug,name,personal,created_at FROM gwf_organizations WHERE id=?`, membership.OrganizationID).Scan(&organization.ID, &organization.Slug, &organization.Name, &personal, &createdAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrResourceNotFound
}
if err != nil {
return nil, fmt.Errorf("identity: read organization: %w", err)
}
organization.Personal = personal == 1
organization.CreatedAt = time.Unix(createdAt, 0).UTC()
result = append(result, organization)
}
sort.Slice(result, func(i, j int) bool {
if result[i].Name == result[j].Name {
return result[i].ID < result[j].ID
}
return result[i].Name < result[j].Name
})
return result, nil
}
type BootstrapInput struct {
Username, Email, DisplayName, Password string
RequirePasswordChange bool
}
type BootstrapResult struct {
User auth.User
Organization organizations.Organization
Binding access.Binding
}
type UserProvisionResult struct {
User auth.User
Organization organizations.Organization
Binding access.Binding
}
// ProvisionUser creates an active local user and the personal organization
// that owns their private work. Shared organization access still requires a
// separately authorized, expiring invitation.
func (services *Services) ProvisionUser(ctx context.Context, input auth.CreateUser) (UserProvisionResult, error) {
user, err := services.Auth.CreateUser(ctx, input)
if err != nil {
return UserProvisionResult{}, fmt.Errorf("identity: create user: %w", err)
}
organization, err := services.Organizations.CreatePersonalOrganization(ctx, user.ID, user.DisplayName)
if err != nil {
return UserProvisionResult{}, fmt.Errorf("identity: create personal organization: %w", err)
}
binding, err := services.Access.Grant(ctx, access.Grant{
SubjectKind: access.User, SubjectID: user.ID, Role: OrganizationOwner,
Scope: access.Scope{OrganizationID: organization.ID}, GrantedBy: user.ID,
})
if err != nil {
return UserProvisionResult{}, fmt.Errorf("identity: grant personal organization ownership: %w", err)
}
return UserProvisionResult{User: user, Organization: organization, Binding: binding}, nil
}
func (services *Services) Bootstrap(ctx context.Context, input BootstrapInput) (BootstrapResult, error) {
lock, err := openBootstrapLock(filepath.Join(services.dataDir, ".bootstrap.lock"))
if err != nil {
return BootstrapResult{}, err
}
defer lock.Close()
var users int
if err = services.control.QueryRowContext(ctx, `SELECT COUNT(*) FROM gwf_users`).Scan(&users); err != nil {
return BootstrapResult{}, fmt.Errorf("identity: inspect bootstrap state: %w", err)
}
if users != 0 {
return BootstrapResult{}, ErrAlreadyBootstrapped
}
provisioned, err := services.ProvisionUser(ctx, auth.CreateUser{
Username: input.Username, Email: input.Email,
DisplayName: input.DisplayName, Password: input.Password,
RequirePasswordChange: input.RequirePasswordChange,
})
if err != nil {
return BootstrapResult{}, fmt.Errorf("identity: create first operator: %w", err)
}
now := time.Now().UTC()
if err = services.Store.GrantRole(ctx, provisioned.User.ID, PlatformOperator, now); err != nil {
return BootstrapResult{}, fmt.Errorf("identity: grant platform operator: %w", err)
}
return BootstrapResult{User: provisioned.User, Organization: provisioned.Organization, Binding: provisioned.Binding}, nil
}
func openBootstrapLock(path string) (*os.File, error) {
file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0o600)
if err != nil {
return nil, fmt.Errorf("identity: open bootstrap lock: %w", err)
}
if err = syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
file.Close()
return nil, errors.New("identity: another bootstrap operation is active")
}
info, err := file.Stat()
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0o600 {
file.Close()
return nil, errors.New("identity: bootstrap lock must be a private regular file")
}
return file, nil
}
func sqliteDSN(path string) string {
return (&url.URL{Scheme: "file", Path: filepath.ToSlash(path), RawQuery: "_pragma=busy_timeout(5000)&_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)&_pragma=synchronous(FULL)"}).String()
}
func ReadSecret(path string, requireRoot bool) (string, error) {
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
return "", errors.New("identity: secret path must be absolute and clean")
}
info, err := os.Lstat(path)
if err != nil {
return "", fmt.Errorf("identity: inspect secret file: %w", err)
}
if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Mode().Perm() != 0o600 {
return "", errors.New("identity: secret must be a regular non-symlink file with mode 0600")
}
if requireRoot {
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok || stat.Uid != 0 {
return "", errors.New("identity: secret must be owned by root")
}
}
value, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("identity: read secret file: %w", err)
}
secret := strings.TrimSuffix(string(value), "\n")
secret = strings.TrimSuffix(secret, "\r")
if secret == "" || strings.ContainsAny(secret, "\x00\r\n") {
return "", errors.New("identity: secret file must contain one non-empty line")
}
return secret, nil
}
func WriteSecret(path, secret string) error {
if !filepath.IsAbs(path) || filepath.Clean(path) != path || secret == "" || len(secret) > 1024 || strings.ContainsAny(secret, "\x00\r\n") {
return errors.New("identity: secret output is invalid")
}
parent := filepath.Dir(path)
info, err := os.Lstat(parent)
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("identity: secret output directory must be an existing non-symlink directory")
}
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW, 0o600)
if err != nil {
return fmt.Errorf("identity: create secret output: %w", err)
}
remove := true
defer func() {
_ = file.Close()
if remove {
_ = os.Remove(path)
}
}()
if err = file.Chmod(0o600); err == nil {
_, err = io.WriteString(file, secret+"\n")
}
if err == nil {
err = file.Sync()
}
if closeErr := file.Close(); err == nil {
err = closeErr
}
if err != nil {
return errors.New("identity: persist secret output")
}
directory, err := os.Open(parent)
if err != nil {
return errors.New("identity: open secret output directory")
}
if err = directory.Sync(); err != nil {
directory.Close()
return errors.New("identity: persist secret output directory")
}
if err = directory.Close(); err != nil {
return errors.New("identity: close secret output directory")
}
remove = false
return nil
}
// RemoveSecret removes only an exact private regular secret file and syncs its
// parent directory. It is used to clean up a generated bootstrap credential
// when bootstrap cannot commit an operator.
func RemoveSecret(path string, requireRoot bool) error {
if _, err := ReadSecret(path, requireRoot); err != nil {
return err
}
if err := os.Remove(path); err != nil {
return fmt.Errorf("identity: remove secret file: %w", err)
}
directory, err := os.Open(filepath.Dir(path))
if err != nil {
return errors.New("identity: open secret output directory")
}
if err = directory.Sync(); err != nil {
directory.Close()
return errors.New("identity: persist secret output directory")
}
if err = directory.Close(); err != nil {
return errors.New("identity: close secret output directory")
}
return nil
}
+344
View File
@@ -0,0 +1,344 @@
// SPDX-License-Identifier: AGPL-3.0-only
package identity
import (
"context"
"errors"
"os"
"path/filepath"
"runtime"
"testing"
"time"
"gamertan.com/web/access"
"gamertan.com/web/auth"
"gamertan.com/web/organizations"
)
func TestBootstrapSeparatesPlatformAndOrganizationAccess(t *testing.T) {
root := t.TempDir()
if err := os.Chmod(root, 0o700); err != nil {
t.Fatal(err)
}
services, err := Open(root)
if err != nil {
t.Fatal(err)
}
defer services.Close()
result, err := services.Bootstrap(context.Background(), BootstrapInput{
Username: "operator", Email: "operator@example.test",
DisplayName: "First Operator", Password: "correct horse battery staple",
})
if err != nil {
t.Fatal(err)
}
if !result.Organization.Personal || result.Binding.Role != OrganizationOwner {
t.Fatalf("result=%+v", result)
}
token, principal, err := services.Auth.Authenticate(context.Background(), "operator", "correct horse battery staple", time.Hour)
if err != nil || token == "" || !principal.Has(PermissionPlatformOperate) {
t.Fatalf("platform session: token_present=%t principal=%+v err=%v", token != "", principal, err)
}
decision, err := services.Access.Authorize(context.Background(), result.User.ID, access.Scope{OrganizationID: result.Organization.ID}, PermissionTelemetryQuery)
if err != nil || !decision.Allowed || decision.Role != OrganizationOwner {
t.Fatalf("query decision=%+v err=%v", decision, err)
}
decision, err = services.Access.Authorize(context.Background(), result.User.ID, access.Scope{OrganizationID: result.Organization.ID}, PermissionTelemetryReadSensitive)
if err != nil || !decision.Allowed {
t.Fatalf("sensitive decision=%+v err=%v", decision, err)
}
decision, err = services.Access.Authorize(context.Background(), result.User.ID, access.Scope{OrganizationID: result.Organization.ID}, PermissionSchemaManage)
if err != nil || !decision.Allowed {
t.Fatalf("schema decision=%+v err=%v", decision, err)
}
if _, err = services.Access.Authorize(context.Background(), result.User.ID, access.Scope{OrganizationID: result.Organization.ID}, PermissionPlatformOperate); err == nil {
t.Fatal("platform permission entered organization access policy")
}
project, err := services.Organizations.CreateProject(context.Background(), organizations.CreateProject{OrganizationID: result.Organization.ID, Slug: "eql-helper", Name: "EQL Helper"})
if err != nil {
t.Fatal(err)
}
environment, err := services.Organizations.CreateEnvironment(context.Background(), organizations.CreateEnvironment{OrganizationID: result.Organization.ID, ProjectID: project.ID, Slug: "production", Name: "Production"})
if err != nil {
t.Fatal(err)
}
application, err := services.Organizations.CreateApplicationService(context.Background(), organizations.CreateApplicationService{OrganizationID: result.Organization.ID, ProjectID: project.ID, EnvironmentID: environment.ID, Slug: "web", Name: "Web"})
if err != nil {
t.Fatal(err)
}
scope := access.Scope{OrganizationID: result.Organization.ID, ProjectID: project.ID, EnvironmentID: environment.ID, ServiceID: application.ID}
if err = services.ValidateResourceScope(context.Background(), scope); err != nil {
t.Fatal(err)
}
scope.ServiceID = "missing1"
if err = services.ValidateResourceScope(context.Background(), scope); !errors.Is(err, ErrResourceNotFound) {
t.Fatalf("missing scope err=%v", err)
}
}
func TestBootstrapIsSingleUse(t *testing.T) {
root := t.TempDir()
if err := os.Chmod(root, 0o700); err != nil {
t.Fatal(err)
}
services, err := Open(root)
if err != nil {
t.Fatal(err)
}
defer services.Close()
input := BootstrapInput{Username: "operator", Email: "operator@example.test", DisplayName: "First Operator", Password: "correct horse battery staple"}
if _, err = services.Bootstrap(context.Background(), input); err != nil {
t.Fatal(err)
}
if _, err = services.Bootstrap(context.Background(), BootstrapInput{Username: "second", Email: "second@example.test", DisplayName: "Second Operator", Password: "correct horse battery staple"}); !errors.Is(err, ErrAlreadyBootstrapped) {
t.Fatalf("second bootstrap err=%v", err)
}
}
func TestBootstrapCanRequirePasswordChange(t *testing.T) {
root := t.TempDir()
if err := os.Chmod(root, 0o700); err != nil {
t.Fatal(err)
}
services, err := Open(root)
if err != nil {
t.Fatal(err)
}
defer services.Close()
result, err := services.Bootstrap(t.Context(), BootstrapInput{
Username: "operator", Email: "operator@example.test", DisplayName: "First Operator",
Password: "temporary correct horse battery staple", RequirePasswordChange: true,
})
if err != nil || !result.User.PasswordChangeRequired {
t.Fatalf("result=%+v err=%v", result, err)
}
_, principal, err := services.Auth.Authenticate(t.Context(), "operator", "temporary correct horse battery staple", time.Hour)
if err != nil || !principal.User.PasswordChangeRequired {
t.Fatalf("principal=%+v err=%v", principal, err)
}
}
func TestRemoveSecretValidatesAndRemovesOnlyPrivateRegularFile(t *testing.T) {
root := t.TempDir()
path := filepath.Join(root, "bootstrap-password")
if err := WriteSecret(path, "temporary secret"); err != nil {
t.Fatal(err)
}
if err := RemoveSecret(path, false); err != nil {
t.Fatal(err)
}
if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("removed path err=%v", err)
}
unsafe := filepath.Join(root, "unsafe")
if err := os.WriteFile(unsafe, []byte("secret\n"), 0o644); err != nil {
t.Fatal(err)
}
if err := RemoveSecret(unsafe, false); err == nil {
t.Fatal("world-readable secret was removed")
}
if _, err := os.Stat(unsafe); err != nil {
t.Fatalf("unsafe file changed: %v", err)
}
}
func TestEvidenceRetentionPrunesOnlyExpiredAudit(t *testing.T) {
ctx := t.Context()
root := t.TempDir()
if err := os.Chmod(root, 0o700); err != nil {
t.Fatal(err)
}
services, err := Open(root)
if err != nil {
t.Fatal(err)
}
defer services.Close()
owner, err := services.Bootstrap(ctx, BootstrapInput{Username: "operator", Email: "operator@example.test", DisplayName: "First Operator", Password: "correct horse battery staple"})
if err != nil {
t.Fatal(err)
}
now := time.Date(2026, 8, 17, 5, 0, 0, 0, time.UTC)
for _, event := range []struct {
id string
created time.Time
}{{"audit-old", now.Add(-401 * 24 * time.Hour)}, {"audit-current", now.Add(-399 * 24 * time.Hour)}} {
if _, err = services.control.ExecContext(ctx, `INSERT INTO gwf_audit_events(id,actor_user_id,action,resource_type,resource_id,summary,created_at) VALUES(?,?,?,?,?,?,?)`, event.id, owner.User.ID, "session.test", "user", owner.User.ID, "Test event", event.created.Unix()); err != nil {
t.Fatal(err)
}
if _, err = services.control.ExecContext(ctx, `INSERT INTO gwf_access_audit_events(id,organization_id,actor_user_id,action,resource_type,resource_id,summary,created_at) VALUES(?,?,?,?,?,?,?,?)`, "access-"+event.id, owner.Organization.ID, owner.User.ID, "access.test", "organization", owner.Organization.ID, "Test event", event.created.Unix()); err != nil {
t.Fatal(err)
}
}
report, err := services.PruneEvidence(ctx, 400, now)
if err != nil {
t.Fatal(err)
}
if report.AuthenticationEvents != 1 || report.OrganizationEvents != 1 {
t.Fatalf("report=%+v", report)
}
for _, table := range []string{"gwf_audit_events", "gwf_access_audit_events"} {
var count int
if err = services.control.QueryRowContext(ctx, `SELECT COUNT(*) FROM `+table).Scan(&count); err != nil || count != 1 {
t.Fatalf("table=%s count=%d err=%v", table, count, err)
}
}
}
func TestTeamsInvitationsRevocationAndBreakGlassRemainOrganizationScoped(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
if err := os.Chmod(root, 0o700); err != nil {
t.Fatal(err)
}
services, err := Open(root)
if err != nil {
t.Fatal(err)
}
defer services.Close()
owner, err := services.Bootstrap(ctx, BootstrapInput{Username: "operator", Email: "operator@example.test", DisplayName: "First Operator", Password: "correct horse battery staple"})
if err != nil {
t.Fatal(err)
}
member, err := services.Auth.CreateUser(ctx, auth.CreateUser{Username: "responder", Email: "responder@example.test", DisplayName: "Incident Responder", Password: "another correct horse battery staple"})
if err != nil {
t.Fatal(err)
}
rawInvitation, invitation, err := services.Organizations.Invite(ctx, owner.Organization.ID, member.Email, owner.User.ID, 15*time.Minute)
if err != nil || rawInvitation == "" || invitation.OrganizationID != owner.Organization.ID {
t.Fatalf("invitation=%+v token_present=%t err=%v", invitation, rawInvitation != "", err)
}
if err = services.Organizations.AcceptInvitation(ctx, rawInvitation, member.ID); err != nil {
t.Fatal(err)
}
team, err := services.Organizations.CreateTeam(ctx, organizations.CreateTeam{OrganizationID: owner.Organization.ID, Slug: "responders", Name: "Incident Responders"})
if err != nil {
t.Fatal(err)
}
if err = services.Organizations.AddTeamMember(ctx, team.ID, member.ID); err != nil {
t.Fatal(err)
}
binding, err := services.Access.Grant(ctx, access.Grant{SubjectKind: access.Team, SubjectID: team.ID, Role: IncidentResponder, Scope: access.Scope{OrganizationID: owner.Organization.ID}, GrantedBy: owner.User.ID})
if err != nil {
t.Fatal(err)
}
decision, err := services.Access.Authorize(ctx, member.ID, access.Scope{OrganizationID: owner.Organization.ID}, PermissionIncidentsManage)
if err != nil || !decision.Allowed || decision.Source != "role" || decision.Role != IncidentResponder {
t.Fatalf("team decision=%+v err=%v", decision, err)
}
decision, err = services.Access.Authorize(ctx, owner.User.ID, access.Scope{OrganizationID: owner.Organization.ID}, PermissionOrganizationManage)
if err != nil || !decision.Allowed || decision.Role != OrganizationOwner {
t.Fatalf("owner organization-management decision=%+v err=%v", decision, err)
}
decision, err = services.Access.Authorize(ctx, member.ID, access.Scope{OrganizationID: owner.Organization.ID}, PermissionOrganizationManage)
if err != nil || decision.Allowed {
t.Fatalf("member organization-management decision=%+v err=%v", decision, err)
}
cancelToken, cancelInvitation, err := services.Organizations.Invite(ctx, owner.Organization.ID, "cancelled@example.test", owner.User.ID, 15*time.Minute)
if err != nil || cancelToken == "" {
t.Fatalf("cancel invitation=%+v token_present=%t err=%v", cancelInvitation, cancelToken != "", err)
}
if err = services.CancelUnusedInvitation(ctx, cancelInvitation.Digest); err != nil {
t.Fatal(err)
}
if err = services.Organizations.AcceptInvitation(ctx, cancelToken, member.ID); err == nil {
t.Fatal("cancelled invitation remained usable")
}
other, err := services.Organizations.CreatePersonalOrganization(ctx, member.ID, member.DisplayName)
if err != nil {
t.Fatal(err)
}
decision, err = services.Access.Authorize(ctx, owner.User.ID, access.Scope{OrganizationID: other.ID}, PermissionTelemetryQuery)
if err != nil || decision.Allowed {
t.Fatalf("cross-organization decision=%+v err=%v", decision, err)
}
decision, err = services.Access.Authorize(ctx, member.ID, access.Scope{OrganizationID: owner.Organization.ID}, PermissionTelemetryReadSensitive)
if err != nil || decision.Allowed {
t.Fatalf("unexpected sensitive decision=%+v err=%v", decision, err)
}
breakGlass, err := services.Access.ActivateBreakGlass(ctx, owner.Organization.ID, member.ID, PermissionTelemetryReadSensitive, "Investigate an active incident", "request-12345678", 15*time.Minute)
if err != nil {
t.Fatal(err)
}
decision, err = services.Access.Authorize(ctx, member.ID, access.Scope{OrganizationID: owner.Organization.ID}, PermissionTelemetryReadSensitive)
if err != nil || !decision.Allowed || decision.Source != "break_glass" {
t.Fatalf("break-glass decision=%+v err=%v", decision, err)
}
audit, err := services.Access.Audit(ctx, owner.Organization.ID, 10)
if err != nil || len(audit) != 1 || audit[0].Action != "break_glass.activate" || audit[0].ResourceID != owner.Organization.ID {
t.Fatalf("audit=%+v err=%v", audit, err)
}
if _, err = services.control.ExecContext(ctx, `UPDATE gwf_break_glass SET expires_at=? WHERE id=?`, time.Now().Add(-time.Minute).Unix(), breakGlass.ID); err != nil {
t.Fatal(err)
}
decision, err = services.Access.Authorize(ctx, member.ID, access.Scope{OrganizationID: owner.Organization.ID}, PermissionTelemetryReadSensitive)
if err != nil || decision.Allowed {
t.Fatalf("expired break-glass decision=%+v err=%v", decision, err)
}
if err = services.Store.Revoke(ctx, binding.ID, owner.User.ID, time.Now().UTC()); err != nil {
t.Fatal(err)
}
decision, err = services.Access.Authorize(ctx, member.ID, access.Scope{OrganizationID: owner.Organization.ID}, PermissionIncidentsManage)
if err != nil || decision.Allowed {
t.Fatalf("revoked team decision=%+v err=%v", decision, err)
}
}
func TestReadSecretRejectsWeakFiles(t *testing.T) {
dir := t.TempDir()
valid := filepath.Join(dir, "password")
if err := os.WriteFile(valid, []byte("correct horse battery staple\n"), 0o600); err != nil {
t.Fatal(err)
}
secret, err := ReadSecret(valid, false)
if err != nil || secret != "correct horse battery staple" {
t.Fatalf("secret=%q err=%v", secret, err)
}
weak := filepath.Join(dir, "weak")
if err = os.WriteFile(weak, []byte("not private"), 0o644); err != nil {
t.Fatal(err)
}
if _, err = ReadSecret(weak, false); err == nil {
t.Fatal("world-readable secret accepted")
}
if runtime.GOOS != "windows" {
link := filepath.Join(dir, "link")
if err = os.Symlink(valid, link); err != nil {
t.Fatal(err)
}
if _, err = ReadSecret(link, false); err == nil {
t.Fatal("symlinked secret accepted")
}
}
}
func TestWriteSecretIsPrivateExclusiveAndReadable(t *testing.T) {
path := filepath.Join(t.TempDir(), "invitation")
const secret = "single-use-invitation-token"
if err := WriteSecret(path, secret); err != nil {
t.Fatal(err)
}
info, err := os.Lstat(path)
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0o600 {
t.Fatalf("info=%v err=%v", info, err)
}
got, err := ReadSecret(path, false)
if err != nil || got != secret {
t.Fatalf("secret=%q err=%v", got, err)
}
if err = WriteSecret(path, "replacement"); err == nil {
t.Fatal("existing secret was overwritten")
}
if err = WriteSecret(filepath.Join(filepath.Dir(path), "multiline"), "first\nsecond"); err == nil {
t.Fatal("multiline secret was accepted")
}
if runtime.GOOS != "windows" {
linkedParent := filepath.Join(filepath.Dir(path), "linked-parent")
if err = os.Symlink(filepath.Dir(path), linkedParent); err != nil {
t.Fatal(err)
}
if err = WriteSecret(filepath.Join(linkedParent, "through-link"), "secret"); err == nil {
t.Fatal("symlinked secret output directory was accepted")
}
}
}
+93
View File
@@ -0,0 +1,93 @@
// SPDX-License-Identifier: AGPL-3.0-only
package identity
import (
"context"
"errors"
"time"
)
type EvidencePruneReport struct {
AuthenticationEvents int64 `json:"authentication_events"`
OrganizationEvents int64 `json:"organization_events"`
ExpiredSessions int64 `json:"expired_sessions"`
ExpiredInvitations int64 `json:"expired_invitations"`
ExpiredBreakGlass int64 `json:"expired_break_glass"`
}
// PruneEvidence applies the server default to platform authentication audit
// events and each organization's approved retention override to its visible
// access audit. Operational credentials are removed only after expiration.
func (services *Services) PruneEvidence(ctx context.Context, defaultDays int, now time.Time) (EvidencePruneReport, error) {
if services == nil || services.control == nil || defaultDays < 1 || defaultDays > 3650 || now.IsZero() {
return EvidencePruneReport{}, errors.New("identity: evidence retention input is invalid")
}
tx, err := services.control.BeginTx(ctx, nil)
if err != nil {
return EvidencePruneReport{}, errors.New("identity: begin evidence retention")
}
defer tx.Rollback()
report := EvidencePruneReport{}
cutoff := now.UTC().Add(-time.Duration(defaultDays) * 24 * time.Hour).Unix()
result, err := tx.ExecContext(ctx, `DELETE FROM gwf_audit_events WHERE created_at<?`, cutoff)
if err != nil {
return report, errors.New("identity: prune authentication audit")
}
report.AuthenticationEvents, _ = result.RowsAffected()
var policyTable int
if err = tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='organization_retention_policies'`).Scan(&policyTable); err != nil {
return report, errors.New("identity: inspect organization retention policy")
}
organizationQuery := `SELECT DISTINCT organization_id,? FROM gwf_access_audit_events ORDER BY organization_id`
if policyTable == 1 {
organizationQuery = `SELECT DISTINCT audit.organization_id,COALESCE(policy.evidence_days,?) FROM gwf_access_audit_events audit LEFT JOIN organization_retention_policies policy ON policy.organization_id=audit.organization_id ORDER BY audit.organization_id`
}
rows, err := tx.QueryContext(ctx, organizationQuery, defaultDays)
if err != nil {
return report, errors.New("identity: list organization audit retention")
}
type organizationCutoff struct {
id string
days int
}
var organizations []organizationCutoff
for rows.Next() {
var organization organizationCutoff
if err = rows.Scan(&organization.id, &organization.days); err != nil || organization.days < 1 || organization.days > 3650 {
_ = rows.Close()
return report, errors.New("identity: organization audit retention is invalid")
}
organizations = append(organizations, organization)
}
if err = rows.Close(); err != nil {
return report, errors.New("identity: close organization audit retention")
}
for _, organization := range organizations {
organizationCutoff := now.UTC().Add(-time.Duration(organization.days) * 24 * time.Hour).Unix()
result, err = tx.ExecContext(ctx, `DELETE FROM gwf_access_audit_events WHERE organization_id=? AND created_at<?`, organization.id, organizationCutoff)
if err != nil {
return report, errors.New("identity: prune organization access audit")
}
removed, _ := result.RowsAffected()
report.OrganizationEvents += removed
}
for _, cleanup := range []struct {
statement string
destination *int64
}{
{`DELETE FROM gwf_auth_sessions WHERE expires_at<=?`, &report.ExpiredSessions},
{`DELETE FROM gwf_organization_invitations WHERE expires_at<=?`, &report.ExpiredInvitations},
{`DELETE FROM gwf_break_glass WHERE expires_at<=?`, &report.ExpiredBreakGlass},
} {
result, err = tx.ExecContext(ctx, cleanup.statement, now.UTC().Unix())
if err != nil {
return report, errors.New("identity: prune expired security state")
}
*cleanup.destination, _ = result.RowsAffected()
}
if err = tx.Commit(); err != nil {
return report, errors.New("identity: commit evidence retention")
}
return report, nil
}
+54
View File
@@ -0,0 +1,54 @@
// SPDX-License-Identifier: AGPL-3.0-only
package model
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"math"
"time"
)
const AlertTransitionVersion = 1
// AlertTransition is a bounded source-reported rule evaluation. Resource
// scope, rule metadata, and incident authority remain server-owned. The
// transition carries no telemetry values.
type AlertTransition struct {
Version int `json:"version"`
RuleID string `json:"rule_id"`
RuleRevision int `json:"rule_revision"`
AgentEpoch string `json:"agent_epoch"`
Sequence uint64 `json:"sequence"`
StreamID string `json:"stream_id"`
BatchSequence uint64 `json:"batch_sequence"`
SegmentDigest string `json:"segment_digest"`
WindowStart time.Time `json:"window_start"`
WindowEnd time.Time `json:"window_end"`
State string `json:"state"`
ObservedAt time.Time `json:"observed_at"`
}
func (value AlertTransition) Validate(now time.Time) error {
if value.Version != AlertTransitionVersion || validateID("rule_id", value.RuleID) != nil || value.RuleRevision < 1 || value.RuleRevision > 1_000_000 || !validLowerHex(value.AgentEpoch, 32) || value.Sequence == 0 || value.Sequence > math.MaxInt64 || ValidateStreamID(value.StreamID) != nil || value.BatchSequence == 0 || value.BatchSequence > math.MaxInt64 || !validLowerHex(value.SegmentDigest, 64) {
return errors.New("alert transition identity is invalid")
}
if value.State != "matched" && value.State != "clear" && value.State != "error" {
return errors.New("alert transition state is invalid")
}
if now.IsZero() || value.WindowStart.IsZero() || value.WindowEnd.Before(value.WindowStart) || value.WindowEnd.Sub(value.WindowStart) > 24*time.Hour || value.ObservedAt.Before(value.WindowEnd) || value.ObservedAt.Before(now.Add(-7*24*time.Hour)) || value.ObservedAt.After(now.Add(10*time.Minute)) {
return errors.New("alert transition time range is invalid")
}
return nil
}
func (value AlertTransition) Digest() (string, error) {
encoded, err := json.Marshal(value)
if err != nil {
return "", errors.New("encode alert transition digest")
}
digest := sha256.Sum256(encoded)
return hex.EncodeToString(digest[:]), nil
}
+40
View File
@@ -0,0 +1,40 @@
// SPDX-License-Identifier: AGPL-3.0-only
package model
import (
"strings"
"testing"
"time"
)
func TestAlertTransitionValidationAndDigest(t *testing.T) {
now := time.Date(2026, 8, 18, 22, 30, 0, 0, time.UTC)
value := AlertTransition{Version: AlertTransitionVersion, RuleID: "rule-a", RuleRevision: 1, AgentEpoch: strings.Repeat("a", 32), Sequence: 1, StreamID: "requests", BatchSequence: 2, SegmentDigest: strings.Repeat("b", 64), WindowStart: now.Add(-time.Minute), WindowEnd: now, State: "matched", ObservedAt: now}
if err := value.Validate(now); err != nil {
t.Fatal(err)
}
first, err := value.Digest()
if err != nil || len(first) != 64 {
t.Fatalf("digest=%q err=%v", first, err)
}
second, err := value.Digest()
if err != nil || first != second {
t.Fatalf("digest changed: %q %q err=%v", first, second, err)
}
invalid := []AlertTransition{
{},
func() AlertTransition { copy := value; copy.AgentEpoch = "not-hex"; return copy }(),
func() AlertTransition { copy := value; copy.Sequence = 0; return copy }(),
func() AlertTransition { copy := value; copy.Sequence = ^uint64(0); return copy }(),
func() AlertTransition { copy := value; copy.BatchSequence = ^uint64(0); return copy }(),
func() AlertTransition { copy := value; copy.State = "firing"; return copy }(),
func() AlertTransition { copy := value; copy.WindowStart = now.Add(-25 * time.Hour); return copy }(),
func() AlertTransition { copy := value; copy.ObservedAt = now.Add(-time.Second); return copy }(),
}
for index, candidate := range invalid {
if err := candidate.Validate(now); err == nil {
t.Fatalf("invalid transition %d accepted", index)
}
}
}
+325
View File
@@ -0,0 +1,325 @@
// SPDX-License-Identifier: AGPL-3.0-only
package model
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math"
"strings"
"time"
"unicode/utf8"
)
// Digest returns the SHA-256 of the canonical JSON representation used by the
// native agent protocol. It binds an acknowledgement to the exact logical
// batch independently of either side's private compressed storage format.
func (b Batch) Digest() (string, error) {
encoded, err := json.Marshal(b)
if err != nil {
return "", errors.New("encode batch digest")
}
digest := sha256.Sum256(encoded)
return hex.EncodeToString(digest[:]), nil
}
const (
BatchVersion = 1
BatchEnvelopeVersion = 1
MaxRecords = 5_000
MaxAttributes = 64
MaxAttributeKey = 128
MaxAttributeValue = 4_096
MaxName = 256
MaxBody = 16_384
MaxDistinctFields = 1_024
)
// BatchEnvelope is the bounded transport metadata for one native batch. The
// enrolled credential supplies source and tenant scope; timestamps are useful
// partition hints and deliberately do not participate in record-level
// deduplication.
type BatchEnvelope struct {
Version int
StreamID string
Sequence uint64
Signal Signal
WireDigest string
BatchDigest string
RecordCount int
EncodedBytes int64
FirstObservedAt time.Time
LastObservedAt time.Time
}
type Signal string
const (
SignalLogs Signal = "logs"
SignalMetrics Signal = "metrics"
SignalTraces Signal = "traces"
SignalDeployments Signal = "deployments"
)
type Batch struct {
Version int `json:"version"`
SourceID string `json:"source_id"`
StreamID string `json:"stream_id"`
Sequence uint64 `json:"sequence"`
ObservedAt time.Time `json:"observed_at"`
Signal Signal `json:"signal"`
Records []Observation `json:"records"`
}
type Observation struct {
Timestamp time.Time `json:"timestamp"`
Name string `json:"name"`
Severity string `json:"severity,omitempty"`
Body string `json:"body,omitempty"`
Value *float64 `json:"value,omitempty"`
TraceID string `json:"trace_id,omitempty"`
SpanID string `json:"span_id,omitempty"`
CorrelationID string `json:"correlation_id,omitempty"`
Attributes map[string]string `json:"attributes,omitempty"`
}
type Scope struct {
OrganizationID string `json:"organization_id"`
ProjectID string `json:"project_id"`
EnvironmentID string `json:"environment_id"`
ServiceID string `json:"service_id"`
}
// Envelope returns transport metadata bound to the exact encoded body and the
// canonical logical batch. The two digests are intentionally distinct even
// when the current JSON encoder happens to produce identical bytes.
func (b Batch) Envelope(encoded []byte) (BatchEnvelope, error) {
if len(encoded) == 0 {
return BatchEnvelope{}, errors.New("encoded batch is empty")
}
batchDigest, err := b.Digest()
if err != nil {
return BatchEnvelope{}, err
}
wireDigest := sha256.Sum256(encoded)
first, last := b.ObservationRange()
return BatchEnvelope{
Version: BatchEnvelopeVersion,
StreamID: b.StreamID,
Sequence: b.Sequence,
Signal: b.Signal,
WireDigest: hex.EncodeToString(wireDigest[:]),
BatchDigest: batchDigest,
RecordCount: len(b.Records),
EncodedBytes: int64(len(encoded)),
FirstObservedAt: first,
LastObservedAt: last,
}, nil
}
func (b Batch) ObservationRange() (time.Time, time.Time) {
if len(b.Records) == 0 {
return time.Time{}, time.Time{}
}
first, last := b.Records[0].Timestamp.UTC(), b.Records[0].Timestamp.UTC()
for _, record := range b.Records[1:] {
observed := record.Timestamp.UTC()
if observed.Before(first) {
first = observed
}
if observed.After(last) {
last = observed
}
}
return first, last
}
func (e BatchEnvelope) Validate(maxEncodedBytes int64) error {
if e.Version != BatchEnvelopeVersion {
return errors.New("unsupported batch envelope version")
}
if err := ValidateStreamID(e.StreamID); err != nil {
return err
}
if e.Sequence == 0 {
return errors.New("sequence must be positive")
}
if !e.Signal.valid() {
return errors.New("unsupported signal")
}
if !validLowerHex(e.WireDigest, sha256.Size*2) || !validLowerHex(e.BatchDigest, sha256.Size*2) {
return errors.New("batch envelope digest is invalid")
}
if e.RecordCount < 1 || e.RecordCount > MaxRecords {
return errors.New("batch envelope record count is invalid")
}
if e.EncodedBytes < 1 || e.EncodedBytes > maxEncodedBytes {
return errors.New("batch envelope byte count is invalid")
}
if e.FirstObservedAt.IsZero() || e.LastObservedAt.IsZero() || e.LastObservedAt.Before(e.FirstObservedAt) {
return errors.New("batch envelope time range is invalid")
}
return nil
}
// Match proves that the decoded batch and exact transport bytes agree with
// the agent-supplied envelope. Tenant scope remains absent by design.
func (e BatchEnvelope) Match(batch Batch, encoded []byte) error {
if err := e.Validate(int64(len(encoded))); err != nil || e.EncodedBytes != int64(len(encoded)) {
return errors.New("batch envelope does not match encoded body")
}
expected, err := batch.Envelope(encoded)
if err != nil {
return err
}
if e != expected {
return errors.New("batch envelope does not match encoded body")
}
return nil
}
func (b Batch) Validate(now time.Time) error {
if b.Version != BatchVersion {
return fmt.Errorf("unsupported batch version %d", b.Version)
}
if err := validateID("source_id", b.SourceID); err != nil {
return err
}
if err := validateID("stream_id", b.StreamID); err != nil {
return err
}
if b.Sequence == 0 {
return errors.New("sequence must be positive")
}
if !b.Signal.valid() {
return errors.New("unsupported signal")
}
if b.ObservedAt.IsZero() || b.ObservedAt.Before(now.Add(-7*24*time.Hour)) || b.ObservedAt.After(now.Add(10*time.Minute)) {
return errors.New("observed_at outside accepted clock-skew window")
}
if len(b.Records) == 0 || len(b.Records) > MaxRecords {
return fmt.Errorf("records must contain between 1 and %d items", MaxRecords)
}
distinctFields := map[string]struct{}{}
for i, record := range b.Records {
if err := record.validate(b.Signal, now); err != nil {
return fmt.Errorf("record %d: %w", i, err)
}
for field := range record.Attributes {
distinctFields[field] = struct{}{}
if len(distinctFields) > MaxDistinctFields {
return fmt.Errorf("batch contains more than %d distinct attribute fields", MaxDistinctFields)
}
}
}
return nil
}
func (s Signal) valid() bool {
switch s {
case SignalLogs, SignalMetrics, SignalTraces, SignalDeployments:
return true
default:
return false
}
}
func (o Observation) validate(signal Signal, now time.Time) error {
if o.Timestamp.IsZero() || o.Timestamp.Before(now.Add(-400*24*time.Hour)) || o.Timestamp.After(now.Add(10*time.Minute)) {
return errors.New("timestamp outside accepted window")
}
if err := validateText("name", o.Name, MaxName, false); err != nil {
return err
}
if err := validateText("body", o.Body, MaxBody, true); err != nil {
return err
}
if err := validateText("severity", o.Severity, 64, true); err != nil {
return err
}
if o.TraceID != "" && !validLowerHex(o.TraceID, 32) {
return errors.New("trace_id must be 16 bytes encoded as lowercase hexadecimal")
}
if o.SpanID != "" && !validLowerHex(o.SpanID, 16) {
return errors.New("span_id must be 8 bytes encoded as lowercase hexadecimal")
}
if err := validateText("correlation_id", o.CorrelationID, 128, true); err != nil {
return err
}
if signal == SignalMetrics && o.Value == nil {
return errors.New("metric requires value")
}
if o.Value != nil && (math.IsNaN(*o.Value) || math.IsInf(*o.Value, 0)) {
return errors.New("value must be finite")
}
if len(o.Attributes) > MaxAttributes {
return fmt.Errorf("too many attributes: maximum %d", MaxAttributes)
}
for key, value := range o.Attributes {
if err := validateText("attribute key", key, MaxAttributeKey, false); err != nil {
return err
}
if err := validateText("attribute value", value, MaxAttributeValue, true); err != nil {
return err
}
}
return nil
}
func validLowerHex(value string, length int) bool {
if len(value) != length {
return false
}
for _, character := range value {
if !(character >= '0' && character <= '9' || character >= 'a' && character <= 'f') {
return false
}
}
return true
}
func (s Scope) Validate() error {
for label, value := range map[string]string{
"organization_id": s.OrganizationID,
"project_id": s.ProjectID,
"environment_id": s.EnvironmentID,
"service_id": s.ServiceID,
} {
if err := validateID(label, value); err != nil {
return err
}
}
return nil
}
func validateID(label, value string) error {
if len(value) < 1 || len(value) > 128 {
return fmt.Errorf("%s length must be between 1 and 128", label)
}
for _, r := range value {
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("._-", r)) {
return fmt.Errorf("%s contains an invalid character", label)
}
}
return nil
}
func ValidateSourceID(value string) error { return validateID("source_id", value) }
func ValidateStreamID(value string) error { return validateID("stream_id", value) }
func validateText(label, value string, max int, empty bool) error {
if !utf8.ValidString(value) || strings.IndexByte(value, 0) >= 0 {
return fmt.Errorf("%s must be valid UTF-8 without NUL", label)
}
if !empty && value == "" {
return fmt.Errorf("%s is required", label)
}
if len(value) > max {
return fmt.Errorf("%s exceeds %d bytes", label, max)
}
return nil
}
+147
View File
@@ -0,0 +1,147 @@
// SPDX-License-Identifier: AGPL-3.0-only
package model
import (
"encoding/json"
"fmt"
"math"
"strings"
"testing"
"time"
)
func TestBatchEnvelopeBindsTransportAndTimePartitionHints(t *testing.T) {
now := time.Date(2026, 8, 18, 20, 0, 0, 0, time.UTC)
batch := Batch{Version: BatchVersion, SourceID: "source", StreamID: "logs", Sequence: 1, ObservedAt: now, Signal: SignalLogs, Records: []Observation{{Timestamp: now, Name: "latest"}, {Timestamp: now.Add(-time.Hour), Name: "earliest"}}}
body, err := json.Marshal(batch)
if err != nil {
t.Fatal(err)
}
envelope, err := batch.Envelope(body)
if err != nil {
t.Fatal(err)
}
if envelope.RecordCount != 2 || envelope.EncodedBytes != int64(len(body)) || envelope.FirstObservedAt != now.Add(-time.Hour) || envelope.LastObservedAt != now || envelope.WireDigest != envelope.BatchDigest {
t.Fatalf("envelope=%+v", envelope)
}
if err = envelope.Match(batch, body); err != nil {
t.Fatal(err)
}
padded := append([]byte(" \n"), body...)
paddedEnvelope, err := batch.Envelope(padded)
if err != nil || paddedEnvelope.WireDigest == envelope.WireDigest || paddedEnvelope.BatchDigest != envelope.BatchDigest || paddedEnvelope.EncodedBytes != int64(len(padded)) {
t.Fatalf("padded=%+v err=%v", paddedEnvelope, err)
}
if err = envelope.Match(batch, padded); err == nil {
t.Fatal("transport mutation was accepted")
}
// Overlapping time ranges are valid metadata, not a uniqueness key.
batch.Sequence = 2
batch.Records = []Observation{{Timestamp: now.Add(-30 * time.Minute), Name: "overlap"}}
body, _ = json.Marshal(batch)
if overlap, overlapErr := batch.Envelope(body); overlapErr != nil || overlap.FirstObservedAt != now.Add(-30*time.Minute) {
t.Fatalf("overlap=%+v err=%v", overlap, overlapErr)
}
}
func TestBatchDigestIsCanonicalAndContentBound(t *testing.T) {
now := time.Date(2026, 8, 17, 18, 0, 0, 0, time.UTC)
left := Batch{Version: BatchVersion, SourceID: "source", StreamID: "logs", Sequence: 1, ObservedAt: now, Signal: SignalLogs, Records: []Observation{{Timestamp: now, Name: "request", Attributes: map[string]string{"z": "last", "a": "first"}}}}
right := left
right.Records = []Observation{{Timestamp: now, Name: "request", Attributes: map[string]string{"a": "first", "z": "last"}}}
leftDigest, err := left.Digest()
if err != nil {
t.Fatal(err)
}
rightDigest, err := right.Digest()
if err != nil {
t.Fatal(err)
}
if leftDigest != rightDigest || len(leftDigest) != 64 || strings.Trim(leftDigest, "0123456789abcdef") != "" {
t.Fatalf("left=%q right=%q", leftDigest, rightDigest)
}
right.Records[0].Name = "changed"
changed, err := right.Digest()
if err != nil || changed == leftDigest {
t.Fatalf("changed=%q err=%v", changed, err)
}
}
func validBatch(now time.Time) Batch {
v := 1.5
return Batch{Version: 1, SourceID: "src_1", StreamID: "metrics", Sequence: 1, ObservedAt: now, Signal: SignalMetrics, Records: []Observation{{Timestamp: now, Name: "http.duration", Value: &v, Attributes: map[string]string{"route": "/"}}}}
}
func TestBatchRejectsDistinctFieldCardinalityAbuse(t *testing.T) {
now := time.Now().UTC()
batch := Batch{Version: BatchVersion, SourceID: "source", StreamID: "logs", Sequence: 1, ObservedAt: now, Signal: SignalLogs}
for recordIndex := 0; recordIndex < 17; recordIndex++ {
record := Observation{Timestamp: now, Name: "record", Attributes: map[string]string{}}
for fieldIndex := 0; fieldIndex < MaxAttributes; fieldIndex++ {
record.Attributes[fmt.Sprintf("field.%d.%d", recordIndex, fieldIndex)] = "value"
}
batch.Records = append(batch.Records, record)
}
if err := batch.Validate(now); err == nil || !strings.Contains(err.Error(), "distinct attribute fields") {
t.Fatalf("cardinality abuse err=%v", err)
}
}
func TestBatchValidation(t *testing.T) {
now := time.Now().UTC()
if err := validBatch(now).Validate(now); err != nil {
t.Fatal(err)
}
b := validBatch(now)
b.SourceID = "../../tenant"
if err := b.Validate(now); err == nil || !strings.Contains(err.Error(), "invalid character") {
t.Fatalf("expected path-like ID rejection, got %v", err)
}
b = validBatch(now)
b.Records[0].Attributes["secret"] = strings.Repeat("x", MaxAttributeValue+1)
if err := b.Validate(now); err == nil || !strings.Contains(err.Error(), "exceeds") {
t.Fatalf("expected attribute bound, got %v", err)
}
}
func TestBatchClockSkewAndRetentionWindowsFailClosed(t *testing.T) {
now := time.Date(2026, 8, 17, 12, 0, 0, 0, time.UTC)
for name, mutate := range map[string]func(*Batch){
"old batch": func(batch *Batch) { batch.ObservedAt = now.Add(-7*24*time.Hour - time.Nanosecond) },
"future batch": func(batch *Batch) { batch.ObservedAt = now.Add(10*time.Minute + time.Nanosecond) },
"old record": func(batch *Batch) { batch.Records[0].Timestamp = now.Add(-400*24*time.Hour - time.Nanosecond) },
"future record": func(batch *Batch) { batch.Records[0].Timestamp = now.Add(10*time.Minute + time.Nanosecond) },
"zero observed": func(batch *Batch) { batch.ObservedAt = time.Time{} },
"zero timestamp": func(batch *Batch) { batch.Records[0].Timestamp = time.Time{} },
} {
t.Run(name, func(t *testing.T) {
batch := validBatch(now)
mutate(&batch)
if err := batch.Validate(now); err == nil {
t.Fatal("out-of-window telemetry was accepted")
}
})
}
}
func TestObservationRejectsUnsafeIdentifiersAndNonFiniteValues(t *testing.T) {
now := time.Now().UTC()
nan := math.NaN()
base := Batch{Version: BatchVersion, SourceID: "source", StreamID: "stream", Sequence: 1, ObservedAt: now, Signal: SignalLogs, Records: []Observation{{Timestamp: now, Name: "record"}}}
for name, mutate := range map[string]func(*Observation){
"trace": func(record *Observation) { record.TraceID = "ABC" },
"span": func(record *Observation) { record.SpanID = strings.Repeat("g", 16) },
"correlation": func(record *Observation) { record.CorrelationID = strings.Repeat("x", 129) },
"value": func(record *Observation) { record.Value = &nan },
} {
t.Run(name, func(t *testing.T) {
batch := base
batch.Records = append([]Observation(nil), base.Records...)
mutate(&batch.Records[0])
if err := batch.Validate(now); err == nil {
t.Fatal("unsafe observation accepted")
}
})
}
}
+74
View File
@@ -0,0 +1,74 @@
// SPDX-License-Identifier: AGPL-3.0-only
package nativeprotocol
import (
"errors"
"net/http"
"strconv"
"time"
"gamertan.com/observatory/internal/model"
)
const (
VersionHeader = "Observatory-Batch-Version"
StreamHeader = "Observatory-Stream-ID"
SequenceHeader = "Observatory-Sequence"
SignalHeader = "Observatory-Signal"
WireDigestHeader = "Observatory-Wire-SHA256"
BatchDigestHeader = "Observatory-Batch-SHA256"
RecordCountHeader = "Observatory-Record-Count"
EncodedBytesHeader = "Observatory-Encoded-Bytes"
FirstObservedHeader = "Observatory-First-Observed-At"
LastObservedHeader = "Observatory-Last-Observed-At"
)
var envelopeHeaders = []string{
VersionHeader, StreamHeader, SequenceHeader, SignalHeader,
WireDigestHeader, BatchDigestHeader, RecordCountHeader,
EncodedBytesHeader, FirstObservedHeader, LastObservedHeader,
}
func SetHeaders(header http.Header, envelope model.BatchEnvelope) {
header.Set(VersionHeader, strconv.Itoa(envelope.Version))
header.Set(StreamHeader, envelope.StreamID)
header.Set(SequenceHeader, strconv.FormatUint(envelope.Sequence, 10))
header.Set(SignalHeader, string(envelope.Signal))
header.Set(WireDigestHeader, envelope.WireDigest)
header.Set(BatchDigestHeader, envelope.BatchDigest)
header.Set(RecordCountHeader, strconv.Itoa(envelope.RecordCount))
header.Set(EncodedBytesHeader, strconv.FormatInt(envelope.EncodedBytes, 10))
header.Set(FirstObservedHeader, envelope.FirstObservedAt.UTC().Format(time.RFC3339Nano))
header.Set(LastObservedHeader, envelope.LastObservedAt.UTC().Format(time.RFC3339Nano))
}
func ParseHeaders(header http.Header, maxEncodedBytes int64) (model.BatchEnvelope, error) {
values := make(map[string]string, len(envelopeHeaders))
for _, name := range envelopeHeaders {
items := header.Values(name)
if len(items) != 1 || items[0] == "" {
return model.BatchEnvelope{}, errors.New("native batch envelope headers are incomplete")
}
values[name] = items[0]
}
version, versionErr := strconv.Atoi(values[VersionHeader])
sequence, sequenceErr := strconv.ParseUint(values[SequenceHeader], 10, 64)
recordCount, recordErr := strconv.Atoi(values[RecordCountHeader])
encodedBytes, bytesErr := strconv.ParseInt(values[EncodedBytesHeader], 10, 64)
first, firstErr := time.Parse(time.RFC3339Nano, values[FirstObservedHeader])
last, lastErr := time.Parse(time.RFC3339Nano, values[LastObservedHeader])
if versionErr != nil || sequenceErr != nil || recordErr != nil || bytesErr != nil || firstErr != nil || lastErr != nil {
return model.BatchEnvelope{}, errors.New("native batch envelope headers are invalid")
}
envelope := model.BatchEnvelope{
Version: version, StreamID: values[StreamHeader], Sequence: sequence,
Signal: model.Signal(values[SignalHeader]), WireDigest: values[WireDigestHeader],
BatchDigest: values[BatchDigestHeader], RecordCount: recordCount,
EncodedBytes: encodedBytes, FirstObservedAt: first.UTC(), LastObservedAt: last.UTC(),
}
if err := envelope.Validate(maxEncodedBytes); err != nil {
return model.BatchEnvelope{}, errors.New("native batch envelope headers are invalid")
}
return envelope, nil
}
+46
View File
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: AGPL-3.0-only
package nativeprotocol
import (
"encoding/json"
"net/http"
"testing"
"time"
"gamertan.com/observatory/internal/model"
)
func TestEnvelopeHeadersRoundTripAndRejectAmbiguity(t *testing.T) {
now := time.Date(2026, 8, 18, 20, 0, 0, 0, time.UTC)
batch := model.Batch{Version: model.BatchVersion, SourceID: "source", StreamID: "logs", Sequence: 7, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now.Add(-time.Second), Name: "first"}, {Timestamp: now, Name: "last"}}}
body, err := json.Marshal(batch)
if err != nil {
t.Fatal(err)
}
envelope, err := batch.Envelope(body)
if err != nil {
t.Fatal(err)
}
header := make(http.Header)
SetHeaders(header, envelope)
parsed, err := ParseHeaders(header, 1<<20)
if err != nil || parsed != envelope {
t.Fatalf("parsed=%+v err=%v", parsed, err)
}
header.Add(SequenceHeader, "8")
if _, err = ParseHeaders(header, 1<<20); err == nil {
t.Fatal("duplicate security-relevant header was accepted")
}
}
func FuzzParseEnvelopeHeaders(f *testing.F) {
f.Add("1", "logs", "1", "logs", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "1", "100", "2026-08-18T20:00:00Z", "2026-08-18T20:00:00Z")
f.Fuzz(func(t *testing.T, version, stream, sequence, signal, wire, batch, count, size, first, last string) {
header := make(http.Header)
for name, value := range map[string]string{VersionHeader: version, StreamHeader: stream, SequenceHeader: sequence, SignalHeader: signal, WireDigestHeader: wire, BatchDigestHeader: batch, RecordCountHeader: count, EncodedBytesHeader: size, FirstObservedHeader: first, LastObservedHeader: last} {
header.Set(name, value)
}
_, _ = ParseHeaders(header, 32<<20)
})
}
+666
View File
@@ -0,0 +1,666 @@
// SPDX-License-Identifier: AGPL-3.0-only
package otlp
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math"
"strconv"
"strings"
"time"
"unicode/utf8"
"gamertan.com/observatory/internal/model"
commonpb "go.opentelemetry.io/proto/otlp/common/v1"
logspb "go.opentelemetry.io/proto/otlp/logs/v1"
metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"
resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
tracepb "go.opentelemetry.io/proto/otlp/trace/v1"
"google.golang.org/protobuf/proto"
)
type Signal string
const (
Logs Signal = "logs"
Metrics Signal = "metrics"
Traces Signal = "traces"
)
func (signal Signal) ModelSignal() model.Signal {
switch signal {
case Logs:
return model.SignalLogs
case Metrics:
return model.SignalMetrics
case Traces:
return model.SignalTraces
default:
return ""
}
}
func (signal Signal) StreamID() string { return "otlp-" + string(signal) }
func Decode(signal Signal, body []byte, now time.Time) ([]model.Observation, error) {
if len(body) == 0 || now.IsZero() {
return nil, errors.New("OTLP request is empty or missing collection time")
}
options := proto.UnmarshalOptions{DiscardUnknown: true, RecursionLimit: 64}
var records []model.Observation
var err error
switch signal {
case Logs:
request := new(logspb.LogsData)
if err = options.Unmarshal(body, request); err == nil {
records, err = decodeLogs(request)
}
case Metrics:
request := new(metricspb.MetricsData)
if err = options.Unmarshal(body, request); err == nil {
records, err = decodeMetrics(request)
}
case Traces:
request := new(tracepb.TracesData)
if err = options.Unmarshal(body, request); err == nil {
records, err = decodeTraces(request)
}
default:
return nil, errors.New("unsupported OTLP signal")
}
if err != nil {
return nil, errors.New("invalid OTLP protobuf payload")
}
if len(records) == 0 {
return nil, errors.New("OTLP request contains no supported records")
}
if len(records) > model.MaxRecords {
return nil, fmt.Errorf("OTLP request exceeds %d records", model.MaxRecords)
}
return records, nil
}
func SuccessResponse(signal Signal) ([]byte, error) {
switch signal {
case Logs, Metrics, Traces:
// Each successful OTLP/HTTP protobuf response is an empty message when
// there is no partial-success detail. The canonical protobuf encoding of
// an empty message is an empty byte sequence.
return []byte{}, nil
default:
return nil, errors.New("unsupported OTLP signal")
}
}
func decodeLogs(request *logspb.LogsData) ([]model.Observation, error) {
var records []model.Observation
for _, resourceLogs := range request.GetResourceLogs() {
resource, err := baseAttributes(resourceLogs.GetResource())
if err != nil {
return nil, err
}
for _, scopeLogs := range resourceLogs.GetScopeLogs() {
base, err := scopeAttributes(resource, scopeLogs.GetScope())
if err != nil {
return nil, err
}
for _, record := range scopeLogs.GetLogRecords() {
attributes, err := mergeAttributes(base, record.GetAttributes())
if err != nil {
return nil, err
}
if record.GetDroppedAttributesCount() > 0 {
if err = addAttribute(attributes, "otel.dropped_attributes", strconv.FormatUint(uint64(record.GetDroppedAttributesCount()), 10)); err != nil {
return nil, err
}
}
body, err := anyValueText(record.GetBody(), model.MaxBody)
if err != nil {
return nil, err
}
name := record.GetEventName()
if name == "" {
name = "otlp.log"
}
when := record.GetTimeUnixNano()
if when == 0 {
when = record.GetObservedTimeUnixNano()
}
timestamp, err := timestamp(when)
if err != nil {
return nil, err
}
traceID, err := identifier(record.GetTraceId(), 16)
if err != nil {
return nil, err
}
spanID, err := identifier(record.GetSpanId(), 8)
if err != nil {
return nil, err
}
severity := record.GetSeverityText()
if severity == "" && record.GetSeverityNumber() != 0 {
severity = record.GetSeverityNumber().String()
}
records = append(records, model.Observation{Timestamp: timestamp, Name: name, Severity: severity, Body: body, TraceID: traceID, SpanID: spanID, CorrelationID: traceID, Attributes: attributes})
if len(records) > model.MaxRecords {
return nil, errors.New("OTLP logs exceed record limit")
}
}
}
}
return records, nil
}
func decodeMetrics(request *metricspb.MetricsData) ([]model.Observation, error) {
var records []model.Observation
for _, resourceMetrics := range request.GetResourceMetrics() {
resource, err := baseAttributes(resourceMetrics.GetResource())
if err != nil {
return nil, err
}
for _, scopeMetrics := range resourceMetrics.GetScopeMetrics() {
base, err := scopeAttributes(resource, scopeMetrics.GetScope())
if err != nil {
return nil, err
}
for _, metric := range scopeMetrics.GetMetrics() {
metricBase := cloneAttributes(base)
if metric.GetUnit() != "" {
if err = addAttribute(metricBase, "metric.unit", metric.GetUnit()); err != nil {
return nil, err
}
}
switch data := metric.Data.(type) {
case *metricspb.Metric_Gauge:
err = appendNumberPoints(&records, metric.GetName(), "gauge", "", metricBase, data.Gauge.GetDataPoints())
case *metricspb.Metric_Sum:
err = appendNumberPoints(&records, metric.GetName(), "sum", data.Sum.GetAggregationTemporality().String(), metricBase, data.Sum.GetDataPoints())
case *metricspb.Metric_Histogram:
err = appendHistogramPoints(&records, metric.GetName(), data.Histogram.GetAggregationTemporality().String(), metricBase, data.Histogram.GetDataPoints())
case *metricspb.Metric_ExponentialHistogram:
err = appendExponentialHistogramPoints(&records, metric.GetName(), data.ExponentialHistogram.GetAggregationTemporality().String(), metricBase, data.ExponentialHistogram.GetDataPoints())
case *metricspb.Metric_Summary:
err = appendSummaryPoints(&records, metric.GetName(), metricBase, data.Summary.GetDataPoints())
default:
err = errors.New("OTLP metric has unsupported data")
}
if err != nil {
return nil, err
}
if len(records) > model.MaxRecords {
return nil, errors.New("OTLP metrics exceed record limit")
}
}
}
}
return records, nil
}
func appendNumberPoints(records *[]model.Observation, name, kind, temporality string, base map[string]string, points []*metricspb.NumberDataPoint) error {
for _, point := range points {
if point.GetFlags()&uint32(metricspb.DataPointFlags_DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK) != 0 {
continue
}
attributes, err := metricAttributes(base, point.GetAttributes(), kind, temporality, point.GetStartTimeUnixNano())
if err != nil {
return err
}
var value float64
switch number := point.Value.(type) {
case *metricspb.NumberDataPoint_AsDouble:
value = number.AsDouble
case *metricspb.NumberDataPoint_AsInt:
value = float64(number.AsInt)
if err = addAttribute(attributes, "metric.int64", strconv.FormatInt(number.AsInt, 10)); err != nil {
return err
}
default:
return errors.New("OTLP number point has no value")
}
if math.IsNaN(value) || math.IsInf(value, 0) {
return errors.New("OTLP metric value is not finite")
}
timestamp, err := timestamp(point.GetTimeUnixNano())
if err != nil {
return err
}
*records = append(*records, model.Observation{Timestamp: timestamp, Name: name, Value: &value, Attributes: attributes})
}
return nil
}
func appendHistogramPoints(records *[]model.Observation, name, temporality string, base map[string]string, points []*metricspb.HistogramDataPoint) error {
for _, point := range points {
if point.GetFlags()&uint32(metricspb.DataPointFlags_DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK) != 0 {
continue
}
attributes, err := metricAttributes(base, point.GetAttributes(), "histogram", temporality, point.GetStartTimeUnixNano())
if err != nil {
return err
}
bounds := point.GetExplicitBounds()
if len(point.GetBucketCounts()) != len(bounds)+1 || !strictlyIncreasingFinite(bounds) {
return errors.New("OTLP histogram buckets are invalid")
}
for key, value := range map[string]any{"metric.bucket_counts": point.GetBucketCounts(), "metric.explicit_bounds": point.GetExplicitBounds(), "metric.count": point.GetCount()} {
if err = addJSONAttribute(attributes, key, value); err != nil {
return err
}
}
value := float64(point.GetCount())
if point.Sum != nil {
value = point.GetSum()
if !finite(value) {
return errors.New("OTLP histogram sum is not finite")
}
if err = addAttribute(attributes, "metric.sum", strconv.FormatFloat(value, 'g', -1, 64)); err != nil {
return err
}
}
if point.Min != nil {
if !finite(point.GetMin()) {
return errors.New("OTLP histogram minimum is not finite")
}
if err = addAttribute(attributes, "metric.min", strconv.FormatFloat(point.GetMin(), 'g', -1, 64)); err != nil {
return err
}
}
if point.Max != nil {
if !finite(point.GetMax()) {
return errors.New("OTLP histogram maximum is not finite")
}
if err = addAttribute(attributes, "metric.max", strconv.FormatFloat(point.GetMax(), 'g', -1, 64)); err != nil {
return err
}
}
timestamp, err := timestamp(point.GetTimeUnixNano())
if err != nil {
return err
}
*records = append(*records, model.Observation{Timestamp: timestamp, Name: name, Value: &value, Attributes: attributes})
}
return nil
}
func appendExponentialHistogramPoints(records *[]model.Observation, name, temporality string, base map[string]string, points []*metricspb.ExponentialHistogramDataPoint) error {
for _, point := range points {
if point.GetFlags()&uint32(metricspb.DataPointFlags_DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK) != 0 {
continue
}
attributes, err := metricAttributes(base, point.GetAttributes(), "exponential_histogram", temporality, point.GetStartTimeUnixNano())
if err != nil {
return err
}
if point.GetScale() < -10 || point.GetScale() > 20 || !finite(point.GetZeroThreshold()) || point.GetZeroThreshold() < 0 {
return errors.New("OTLP exponential histogram parameters are invalid")
}
values := map[string]any{
"metric.count": point.GetCount(), "metric.scale": point.GetScale(), "metric.zero_count": point.GetZeroCount(),
"metric.zero_threshold": point.GetZeroThreshold(), "metric.positive": point.GetPositive(), "metric.negative": point.GetNegative(),
}
for key, value := range values {
if err = addJSONAttribute(attributes, key, value); err != nil {
return err
}
}
value := float64(point.GetCount())
if point.Sum != nil {
value = point.GetSum()
if !finite(value) {
return errors.New("OTLP exponential histogram sum is not finite")
}
if err = addAttribute(attributes, "metric.sum", strconv.FormatFloat(value, 'g', -1, 64)); err != nil {
return err
}
}
timestamp, err := timestamp(point.GetTimeUnixNano())
if err != nil {
return err
}
*records = append(*records, model.Observation{Timestamp: timestamp, Name: name, Value: &value, Attributes: attributes})
}
return nil
}
func appendSummaryPoints(records *[]model.Observation, name string, base map[string]string, points []*metricspb.SummaryDataPoint) error {
for _, point := range points {
if point.GetFlags()&uint32(metricspb.DataPointFlags_DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK) != 0 {
continue
}
attributes, err := metricAttributes(base, point.GetAttributes(), "summary", "", point.GetStartTimeUnixNano())
if err != nil {
return err
}
if err = addJSONAttribute(attributes, "metric.count", point.GetCount()); err != nil {
return err
}
quantiles := make([][2]float64, 0, len(point.GetQuantileValues()))
for _, quantile := range point.GetQuantileValues() {
if !finite(quantile.GetQuantile()) || quantile.GetQuantile() < 0 || quantile.GetQuantile() > 1 || !finite(quantile.GetValue()) {
return errors.New("OTLP summary quantile is invalid")
}
quantiles = append(quantiles, [2]float64{quantile.GetQuantile(), quantile.GetValue()})
}
if err = addJSONAttribute(attributes, "metric.quantiles", quantiles); err != nil {
return err
}
value := point.GetSum()
if !finite(value) {
return errors.New("OTLP summary sum is not finite")
}
if err = addAttribute(attributes, "metric.sum", strconv.FormatFloat(value, 'g', -1, 64)); err != nil {
return err
}
timestamp, err := timestamp(point.GetTimeUnixNano())
if err != nil {
return err
}
*records = append(*records, model.Observation{Timestamp: timestamp, Name: name, Value: &value, Attributes: attributes})
}
return nil
}
func decodeTraces(request *tracepb.TracesData) ([]model.Observation, error) {
var records []model.Observation
for _, resourceSpans := range request.GetResourceSpans() {
resource, err := baseAttributes(resourceSpans.GetResource())
if err != nil {
return nil, err
}
for _, scopeSpans := range resourceSpans.GetScopeSpans() {
base, err := scopeAttributes(resource, scopeSpans.GetScope())
if err != nil {
return nil, err
}
for _, span := range scopeSpans.GetSpans() {
attributes, err := mergeAttributes(base, span.GetAttributes())
if err != nil {
return nil, err
}
traceID, err := identifier(span.GetTraceId(), 16)
if err != nil || traceID == "" {
return nil, errors.New("OTLP span has invalid trace ID")
}
spanID, err := identifier(span.GetSpanId(), 8)
if err != nil || spanID == "" {
return nil, errors.New("OTLP span has invalid span ID")
}
if parent, parentErr := identifier(span.GetParentSpanId(), 8); parentErr != nil {
return nil, parentErr
} else if parent != "" {
if err = addAttribute(attributes, "span.parent_id", parent); err != nil {
return nil, err
}
}
start, err := timestamp(span.GetStartTimeUnixNano())
if err != nil {
return nil, err
}
end, err := timestamp(span.GetEndTimeUnixNano())
if err != nil || end.Before(start) {
return nil, errors.New("OTLP span has invalid time range")
}
duration := float64(end.Sub(start).Nanoseconds())
if err = addAttribute(attributes, "span.duration_ns", strconv.FormatInt(end.Sub(start).Nanoseconds(), 10)); err != nil {
return nil, err
}
if err = addAttribute(attributes, "span.kind", span.GetKind().String()); err != nil {
return nil, err
}
if status := span.GetStatus(); status != nil {
if err = addAttribute(attributes, "span.status", status.GetCode().String()); err != nil {
return nil, err
}
}
for key, count := range map[string]uint64{"span.events_count": uint64(len(span.GetEvents())), "span.links_count": uint64(len(span.GetLinks())), "otel.dropped_attributes": uint64(span.GetDroppedAttributesCount()), "otel.dropped_events": uint64(span.GetDroppedEventsCount()), "otel.dropped_links": uint64(span.GetDroppedLinksCount())} {
if count > 0 {
if err = addAttribute(attributes, key, strconv.FormatUint(count, 10)); err != nil {
return nil, err
}
}
}
records = append(records, model.Observation{Timestamp: start, Name: span.GetName(), Value: &duration, TraceID: traceID, SpanID: spanID, CorrelationID: traceID, Attributes: attributes})
if len(records) > model.MaxRecords {
return nil, errors.New("OTLP traces exceed record limit")
}
}
}
}
return records, nil
}
func baseAttributes(resource *resourcepb.Resource) (map[string]string, error) {
if resource == nil {
return map[string]string{}, nil
}
attributes, err := mergeAttributes(nil, resource.GetAttributes())
if err != nil {
return nil, err
}
if resource.GetDroppedAttributesCount() > 0 {
err = addAttribute(attributes, "otel.resource.dropped_attributes", strconv.FormatUint(uint64(resource.GetDroppedAttributesCount()), 10))
}
return attributes, err
}
func scopeAttributes(base map[string]string, scope *commonpb.InstrumentationScope) (map[string]string, error) {
attributes := cloneAttributes(base)
if scope == nil {
return attributes, nil
}
if scope.GetName() != "" {
if err := addAttribute(attributes, "otel.scope.name", scope.GetName()); err != nil {
return nil, err
}
}
if scope.GetVersion() != "" {
if err := addAttribute(attributes, "otel.scope.version", scope.GetVersion()); err != nil {
return nil, err
}
}
for _, pair := range scope.GetAttributes() {
if pair.GetKey() == "" || deniedKey(pair.GetKey()) {
continue
}
value, err := anyValueText(pair.GetValue(), model.MaxAttributeValue)
if err != nil {
return nil, err
}
if err = addAttribute(attributes, "otel.scope.attribute."+pair.GetKey(), value); err != nil {
return nil, err
}
}
return attributes, nil
}
func metricAttributes(base map[string]string, pairs []*commonpb.KeyValue, kind, temporality string, start uint64) (map[string]string, error) {
attributes, err := mergeAttributes(base, pairs)
if err != nil {
return nil, err
}
if err = addAttribute(attributes, "metric.kind", kind); err != nil {
return nil, err
}
if temporality != "" {
if err = addAttribute(attributes, "metric.temporality", temporality); err != nil {
return nil, err
}
}
if start != 0 {
if err = addAttribute(attributes, "metric.start_unix_nano", strconv.FormatUint(start, 10)); err != nil {
return nil, err
}
}
return attributes, nil
}
func mergeAttributes(base map[string]string, pairs []*commonpb.KeyValue) (map[string]string, error) {
attributes := cloneAttributes(base)
for _, pair := range pairs {
key := pair.GetKey()
if key == "" || deniedKey(key) {
continue
}
value, err := anyValueText(pair.GetValue(), model.MaxAttributeValue)
if err != nil {
return nil, err
}
if err = addAttribute(attributes, key, value); err != nil {
return nil, err
}
}
return attributes, nil
}
func cloneAttributes(source map[string]string) map[string]string {
copy := make(map[string]string, len(source))
for key, value := range source {
copy[key] = value
}
return copy
}
func addAttribute(attributes map[string]string, key, value string) error {
if key == "" || len(key) > model.MaxAttributeKey || !utf8.ValidString(key) || strings.IndexByte(key, 0) >= 0 || len(value) > model.MaxAttributeValue || !utf8.ValidString(value) || strings.IndexByte(value, 0) >= 0 {
return errors.New("OTLP attribute exceeds accepted bounds")
}
if _, exists := attributes[key]; !exists && len(attributes) >= model.MaxAttributes {
return errors.New("OTLP record exceeds attribute limit")
}
attributes[key] = value
return nil
}
func addJSONAttribute(attributes map[string]string, key string, value any) error {
body, err := json.Marshal(value)
if err != nil || len(body) > model.MaxAttributeValue {
return errors.New("OTLP structured attribute exceeds accepted bounds")
}
return addAttribute(attributes, key, string(body))
}
func anyValueText(value *commonpb.AnyValue, maximum int) (string, error) {
converted, err := anyValue(value, 0)
if err != nil {
return "", err
}
if text, ok := converted.(string); ok {
if len(text) > maximum || !utf8.ValidString(text) || strings.IndexByte(text, 0) >= 0 {
return "", errors.New("OTLP string value exceeds accepted bounds")
}
return text, nil
}
body, err := json.Marshal(converted)
if err != nil || len(body) > maximum {
return "", errors.New("OTLP value exceeds accepted bounds")
}
return string(body), nil
}
func anyValue(value *commonpb.AnyValue, depth int) (any, error) {
if value == nil {
return "", nil
}
if depth > 8 {
return nil, errors.New("OTLP value exceeds nesting limit")
}
switch content := value.Value.(type) {
case *commonpb.AnyValue_StringValue:
return content.StringValue, nil
case *commonpb.AnyValue_BoolValue:
return content.BoolValue, nil
case *commonpb.AnyValue_IntValue:
return content.IntValue, nil
case *commonpb.AnyValue_DoubleValue:
if math.IsNaN(content.DoubleValue) || math.IsInf(content.DoubleValue, 0) {
return nil, errors.New("OTLP value is not finite")
}
return content.DoubleValue, nil
case *commonpb.AnyValue_BytesValue:
if len(content.BytesValue) > model.MaxAttributeValue/2 {
return nil, errors.New("OTLP byte value exceeds accepted bounds")
}
return hex.EncodeToString(content.BytesValue), nil
case *commonpb.AnyValue_ArrayValue:
values := content.ArrayValue.GetValues()
if len(values) > 64 {
return nil, errors.New("OTLP array exceeds element limit")
}
result := make([]any, 0, len(values))
for _, item := range values {
converted, err := anyValue(item, depth+1)
if err != nil {
return nil, err
}
result = append(result, converted)
}
return result, nil
case *commonpb.AnyValue_KvlistValue:
values := content.KvlistValue.GetValues()
if len(values) > 64 {
return nil, errors.New("OTLP key-value list exceeds element limit")
}
result := make(map[string]any, len(values))
for _, pair := range values {
key := pair.GetKey()
if key == "" || deniedKey(key) {
continue
}
converted, err := anyValue(pair.GetValue(), depth+1)
if err != nil {
return nil, err
}
result[key] = converted
}
return result, nil
case *commonpb.AnyValue_StringValueStrindex:
return "", nil
default:
return "", nil
}
}
func deniedKey(key string) bool {
normalized := strings.NewReplacer("-", "_", ".", "_", "/", "_").Replace(strings.ToLower(key))
for _, denied := range []string{"authorization", "proxy_authorization", "cookie", "set_cookie", "password", "passwd", "secret", "api_key", "apikey", "access_token", "refresh_token", "client_secret"} {
if strings.Contains(normalized, denied) {
return true
}
}
return false
}
func finite(value float64) bool { return !math.IsNaN(value) && !math.IsInf(value, 0) }
func strictlyIncreasingFinite(values []float64) bool {
for index, value := range values {
if !finite(value) || index > 0 && value <= values[index-1] {
return false
}
}
return true
}
func identifier(value []byte, bytes int) (string, error) {
if len(value) == 0 {
return "", nil
}
if len(value) != bytes {
return "", errors.New("OTLP identifier has invalid length")
}
return hex.EncodeToString(value), nil
}
func timestamp(nanoseconds uint64) (time.Time, error) {
if nanoseconds == 0 {
return time.Time{}, errors.New("OTLP timestamp is required")
}
if nanoseconds > math.MaxInt64 {
return time.Time{}, errors.New("OTLP timestamp exceeds supported range")
}
return time.Unix(0, int64(nanoseconds)).UTC(), nil
}
+146
View File
@@ -0,0 +1,146 @@
// SPDX-License-Identifier: AGPL-3.0-only
package otlp
import (
"bytes"
"math"
"testing"
"time"
commonpb "go.opentelemetry.io/proto/otlp/common/v1"
logspb "go.opentelemetry.io/proto/otlp/logs/v1"
metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"
resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
tracepb "go.opentelemetry.io/proto/otlp/trace/v1"
"google.golang.org/protobuf/proto"
)
func TestDecodeLogsDropsCredentialsAndPreservesTelemetry(t *testing.T) {
now := time.Date(2026, 8, 17, 3, 0, 0, 0, time.UTC)
request := &logspb.LogsData{ResourceLogs: []*logspb.ResourceLogs{{
Resource: &resourcepb.Resource{Attributes: []*commonpb.KeyValue{
stringAttribute("service.name", "eql"),
stringAttribute("http.request.header.authorization", "Bearer do-not-store"),
}},
ScopeLogs: []*logspb.ScopeLogs{{
Scope: &commonpb.InstrumentationScope{Name: "test", Version: "1"},
LogRecords: []*logspb.LogRecord{{
TimeUnixNano: uint64(now.UnixNano()), EventName: "http.request", SeverityText: "INFO",
Body: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: "complete"}},
TraceId: bytes.Repeat([]byte{0x11}, 16), SpanId: bytes.Repeat([]byte{0x22}, 8),
Attributes: []*commonpb.KeyValue{stringAttribute("http.route", "/items/{id}")},
}},
}},
}}}
records, err := Decode(Logs, marshal(t, request), now)
if err != nil {
t.Fatal(err)
}
if len(records) != 1 || records[0].Name != "http.request" || records[0].Body != "complete" || records[0].TraceID != "11111111111111111111111111111111" {
t.Fatalf("records=%+v", records)
}
if records[0].Attributes["service.name"] != "eql" || records[0].Attributes["http.route"] != "/items/{id}" || records[0].Attributes["otel.scope.name"] != "test" {
t.Fatalf("attributes=%+v", records[0].Attributes)
}
if _, exists := records[0].Attributes["http.request.header.authorization"]; exists {
t.Fatal("credential-bearing attribute was retained")
}
}
func TestDecodeMetricsAndTraces(t *testing.T) {
now := time.Date(2026, 8, 17, 3, 0, 0, 0, time.UTC)
point := &metricspb.NumberDataPoint{
TimeUnixNano: uint64(now.UnixNano()),
Value: &metricspb.NumberDataPoint_AsDouble{AsDouble: 12.5},
Attributes: []*commonpb.KeyValue{stringAttribute("http.route", "/")},
}
metric := &metricspb.Metric{Name: "http.server.duration", Unit: "ms", Data: &metricspb.Metric_Gauge{Gauge: &metricspb.Gauge{DataPoints: []*metricspb.NumberDataPoint{point}}}}
metricRequest := &metricspb.MetricsData{ResourceMetrics: []*metricspb.ResourceMetrics{{ScopeMetrics: []*metricspb.ScopeMetrics{{Metrics: []*metricspb.Metric{metric}}}}}}
metrics, err := Decode(Metrics, marshal(t, metricRequest), now)
if err != nil {
t.Fatal(err)
}
if len(metrics) != 1 || metrics[0].Value == nil || *metrics[0].Value != 12.5 || metrics[0].Attributes["metric.unit"] != "ms" {
t.Fatalf("metrics=%+v", metrics)
}
span := &tracepb.Span{
TraceId: bytes.Repeat([]byte{0x33}, 16), SpanId: bytes.Repeat([]byte{0x44}, 8), Name: "GET /", Kind: tracepb.Span_SPAN_KIND_SERVER,
StartTimeUnixNano: uint64(now.UnixNano()), EndTimeUnixNano: uint64(now.Add(7 * time.Millisecond).UnixNano()), Status: &tracepb.Status{Code: tracepb.Status_STATUS_CODE_OK},
}
traceRequest := &tracepb.TracesData{ResourceSpans: []*tracepb.ResourceSpans{{ScopeSpans: []*tracepb.ScopeSpans{{Spans: []*tracepb.Span{span}}}}}}
traces, err := Decode(Traces, marshal(t, traceRequest), now)
if err != nil {
t.Fatal(err)
}
if len(traces) != 1 || traces[0].Name != "GET /" || traces[0].Value == nil || *traces[0].Value != float64((7*time.Millisecond).Nanoseconds()) || traces[0].Attributes["span.status"] != "STATUS_CODE_OK" {
t.Fatalf("traces=%+v", traces)
}
}
func TestDecodeRejectsMalformedAndNonFiniteData(t *testing.T) {
now := time.Date(2026, 8, 17, 3, 0, 0, 0, time.UTC)
badPoint := &metricspb.NumberDataPoint{TimeUnixNano: uint64(now.UnixNano()), Value: &metricspb.NumberDataPoint_AsDouble{AsDouble: math.NaN()}}
badMetricValue := &metricspb.Metric{Name: "bad", Data: &metricspb.Metric_Gauge{Gauge: &metricspb.Gauge{DataPoints: []*metricspb.NumberDataPoint{badPoint}}}}
badMetric := &metricspb.MetricsData{ResourceMetrics: []*metricspb.ResourceMetrics{{ScopeMetrics: []*metricspb.ScopeMetrics{{Metrics: []*metricspb.Metric{badMetricValue}}}}}}
if _, err := Decode(Metrics, marshal(t, badMetric), now); err == nil {
t.Fatal("non-finite metric accepted")
}
badTrace := &tracepb.TracesData{ResourceSpans: []*tracepb.ResourceSpans{{ScopeSpans: []*tracepb.ScopeSpans{{Spans: []*tracepb.Span{{TraceId: []byte{1}, SpanId: bytes.Repeat([]byte{2}, 8), Name: "bad", StartTimeUnixNano: uint64(now.UnixNano()), EndTimeUnixNano: uint64(now.UnixNano())}}}}}}}
if _, err := Decode(Traces, marshal(t, badTrace), now); err == nil {
t.Fatal("invalid trace identifier accepted")
}
if _, err := Decode(Logs, []byte{0xff, 0xff}, now); err == nil {
t.Fatal("malformed protobuf accepted")
}
}
func TestSuccessResponseIsDeterministicAndValid(t *testing.T) {
for _, signal := range []Signal{Logs, Metrics, Traces} {
first, err := SuccessResponse(signal)
if err != nil {
t.Fatal(err)
}
second, _ := SuccessResponse(signal)
if !bytes.Equal(first, second) {
t.Fatalf("%s response is not deterministic", signal)
}
if len(first) != 0 {
t.Fatalf("%s response has non-canonical empty encoding", signal)
}
}
}
func FuzzDecode(f *testing.F) {
now := time.Date(2026, 8, 17, 3, 0, 0, 0, time.UTC)
seed, err := proto.Marshal(&logspb.LogsData{ResourceLogs: []*logspb.ResourceLogs{{ScopeLogs: []*logspb.ScopeLogs{{LogRecords: []*logspb.LogRecord{{TimeUnixNano: uint64(now.UnixNano()), EventName: "seed"}}}}}}})
if err != nil {
f.Fatal(err)
}
f.Add(uint8(0), seed)
f.Add(uint8(1), []byte{0xff, 0x00})
f.Fuzz(func(t *testing.T, selected uint8, body []byte) {
if len(body) > 1<<20 {
return
}
signal := []Signal{Logs, Metrics, Traces}[selected%3]
records, _ := Decode(signal, body, now)
if len(records) > 5_000 {
t.Fatalf("decoded %d records", len(records))
}
})
}
func stringAttribute(key, value string) *commonpb.KeyValue {
return &commonpb.KeyValue{Key: key, Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: value}}}
}
func marshal(t *testing.T, message proto.Message) []byte {
t.Helper()
body, err := proto.MarshalOptions{Deterministic: true}.Marshal(message)
if err != nil {
t.Fatal(err)
}
return body
}
+151
View File
@@ -0,0 +1,151 @@
// SPDX-License-Identifier: AGPL-3.0-only
package query
import (
"math"
"regexp"
"strconv"
"strings"
"time"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/schema"
)
type FieldLookup func(field string) (string, bool)
// MatchesFilters applies the query's typed filters to a bounded record value
// lookup. Storage projections and the local agent evaluator share this path so
// edge and central comparisons cannot drift silently.
func MatchesFilters(ast AST, registry Registry, lookup FieldLookup) (bool, error) {
for _, filter := range ast.Filters {
field := CanonicalField(filter.Field)
descriptor, _ := ResolveDescriptor(ast.Signal, field, registry)
value, present := lookup(field)
if !present {
return false, nil
}
matched, err := CompareValue(value, filter.Value, filter.Op, descriptor.Type)
if err != nil {
return false, err
}
if !matched {
return false, nil
}
}
return true, nil
}
func MatchObservation(observation model.Observation, ast AST, registry Registry) (bool, error) {
return MatchesFilters(ast, registry, func(field string) (string, bool) {
switch CanonicalField(field) {
case "timestamp":
return observation.Timestamp.UTC().Format(time.RFC3339Nano), !observation.Timestamp.IsZero()
case "name":
return observation.Name, observation.Name != ""
case "severity":
return observation.Severity, observation.Severity != ""
case "body":
return observation.Body, observation.Body != ""
case "value":
if observation.Value == nil {
return "", false
}
return strconv.FormatFloat(*observation.Value, 'g', -1, 64), true
case "trace_id":
return observation.TraceID, observation.TraceID != ""
case "span_id":
return observation.SpanID, observation.SpanID != ""
case "correlation_id":
return observation.CorrelationID, observation.CorrelationID != ""
default:
value, ok := observation.Attributes[CanonicalField(field)]
return value, ok
}
})
}
func CompareValue(left, right, operator string, valueType schema.Type) (bool, error) {
if operator == "=~" {
if valueType != schema.TypeString {
return false, ErrTypeMismatch
}
expression, err := regexp.Compile(right)
if err != nil {
return false, ErrTypeMismatch
}
return expression.MatchString(left), nil
}
var comparison int
switch valueType {
case schema.TypeInteger, schema.TypeFloat, schema.TypeDuration:
rightNumber, rightErr := strconv.ParseFloat(right, 64)
if rightErr != nil || math.IsNaN(rightNumber) || math.IsInf(rightNumber, 0) {
return false, ErrTypeMismatch
}
leftNumber, leftErr := strconv.ParseFloat(left, 64)
if leftErr != nil || math.IsNaN(leftNumber) || math.IsInf(leftNumber, 0) {
return false, nil
}
comparison = compareFloat(leftNumber, rightNumber)
case schema.TypeTime:
rightTime, rightErr := time.Parse(time.RFC3339Nano, right)
if rightErr != nil {
return false, ErrTypeMismatch
}
leftTime, leftErr := time.Parse(time.RFC3339Nano, left)
if leftErr != nil {
return false, nil
}
comparison = leftTime.Compare(rightTime)
case schema.TypeBoolean:
rightBool, rightErr := strconv.ParseBool(right)
if rightErr != nil {
return false, ErrTypeMismatch
}
leftBool, leftErr := strconv.ParseBool(left)
if leftErr != nil {
return false, nil
}
comparison = compareBool(leftBool, rightBool)
default:
comparison = strings.Compare(left, right)
}
switch operator {
case "==":
return comparison == 0, nil
case "!=":
return comparison != 0, nil
case ">":
return comparison > 0, nil
case ">=":
return comparison >= 0, nil
case "<":
return comparison < 0, nil
case "<=":
return comparison <= 0, nil
default:
return false, ErrTypeMismatch
}
}
func compareFloat(left, right float64) int {
if left < right {
return -1
}
if left > right {
return 1
}
return 0
}
func compareBool(left, right bool) int {
if left == right {
return 0
}
if !left {
return -1
}
return 1
}
+44
View File
@@ -0,0 +1,44 @@
// SPDX-License-Identifier: AGPL-3.0-only
package query
import (
"testing"
"time"
"gamertan.com/observatory/internal/model"
)
func TestMatchObservationUsesCanonicalTypedFilters(t *testing.T) {
now := time.Date(2026, 8, 18, 23, 55, 0, 0, time.UTC)
observation := model.Observation{Timestamp: now, Name: "http.request", Severity: "error", Attributes: map[string]string{"http.status_code": "503", "http.route": "/failed"}}
ast, err := Parse(`logs | where status >= 500 | where route == "/failed" | limit 10`, 100)
if err != nil {
t.Fatal(err)
}
matched, err := MatchObservation(observation, ast, nil)
if err != nil || !matched {
t.Fatalf("matched=%t err=%v", matched, err)
}
observation.Attributes["http.status_code"] = "200"
matched, err = MatchObservation(observation, ast, nil)
if err != nil || matched {
t.Fatalf("matched=%t err=%v", matched, err)
}
delete(observation.Attributes, "http.status_code")
matched, err = MatchObservation(observation, ast, nil)
if err != nil || matched {
t.Fatalf("missing field matched=%t err=%v", matched, err)
}
}
func TestMatchObservationRejectsInvalidTypedFilterValue(t *testing.T) {
ast, err := Parse(`logs | where status >= nope | limit 10`, 100)
if err != nil {
t.Fatal(err)
}
observation := model.Observation{Timestamp: time.Now().UTC(), Name: "http.request", Attributes: map[string]string{"http.status_code": "503"}}
if _, err = MatchObservation(observation, ast, nil); err != ErrTypeMismatch {
t.Fatalf("err=%v", err)
}
}
+248
View File
@@ -0,0 +1,248 @@
// SPDX-License-Identifier: AGPL-3.0-only
package query
import (
"errors"
"fmt"
"sort"
"strings"
"time"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/schema"
)
var ErrSensitivePermissionRequired = errors.New("query requires sensitive-field permission")
type Scope struct {
OrganizationID string `json:"organization_id"`
ProjectID string `json:"project_id,omitempty"`
EnvironmentID string `json:"environment_id,omitempty"`
ServiceID string `json:"service_id,omitempty"`
Sensitive bool `json:"sensitive"`
}
type Budget struct {
MaxDuration time.Duration `json:"-"`
MaxRows int `json:"max_rows"`
MaxScannedBytes int64 `json:"max_scanned_bytes"`
MaxMemoryBytes int64 `json:"max_memory_bytes"`
}
type FieldPlan struct {
Field string `json:"field"`
Descriptor schema.Descriptor `json:"descriptor"`
Indexed bool `json:"indexed"`
Unknown bool `json:"unknown"`
}
type Explain struct {
AST AST `json:"ast"`
ProjectedSources []string `json:"projected_sources"`
Fields []FieldPlan `json:"fields"`
EstimatedScanBytes int64 `json:"estimated_scan_bytes"`
CacheEligible bool `json:"cache_eligible"`
RequiredPermissions []string `json:"required_permissions"`
Budget Budget `json:"budget"`
}
type Registry interface {
Lookup(model.Signal, string) (schema.Descriptor, bool)
}
type MapRegistry map[string]schema.Descriptor
func (registry MapRegistry) Lookup(signal model.Signal, field string) (schema.Descriptor, bool) {
descriptor, ok := registry[string(signal)+":"+CanonicalField(field)]
return descriptor, ok
}
func Plan(ast AST, scope Scope, registry Registry, estimatedScanBytes int64, budget Budget) (Explain, error) {
if err := Validate(ast, budget.MaxRows); err != nil {
return Explain{}, err
}
if !safeScope(scope) {
return Explain{}, errors.New("query scope is invalid")
}
if budget.MaxDuration < time.Millisecond || budget.MaxDuration > time.Minute || budget.MaxRows < 1 || budget.MaxScannedBytes < 1 || budget.MaxMemoryBytes < 1 {
return Explain{}, errors.New("query budget is invalid")
}
if estimatedScanBytes < 0 || estimatedScanBytes > budget.MaxScannedBytes {
return Explain{}, errors.New("estimated query scan exceeds budget")
}
fields := ReferencedFields(ast)
plans := make([]FieldPlan, 0, len(fields))
requiresSensitive := false
cacheEligible := true
for _, field := range fields {
canonical := CanonicalField(field)
descriptor, unknown := ResolveDescriptor(ast.Signal, canonical, registry)
if err := descriptor.Validate(); err != nil {
return Explain{}, fmt.Errorf("field %s descriptor: %w", field, err)
}
if descriptor.Sensitivity == schema.SensitivitySensitive {
requiresSensitive = true
cacheEligible = false
}
plans = append(plans, FieldPlan{Field: field, Descriptor: descriptor, Indexed: descriptor.Index != schema.IndexNone, Unknown: unknown})
}
if requiresSensitive && !scope.Sensitive {
return Explain{}, ErrSensitivePermissionRequired
}
for _, filter := range ast.Filters {
if filter.Op == "=~" {
cacheEligible = false
}
}
permissions := []string{"telemetry:query"}
if requiresSensitive {
permissions = append(permissions, "telemetry:sensitive")
}
source := "organization:" + scope.OrganizationID + "/signal:" + string(ast.Signal)
if scope.ProjectID != "" {
source += "/project:" + scope.ProjectID
}
if scope.EnvironmentID != "" {
source += "/environment:" + scope.EnvironmentID
}
if scope.ServiceID != "" {
source += "/service:" + scope.ServiceID
}
return Explain{AST: ast, ProjectedSources: []string{source}, Fields: plans, EstimatedScanBytes: estimatedScanBytes, CacheEligible: cacheEligible, RequiredPermissions: permissions, Budget: budget}, nil
}
func ReferencedFields(ast AST) []string {
seen := map[string]bool{}
var fields []string
add := func(field string) {
if field != "" && !seen[field] {
seen[field] = true
fields = append(fields, field)
}
}
for _, filter := range ast.Filters {
add(filter.Field)
}
if ast.Sort != nil {
isAggregateAlias := false
if ast.Summary != nil {
for _, aggregate := range ast.Summary.Aggregates {
if aggregate.Alias == ast.Sort.Field {
isAggregateAlias = true
break
}
}
}
if !isAggregateAlias {
add(ast.Sort.Field)
}
}
if ast.Summary != nil {
for _, aggregate := range ast.Summary.Aggregates {
add(aggregate.Field)
}
for _, field := range ast.Summary.GroupBy {
add(field)
}
}
sort.Strings(fields)
return fields
}
func CanonicalField(field string) string {
switch field {
case "service":
return "service.id"
case "project":
return "project.id"
case "environment":
return "environment.id"
case "route":
return "http.route"
case "status":
return "http.status_code"
case "duration":
return "duration_ns"
default:
return field
}
}
func ResolveDescriptor(signal model.Signal, field string, registry Registry) (schema.Descriptor, bool) {
canonical := CanonicalField(field)
descriptor, ok := BuiltinDescriptor(signal, canonical)
if !ok && registry != nil {
descriptor, ok = registry.Lookup(signal, canonical)
}
if !ok {
return schema.Unknown(signal, canonical), true
}
return descriptor, false
}
func BuiltinDescriptor(signal model.Signal, field string) (schema.Descriptor, bool) {
descriptors := map[string]schema.Descriptor{
"service.id": descriptor(signal, "service.id", schema.TypeString, "Application service identifier.", schema.SensitivityInternal, schema.CardinalityLow, schema.IndexExact, ""),
"project.id": descriptor(signal, "project.id", schema.TypeString, "Application project identifier.", schema.SensitivityInternal, schema.CardinalityLow, schema.IndexExact, ""),
"environment.id": descriptor(signal, "environment.id", schema.TypeString, "Deployment environment identifier.", schema.SensitivityInternal, schema.CardinalityLow, schema.IndexExact, ""),
"timestamp": descriptor(signal, "timestamp", schema.TypeTime, "Observation timestamp.", schema.SensitivityInternal, schema.CardinalityHigh, schema.IndexRange, "s"),
"name": descriptor(signal, "name", schema.TypeString, "Observation name.", schema.SensitivityInternal, schema.CardinalityMedium, schema.IndexExact, ""),
"severity": descriptor(signal, "severity", schema.TypeString, "Log severity.", schema.SensitivityInternal, schema.CardinalityLow, schema.IndexExact, ""),
"value": descriptor(signal, "value", schema.TypeFloat, "Numeric observation value.", schema.SensitivityInternal, schema.CardinalityHigh, schema.IndexRange, ""),
"http.route": descriptor(signal, "http.route", schema.TypeString, "Application-normalized HTTP route.", schema.SensitivityInternal, schema.CardinalityMedium, schema.IndexExact, ""),
"http.status_code": descriptor(signal, "http.status_code", schema.TypeInteger, "HTTP response status code.", schema.SensitivityPublic, schema.CardinalityLow, schema.IndexExact, ""),
"duration_ns": descriptor(signal, "duration_ns", schema.TypeDuration, "Observed duration in nanoseconds.", schema.SensitivityInternal, schema.CardinalityHigh, schema.IndexRange, "ns"),
"state": descriptor(signal, "state", schema.TypeString, "Bounded metric state dimension.", schema.SensitivityInternal, schema.CardinalityLow, schema.IndexExact, ""),
"period": descriptor(signal, "period", schema.TypeString, "Bounded measurement period dimension.", schema.SensitivityInternal, schema.CardinalityLow, schema.IndexExact, ""),
"interface": descriptor(signal, "interface", schema.TypeString, "Configured network interface dimension.", schema.SensitivityInternal, schema.CardinalityMedium, schema.IndexExact, ""),
"direction": descriptor(signal, "direction", schema.TypeString, "Bounded input or output direction dimension.", schema.SensitivityInternal, schema.CardinalityLow, schema.IndexExact, ""),
"filesystem": descriptor(signal, "filesystem", schema.TypeString, "Configured filesystem dimension.", schema.SensitivityInternal, schema.CardinalityMedium, schema.IndexExact, ""),
"process": descriptor(signal, "process", schema.TypeString, "Configured process dimension.", schema.SensitivityInternal, schema.CardinalityMedium, schema.IndexExact, ""),
"cgroup": descriptor(signal, "cgroup", schema.TypeString, "Configured cgroup dimension.", schema.SensitivityInternal, schema.CardinalityMedium, schema.IndexExact, ""),
"unit": descriptor(signal, "unit", schema.TypeString, "Metric unit supplied by a bounded collector.", schema.SensitivityInternal, schema.CardinalityLow, schema.IndexExact, ""),
"trace_id": descriptor(signal, "trace_id", schema.TypeString, "Trace correlation identifier.", schema.SensitivityInternal, schema.CardinalityHigh, schema.IndexRange, ""),
"span_id": descriptor(signal, "span_id", schema.TypeString, "Span correlation identifier.", schema.SensitivityInternal, schema.CardinalityHigh, schema.IndexRange, ""),
"correlation_id": descriptor(signal, "correlation_id", schema.TypeString, "Cross-signal correlation identifier.", schema.SensitivityInternal, schema.CardinalityHigh, schema.IndexRange, ""),
"body": descriptor(signal, "body", schema.TypeString, "Optional retained log text.", schema.SensitivitySensitive, schema.CardinalityHigh, schema.IndexNone, ""),
}
descriptor, ok := descriptors[field]
if ok && signal != model.SignalMetrics {
switch field {
case "state", "period", "interface", "direction", "filesystem", "process", "cgroup", "unit":
return schema.Descriptor{}, false
}
}
if ok && signal == model.SignalMetrics {
switch field {
case "http.route", "http.status_code", "state", "period", "interface", "direction", "filesystem", "process", "cgroup", "unit":
descriptor.Retention = schema.RetentionMetric
}
}
return descriptor, ok
}
func descriptor(signal model.Signal, field string, valueType schema.Type, meaning string, sensitivity schema.Sensitivity, cardinality schema.Cardinality, index schema.IndexPolicy, unit string) schema.Descriptor {
return schema.Descriptor{Version: schema.DescriptorVersion, Signal: signal, Field: field, Type: valueType, Unit: unit, Meaning: meaning, Sensitivity: sensitivity, Cardinality: cardinality, Index: index, Retention: schema.RetentionRaw, ProjectionVersion: 1}
}
func safeScope(scope Scope) bool {
values := []string{scope.OrganizationID, scope.ProjectID, scope.EnvironmentID, scope.ServiceID}
if values[0] == "" {
return false
}
for _, value := range values {
if value == "" {
continue
}
if len(value) > 128 {
return false
}
for _, r := range value {
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("._-", r)) {
return false
}
}
}
return true
}
+80
View File
@@ -0,0 +1,80 @@
// SPDX-License-Identifier: AGPL-3.0-only
package query
import (
"testing"
"time"
"gamertan.com/observatory/internal/model"
"gamertan.com/observatory/internal/schema"
)
func TestPlanInjectsScopeAndReportsIndexes(t *testing.T) {
ast, err := Parse(`logs | where service == "eql" | where status >= 500 | window 24h | sort timestamp desc | limit 50`, 1000)
if err != nil {
t.Fatal(err)
}
explain, err := Plan(ast, Scope{OrganizationID: "personal-cole", ProjectID: "eql", EnvironmentID: "production"}, nil, 10<<20, Budget{MaxDuration: 5 * time.Second, MaxRows: 1000, MaxScannedBytes: 100 << 20, MaxMemoryBytes: 64 << 20})
if err != nil {
t.Fatal(err)
}
if len(explain.ProjectedSources) != 1 || explain.ProjectedSources[0] != "organization:personal-cole/signal:logs/project:eql/environment:production" || len(explain.Fields) != 3 {
t.Fatalf("explain=%+v", explain)
}
for _, field := range explain.Fields {
if !field.Indexed || field.Unknown {
t.Fatalf("field=%+v", field)
}
}
}
func TestPlanRequiresSensitivePermissionForUnknownAndBody(t *testing.T) {
for _, text := range []string{`logs | where vendor.unknown == "x" | limit 10`, `logs | where body =~ "error" | limit 10`} {
ast, err := Parse(text, 100)
if err != nil {
t.Fatal(err)
}
budget := Budget{MaxDuration: time.Second, MaxRows: 100, MaxScannedBytes: 1 << 20, MaxMemoryBytes: 1 << 20}
if _, err := Plan(ast, Scope{OrganizationID: "org"}, nil, 100, budget); err == nil {
t.Fatalf("expected sensitive rejection for %q", text)
}
explain, err := Plan(ast, Scope{OrganizationID: "org", Sensitive: true}, nil, 100, budget)
if err != nil {
t.Fatal(err)
}
if len(explain.RequiredPermissions) != 2 || explain.CacheEligible {
t.Fatalf("explain=%+v", explain)
}
}
}
func TestPlanRejectsCrossTenantScopeAndScanBudget(t *testing.T) {
ast, _ := Parse(`metrics | limit 10`, 100)
budget := Budget{MaxDuration: time.Second, MaxRows: 100, MaxScannedBytes: 1000, MaxMemoryBytes: 1000}
if _, err := Plan(ast, Scope{OrganizationID: "../other"}, nil, 10, budget); err == nil {
t.Fatal("expected scope rejection")
}
if _, err := Plan(ast, Scope{OrganizationID: "org"}, nil, 1001, budget); err == nil {
t.Fatal("expected scan-budget rejection")
}
}
func TestBuiltinMetricDimensionsAreSignalScopedAndRetentionAware(t *testing.T) {
state, ok := BuiltinDescriptor(model.SignalMetrics, "state")
if !ok || state.Retention != schema.RetentionMetric {
t.Fatalf("metric state descriptor=%+v ok=%t", state, ok)
}
if _, ok = BuiltinDescriptor(model.SignalLogs, "state"); ok {
t.Fatal("metric-only state dimension was exposed to logs")
}
metricRoute, ok := BuiltinDescriptor(model.SignalMetrics, "http.route")
if !ok || metricRoute.Retention != schema.RetentionMetric {
t.Fatalf("metric route descriptor=%+v ok=%t", metricRoute, ok)
}
logRoute, ok := BuiltinDescriptor(model.SignalLogs, "http.route")
if !ok || logRoute.Retention != schema.RetentionRaw {
t.Fatalf("log route descriptor=%+v ok=%t", logRoute, ok)
}
}
+300
View File
@@ -0,0 +1,300 @@
// SPDX-License-Identifier: AGPL-3.0-only
package query
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"gamertan.com/observatory/internal/model"
)
const (
ASTVersion = 1
maxQueryWindow = 3650 * 24 * time.Hour
)
type AST struct {
Version int `json:"version"`
Signal model.Signal `json:"signal"`
Filters []Filter `json:"filters,omitempty"`
Sort *Sort `json:"sort,omitempty"`
Summary *Summary `json:"summary,omitempty"`
Limit int `json:"limit"`
Window time.Duration `json:"-"`
WindowText string `json:"window,omitempty"`
Bucket time.Duration `json:"-"`
BucketText string `json:"bucket,omitempty"`
}
type Filter struct {
Field string `json:"field"`
Op string `json:"op"`
Value string `json:"value"`
}
type Sort struct {
Field string `json:"field"`
Descending bool `json:"descending"`
}
type Summary struct {
Aggregates []Aggregate `json:"aggregates"`
GroupBy []string `json:"group_by,omitempty"`
}
type Aggregate struct {
Function string `json:"function"`
Field string `json:"field,omitempty"`
Alias string `json:"alias"`
}
func Parse(text string, maxLimit int) (AST, error) {
if len(text) == 0 || len(text) > 16_384 {
return AST{}, errors.New("query length outside accepted bounds")
}
parts := strings.Split(text, "|")
if len(parts) > 16 {
return AST{}, errors.New("too many query stages")
}
ast := AST{Version: ASTVersion, Signal: model.Signal(strings.TrimSpace(parts[0])), Limit: min(100, maxLimit)}
if ast.Signal != model.SignalLogs && ast.Signal != model.SignalMetrics && ast.Signal != model.SignalTraces && ast.Signal != model.SignalDeployments {
return AST{}, errors.New("query must begin with logs, metrics, traces, or deployments")
}
for _, raw := range parts[1:] {
stage := strings.TrimSpace(raw)
switch {
case strings.HasPrefix(stage, "where "):
filter, err := parseFilter(strings.TrimSpace(strings.TrimPrefix(stage, "where ")))
if err != nil {
return AST{}, err
}
ast.Filters = append(ast.Filters, filter)
case strings.HasPrefix(stage, "sort "):
fields := strings.Fields(strings.TrimSpace(strings.TrimPrefix(stage, "sort ")))
if len(fields) < 1 || len(fields) > 2 || !validField(fields[0]) {
return AST{}, errors.New("invalid sort stage")
}
desc := len(fields) == 2 && fields[1] == "desc"
if len(fields) == 2 && fields[1] != "asc" && fields[1] != "desc" {
return AST{}, errors.New("sort direction must be asc or desc")
}
ast.Sort = &Sort{Field: fields[0], Descending: desc}
case strings.HasPrefix(stage, "summarize "):
if ast.Summary != nil {
return AST{}, errors.New("query may contain only one summarize stage")
}
summary, bucket, bucketText, err := parseSummary(strings.TrimSpace(strings.TrimPrefix(stage, "summarize ")))
if err != nil {
return AST{}, err
}
ast.Summary = &summary
if bucket > 0 {
ast.Bucket, ast.BucketText = bucket, bucketText
}
case strings.HasPrefix(stage, "limit "):
n, err := strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(stage, "limit ")))
if err != nil || n < 1 || n > maxLimit {
return AST{}, fmt.Errorf("limit must be between 1 and %d", maxLimit)
}
ast.Limit = n
case strings.HasPrefix(stage, "window "):
windowText := strings.TrimSpace(strings.TrimPrefix(stage, "window "))
d, err := time.ParseDuration(windowText)
if err != nil || d < time.Second || d > maxQueryWindow {
return AST{}, errors.New("window must be between 1s and 87600h")
}
ast.Window, ast.WindowText = d, windowText
default:
return AST{}, fmt.Errorf("unsupported query stage %q", stage)
}
}
if err := Validate(ast, maxLimit); err != nil {
return AST{}, err
}
return ast, nil
}
func Validate(ast AST, maxLimit int) error {
if ast.Version != ASTVersion || (ast.Signal != model.SignalLogs && ast.Signal != model.SignalMetrics && ast.Signal != model.SignalTraces && ast.Signal != model.SignalDeployments) {
return errors.New("query AST identity is invalid")
}
if ast.Limit < 1 || ast.Limit > maxLimit {
return fmt.Errorf("limit must be between 1 and %d", maxLimit)
}
if ast.Window < 0 || ast.Window > maxQueryWindow || ast.Window > 0 && ast.Window < time.Second {
return errors.New("query window is invalid")
}
if ast.Bucket < 0 || ast.Bucket > maxQueryWindow || ast.Bucket > 0 && (ast.Bucket < time.Second || ast.Summary == nil) {
return errors.New("query summary bucket is invalid")
}
if len(ast.Filters) > 16 {
return errors.New("too many query filters")
}
for _, filter := range ast.Filters {
if !validField(filter.Field) || len(filter.Value) > 4096 {
return errors.New("query filter is invalid")
}
switch filter.Op {
case "!=", ">=", "<=", "==", ">", "<":
case "=~":
if len(filter.Value) > 512 {
return errors.New("regular expression exceeds 512 bytes")
}
if _, err := regexp.Compile(filter.Value); err != nil {
return errors.New("invalid regular expression")
}
default:
return errors.New("query filter operator is invalid")
}
}
if ast.Sort != nil && !validField(ast.Sort.Field) {
return errors.New("query sort is invalid")
}
if ast.Summary != nil {
if len(ast.Summary.Aggregates) < 1 || len(ast.Summary.Aggregates) > 16 || len(ast.Summary.GroupBy) > 16 {
return errors.New("query summary is invalid")
}
aliases := map[string]bool{}
for _, aggregate := range ast.Summary.Aggregates {
switch aggregate.Function {
case "count":
if aggregate.Field != "" {
return errors.New("count accepts no field")
}
case "min", "max", "sum", "avg", "p50", "p95", "p99":
if !validField(aggregate.Field) {
return errors.New("aggregate field is invalid")
}
default:
return errors.New("aggregate function is unsupported")
}
if !validField(aggregate.Alias) || aliases[aggregate.Alias] {
return errors.New("aggregate alias is invalid or duplicated")
}
aliases[aggregate.Alias] = true
}
for _, group := range ast.Summary.GroupBy {
if !validField(group) {
return errors.New("grouping field is invalid")
}
if aliases[group] {
return errors.New("grouping field conflicts with aggregate alias")
}
}
}
return nil
}
func parseFilter(expr string) (Filter, error) {
for _, op := range []string{"!=", ">=", "<=", "==", "=~", ">", "<"} {
if i := strings.Index(expr, op); i > 0 {
field := strings.TrimSpace(expr[:i])
value := strings.TrimSpace(expr[i+len(op):])
if !validField(field) || value == "" || len(value) > 4096 {
return Filter{}, errors.New("invalid where stage")
}
if len(value) >= 2 && value[0] == '"' && value[len(value)-1] == '"' {
unquoted, err := strconv.Unquote(value)
if err != nil {
return Filter{}, errors.New("invalid quoted filter value")
}
value = unquoted
}
if op == "=~" {
if len(value) > 512 {
return Filter{}, errors.New("regular expression exceeds 512 bytes")
}
if _, err := regexp.Compile(value); err != nil {
return Filter{}, errors.New("invalid regular expression")
}
}
return Filter{Field: field, Op: op, Value: value}, nil
}
}
return Filter{}, errors.New("where stage requires a comparison")
}
func parseSummary(stage string) (Summary, time.Duration, string, error) {
aggregateText, groupText, found := strings.Cut(stage, " by ")
aggregateParts := strings.Split(aggregateText, ",")
if len(aggregateParts) < 1 || len(aggregateParts) > 16 {
return Summary{}, 0, "", errors.New("summarize requires between 1 and 16 aggregates")
}
summary := Summary{}
aliases := map[string]bool{}
for _, raw := range aggregateParts {
expression := strings.TrimSpace(raw)
open := strings.IndexByte(expression, '(')
if open < 1 || !strings.HasSuffix(expression, ")") {
return Summary{}, 0, "", errors.New("invalid aggregate")
}
function := expression[:open]
field := strings.TrimSpace(expression[open+1 : len(expression)-1])
switch function {
case "count":
if field != "" {
return Summary{}, 0, "", errors.New("count accepts no field")
}
case "min", "max", "sum", "avg", "p50", "p95", "p99":
if !validField(field) {
return Summary{}, 0, "", errors.New("aggregate field is invalid")
}
default:
return Summary{}, 0, "", errors.New("aggregate function is unsupported")
}
alias := function
if field != "" {
alias += "_" + strings.ReplaceAll(field, ".", "_")
}
if aliases[alias] {
return Summary{}, 0, "", errors.New("aggregate alias is duplicated")
}
aliases[alias] = true
summary.Aggregates = append(summary.Aggregates, Aggregate{Function: function, Field: field, Alias: alias})
}
var window time.Duration
var windowText string
if found {
groups := strings.Split(groupText, ",")
if len(groups) > 16 {
return Summary{}, 0, "", errors.New("too many grouping fields")
}
for _, raw := range groups {
group := strings.TrimSpace(raw)
if strings.HasPrefix(group, "window(") && strings.HasSuffix(group, ")") {
if window > 0 {
return Summary{}, 0, "", errors.New("summary window is duplicated")
}
windowText = strings.TrimSpace(group[len("window(") : len(group)-1])
parsed, err := time.ParseDuration(windowText)
if err != nil || parsed < time.Second || parsed > maxQueryWindow {
return Summary{}, 0, "", errors.New("summary window must be between 1s and 87600h")
}
window = parsed
continue
}
if !validField(group) {
return Summary{}, 0, "", errors.New("grouping field is invalid")
}
summary.GroupBy = append(summary.GroupBy, group)
}
}
return summary, window, windowText, nil
}
func validField(field string) bool {
if field == "" || len(field) > 128 {
return false
}
for _, r := range field {
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_' || r == '.') {
return false
}
}
return true
}
+104
View File
@@ -0,0 +1,104 @@
// SPDX-License-Identifier: AGPL-3.0-only
package query
import (
"encoding/json"
"reflect"
"testing"
)
func TestParseBoundedQuery(t *testing.T) {
ast, err := Parse(`logs | where service == "eql" | where status >= 500 | window 24h | sort timestamp desc | limit 50`, 1000)
if err != nil {
t.Fatal(err)
}
if ast.Limit != 50 || len(ast.Filters) != 2 || ast.WindowText != "24h" || ast.Sort == nil || !ast.Sort.Descending {
t.Fatalf("unexpected AST: %#v", ast)
}
}
func TestTextAndVisualBuilderShareValidatedAST(t *testing.T) {
fromText, err := Parse(`metrics | where service == "eql" | window 1h | limit 25`, 1000)
if err != nil {
t.Fatal(err)
}
b, err := json.Marshal(fromText)
if err != nil {
t.Fatal(err)
}
var fromBuilder AST
if err := json.Unmarshal(b, &fromBuilder); err != nil {
t.Fatal(err)
}
fromBuilder.Window = fromText.Window
fromBuilder.Bucket = fromText.Bucket
if err := Validate(fromBuilder, 1000); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(fromText, fromBuilder) {
t.Fatalf("text=%+v builder=%+v", fromText, fromBuilder)
}
fromBuilder.Filters[0].Op = "SQL"
if err := Validate(fromBuilder, 1000); err == nil {
t.Fatal("expected hostile builder AST rejection")
}
}
func TestParseRejectsSQLAndUnboundedLimit(t *testing.T) {
for _, input := range []string{"select * from logs", "logs | limit 1001", "logs | where route;drop == x"} {
if _, err := Parse(input, 1000); err == nil {
t.Fatalf("expected rejection for %q", input)
}
}
}
func TestParseUnifiedSummaryAndSafeRegex(t *testing.T) {
ast, err := Parse(`logs | where route =~ "^/items/[0-9]+$" | summarize count(), p95(duration) by route, window(5m) | sort count desc | limit 50`, 1000)
if err != nil {
t.Fatal(err)
}
if ast.Summary == nil || len(ast.Summary.Aggregates) != 2 || len(ast.Summary.GroupBy) != 1 || ast.WindowText != "" || ast.BucketText != "5m" || ast.Summary.Aggregates[1].Alias != "p95_duration" {
t.Fatalf("ast=%+v", ast)
}
if _, err := Parse(`logs | where route =~ "["`, 1000); err == nil {
t.Fatal("expected invalid regular expression rejection")
}
}
func TestParseSupportsApprovedTenYearColdLookback(t *testing.T) {
ast, err := Parse(`logs | window 87600h | limit 10`, 100)
if err != nil || ast.Window != maxQueryWindow {
t.Fatalf("ast=%+v err=%v", ast, err)
}
if _, err = Parse(`logs | window 87601h | limit 10`, 100); err == nil {
t.Fatal("lookback beyond retention ceiling was accepted")
}
}
func FuzzParse(f *testing.F) {
for _, seed := range []string{
`logs | where service == "eql" | limit 50`,
`metrics | summarize count(), p95(duration) by route, window(5m) | limit 50`,
`traces | where trace_id =~ "^[0-9a-f]{32}$" | window 1h | limit 10`,
`select * from logs`,
string([]byte{0, 1, 2, 3}),
} {
f.Add(seed)
}
f.Fuzz(func(t *testing.T, text string) {
if len(text) > 20_000 {
return
}
ast, err := Parse(text, 1_000)
if err != nil {
return
}
if err = Validate(ast, 1_000); err != nil {
t.Fatalf("parser returned an invalid AST: %v", err)
}
if ast.Limit < 1 || ast.Limit > 1_000 || len(ast.Filters) > 16 {
t.Fatalf("accepted AST violates hard bounds: %+v", ast)
}
})
}
+45
View File
@@ -0,0 +1,45 @@
// SPDX-License-Identifier: AGPL-3.0-only
package query
import (
"errors"
"gamertan.com/observatory/internal/schema"
)
const ResultVersion = 1
var (
ErrBudgetExceeded = errors.New("query execution budget exceeded")
ErrTypeMismatch = errors.New("query value does not match its field type")
)
type Column struct {
Field string `json:"field"`
Type schema.Type `json:"type"`
Unit string `json:"unit,omitempty"`
}
// Row values align positionally with Result.Columns. Nil is a missing value;
// non-nil values use the canonical string form described by the column type.
type Row struct {
Values []*string `json:"values"`
}
type Statistics struct {
ScannedRows int `json:"scanned_rows"`
MatchedRows int `json:"matched_rows"`
ScannedBytes int64 `json:"scanned_bytes"`
DurationNS int64 `json:"duration_ns"`
Truncated bool `json:"truncated"`
Approximate bool `json:"approximate,omitempty"`
}
type Result struct {
Version int `json:"version"`
Explain Explain `json:"explain"`
Columns []Column `json:"columns"`
Rows []Row `json:"rows"`
Stats Statistics `json:"statistics"`
}
+138
View File
@@ -0,0 +1,138 @@
// SPDX-License-Identifier: AGPL-3.0-only
package schema
import (
"errors"
"fmt"
"regexp"
"strings"
"gamertan.com/observatory/internal/model"
)
const DescriptorVersion = 1
type Type string
type Sensitivity string
type Cardinality string
type IndexPolicy string
type RetentionClass string
const (
TypeString Type = "string"
TypeInteger Type = "integer"
TypeFloat Type = "float"
TypeBoolean Type = "boolean"
TypeDuration Type = "duration"
TypeTime Type = "time"
SensitivityPublic Sensitivity = "public"
SensitivityInternal Sensitivity = "internal"
SensitivitySensitive Sensitivity = "sensitive"
CardinalityLow Cardinality = "low"
CardinalityMedium Cardinality = "medium"
CardinalityHigh Cardinality = "high"
IndexNone IndexPolicy = "none"
IndexExact IndexPolicy = "exact"
IndexRange IndexPolicy = "range"
RetentionRaw RetentionClass = "raw"
RetentionMetric RetentionClass = "metric"
RetentionEvidence RetentionClass = "evidence"
)
var fieldPattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_.]{0,127}$`)
var unitPattern = regexp.MustCompile(`^[A-Za-z0-9%/._-]{0,64}$`)
type Descriptor struct {
Version int `json:"version"`
Signal model.Signal `json:"signal"`
Field string `json:"field"`
Type Type `json:"type"`
Unit string `json:"unit,omitempty"`
Meaning string `json:"meaning"`
Sensitivity Sensitivity `json:"sensitivity"`
Cardinality Cardinality `json:"cardinality"`
Index IndexPolicy `json:"index"`
Retention RetentionClass `json:"retention"`
ProjectionVersion int `json:"projection_version"`
}
type Proposal struct {
Descriptor Descriptor `json:"descriptor"`
ObservedValues int64 `json:"observed_values"`
EstimatedBytes int64 `json:"estimated_bytes"`
ExampleQueries []string `json:"example_queries"`
}
func (d Descriptor) Validate() error {
if d.Version != DescriptorVersion || !validSignal(d.Signal) || !fieldPattern.MatchString(d.Field) || !unitPattern.MatchString(d.Unit) {
return errors.New("descriptor identity is invalid")
}
switch d.Type {
case TypeString, TypeInteger, TypeFloat, TypeBoolean, TypeDuration, TypeTime:
default:
return errors.New("descriptor type is invalid")
}
if len(d.Meaning) < 1 || len(d.Meaning) > 512 || strings.IndexByte(d.Meaning, 0) >= 0 {
return errors.New("descriptor meaning is invalid")
}
switch d.Sensitivity {
case SensitivityPublic, SensitivityInternal, SensitivitySensitive:
default:
return errors.New("descriptor sensitivity is invalid")
}
switch d.Cardinality {
case CardinalityLow, CardinalityMedium, CardinalityHigh:
default:
return errors.New("descriptor cardinality is invalid")
}
switch d.Index {
case IndexNone, IndexExact, IndexRange:
default:
return errors.New("descriptor index policy is invalid")
}
if d.Cardinality == CardinalityHigh && d.Index == IndexExact {
return errors.New("high-cardinality exact indexes require a reviewed exception")
}
switch d.Retention {
case RetentionRaw, RetentionMetric, RetentionEvidence:
default:
return errors.New("descriptor retention class is invalid")
}
if d.ProjectionVersion < 1 {
return errors.New("projection version must be positive")
}
return nil
}
func (p Proposal) Validate() error {
if err := p.Descriptor.Validate(); err != nil {
return err
}
if p.ObservedValues < 1 || p.EstimatedBytes < 0 || len(p.ExampleQueries) > 16 {
return errors.New("proposal evidence is invalid")
}
for _, example := range p.ExampleQueries {
if len(example) < 1 || len(example) > 4096 || strings.IndexByte(example, 0) >= 0 {
return fmt.Errorf("proposal example query is invalid")
}
}
return nil
}
func Unknown(signal model.Signal, field string) Descriptor {
return Descriptor{Version: DescriptorVersion, Signal: signal, Field: field, Type: TypeString, Meaning: "Unreviewed field retained in raw evidence.", Sensitivity: SensitivitySensitive, Cardinality: CardinalityHigh, Index: IndexNone, Retention: RetentionRaw, ProjectionVersion: 1}
}
func validSignal(signal model.Signal) bool {
switch signal {
case model.SignalLogs, model.SignalMetrics, model.SignalTraces, model.SignalDeployments:
return true
default:
return false
}
}
+26
View File
@@ -0,0 +1,26 @@
// SPDX-License-Identifier: AGPL-3.0-only
package schema
import (
"testing"
"gamertan.com/observatory/internal/model"
)
func TestUnknownFieldsAreSensitiveAndUnindexed(t *testing.T) {
descriptor := Unknown(model.SignalLogs, "vendor.unreviewed")
if err := descriptor.Validate(); err != nil {
t.Fatal(err)
}
if descriptor.Sensitivity != SensitivitySensitive || descriptor.Index != IndexNone || descriptor.Cardinality != CardinalityHigh {
t.Fatalf("descriptor=%+v", descriptor)
}
}
func TestDescriptorRejectsHighCardinalityExactIndex(t *testing.T) {
descriptor := Descriptor{Version: 1, Signal: model.SignalLogs, Field: "request.id", Type: TypeString, Meaning: "A request correlation identifier.", Sensitivity: SensitivityInternal, Cardinality: CardinalityHigh, Index: IndexExact, Retention: RetentionRaw, ProjectionVersion: 1}
if err := descriptor.Validate(); err == nil {
t.Fatal("expected unsafe index rejection")
}
}
+554
View File
@@ -0,0 +1,554 @@
// SPDX-License-Identifier: AGPL-3.0-only
package segment
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"gamertan.com/observatory/internal/model"
"github.com/klauspost/compress/zstd"
)
const (
MaxDecodedSegment = 64 << 20
MaxEncodedSegment = MaxDecodedSegment + 1<<20
metadataReadBatch = 128
)
type Store struct {
root string
}
type Committed struct {
Path string
Digest string
Compressed int64
Uncompressed int64
}
type Entry struct {
OrganizationID string
Committed Committed
Batch model.Batch
}
// Metadata identifies one immutable raw object without reading, checksumming,
// decompressing, or decoding its contents. It is safe to retain while walking
// a large store because it contains no telemetry records.
type Metadata struct {
OrganizationID string
SourceID string
StreamID string
Sequence uint64
Path string
Digest string
Compressed int64
}
func New(root string) (*Store, error) {
if !filepath.IsAbs(root) || filepath.Clean(root) != root {
return nil, errors.New("segment root must be an absolute clean path")
}
if err := os.MkdirAll(root, 0o700); err != nil {
return nil, fmt.Errorf("create segment root: %w", err)
}
info, err := os.Lstat(root)
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 || info.Mode().Perm()&0o077 != 0 {
return nil, errors.New("segment root must be a private non-symlink directory")
}
return &Store{root: root}, nil
}
func (s *Store) Commit(scope model.Scope, batch model.Batch) (Committed, error) {
if err := scope.Validate(); err != nil {
return Committed{}, err
}
raw, err := json.Marshal(batch)
if err != nil {
return Committed{}, fmt.Errorf("encode batch: %w", err)
}
if len(raw) > MaxDecodedSegment {
return Committed{}, errors.New("decoded segment exceeds limit")
}
enc, err := zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1), zstd.WithEncoderLevel(zstd.SpeedBetterCompression))
if err != nil {
return Committed{}, fmt.Errorf("create compressor: %w", err)
}
compressed := enc.EncodeAll(raw, nil)
enc.Close()
if len(compressed) > MaxEncodedSegment {
return Committed{}, errors.New("encoded segment exceeds limit")
}
sum := sha256.Sum256(compressed)
digest := hex.EncodeToString(sum[:])
dir := filepath.Join(s.root, "raw", scope.OrganizationID, batch.SourceID, batch.StreamID)
if err := ensurePrivateDirectoryChain(s.root, dir); err != nil {
return Committed{}, err
}
name := fmt.Sprintf("%020d-%s.zst", batch.Sequence, digest)
final := filepath.Join(dir, name)
if existing, err := readRegular(final, MaxEncodedSegment); err == nil {
if bytes.Equal(existing, compressed) {
return Committed{Path: final, Digest: digest, Compressed: int64(len(compressed)), Uncompressed: int64(len(raw))}, nil
}
return Committed{}, errors.New("existing segment digest collision")
} else if !errors.Is(err, os.ErrNotExist) {
return Committed{}, fmt.Errorf("inspect existing segment: %w", err)
}
tmp, err := os.CreateTemp(dir, ".segment-*")
if err != nil {
return Committed{}, fmt.Errorf("create segment temporary file: %w", err)
}
tmpName := tmp.Name()
cleanup := func() { _ = os.Remove(tmpName) }
defer cleanup()
if err := tmp.Chmod(0o600); err != nil {
_ = tmp.Close()
return Committed{}, fmt.Errorf("set segment mode: %w", err)
}
if _, err := tmp.Write(compressed); err != nil {
_ = tmp.Close()
return Committed{}, fmt.Errorf("write segment: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return Committed{}, fmt.Errorf("sync segment: %w", err)
}
if err := tmp.Close(); err != nil {
return Committed{}, fmt.Errorf("close segment: %w", err)
}
if err := os.Rename(tmpName, final); err != nil {
return Committed{}, fmt.Errorf("commit segment: %w", err)
}
d, err := os.Open(dir)
if err != nil {
return Committed{}, fmt.Errorf("open segment directory: %w", err)
}
if err := d.Sync(); err != nil {
_ = d.Close()
return Committed{}, fmt.Errorf("sync segment directory: %w", err)
}
if err := d.Close(); err != nil {
return Committed{}, fmt.Errorf("close segment directory: %w", err)
}
return Committed{Path: final, Digest: digest, Compressed: int64(len(compressed)), Uncompressed: int64(len(raw))}, nil
}
func (s *Store) Read(path, expectedDigest string) (model.Batch, error) {
var batch model.Batch
cleanRoot := filepath.Clean(s.root) + string(os.PathSeparator)
cleanPath := filepath.Clean(path)
if !strings.HasPrefix(cleanPath, cleanRoot) {
return batch, errors.New("segment path escapes store")
}
if err := validatePrivateDirectoryChain(s.root, filepath.Dir(cleanPath)); err != nil {
return batch, err
}
b, err := readRegular(cleanPath, MaxEncodedSegment)
if err != nil {
return batch, fmt.Errorf("read segment: %w", err)
}
sum := sha256.Sum256(b)
if hex.EncodeToString(sum[:]) != expectedDigest {
return batch, errors.New("segment checksum mismatch")
}
dec, err := zstd.NewReader(bytes.NewReader(b), zstd.WithDecoderConcurrency(1), zstd.WithDecoderMaxMemory(MaxDecodedSegment))
if err != nil {
return batch, fmt.Errorf("create decompressor: %w", err)
}
decompressed, err := io.ReadAll(io.LimitReader(dec, MaxDecodedSegment+1))
dec.Close()
if err != nil {
return batch, fmt.Errorf("decompress segment: %w", err)
}
if len(decompressed) > MaxDecodedSegment {
return batch, errors.New("decoded segment exceeds limit")
}
decoder := json.NewDecoder(bytes.NewReader(decompressed))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&batch); err != nil {
return batch, fmt.Errorf("decode segment: %w", err)
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return batch, errors.New("segment contains trailing JSON")
}
return batch, nil
}
// ReadEntry validates and decodes exactly one object previously returned by
// WalkMetadata. Callers can therefore keep startup discovery bounded and pay
// the decompression cost only for an object that actually needs recovery.
func (s *Store) ReadEntry(metadata Metadata) (Entry, error) {
actual, err := s.metadata(metadata.Path)
if err != nil {
return Entry{}, err
}
if actual != metadata {
return Entry{}, errors.New("segment metadata changed before decode")
}
batch, err := s.Read(metadata.Path, metadata.Digest)
if err != nil {
return Entry{}, err
}
if batch.SourceID != metadata.SourceID || batch.StreamID != metadata.StreamID || batch.Sequence != metadata.Sequence {
return Entry{}, errors.New("segment path does not match batch identity")
}
raw, err := json.Marshal(batch)
if err != nil {
return Entry{}, fmt.Errorf("measure decoded segment: %w", err)
}
return Entry{
OrganizationID: metadata.OrganizationID,
Committed: Committed{
Path: metadata.Path,
Digest: metadata.Digest,
Compressed: metadata.Compressed,
Uncompressed: int64(len(raw)),
},
Batch: batch,
}, nil
}
// Delete removes one already-retired segment after verifying that the path,
// filename, file type, and content digest still identify the exact committed
// object. A missing object is an idempotent success for crash recovery.
func (s *Store) Delete(path, expectedDigest string) error {
if len(expectedDigest) != 64 {
return errors.New("segment deletion digest is invalid")
}
rawRoot := filepath.Join(filepath.Clean(s.root), "raw") + string(os.PathSeparator)
coldRoot := filepath.Join(filepath.Clean(s.root), "cold") + string(os.PathSeparator)
cleanPath := filepath.Clean(path)
if (!strings.HasPrefix(cleanPath, rawRoot) && !strings.HasPrefix(cleanPath, coldRoot)) || !strings.HasSuffix(filepath.Base(cleanPath), "-"+expectedDigest+".zst") {
return errors.New("segment deletion path is invalid")
}
if err := validatePrivateDirectoryChain(s.root, filepath.Dir(cleanPath)); err != nil {
return err
}
if _, err := os.Lstat(cleanPath); errors.Is(err, os.ErrNotExist) {
return nil
} else if err != nil {
return fmt.Errorf("inspect retired segment: %w", err)
}
if _, err := s.Read(cleanPath, expectedDigest); err != nil {
return fmt.Errorf("verify retired segment: %w", err)
}
if err := os.Remove(cleanPath); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("remove retired segment: %w", err)
}
directory, err := os.Open(filepath.Dir(cleanPath))
if err != nil {
return fmt.Errorf("open retired segment directory: %w", err)
}
if err = directory.Sync(); err != nil {
_ = directory.Close()
return fmt.Errorf("sync retired segment directory: %w", err)
}
if err = directory.Close(); err != nil {
return fmt.Errorf("close retired segment directory: %w", err)
}
return nil
}
// MoveToCold atomically relocates one verified hot object beneath the cold
// archive. It is idempotent across a crash after rename: when the source is
// absent, the exact destination must already exist and match its digest.
func (s *Store) MoveToCold(path, target, expectedDigest string) error {
if len(expectedDigest) != 64 {
return errors.New("segment archive digest is invalid")
}
cleanPath, cleanTarget := filepath.Clean(path), filepath.Clean(target)
rawRoot := filepath.Join(filepath.Clean(s.root), "raw") + string(os.PathSeparator)
coldRoot := filepath.Join(filepath.Clean(s.root), "cold") + string(os.PathSeparator)
if !strings.HasPrefix(cleanPath, rawRoot) || !strings.HasPrefix(cleanTarget, coldRoot) || filepath.Base(cleanPath) != filepath.Base(cleanTarget) || !strings.HasSuffix(filepath.Base(cleanPath), "-"+expectedDigest+".zst") {
return errors.New("segment archive path is invalid")
}
if err := validatePrivateDirectoryChain(s.root, filepath.Dir(cleanPath)); err != nil {
return err
}
if err := ensurePrivateDirectoryChain(s.root, filepath.Dir(cleanTarget)); err != nil {
return err
}
if _, err := os.Lstat(cleanPath); errors.Is(err, os.ErrNotExist) {
if _, readErr := s.Read(cleanTarget, expectedDigest); readErr != nil {
return fmt.Errorf("recover archived segment: %w", readErr)
}
for _, directory := range []string{filepath.Dir(cleanTarget), filepath.Dir(cleanPath)} {
if syncErr := syncDirectory(directory); syncErr != nil {
return syncErr
}
}
return nil
} else if err != nil {
return fmt.Errorf("inspect hot segment: %w", err)
}
if _, err := os.Lstat(cleanTarget); err == nil {
return errors.New("cold segment destination already exists")
} else if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("inspect cold segment destination: %w", err)
}
if _, err := s.Read(cleanPath, expectedDigest); err != nil {
return fmt.Errorf("verify hot segment: %w", err)
}
if err := os.Rename(cleanPath, cleanTarget); err != nil {
return fmt.Errorf("archive segment: %w", err)
}
for _, directory := range []string{filepath.Dir(cleanTarget), filepath.Dir(cleanPath)} {
if err := syncDirectory(directory); err != nil {
return err
}
}
return nil
}
func syncDirectory(path string) error {
directory, err := os.Open(path)
if err != nil {
return fmt.Errorf("open segment directory: %w", err)
}
if err = directory.Sync(); err != nil {
_ = directory.Close()
return fmt.Errorf("sync segment directory: %w", err)
}
if err = directory.Close(); err != nil {
return fmt.Errorf("close segment directory: %w", err)
}
return nil
}
func validatePrivateDirectoryChain(root, directory string) error {
root = filepath.Clean(root)
directory = filepath.Clean(directory)
relative, err := filepath.Rel(root, directory)
if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(os.PathSeparator)) {
return errors.New("segment directory escapes store")
}
candidates := []string{root}
current := root
if relative != "." {
for _, component := range strings.Split(relative, string(os.PathSeparator)) {
if component == "" || component == "." || component == ".." {
return errors.New("segment directory path is invalid")
}
current = filepath.Join(current, component)
candidates = append(candidates, current)
}
}
for _, candidate := range candidates {
info, inspectErr := os.Lstat(candidate)
if inspectErr != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 || info.Mode().Perm()&0o077 != 0 {
return errors.New("segment directory chain must be private and non-symlinked")
}
}
return nil
}
func ensurePrivateDirectoryChain(root, directory string) error {
root = filepath.Clean(root)
directory = filepath.Clean(directory)
relative, err := filepath.Rel(root, directory)
if err != nil || relative == "." || relative == ".." || strings.HasPrefix(relative, ".."+string(os.PathSeparator)) {
return errors.New("segment directory path is invalid")
}
current := root
for _, component := range strings.Split(relative, string(os.PathSeparator)) {
if component == "" || component == "." || component == ".." {
return errors.New("segment directory path is invalid")
}
current = filepath.Join(current, component)
info, inspectErr := os.Lstat(current)
if errors.Is(inspectErr, os.ErrNotExist) {
if inspectErr = os.Mkdir(current, 0o700); inspectErr != nil && !errors.Is(inspectErr, os.ErrExist) {
return fmt.Errorf("create segment directory: %w", inspectErr)
}
info, inspectErr = os.Lstat(current)
}
if inspectErr != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 || info.Mode().Perm()&0o077 != 0 {
return errors.New("segment directory chain must be private and non-symlinked")
}
}
return nil
}
func readRegular(path string, maximum int) ([]byte, error) {
before, err := os.Lstat(path)
if err != nil {
return nil, err
}
if !before.Mode().IsRegular() || before.Mode()&os.ModeSymlink != 0 || before.Size() > int64(maximum) {
return nil, errors.New("segment is not a bounded regular file")
}
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
after, err := file.Stat()
if err != nil || !after.Mode().IsRegular() || !os.SameFile(before, after) {
return nil, errors.New("segment changed during open")
}
body, err := io.ReadAll(io.LimitReader(file, int64(maximum)+1))
if err != nil {
return nil, err
}
if len(body) > maximum {
return nil, errors.New("encoded segment exceeds limit")
}
return body, nil
}
// WalkMetadata derives bounded committed-object identities from the filesystem
// so a crash after rename but before control-database bookkeeping cannot hide
// a segment. It deliberately does not read or decode segment contents.
func (s *Store) WalkMetadata(visit func(Metadata) error) error {
if visit == nil {
return errors.New("segment metadata visitor is required")
}
base := filepath.Join(s.root, "raw")
if _, err := os.Lstat(base); errors.Is(err, os.ErrNotExist) {
return nil
} else if err != nil {
return fmt.Errorf("inspect raw segment root: %w", err)
}
if err := validatePrivateDirectoryChain(s.root, base); err != nil {
return err
}
err := s.walkMetadataDirectory(base, 0, visit)
if err != nil {
return fmt.Errorf("walk raw segments: %w", err)
}
return nil
}
func (s *Store) walkMetadataDirectory(directoryPath string, depth int, visit func(Metadata) error) error {
directory, err := os.Open(directoryPath)
if err != nil {
return fmt.Errorf("open raw segment directory: %w", err)
}
defer directory.Close()
info, err := directory.Stat()
if err != nil || !info.IsDir() || info.Mode().Perm()&0o077 != 0 {
return errors.New("raw segment directory must be private")
}
for {
entries, readErr := directory.ReadDir(metadataReadBatch)
for _, entry := range entries {
path := filepath.Join(directoryPath, entry.Name())
if entry.Type()&os.ModeSymlink != 0 {
return errors.New("raw segment tree contains a symlink")
}
if entry.IsDir() {
if depth >= 3 {
return errors.New("raw segment tree has invalid depth")
}
if err = s.walkMetadataDirectory(path, depth+1, visit); err != nil {
return err
}
continue
}
if !strings.HasSuffix(entry.Name(), ".zst") {
continue
}
metadata, metadataErr := s.metadata(path)
if metadataErr != nil {
return metadataErr
}
if visitErr := visit(metadata); visitErr != nil {
return visitErr
}
}
if errors.Is(readErr, io.EOF) {
break
}
if readErr != nil {
return fmt.Errorf("read raw segment directory: %w", readErr)
}
}
if err = directory.Close(); err != nil {
return fmt.Errorf("close raw segment directory: %w", err)
}
return nil
}
func (s *Store) metadata(path string) (Metadata, error) {
base := filepath.Join(s.root, "raw")
cleanPath := filepath.Clean(path)
relative, err := filepath.Rel(base, cleanPath)
if err != nil || relative == "." || relative == ".." || strings.HasPrefix(relative, ".."+string(os.PathSeparator)) {
return Metadata{}, errors.New("segment path escapes raw store")
}
pathParts := strings.Split(filepath.ToSlash(relative), "/")
if len(pathParts) != 4 {
return Metadata{}, errors.New("raw segment path has invalid depth")
}
if err = model.ValidateSourceID(pathParts[0]); err != nil {
return Metadata{}, errors.New("raw segment organization is invalid")
}
if err = model.ValidateSourceID(pathParts[1]); err != nil {
return Metadata{}, errors.New("raw segment source is invalid")
}
if err = model.ValidateStreamID(pathParts[2]); err != nil {
return Metadata{}, errors.New("raw segment stream is invalid")
}
name := strings.TrimSuffix(pathParts[3], ".zst")
parts := strings.Split(name, "-")
if len(parts) != 2 || len(parts[0]) != 20 || len(parts[1]) != 64 || strings.ToLower(parts[1]) != parts[1] {
return Metadata{}, fmt.Errorf("invalid segment filename %q", pathParts[3])
}
sequence, err := strconv.ParseUint(parts[0], 10, 64)
if err != nil || sequence == 0 {
return Metadata{}, fmt.Errorf("invalid segment sequence %q", parts[0])
}
if _, err = hex.DecodeString(parts[1]); err != nil {
return Metadata{}, errors.New("segment filename digest is invalid")
}
if err = validatePrivateDirectoryChain(s.root, filepath.Dir(cleanPath)); err != nil {
return Metadata{}, err
}
info, err := os.Lstat(cleanPath)
if err != nil {
return Metadata{}, fmt.Errorf("inspect raw segment: %w", err)
}
if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Mode().Perm()&0o077 != 0 || info.Size() > MaxEncodedSegment {
return Metadata{}, errors.New("raw segment must be a private bounded regular file")
}
return Metadata{
OrganizationID: pathParts[0],
SourceID: pathParts[1],
StreamID: pathParts[2],
Sequence: sequence,
Path: cleanPath,
Digest: parts[1],
Compressed: info.Size(),
}, nil
}
// List retains the complete decoding API for explicit forensic callers and
// tests. Startup recovery uses WalkMetadata and decodes only missing work.
func (s *Store) List() ([]Entry, error) {
var entries []Entry
err := s.WalkMetadata(func(metadata Metadata) error {
entry, readErr := s.ReadEntry(metadata)
if readErr != nil {
return readErr
}
entries = append(entries, entry)
return nil
})
if err != nil {
return nil, err
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Committed.Path < entries[j].Committed.Path })
return entries, nil
}
+302
View File
@@ -0,0 +1,302 @@
// SPDX-License-Identifier: AGPL-3.0-only
package segment
import (
"errors"
"os"
"path/filepath"
"sync"
"testing"
"time"
"gamertan.com/observatory/internal/model"
)
func TestCommitReadAndCorruption(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
store, err := New(root)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
batch := model.Batch{Version: 1, SourceID: "source", StreamID: "access", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "http.request", Body: "safe"}}}
scope := model.Scope{OrganizationID: "org", ProjectID: "project", EnvironmentID: "prod", ServiceID: "site"}
committed, err := store.Commit(scope, batch)
if err != nil {
t.Fatal(err)
}
got, err := store.Read(committed.Path, committed.Digest)
if err != nil {
t.Fatal(err)
}
if got.Sequence != 1 || got.SourceID != "source" {
t.Fatalf("unexpected batch: %#v", got)
}
before, err := os.Stat(committed.Path)
if err != nil {
t.Fatal(err)
}
again, err := store.Commit(scope, batch)
if err != nil {
t.Fatal(err)
}
after, _ := os.Stat(again.Path)
if !before.ModTime().Equal(after.ModTime()) {
t.Fatal("idempotent commit changed segment mtime")
}
if err := os.WriteFile(committed.Path, []byte("corrupt"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := store.Read(committed.Path, committed.Digest); err == nil {
t.Fatal("expected checksum failure")
}
}
func TestConcurrentCommitsCreateOnePrivateDirectoryChain(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
store, err := New(root)
if err != nil {
t.Fatal(err)
}
const writers = 64
now := time.Now().UTC()
scope := model.Scope{OrganizationID: "org", ProjectID: "project", EnvironmentID: "prod", ServiceID: "site"}
start := make(chan struct{})
errorsChannel := make(chan error, writers)
var wait sync.WaitGroup
for index := 0; index < writers; index++ {
wait.Add(1)
go func(sequence uint64) {
defer wait.Done()
<-start
batch := model.Batch{Version: 1, SourceID: "source", StreamID: "access", Sequence: sequence, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "http.request"}}}
if _, commitErr := store.Commit(scope, batch); commitErr != nil {
errorsChannel <- commitErr
}
}(uint64(index + 1))
}
close(start)
wait.Wait()
close(errorsChannel)
for commitErr := range errorsChannel {
t.Errorf("concurrent commit: %v", commitErr)
}
entries, err := store.List()
if err != nil {
t.Fatal(err)
}
if len(entries) != writers {
t.Fatalf("committed entries=%d want=%d", len(entries), writers)
}
}
func TestListFindsCommittedSegments(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
store, err := New(root)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
batch := model.Batch{Version: 1, SourceID: "source", StreamID: "access", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "http.request"}}}
_, err = store.Commit(model.Scope{OrganizationID: "org", ProjectID: "project", EnvironmentID: "prod", ServiceID: "site"}, batch)
if err != nil {
t.Fatal(err)
}
entries, err := store.List()
if err != nil {
t.Fatal(err)
}
if len(entries) != 1 || entries[0].Batch.Sequence != 1 || entries[0].Committed.Digest == "" {
t.Fatalf("unexpected entries: %#v", entries)
}
}
func TestWalkMetadataDoesNotDecodeSegmentContents(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
store, err := New(root)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
batch := model.Batch{Version: 1, SourceID: "source", StreamID: "access", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "http.request"}}}
committed, err := store.Commit(model.Scope{OrganizationID: "org", ProjectID: "project", EnvironmentID: "prod", ServiceID: "site"}, batch)
if err != nil {
t.Fatal(err)
}
body, err := os.ReadFile(committed.Path)
if err != nil {
t.Fatal(err)
}
body[0] ^= 0xff
if err = os.WriteFile(committed.Path, body, 0o600); err != nil {
t.Fatal(err)
}
var metadata Metadata
if err = store.WalkMetadata(func(candidate Metadata) error {
metadata = candidate
return nil
}); err != nil {
t.Fatalf("metadata walk decoded content: %v", err)
}
if metadata.Path != committed.Path || metadata.Digest != committed.Digest || metadata.Compressed != committed.Compressed {
t.Fatalf("metadata=%+v committed=%+v", metadata, committed)
}
if _, err = store.ReadEntry(metadata); err == nil {
t.Fatal("corrupt segment decoded successfully")
}
}
func TestInterruptedTemporarySegmentIsIgnoredUntilAtomicCommit(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
store, err := New(root)
if err != nil {
t.Fatal(err)
}
dir := filepath.Join(root, "raw", "organization", "source", "stream")
if err = os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
partial := filepath.Join(dir, ".segment-interrupted")
if err = os.WriteFile(partial, []byte("partial compressed bytes"), 0o600); err != nil {
t.Fatal(err)
}
entries, err := store.List()
if err != nil || len(entries) != 0 {
t.Fatalf("entries=%+v err=%v", entries, err)
}
if body, readErr := os.ReadFile(partial); readErr != nil || string(body) != "partial compressed bytes" {
t.Fatalf("partial=%q err=%v", body, readErr)
}
}
func TestReadRejectsSymlinksAndOversizedEncodedSegments(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
store, err := New(root)
if err != nil {
t.Fatal(err)
}
if err = os.MkdirAll(filepath.Join(root, "raw"), 0o700); err != nil {
t.Fatal(err)
}
target := filepath.Join(root, "raw", "target")
if err = os.WriteFile(target, []byte("safe"), 0o600); err != nil {
t.Fatal(err)
}
link := filepath.Join(root, "raw", "link")
if err = os.Symlink(target, link); err != nil {
t.Fatal(err)
}
if _, err = store.Read(link, "unused"); err == nil {
t.Fatal("symlink segment accepted")
}
oversized := filepath.Join(root, "raw", "oversized")
file, err := os.Create(oversized)
if err != nil {
t.Fatal(err)
}
if err = file.Truncate(MaxEncodedSegment + 1); err != nil {
_ = file.Close()
t.Fatal(err)
}
if err = file.Close(); err != nil {
t.Fatal(err)
}
if _, err = store.Read(oversized, "unused"); err == nil {
t.Fatal("oversized encoded segment accepted")
}
}
func TestCommitRejectsSymlinkedDirectoryChain(t *testing.T) {
base := t.TempDir()
root := filepath.Join(base, "data")
if err := os.Mkdir(root, 0o700); err != nil {
t.Fatal(err)
}
store, err := New(root)
if err != nil {
t.Fatal(err)
}
if err = os.Mkdir(filepath.Join(root, "raw"), 0o700); err != nil {
t.Fatal(err)
}
target := filepath.Join(base, "outside")
if err = os.Mkdir(target, 0o700); err != nil {
t.Fatal(err)
}
if err = os.Symlink(target, filepath.Join(root, "raw", "org")); err != nil {
t.Skipf("symlink unavailable: %v", err)
}
now := time.Now().UTC()
batch := model.Batch{Version: 1, SourceID: "source", StreamID: "access", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "http.request"}}}
if _, err = store.Commit(model.Scope{OrganizationID: "org", ProjectID: "project", EnvironmentID: "prod", ServiceID: "site"}, batch); err == nil {
t.Fatal("symlinked segment directory was accepted")
}
entries, err := os.ReadDir(target)
if err != nil || len(entries) != 0 {
t.Fatalf("symlink target was changed: entries=%v err=%v", entries, err)
}
}
func TestMoveToColdIsVerifiedAndCrashIdempotent(t *testing.T) {
root := filepath.Join(t.TempDir(), "data")
store, err := New(root)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
batch := model.Batch{Version: 1, SourceID: "source", StreamID: "access", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "http.request"}}}
committed, err := store.Commit(model.Scope{OrganizationID: "org", ProjectID: "project", EnvironmentID: "prod", ServiceID: "site"}, batch)
if err != nil {
t.Fatal(err)
}
target := filepath.Join(root, "cold", "org", "logs", "source", "access", filepath.Base(committed.Path))
if err = store.MoveToCold(committed.Path, target, committed.Digest); err != nil {
t.Fatal(err)
}
if _, err = os.Lstat(committed.Path); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("hot segment still exists: %v", err)
}
if got, readErr := store.Read(target, committed.Digest); readErr != nil || got.Sequence != 1 {
t.Fatalf("cold batch=%+v err=%v", got, readErr)
}
if err = store.MoveToCold(committed.Path, target, committed.Digest); err != nil {
t.Fatalf("idempotent archive: %v", err)
}
if err = store.MoveToCold(target, committed.Path, committed.Digest); err == nil {
t.Fatal("reverse cold-to-hot move was accepted")
}
}
func TestMoveToColdRejectsSymlinkedDestination(t *testing.T) {
base := t.TempDir()
root := filepath.Join(base, "data")
store, err := New(root)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
batch := model.Batch{Version: 1, SourceID: "source", StreamID: "access", Sequence: 1, ObservedAt: now, Signal: model.SignalLogs, Records: []model.Observation{{Timestamp: now, Name: "http.request"}}}
committed, err := store.Commit(model.Scope{OrganizationID: "org", ProjectID: "project", EnvironmentID: "prod", ServiceID: "site"}, batch)
if err != nil {
t.Fatal(err)
}
outside := filepath.Join(base, "outside")
if err = os.Mkdir(outside, 0o700); err != nil {
t.Fatal(err)
}
if err = os.Symlink(outside, filepath.Join(root, "cold")); err != nil {
t.Skipf("symlink unavailable: %v", err)
}
target := filepath.Join(root, "cold", "org", "logs", "source", "access", filepath.Base(committed.Path))
if err = store.MoveToCold(committed.Path, target, committed.Digest); err == nil {
t.Fatal("symlinked cold destination was accepted")
}
if _, err = os.Stat(committed.Path); err != nil {
t.Fatalf("hot segment changed: %v", err)
}
entries, err := os.ReadDir(outside)
if err != nil || len(entries) != 0 {
t.Fatalf("outside entries=%v err=%v", entries, err)
}
}
+126
View File
@@ -0,0 +1,126 @@
<?sando go
package site
func App(view AppView)
?>
<?# SPDX-License-Identifier: AGPL-3.0-only ?>
<!doctype html>
<html lang="en">
<head><?~ Head(view.Head) ?></head>
<body>
<a class="skip-link" href="#main">Skip to content</a>
<?~ SiteHeader(true, "overview", view.Organization.ID) ?>
<main id="main">
<section class="app-intro" aria-labelledby="overview-title">
<div><p class="eyebrow">Organization overview</p><h1 id="overview-title"><?= view.Organization.Name ?></h1><p>Welcome, <?= view.DisplayName ?>. Last refreshed <?= view.RefreshedAt ?>.</p></div>
<form class="logout" method="post" action="/logout/">
<input type="hidden" name="csrf_token" value="<?= view.CSRFToken ?>">
<button class="secondary" type="submit">Sign out</button>
</form>
</section>
<? if len(view.Organizations) > 1 { ?>
<nav class="organization-nav" aria-label="Organizations">
<span>Organization:</span>
<? for _, organization := range view.Organizations { ?>
<? if organization.Selected { ?>
<a href="/app/?organization=<?= organization.ID ?>" aria-current="page"><?= organization.Name ?></a>
<? } else { ?>
<a href="/app/?organization=<?= organization.ID ?>"><?= organization.Name ?></a>
<? } ?>
<? } ?>
</nav>
<? } ?>
<? if view.PendingBatches > 0 { ?>
<aside class="live-status" role="status">
<p><strong>Durable evidence is still being indexed.</strong> Accepted batches safely stored: <?= view.PendingBatches ?>. Recent queries may lag by <?= view.ProjectionLag ?>.</p>
</aside>
<? } ?>
<aside class="live-status" data-events-url="<?= view.EventsURL ?>" hidden>
<p><strong>New observations are available.</strong> <a href="/app/?organization=<?= view.Organization.ID ?>">Refresh this overview</a>.</p>
</aside>
<section class="signal-grid" aria-label="Recent telemetry">
<? for _, signal := range view.Signals { ?>
<article class="signal-card" id="<?= signal.ID ?>">
<p class="eyebrow"><?= signal.Name ?></p>
<h2>Recent <?= signal.Name ?></h2>
<p><?= signal.Description ?></p>
<details><summary>Query</summary><pre><code><?= signal.Query ?></code></pre></details>
<?~ ResultTable(signal.Table) ?>
</article>
<? } ?>
</section>
<section class="section-grid" aria-labelledby="saved-work">
<div><p class="eyebrow">Saved work</p><h2 id="saved-work">Queries and dashboards</h2></div>
<div class="saved-grid">
<section aria-labelledby="saved-queries"><h3 id="saved-queries">Saved queries</h3>
<? if len(view.SavedQueries) == 0 { ?><p>No saved queries yet.</p><? } ?>
<? for _, item := range view.SavedQueries { ?><article><h4><?= item.Name ?></h4><p><?= item.Description ?></p><pre><code><?= item.Query ?></code></pre></article><? } ?>
</section>
<section aria-labelledby="dashboards"><h3 id="dashboards">Dashboards</h3>
<? if len(view.Dashboards) == 0 { ?><p>No dashboards yet.</p><? } ?>
<? for _, item := range view.Dashboards { ?><article><h4><a href="/app/dashboards/<?= item.Slug ?>/?organization=<?= view.Organization.ID ?>"><?= item.Name ?></a></h4><p><?= item.Description ?></p><p><?= item.PanelCount ?> panels</p></article><? } ?>
</section>
</div>
</section>
<section class="section-grid" aria-labelledby="incident-work">
<div><p class="eyebrow">Incident response</p><h2 id="incident-work">Attention without noise</h2></div>
<div><p><?= view.OpenIncidents ?> open incidents are visible in the authorized inbox. Alert rules execute the same bounded saved-query AST used everywhere else.</p><p><a class="button secondary" href="<?= view.IncidentsURL ?>">Open incident inbox</a></p></div>
</section>
<? if view.CanManage { ?>
<section class="section-grid" aria-labelledby="manage-work">
<div><p class="eyebrow">Organization workshop</p><h2 id="manage-work">Save a reusable view</h2><p>Assisted controls and typed text enter the same parser and versioned AST. Every form is an ordinary server request; nothing is generated or executed on page load.</p></div>
<div class="editor-grid">
<form class="editor-card builder-card" method="post" action="/app/queries/builder/">
<h3>Build a query</h3>
<p>Choose one bounded evidence source, an optional filter, and an optional summary. The saved result remains ordinary reviewable query text.</p>
<input type="hidden" name="organization_id" value="<?= view.Organization.ID ?>">
<input type="hidden" name="csrf_token" value="<?= view.ManageCSRF ?>">
<div class="field-grid">
<div><label for="builder-name">Name</label><input id="builder-name" name="name" required maxlength="128"></div>
<div><label for="builder-description">Description</label><textarea id="builder-description" name="description" required maxlength="1024"></textarea></div>
<div><label for="builder-signal">Evidence</label><select id="builder-signal" name="signal" required><option value="logs">Logs</option><option value="metrics">Metrics</option><option value="traces">Traces</option><option value="deployments">Deployments</option></select></div>
<div><label for="builder-window">Lookback</label><select id="builder-window" name="window" required><option value="15m">15 minutes</option><option value="1h" selected>1 hour</option><option value="6h">6 hours</option><option value="24h">24 hours</option><option value="168h">7 days</option></select></div>
<div><label for="builder-filter-field">Filter field <span class="optional">(optional)</span></label><select id="builder-filter-field" name="filter_field"><option value="">No filter</option><option value="service">Service</option><option value="project">Project</option><option value="environment">Environment</option><option value="route">HTTP route</option><option value="status">HTTP status</option><option value="duration">Duration</option><option value="name">Name</option><option value="severity">Severity</option><option value="value">Metric value</option><option value="trace_id">Trace ID</option><option value="correlation_id">Correlation ID</option></select></div>
<div><label for="builder-filter-operator">Filter comparison</label><select id="builder-filter-operator" name="filter_operator" required><option value="==">equals</option><option value="!=">does not equal</option><option value=">=">at least</option><option value="&lt;=">at most</option><option value=">">greater than</option><option value="&lt;">less than</option></select></div>
<div><label for="builder-filter-value">Filter value <span class="optional">(optional)</span></label><input id="builder-filter-value" name="filter_value" maxlength="256"></div>
<div><label for="builder-aggregate">Summary</label><select id="builder-aggregate" name="aggregate" required><option value="none">No summary</option><option value="count">Count</option><option value="min">Minimum</option><option value="max">Maximum</option><option value="sum">Sum</option><option value="avg">Average</option><option value="p50">50th percentile</option><option value="p95">95th percentile</option><option value="p99">99th percentile</option></select></div>
<div><label for="builder-aggregate-field">Numeric summary field <span class="optional">(not used by count)</span></label><select id="builder-aggregate-field" name="aggregate_field"><option value="">No field</option><option value="value">Metric value</option><option value="duration">Duration</option><option value="status">HTTP status</option></select></div>
<div><label for="builder-group">Group by <span class="optional">(optional)</span></label><select id="builder-group" name="group_by"><option value="">No grouping</option><option value="service">Service</option><option value="project">Project</option><option value="environment">Environment</option><option value="route">HTTP route</option><option value="status">HTTP status</option><option value="name">Name</option><option value="severity">Severity</option></select></div>
<div><label for="builder-bucket">Time bucket <span class="optional">(optional)</span></label><select id="builder-bucket" name="bucket"><option value="">No time bucket</option><option value="1m">1 minute</option><option value="5m">5 minutes</option><option value="15m">15 minutes</option><option value="1h">1 hour</option></select></div>
<div><label for="builder-limit">Maximum rows</label><select id="builder-limit" name="limit" required><option value="10">10</option><option value="20">20</option><option value="50" selected>50</option><option value="100">100</option><option value="250">250</option></select></div>
</div>
<button type="submit">Build and save query</button>
</form>
<form class="editor-card" method="post" action="/app/queries/">
<h3>Write a query</h3>
<input type="hidden" name="organization_id" value="<?= view.Organization.ID ?>">
<input type="hidden" name="csrf_token" value="<?= view.ManageCSRF ?>">
<label for="query-name">Name</label><input id="query-name" name="name" required maxlength="128">
<label for="query-description">Description</label><textarea id="query-description" name="description" required maxlength="1024"></textarea>
<label for="query-text">Typed query</label><textarea id="query-text" name="query" required maxlength="16384">logs | window 1h | limit 50</textarea>
<button type="submit">Save query</button>
</form>
<form class="editor-card" method="post" action="/app/dashboards/">
<h3>Create a one-panel dashboard</h3>
<input type="hidden" name="organization_id" value="<?= view.Organization.ID ?>">
<input type="hidden" name="csrf_token" value="<?= view.ManageCSRF ?>">
<label for="dashboard-slug">URL slug</label><input id="dashboard-slug" name="slug" required maxlength="63" pattern="[a-z][a-z0-9-]+">
<label for="dashboard-name">Name</label><input id="dashboard-name" name="name" required maxlength="128">
<label for="dashboard-description">Description</label><textarea id="dashboard-description" name="description" required maxlength="1024"></textarea>
<label for="panel-title">Panel title</label><input id="panel-title" name="panel_title" required maxlength="128">
<label for="saved-query">Saved query</label>
<select id="saved-query" name="saved_query_id" required>
<option value="">Choose a saved query</option>
<? for _, item := range view.SavedQueries { ?><option value="<?= item.ID ?>"><?= item.Name ?></option><? } ?>
</select>
<label for="visualization">Presentation</label>
<select id="visualization" name="visualization" required><option value="table">Table</option><option value="stat">Single statistic with table</option><option value="timeseries">Time series table</option></select>
<? if len(view.SavedQueries) == 0 { ?><button type="submit" disabled>Create dashboard</button><? } else { ?><button type="submit">Create dashboard</button><? } ?>
</form>
</div>
</section>
<? } ?>
</main>
<?~ SiteFooter() ?>
</body>
</html>
+497
View File
@@ -0,0 +1,497 @@
// Code generated by himesan; DO NOT EDIT.
// himesan:compiler v1.0.0-beta.2
// himesan:runtime-abi sando.v1
// himesan:source-sha256 ab6403781ccb2a659b749730243555dcb8a3f319720ad6a972252eb30847c5f4
package site
import (
__himesan_context "context"
__himesan_sando "gamertan.com/sandwich-hime/sando"
__himesan_io "io"
)
var _ = __himesan_sando.ABISandoV1
func App(view AppView) __himesan_sando.Component {
return __himesan_sando.ComponentFunc(func(__himesan_render_context __himesan_context.Context, __himesan_writer __himesan_io.Writer) error {
_ = __himesan_render_context
//line internal/site/app.sando:5:3
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:6:46
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n<!doctype html>\n<html lang=\"en\">\n<head>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:9:11
if __himesan_error := __himesan_sando.Render(__himesan_render_context, __himesan_writer, (Head(view.Head))); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:9:29
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</head>\n<body>\n <a class=\"skip-link\" href=\"#main\">Skip to content</a>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:12:7
if __himesan_error := __himesan_sando.Render(__himesan_render_context, __himesan_writer, (SiteHeader(true, "overview", view.Organization.ID))); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:12:60
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n <main id=\"main\">\n <section class=\"app-intro\" aria-labelledby=\"overview-title\">\n <div><p class=\"eyebrow\">Organization overview</p><h1 id=\"overview-title\">"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:15:84
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (view.Organization.Name)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:15:109
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</h1><p>Welcome, "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:15:130
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (view.DisplayName)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:15:149
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, ". Last refreshed "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:15:170
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (view.RefreshedAt)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:15:189
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, ".</p></div>\n <form class=\"logout\" method=\"post\" action=\"/logout/\">\n <input type=\"hidden\" name=\"csrf_token\" value=\""); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:17:59
if __himesan_error := __himesan_sando.WriteAttr(__himesan_writer, (view.CSRFToken)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:17:76
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\">\n <button class=\"secondary\" type=\"submit\">Sign out</button>\n </form>\n </section>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:21:8
if len(view.Organizations) > 1 {
//line internal/site/app.sando:21:43
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n <nav class=\"organization-nav\" aria-label=\"Organizations\">\n <span>Organization:</span>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:24:10
for _, organization := range view.Organizations {
//line internal/site/app.sando:24:62
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:25:12
if organization.Selected {
//line internal/site/app.sando:25:41
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n <a href=\"/app/?organization="); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:26:43
if __himesan_error := __himesan_sando.WriteURL(__himesan_writer, (organization.ID)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:26:61
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\" aria-current=\"page\">"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:26:87
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (organization.Name)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:26:107
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</a>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:27:12
} else {
//line internal/site/app.sando:27:23
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n <a href=\"/app/?organization="); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:28:43
if __himesan_error := __himesan_sando.WriteURL(__himesan_writer, (organization.ID)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:28:61
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\">"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:28:67
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (organization.Name)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:28:87
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</a>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:29:12
}
//line internal/site/app.sando:29:16
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:30:10
}
//line internal/site/app.sando:30:14
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n </nav>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:32:8
}
//line internal/site/app.sando:32:12
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:33:8
if view.PendingBatches > 0 {
//line internal/site/app.sando:33:39
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n <aside class=\"live-status\" role=\"status\">\n <p><strong>Durable evidence is still being indexed.</strong> Accepted batches safely stored: "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:35:104
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (view.PendingBatches)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:35:126
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, ". Recent queries may lag by "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:35:158
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (view.ProjectionLag)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:35:179
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, ".</p>\n </aside>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:37:8
}
//line internal/site/app.sando:37:12
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n <aside class=\"live-status\" data-events-url=\""); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:38:53
if __himesan_error := __himesan_sando.WriteAttr(__himesan_writer, (view.EventsURL)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:38:70
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\" hidden>\n <p><strong>New observations are available.</strong> <a href=\"/app/?organization="); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:39:91
if __himesan_error := __himesan_sando.WriteURL(__himesan_writer, (view.Organization.ID)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:39:114
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\">Refresh this overview</a>.</p>\n </aside>\n <section class=\"signal-grid\" aria-label=\"Recent telemetry\">\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:42:8
for _, signal := range view.Signals {
//line internal/site/app.sando:42:48
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n <article class=\"signal-card\" id=\""); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:43:44
if __himesan_error := __himesan_sando.WriteAttr(__himesan_writer, (signal.ID)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:43:56
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\">\n <p class=\"eyebrow\">"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:44:32
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (signal.Name)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:44:46
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</p>\n <h2>Recent "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:45:24
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (signal.Name)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:45:38
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</h2>\n <p>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:46:16
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (signal.Description)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:46:37
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</p>\n <details><summary>Query</summary><pre><code>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:47:57
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (signal.Query)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:47:72
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</code></pre></details>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:48:13
if __himesan_error := __himesan_sando.Render(__himesan_render_context, __himesan_writer, (ResultTable(signal.Table))); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:48:41
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n </article>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:50:8
}
//line internal/site/app.sando:50:12
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n </section>\n <section class=\"section-grid\" aria-labelledby=\"saved-work\">\n <div><p class=\"eyebrow\">Saved work</p><h2 id=\"saved-work\">Queries and dashboards</h2></div>\n <div class=\"saved-grid\">\n <section aria-labelledby=\"saved-queries\"><h3 id=\"saved-queries\">Saved queries</h3>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:56:12
if len(view.SavedQueries) == 0 {
//line internal/site/app.sando:56:47
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "<p>No saved queries yet.</p>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:56:78
}
//line internal/site/app.sando:56:82
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:57:12
for _, item := range view.SavedQueries {
//line internal/site/app.sando:57:55
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "<article><h4>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:57:72
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (item.Name)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:57:84
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</h4><p>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:57:96
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (item.Description)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:57:115
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</p><pre><code>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:57:134
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (item.Query)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:57:147
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</code></pre></article>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:57:173
}
//line internal/site/app.sando:57:177
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n </section>\n <section aria-labelledby=\"dashboards\"><h3 id=\"dashboards\">Dashboards</h3>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:60:12
if len(view.Dashboards) == 0 {
//line internal/site/app.sando:60:45
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "<p>No dashboards yet.</p>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:60:73
}
//line internal/site/app.sando:60:77
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:61:12
for _, item := range view.Dashboards {
//line internal/site/app.sando:61:53
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "<article><h4><a href=\"/app/dashboards/"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:61:95
if __himesan_error := __himesan_sando.WriteURL(__himesan_writer, (item.Slug)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:61:107
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "/?organization="); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:61:126
if __himesan_error := __himesan_sando.WriteURL(__himesan_writer, (view.Organization.ID)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:61:149
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\">"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:61:155
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (item.Name)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:61:167
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</a></h4><p>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:61:183
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (item.Description)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:61:202
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</p><p>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:61:213
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (item.PanelCount)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:61:231
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, " panels</p></article>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:61:255
}
//line internal/site/app.sando:61:259
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n </section>\n </div>\n </section>\n <section class=\"section-grid\" aria-labelledby=\"incident-work\">\n <div><p class=\"eyebrow\">Incident response</p><h2 id=\"incident-work\">Attention without noise</h2></div>\n <div><p>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:67:19
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (view.OpenIncidents)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:67:40
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, " open incidents are visible in the authorized inbox. Alert rules execute the same bounded saved-query AST used everywhere else.</p><p><a class=\"button secondary\" href=\""); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:67:212
if __himesan_error := __himesan_sando.WriteURL(__himesan_writer, (view.IncidentsURL)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:67:232
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\">Open incident inbox</a></p></div>\n </section>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:69:8
if view.CanManage {
//line internal/site/app.sando:69:30
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n <section class=\"section-grid\" aria-labelledby=\"manage-work\">\n <div><p class=\"eyebrow\">Organization workshop</p><h2 id=\"manage-work\">Save a reusable view</h2><p>Assisted controls and typed text enter the same parser and versioned AST. Every form is an ordinary server request; nothing is generated or executed on page load.</p></div>\n <div class=\"editor-grid\">\n <form class=\"editor-card builder-card\" method=\"post\" action=\"/app/queries/builder/\">\n <h3>Build a query</h3>\n <p>Choose one bounded evidence source, an optional filter, and an optional summary. The saved result remains ordinary reviewable query text.</p>\n <input type=\"hidden\" name=\"organization_id\" value=\""); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:76:66
if __himesan_error := __himesan_sando.WriteAttr(__himesan_writer, (view.Organization.ID)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:76:89
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\">\n <input type=\"hidden\" name=\"csrf_token\" value=\""); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:77:61
if __himesan_error := __himesan_sando.WriteAttr(__himesan_writer, (view.ManageCSRF)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:77:79
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\">\n <div class=\"field-grid\">\n <div><label for=\"builder-name\">Name</label><input id=\"builder-name\" name=\"name\" required maxlength=\"128\"></div>\n <div><label for=\"builder-description\">Description</label><textarea id=\"builder-description\" name=\"description\" required maxlength=\"1024\"></textarea></div>\n <div><label for=\"builder-signal\">Evidence</label><select id=\"builder-signal\" name=\"signal\" required><option value=\"logs\">Logs</option><option value=\"metrics\">Metrics</option><option value=\"traces\">Traces</option><option value=\"deployments\">Deployments</option></select></div>\n <div><label for=\"builder-window\">Lookback</label><select id=\"builder-window\" name=\"window\" required><option value=\"15m\">15 minutes</option><option value=\"1h\" selected>1 hour</option><option value=\"6h\">6 hours</option><option value=\"24h\">24 hours</option><option value=\"168h\">7 days</option></select></div>\n <div><label for=\"builder-filter-field\">Filter field <span class=\"optional\">(optional)</span></label><select id=\"builder-filter-field\" name=\"filter_field\"><option value=\"\">No filter</option><option value=\"service\">Service</option><option value=\"project\">Project</option><option value=\"environment\">Environment</option><option value=\"route\">HTTP route</option><option value=\"status\">HTTP status</option><option value=\"duration\">Duration</option><option value=\"name\">Name</option><option value=\"severity\">Severity</option><option value=\"value\">Metric value</option><option value=\"trace_id\">Trace ID</option><option value=\"correlation_id\">Correlation ID</option></select></div>\n <div><label for=\"builder-filter-operator\">Filter comparison</label><select id=\"builder-filter-operator\" name=\"filter_operator\" required><option value=\"==\">equals</option><option value=\"!=\">does not equal</option><option value=\">=\">at least</option><option value=\"&lt;=\">at most</option><option value=\">\">greater than</option><option value=\"&lt;\">less than</option></select></div>\n <div><label for=\"builder-filter-value\">Filter value <span class=\"optional\">(optional)</span></label><input id=\"builder-filter-value\" name=\"filter_value\" maxlength=\"256\"></div>\n <div><label for=\"builder-aggregate\">Summary</label><select id=\"builder-aggregate\" name=\"aggregate\" required><option value=\"none\">No summary</option><option value=\"count\">Count</option><option value=\"min\">Minimum</option><option value=\"max\">Maximum</option><option value=\"sum\">Sum</option><option value=\"avg\">Average</option><option value=\"p50\">50th percentile</option><option value=\"p95\">95th percentile</option><option value=\"p99\">99th percentile</option></select></div>\n <div><label for=\"builder-aggregate-field\">Numeric summary field <span class=\"optional\">(not used by count)</span></label><select id=\"builder-aggregate-field\" name=\"aggregate_field\"><option value=\"\">No field</option><option value=\"value\">Metric value</option><option value=\"duration\">Duration</option><option value=\"status\">HTTP status</option></select></div>\n <div><label for=\"builder-group\">Group by <span class=\"optional\">(optional)</span></label><select id=\"builder-group\" name=\"group_by\"><option value=\"\">No grouping</option><option value=\"service\">Service</option><option value=\"project\">Project</option><option value=\"environment\">Environment</option><option value=\"route\">HTTP route</option><option value=\"status\">HTTP status</option><option value=\"name\">Name</option><option value=\"severity\">Severity</option></select></div>\n <div><label for=\"builder-bucket\">Time bucket <span class=\"optional\">(optional)</span></label><select id=\"builder-bucket\" name=\"bucket\"><option value=\"\">No time bucket</option><option value=\"1m\">1 minute</option><option value=\"5m\">5 minutes</option><option value=\"15m\">15 minutes</option><option value=\"1h\">1 hour</option></select></div>\n <div><label for=\"builder-limit\">Maximum rows</label><select id=\"builder-limit\" name=\"limit\" required><option value=\"10\">10</option><option value=\"20\">20</option><option value=\"50\" selected>50</option><option value=\"100\">100</option><option value=\"250\">250</option></select></div>\n </div>\n <button type=\"submit\">Build and save query</button>\n </form>\n <form class=\"editor-card\" method=\"post\" action=\"/app/queries/\">\n <h3>Write a query</h3>\n <input type=\"hidden\" name=\"organization_id\" value=\""); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:96:66
if __himesan_error := __himesan_sando.WriteAttr(__himesan_writer, (view.Organization.ID)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:96:89
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\">\n <input type=\"hidden\" name=\"csrf_token\" value=\""); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:97:61
if __himesan_error := __himesan_sando.WriteAttr(__himesan_writer, (view.ManageCSRF)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:97:79
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\">\n <label for=\"query-name\">Name</label><input id=\"query-name\" name=\"name\" required maxlength=\"128\">\n <label for=\"query-description\">Description</label><textarea id=\"query-description\" name=\"description\" required maxlength=\"1024\"></textarea>\n <label for=\"query-text\">Typed query</label><textarea id=\"query-text\" name=\"query\" required maxlength=\"16384\">logs | window 1h | limit 50</textarea>\n <button type=\"submit\">Save query</button>\n </form>\n <form class=\"editor-card\" method=\"post\" action=\"/app/dashboards/\">\n <h3>Create a one-panel dashboard</h3>\n <input type=\"hidden\" name=\"organization_id\" value=\""); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:105:66
if __himesan_error := __himesan_sando.WriteAttr(__himesan_writer, (view.Organization.ID)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:105:89
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\">\n <input type=\"hidden\" name=\"csrf_token\" value=\""); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:106:61
if __himesan_error := __himesan_sando.WriteAttr(__himesan_writer, (view.ManageCSRF)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:106:79
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\">\n <label for=\"dashboard-slug\">URL slug</label><input id=\"dashboard-slug\" name=\"slug\" required maxlength=\"63\" pattern=\"[a-z][a-z0-9-]+\">\n <label for=\"dashboard-name\">Name</label><input id=\"dashboard-name\" name=\"name\" required maxlength=\"128\">\n <label for=\"dashboard-description\">Description</label><textarea id=\"dashboard-description\" name=\"description\" required maxlength=\"1024\"></textarea>\n <label for=\"panel-title\">Panel title</label><input id=\"panel-title\" name=\"panel_title\" required maxlength=\"128\">\n <label for=\"saved-query\">Saved query</label>\n <select id=\"saved-query\" name=\"saved_query_id\" required>\n <option value=\"\">Choose a saved query</option>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:114:16
for _, item := range view.SavedQueries {
//line internal/site/app.sando:114:59
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "<option value=\""); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:114:78
if __himesan_error := __himesan_sando.WriteAttr(__himesan_writer, (item.ID)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:114:88
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\">"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:114:94
if __himesan_error := __himesan_sando.WriteText(__himesan_writer, (item.Name)); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:114:106
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "</option>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:114:118
}
//line internal/site/app.sando:114:122
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n </select>\n <label for=\"visualization\">Presentation</label>\n <select id=\"visualization\" name=\"visualization\" required><option value=\"table\">Table</option><option value=\"stat\">Single statistic with table</option><option value=\"timeseries\">Time series table</option></select>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:118:14
if len(view.SavedQueries) == 0 {
//line internal/site/app.sando:118:49
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "<button type=\"submit\" disabled>Create dashboard</button>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:118:108
} else {
//line internal/site/app.sando:118:119
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "<button type=\"submit\">Create dashboard</button>"); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:118:169
}
//line internal/site/app.sando:118:173
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n </form>\n </div>\n </section>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:122:8
}
//line internal/site/app.sando:122:12
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n </main>\n "); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:124:7
if __himesan_error := __himesan_sando.Render(__himesan_render_context, __himesan_writer, (SiteFooter())); __himesan_error != nil {
return __himesan_error
}
//line internal/site/app.sando:124:22
if __himesan_error := __himesan_sando.WriteString(__himesan_writer, "\n</body>\n</html>\n"); __himesan_error != nil {
return __himesan_error
}
return nil
})
}
+49
View File
@@ -0,0 +1,49 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Package site contains Observatory's typed Sandwich Hime interface and its
// immutable browser assets. HTTP policy remains owned by internal/httpserver.
package site
import (
"crypto/sha256"
_ "embed"
"encoding/hex"
)
//go:embed assets/site.css
var style []byte
//go:embed assets/site.js
var script []byte
//go:embed assets/observatory.svg
var icon []byte
type Assets struct {
StylePath string
ScriptPath string
IconPath string
}
func AssetPaths() Assets {
return Assets{StylePath: fingerprintedPath("site", "css", style), ScriptPath: fingerprintedPath("site", "js", script), IconPath: fingerprintedPath("observatory", "svg", icon)}
}
func Asset(path string) (body []byte, contentType string, ok bool) {
assets := AssetPaths()
switch path {
case assets.StylePath:
return style, "text/css; charset=utf-8", true
case assets.ScriptPath:
return script, "text/javascript; charset=utf-8", true
case assets.IconPath:
return icon, "image/svg+xml", true
default:
return nil, "", false
}
}
func fingerprintedPath(name, extension string, body []byte) string {
digest := sha256.Sum256(body)
return "/assets/" + name + "-" + hex.EncodeToString(digest[:8]) + "." + extension
}

Some files were not shown because too many files have changed in this diff Show More