From 0c5a57556ae17838bbfb84d0c33a2455c60acad3 Mon Sep 17 00:00:00 2001 From: Veillax <126523099+Veillax@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:21:56 -0600 Subject: [PATCH] Initial commit: notifications, monitoring, on-call and incidents One binary and one SQLite file. Topics with ntfy-style publish and subscribe, HTTP/TCP/DNS/TLS/heartbeat monitors with a public status page, schedules and escalation policies, and incidents with a timeline and post-mortem. The UI follows the Lightwell design language. Builds against an unreleased Reef (secretbox) through a local replace line. Co-Authored-By: Claude Sonnet 5.5 --- .env.example | 35 ++ .gitea/workflows/ci.yml | 52 ++ .gitignore | 7 + Dockerfile | 28 + LICENSE | 235 +++++++++ README.md | 144 ++++++ cmd/sandbar/main.go | 123 +++++ docs/design.md | 61 +++ go.mod | 24 + go.sum | 52 ++ internal/sandbar/api.go | 860 +++++++++++++++++++++++++++++++ internal/sandbar/auth.go | 229 ++++++++ internal/sandbar/incident.go | 200 +++++++ internal/sandbar/monitor.go | 390 ++++++++++++++ internal/sandbar/notify.go | 342 ++++++++++++ internal/sandbar/oncall.go | 327 ++++++++++++ internal/sandbar/sandbar_test.go | 550 ++++++++++++++++++++ internal/sandbar/server.go | 119 +++++ internal/sandbar/store.go | 239 +++++++++ internal/sandbar/web/index.html | 775 ++++++++++++++++++++++++++++ internal/sandbar/web/status.html | 104 ++++ scripts/lint-design.mjs | 57 ++ 22 files changed, 4953 insertions(+) create mode 100644 .env.example create mode 100644 .gitea/workflows/ci.yml create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 README.md create mode 100644 cmd/sandbar/main.go create mode 100644 docs/design.md create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/sandbar/api.go create mode 100644 internal/sandbar/auth.go create mode 100644 internal/sandbar/incident.go create mode 100644 internal/sandbar/monitor.go create mode 100644 internal/sandbar/notify.go create mode 100644 internal/sandbar/oncall.go create mode 100644 internal/sandbar/sandbar_test.go create mode 100644 internal/sandbar/server.go create mode 100644 internal/sandbar/store.go create mode 100644 internal/sandbar/web/index.html create mode 100644 internal/sandbar/web/status.html create mode 100644 scripts/lint-design.mjs diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..dedc78a --- /dev/null +++ b/.env.example @@ -0,0 +1,35 @@ +# Copy this file to .env and fill it in. Sandbar reads .env from its working directory +# (or pass -env /path/to/file). Real environment variables always win over the file. +# Never commit .env. + +# Encrypts saved secrets (channel webhook URLs and email addresses) inside the database. +# Generate one with: sandbar -genkey +# Keep it apart from the data folder and back it up: without it those secrets cannot be read. +# If you leave it unset, a key is generated into /master.key instead. +SANDBAR_MASTER_KEY= + +# Creates the first administrator at startup (otherwise use the setup page in the browser). +#SANDBAR_ADMIN_EMAIL=you@example.com +#SANDBAR_ADMIN_PASSWORD= + +# Address to listen on, and the folder for the database. +#SANDBAR_LISTEN=:8090 +#SANDBAR_DATA=./sandbar-data + +# Public address people use to reach Sandbar. Links in notifications use it. +#SANDBAR_URL=https://sandbar.example.com + +# Serves Prometheus metrics at /metrics for a scraper that sends this as a bearer token. +# Leave empty and /metrics does not exist. +#SANDBAR_METRICS_TOKEN= + +# How long topic messages and monitor results are kept, in days. +#SANDBAR_MESSAGE_DAYS=30 +#SANDBAR_CHECK_DAYS=30 + +# Outgoing email, for email channels and for paging people by email. +#SANDBAR_SMTP_HOST=smtp.example.com +#SANDBAR_SMTP_PORT=587 +#SANDBAR_SMTP_USER= +#SANDBAR_SMTP_PASSWORD= +#SANDBAR_SMTP_FROM=sandbar@example.com diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..1001bc5 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,52 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + # Sandbar needs secretbox, which is not in a tagged Reef release yet. Build against Reef's + # main branch until it is, then delete this step and the replace line in go.mod. + - uses: actions/checkout@v4 + with: + repository: Veillax/reef + path: reef-src + token: ${{ secrets.REEF_TOKEN }} + + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Use the checked-out Reef + run: go mod edit -replace git.veillax.com/Veillax/reef=./reef-src + + - name: Formatting + run: | + unformatted=$(gofmt -l cmd internal) + if [ -n "$unformatted" ]; then + echo "These files need gofmt:" + echo "$unformatted" + exit 1 + fi + + - name: Vet + run: go vet ./... + + - name: Test + run: go test ./... + + - name: Design lint + run: node scripts/lint-design.mjs + + - name: Builds on every platform + run: | + for t in linux/amd64 linux/arm64 linux/arm windows/amd64 darwin/amd64 darwin/arm64; do + echo "building for $t" + GOOS=${t%/*} GOARCH=${t#*/} GOARM=7 CGO_ENABLED=0 go build ./... + done diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..882ce02 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.env +*.db +*.db-wal +*.db-shm +master.key +.devdata/ +bin/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..927ef84 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,28 @@ +# syntax=docker/dockerfile:1 +# Packages a binary that was already built for each architecture, so the arm64 image needs +# no emulation. Build the binaries, then the image: +# +# for a in amd64 arm64; do +# mkdir -p dist/bin/linux_$a +# CGO_ENABLED=0 GOOS=linux GOARCH=$a go build -trimpath -ldflags "-s -w" -o dist/bin/linux_$a/sandbar ./cmd/sandbar +# done +# docker buildx build --platform linux/amd64,linux/arm64 -t sandbar . +FROM --platform=$BUILDPLATFORM alpine:3.22 AS prep +RUN apk add --no-cache ca-certificates \ + && mkdir /data && chown 65532:65532 /data + +FROM scratch +ARG TARGETARCH +LABEL org.opencontainers.image.title="Sandbar" \ + org.opencontainers.image.description="Notifications, monitoring, on-call and incident response" \ + org.opencontainers.image.source="https://git.veillax.com/Veillax/sandbar" \ + org.opencontainers.image.licenses="AGPL-3.0-only" +COPY --from=prep /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt +COPY --from=prep --chown=65532:65532 /data /data +COPY dist/bin/linux_${TARGETARCH}/sandbar /sandbar +USER 65532:65532 +ENV SANDBAR_DATA=/data +VOLUME ["/data"] +EXPOSE 8090 +ENTRYPOINT ["/sandbar"] +CMD ["-listen", ":8090"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f45c74d --- /dev/null +++ b/LICENSE @@ -0,0 +1,235 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +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. + + Reef + Copyright (C) 2026 Veillax + + 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 . + +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 . diff --git a/README.md b/README.md new file mode 100644 index 0000000..ffd302a --- /dev/null +++ b/README.md @@ -0,0 +1,144 @@ +# Sandbar + +Self-hosted notifications, monitoring, on-call and incident response in one small program. +One binary, one SQLite file, and everything is done in the web UI. + +Sandbar covers the ground of four tools: + +| Area | Like | What it does | +|---|---|---| +| **Topics** | ntfy | Publish a message to a topic with one HTTP request. Subscribe in the browser, with `curl`, or with the ntfy phone app | +| **Monitors** | Tianji, Uptime Kuma | Website, port, DNS and certificate checks, heartbeats for cron jobs, and a public status page | +| **On-call** | Opsgenie | Rotating schedules, escalation policies, and alerts that are acknowledged, snoozed or resolved | +| **Incidents** | incident.io | Declare, assign, update and close an incident, with a timeline and a post-mortem | + +It is built in the same style as Hammerhead, Blacktip and Bamboo and shares [Reef](https://git.veillax.com/Veillax/reef) +with them (`dotenv`, `netguard`, `secretbox`). + +## Quick start + +``` +go build -o bin/ ./cmd/... + +cp .env.example .env +bin/sandbar -genkey # paste the output into .env as SANDBAR_MASTER_KEY= + +bin/sandbar -listen :8090 -url https://sandbar.example.com +``` + +Open `http://localhost:8090` and create the first administrator. Or set `SANDBAR_ADMIN_EMAIL` and +`SANDBAR_ADMIN_PASSWORD` in `.env` to create it at startup. + +Docker: `docker run -p 8090:8090 -v sandbar-data:/data -e SANDBAR_MASTER_KEY=... sandbar`. + +## How the pieces fit + +``` +monitor fails ─┐ +API request ───┼─> alert ─> escalation policy ─> person ─> topic + email +Alertmanager ──┘ │ (repeat until acknowledged) + └─> broadcast channels (Slack, Discord, ntfy, email) + └─> optionally an incident, with a timeline +``` + +Every alert is deduplicated by its key, so a monitor that stays down is one alert, not one per check. + +## Topics + +``` +# publish (ntfy-style headers) +curl -H "Authorization: Bearer sb_..." -H "Title: Disk full" -H "Priority: urgent" -H "Tags: warning,disk" \ + -d "web-1 is at 98%" https://sandbar.example.com/ops + +# subscribe: server-sent events, or JSON lines; ?since=all replays stored messages +curl -N -H "Authorization: Bearer sb_..." https://sandbar.example.com/ops/sse +curl -N -H "Authorization: Bearer sb_..." "https://sandbar.example.com/ops/json?since=all" +``` + +A topic is 1 to 64 letters, digits, `-` or `_`. Publishing and subscribing both need a signed-in session or an +API key (create one on the Account page). Clients that use basic auth can send the key as the password. +Messages are kept for `SANDBAR_MESSAGE_DAYS` (default 30). + +Two topics are filled for you: `alerts` gets every alert and its recovery, and `incidents` gets every incident +update. Each person also has a personal topic (`u-`, shown on the Account page). Subscribe to it in the ntfy +app to be paged on your phone when an escalation policy reaches you. + +## Monitors + +| Type | Passes when | Notes | +|---|---|---| +| Website (HTTP) | The status is in the expected range (default 2xx) and the page contains the text you set | Redirects are not followed | +| Port (TCP) | A connection opens | | +| DNS lookup | The name resolves | | +| Certificate expiry | The certificate has more than N days left (default 14) | | +| Heartbeat | Your job requests `/api/v1/hb/` within its interval plus the allowed delay | A request on a down heartbeat recovers it at once | + +A monitor goes down after the set number of failures in a row (default 2), raises an alert with the monitor's +escalation policy, and recovers on the first success. Monitors marked public appear on `/status`, together with +incidents marked public. The status page never shows staff names or private monitors. + +Monitors cannot probe private or internal addresses unless you tick **Allow targets on private networks** on that +monitor, so a user who can add a monitor cannot use Sandbar to scan your network. + +## On-call + +- A **schedule** rotates through people, handing over every N hours from a start time. **Overrides** cover a + holiday or swap a shift. +- An **escalation policy** is a list of steps. Each step waits some minutes, then tells people and/or whoever is + on call for a schedule. It can start over after the last step until someone acknowledges. +- Alerts are stored with the time their next step is due, so restarting Sandbar loses nothing and repeats nothing. +- **Acknowledge** stops escalation. **Snooze** pauses it and resumes at the same step. **Resolve** closes the alert. + +## Incidents + +Declare one from the UI or `POST /api/v1/incidents`, or from an open alert (which links them). An incident has a +severity (sev1 to sev3), a status (investigating, identified, monitoring, resolved), a lead and a communications +owner, a timeline of everything that happened, comments, and a post-mortem with a template filled from the +timeline. Every change is announced on the `incidents` topic and on all channels. + +## Sending alerts in + +``` +# generic +curl -H "Authorization: Bearer sb_..." -H "Content-Type: application/json" \ + -d '{"key":"cpu-web-1","summary":"CPU above 90%","severity":"warning","policy":""}' \ + https://sandbar.example.com/api/v1/alerts + +# resolve it later with the same key +curl ... -d '{"key":"cpu-web-1","status":"resolved"}' https://sandbar.example.com/api/v1/alerts +``` + +Prometheus Alertmanager and Grafana can post their webhook to +`/api/v1/integrations/alertmanager?policy=` with an API key as the bearer token. + +## Channels + +A channel receives every alert and incident update: an email address list, or a webhook in Slack, Discord, ntfy or +plain JSON format. The address is stored encrypted and is never sent back to the browser. Webhooks cannot point at +internal addresses. + +## Configuration and secrets + +`.env.example` lists every setting. Secrets at rest use AES-256-GCM with `SANDBAR_MASTER_KEY`; passwords are bcrypt +hashes and API keys and sessions are stored as SHA-256 hashes. With the wrong key, saved channel addresses cannot be +read. If you do not set a key, one is generated into `/master.key`; move it into `.env`, and **back it up +separately**. + +Prometheus metrics are served at `/metrics` when `SANDBAR_METRICS_TOKEN` is set. + +## Database + +SQLite (pure Go, no C compiler), in WAL mode, in `/sandbar.db`. Messages, monitor results and alerts older +than their retention are pruned hourly. Back up by copying the data folder while Sandbar is stopped, plus the key. + +## Limits and notes + +- One instance, one organization. SQLite means no clustering. +- No ICMP ping monitor, no SMS or voice, and no two-factor or single sign-on yet. +- Sandbar serves plain HTTP. Put it behind HTTPS and set `-url`, or keep it on a private network. +- Sign-in attempts are limited to 10 per 10 minutes per address. +- Tests: `go test ./...`. Style: `node scripts/lint-design.mjs` (see `docs/design.md`). + +## License + +AGPL-3.0. See `LICENSE`. diff --git a/cmd/sandbar/main.go b/cmd/sandbar/main.go new file mode 100644 index 0000000..a92b832 --- /dev/null +++ b/cmd/sandbar/main.go @@ -0,0 +1,123 @@ +// Command sandbar is a self-hosted notification, monitoring, on-call and incident tool. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "log" + "net/http" + "os" + "os/signal" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" + + "git.veillax.com/Veillax/reef/dotenv" + "git.veillax.com/Veillax/reef/secretbox" + "git.veillax.com/Veillax/sandbar/internal/sandbar" +) + +var version = "dev" + +func env(k, def string) string { + if v := os.Getenv(k); v != "" { + return v + } + return def +} + +func main() { + envFile := "./.env" + for i, a := range os.Args { + if (a == "-env" || a == "--env") && i+1 < len(os.Args) { + envFile = os.Args[i+1] + } + } + if _, err := dotenv.Load(envFile); err != nil { + log.Fatalf("reading %s: %v", envFile, err) + } + + listen := flag.String("listen", env("SANDBAR_LISTEN", ":8090"), "address for the web UI, API and topics") + data := flag.String("data", env("SANDBAR_DATA", "./sandbar-data"), "directory for the database") + url := flag.String("url", env("SANDBAR_URL", ""), "public URL (used for links in notifications)") + flag.String("env", ".env", "file to read secrets and settings from") + genkey := flag.Bool("genkey", false, "print a new random SANDBAR_MASTER_KEY and exit") + showVersion := flag.Bool("version", false, "print the version and exit") + flag.Parse() + + if *showVersion { + fmt.Println("sandbar", version) + return + } + if *genkey { + fmt.Println(secretbox.GenerateKey()) + return + } + + key, err := masterKey(*data) + if err != nil { + log.Fatal(err) + } + box, err := secretbox.New(key) + if err != nil { + log.Fatalf("SANDBAR_MASTER_KEY: %v", err) + } + st, err := sandbar.OpenStore(*data, box) + if err != nil { + log.Fatal(err) + } + defer st.Close() + + atoi := func(k string) int { n, _ := strconv.Atoi(os.Getenv(k)); return n } + srv := sandbar.New(sandbar.Options{ + DataDir: *data, + URL: strings.TrimRight(*url, "/"), + MetricsToken: os.Getenv("SANDBAR_METRICS_TOKEN"), + MessageDays: atoi("SANDBAR_MESSAGE_DAYS"), + CheckDays: atoi("SANDBAR_CHECK_DAYS"), + SMTP: sandbar.SMTPConfig{Host: os.Getenv("SANDBAR_SMTP_HOST"), Port: os.Getenv("SANDBAR_SMTP_PORT"), + User: os.Getenv("SANDBAR_SMTP_USER"), Password: os.Getenv("SANDBAR_SMTP_PASSWORD"), From: env("SANDBAR_SMTP_FROM", "sandbar@localhost")}, + }, st) + srv.BootstrapAdmin(os.Getenv("SANDBAR_ADMIN_EMAIL"), os.Getenv("SANDBAR_ADMIN_PASSWORD")) + srv.Start() + + hs := &http.Server{Addr: *listen, Handler: srv.Handler(), ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 2 * time.Minute} + go func() { + log.Printf("sandbar %s listening on %s", version, *listen) + if err := hs.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Fatal(err) + } + }() + sig := make(chan os.Signal, 1) + signal.Notify(sig, os.Interrupt, syscall.SIGTERM) + <-sig + srv.Close() // ends open subscriptions so Shutdown doesn't wait on them + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + hs.Shutdown(ctx) +} + +// masterKey returns SANDBAR_MASTER_KEY, or generates one into /master.key so +// it works out of the box (move it into .env so a backup of the folder doesn't carry it). +func masterKey(dir string) (string, error) { + if k := strings.TrimSpace(os.Getenv("SANDBAR_MASTER_KEY")); k != "" { + return k, nil + } + p := filepath.Join(dir, "master.key") + if b, err := os.ReadFile(p); err == nil { + return strings.TrimSpace(string(b)), nil + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", err + } + k := secretbox.GenerateKey() + if err := os.WriteFile(p, []byte(k+"\n"), 0o600); err != nil { + return "", err + } + log.Printf("generated %s; copy it into .env as SANDBAR_MASTER_KEY and delete the file. Back it up: without it, saved secrets can't be recovered", p) + return k, nil +} diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..a2396cd --- /dev/null +++ b/docs/design.md @@ -0,0 +1,61 @@ +# Sandbar design language + +Sandbar's pages follow the Lightwell design language, as Hammerhead does. The references are `docs/design.md` in the Lightwell repository and in the Hammerhead repository. This page records how that language is applied here. When they disagree, Lightwell's document wins. + +## What is shared + +* **Tokens.** Colors, spacing (4px scale), radius (6px and 10px), type sizes (12 to 28px), the single shadow and the dark theme are the Lightwell values, copied from Hammerhead. The accent is Lightwell's teal, `#1f5c5c`, with white text on it. +* **Principles.** Quiet neutrals with one accent, plain and specific wording, one way to do each thing, calm density, and WCAG 2.1 AA. +* **Voice.** No emoji, no em or en dashes, no exclamation marks, sentence case, buttons that name the result, and errors that say what happened and what to do next. Errors from the server are capitalized in one place (`bad` in `api.go`). +* **Status carries text.** A status is a badge with a label ("Firing", "Down", "Resolved"), never a colored dot on its own. + +## Where it lives + +| File | What it holds | +| --- | --- | +| `internal/sandbar/web/index.html` | The app. The token block sits between `tokens:begin` and `tokens:end`; raw colors are allowed only there. | +| `internal/sandbar/web/status.html` | The public status page. Same token block, repeated. | + +Both are single files with no build step. Change a token in both, and in Hammerhead when the language changes. + +## Components + +The helpers at the top of the script in `index.html` are the same as Hammerhead's: `card`, `pageHeader`, `field`, `chk`, `badge`, `emptyState`, `modal`, `dialogForm`, `confirmDialog`, `ask`, `toast`, `skeleton`. Feature code uses these and does not style one-off. Sandbar adds three, built only from tokens: + +| Helper | Use | +| --- | --- | +| `table(head, rows)` | A table inside a flush card, with column headers | +| `rowList(addLabel, make, initial)` | A list the person adds to and removes from, such as people in a rotation or steps in a policy | +| `timeline(events)` | Dated entries for an alert or an incident | + +## Icons + +Lucide style, outline only, stroke 1.75, round caps, `currentColor`. Sizes are 16, 18 and 22 pixels. They are inline in the `ICONS` table. An icon goes with a text label, and icon-only buttons carry an `aria-label`. + +Approved names: `sandbar`, `alerts`, `incidents`, `oncall`, `monitors`, `topics`, `channels`, `status`, `users`, `account`, `out`, `menu`, `close`, `add`, `check`, `back`, `light`, `dark`, `alert`. Add a name here and in `ICONS` together. + +## Patterns + +* **One primary action per view.** It sits in the page header ("Declare incident", "Add monitor"). +* **List pages** show the page header, a filter or tab row where there is one, then the table in a card with no second title. +* **Detail pages** (an incident) use a back link, the title with its status badge, then cards, most important first. +* **Dialogs and forms** end with Cancel and then the primary action, at the bottom right. Labels sit above fields, and rules such as "At least 10 characters" are hints below them. +* **Destructive actions** always use `confirmDialog`. The title names the object, the body says what is lost and whether it can be undone. +* **Dates** have the month written out ("Nov 2, 2026"), with `fmtDate` and `fmtTime`. +* **Empty states** say why the list is empty and what will appear there. +* **Secrets** such as a channel's address are never sent back to the browser. The form says it is stored encrypted and hidden. + +## Layout + +* Content is capped at 1120px. Below 860px the sidebar becomes a slide-in drawer with a top bar. Phones keep a 16px side gutter. +* On touch screens controls are at least 44px high and inputs are 16px so the page does not zoom. +* Motion is minimal and turns off under `prefers-reduced-motion`. The theme follows the system and can be switched from the sidebar. +* The public status page is a single column, 720px wide, and has no navigation. + +## Checking a change + +``` +node scripts/lint-design.mjs +``` + +It fails on em and en dashes, emoji, and raw colors outside the token block, in the pages, the docs and the Go source. Then check the page in light and dark, at phone and desktop width, using only the keyboard. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c35b0eb --- /dev/null +++ b/go.mod @@ -0,0 +1,24 @@ +module git.veillax.com/Veillax/sandbar + +go 1.27.3 + +require ( + git.veillax.com/Veillax/reef v0.1.7 + golang.org/x/crypto v0.58.0 + modernc.org/sqlite v1.61.0 +) + +require ( + github.com/dustin/go-humanize v1.1.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/ncruces/go-strftime v1.1.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/sys v0.49.0 // indirect + modernc.org/libc v1.79.0 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.12.1 // indirect +) + +// Local development against an unreleased Reef (it gains secretbox). Remove once Reef is tagged. +replace git.veillax.com/Veillax/reef => ../reef diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..612879d --- /dev/null +++ b/go.sum @@ -0,0 +1,52 @@ +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM= +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/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.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= +modernc.org/cc/v4 v4.30.3 h1:aDq8gIX1X7+VFgO/JYYji6pLWL2H4tv3g8WatT3KCys= +modernc.org/cc/v4 v4.30.3/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.37.0 h1:BAuJCUtIHIxFIYaFhqXIw5YaoMBlNCUlFovejHfMip4= +modernc.org/ccgo/v4 v4.37.0/go.mod h1:/8627VhwWtAbqUXmPORxFQU5SgLrAx2jl9seLw9GBhY= +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.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o= +modernc.org/gc/v3 v3.2.0/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.79.0 h1:9Dvvv++bAMSkSuBzuOFAatbTV5OIoq6Y6FohmD3e7q8= +modernc.org/libc v1.79.0/go.mod h1:uT3kR61NsbeKJSLqq83GJwSnZMVLlSjyAz4DfTaBy1M= +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.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/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.61.0 h1:sQi63oLQ9uquAUA4CzOisH35Q3pEszkPBuHM0tFL8CY= +modernc.org/sqlite v1.61.0/go.mod h1:f4gr5tbpx2umklaT/QVtbi/50hNdM+4ng+2zMo8KXJ0= +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= diff --git a/internal/sandbar/api.go b/internal/sandbar/api.go new file mode 100644 index 0000000..c2f573b --- /dev/null +++ b/internal/sandbar/api.go @@ -0,0 +1,860 @@ +package sandbar + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf8" +) + +// Handler returns the HTTP handler for the whole app. +func (s *Server) Handler() http.Handler { + mux := http.NewServeMux() + + // pages + mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { servePage(w, indexHTML) }) + mux.HandleFunc("GET /status", func(w http.ResponseWriter, r *http.Request) { servePage(w, statusHTML) }) + mux.HandleFunc("GET /status.json", s.statusJSON) + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok") }) + mux.HandleFunc("GET /metrics", s.metrics) + mux.HandleFunc("GET /api/v1/hb/{token}", s.heartbeat) + mux.HandleFunc("POST /api/v1/hb/{token}", s.heartbeat) + + // session + mux.HandleFunc("GET /api/v1/state", s.getState) + mux.HandleFunc("POST /api/v1/setup", s.setup) + mux.HandleFunc("POST /api/v1/login", s.apiLogin) + mux.HandleFunc("POST /api/v1/logout", func(w http.ResponseWriter, r *http.Request) { s.logout(w, r); writeJSON(w, 200, ok) }) + + // topics, ntfy-style + mux.HandleFunc("POST /{topic}", s.auth(false, s.publishHTTP)) + mux.HandleFunc("PUT /{topic}", s.auth(false, s.publishHTTP)) + mux.HandleFunc("GET /{topic}/sse", s.auth(false, s.subscribeHTTP)) + mux.HandleFunc("GET /{topic}/json", s.auth(false, s.subscribeHTTP)) + mux.HandleFunc("GET /api/v1/topics/{topic}/messages", s.auth(false, func(w http.ResponseWriter, r *http.Request) { + since, _ := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64) + writeJSON(w, 200, s.MessagesSince(r.PathValue("topic"), since, 200)) + })) + + // people + mux.HandleFunc("GET /api/v1/users", s.auth(false, func(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, s.listUsers()) })) + mux.HandleFunc("POST /api/v1/users", s.auth(true, s.createUserHTTP)) + mux.HandleFunc("DELETE /api/v1/users/{id}", s.auth(true, s.deleteUser)) + mux.HandleFunc("POST /api/v1/users/{id}/password", s.auth(false, s.passwordHTTP)) + mux.HandleFunc("GET /api/v1/apikeys", s.auth(false, s.listKeys)) + mux.HandleFunc("POST /api/v1/apikeys", s.auth(false, s.createKeyHTTP)) + mux.HandleFunc("DELETE /api/v1/apikeys/{id}", s.auth(false, s.deleteKey)) + + // configuration documents + s.crud(mux, "channels", "channel", true, func() any { return &Channel{} }, func(v any, id string) error { + ch := v.(*Channel) + ch.ID = id + if ch.Target == redactedTarget { // an edit that left the hidden secret alone keeps the stored one + old, err := getOf[Channel](s.st, "channel", id) + if err != nil { + return err + } + ch.Target = s.st.open(old.Target) + } + if err := validateChannel(ch); err != nil { + return err + } + ch.Target = s.st.seal(ch.Target) + return nil + }, redactChannel) + s.crud(mux, "monitors", "monitor", true, func() any { return &Monitor{} }, func(v any, id string) error { + m := v.(*Monitor) + m.ID = id + return validateMonitor(m) + }, nil) + s.crud(mux, "schedules", "schedule", true, func() any { return &Schedule{} }, func(v any, id string) error { + sc := v.(*Schedule) + sc.ID = id + if strings.TrimSpace(sc.Name) == "" { + return errors.New("give the schedule a name") + } + if sc.RotationHours < 1 { + sc.RotationHours = 24 * 7 + } + if sc.Start == 0 { + sc.Start = s.now().Unix() + } + for _, o := range sc.Overrides { + if o.To <= o.From { + return errors.New("an override must end after it starts") + } + } + return nil + }, nil) + s.crud(mux, "policies", "policy", true, func() any { return &Policy{} }, func(v any, id string) error { + p := v.(*Policy) + p.ID = id + if strings.TrimSpace(p.Name) == "" { + return errors.New("give the policy a name") + } + if len(p.Steps) == 0 { + return errors.New("a policy needs at least one step") + } + return nil + }, nil) + mux.HandleFunc("POST /api/v1/channels/{id}/test", s.auth(true, s.testChannel)) + mux.HandleFunc("GET /api/v1/oncall", s.auth(false, s.onCallNow)) + + // monitors + mux.HandleFunc("GET /api/v1/monitors/{id}/checks", s.auth(false, func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, 200, s.recentChecks(r.PathValue("id"), 100)) + })) + mux.HandleFunc("GET /api/v1/monitor-states", s.auth(false, func(w http.ResponseWriter, r *http.Request) { + out := map[string]MonitorState{} + mons, _ := listOf[Monitor](s.st, "monitor") + for _, m := range mons { + out[m.ID] = s.monitorState(m.ID) + } + writeJSON(w, 200, out) + })) + + // alerts + mux.HandleFunc("GET /api/v1/alerts", s.auth(false, func(w http.ResponseWriter, r *http.Request) { + limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) + if limit <= 0 || limit > 500 { + limit = 100 + } + writeJSON(w, 200, s.listAlerts(r.URL.Query().Get("status"), limit)) + })) + mux.HandleFunc("POST /api/v1/alerts", s.auth(false, s.inboundAlert)) + mux.HandleFunc("POST /api/v1/integrations/alertmanager", s.auth(false, s.alertmanager)) + mux.HandleFunc("GET /api/v1/alerts/{id}", s.auth(false, func(w http.ResponseWriter, r *http.Request) { + a, err := s.getAlert(r.PathValue("id")) + if err != nil { + fail(w, err) + return + } + a.Timeline = s.st.events("alert", a.ID) + writeJSON(w, 200, a) + })) + mux.HandleFunc("POST /api/v1/alerts/{id}/ack", s.auth(false, func(w http.ResponseWriter, r *http.Request) { + fail2(w, s.AckAlert(r.PathValue("id"), userFrom(r.Context()).Name)) + })) + mux.HandleFunc("POST /api/v1/alerts/{id}/resolve", s.auth(false, func(w http.ResponseWriter, r *http.Request) { + fail2(w, s.ResolveAlert(r.PathValue("id"), userFrom(r.Context()).Name)) + })) + mux.HandleFunc("POST /api/v1/alerts/{id}/snooze", s.auth(false, func(w http.ResponseWriter, r *http.Request) { + var in struct { + Minutes int `json:"minutes"` + } + decode(r, &in) + if in.Minutes < 1 || in.Minutes > 24*60 { + in.Minutes = 30 + } + fail2(w, s.SnoozeAlert(r.PathValue("id"), userFrom(r.Context()).Name, time.Duration(in.Minutes)*time.Minute)) + })) + + // incidents + mux.HandleFunc("GET /api/v1/incidents", s.auth(false, func(w http.ResponseWriter, r *http.Request) { + list, err := listOf[Incident](s.st, "incident") + if err != nil { + fail(w, err) + return + } + sortIncidents(list) // ids are random, so order by time + writeJSON(w, 200, list) + })) + mux.HandleFunc("POST /api/v1/incidents", s.auth(false, s.declareHTTP)) + mux.HandleFunc("GET /api/v1/incidents/{id}", s.auth(false, func(w http.ResponseWriter, r *http.Request) { + in, err := getOf[Incident](s.st, "incident", r.PathValue("id")) + if err != nil { + fail(w, err) + return + } + in.Timeline = s.st.events("incident", in.ID) + writeJSON(w, 200, in) + })) + mux.HandleFunc("PATCH /api/v1/incidents/{id}", s.auth(false, func(w http.ResponseWriter, r *http.Request) { + var p IncidentPatch + if !decode(r, &p) { + bad(w, "invalid request") + return + } + in, err := s.UpdateIncident(r.PathValue("id"), userFrom(r.Context()).Name, p) + if err != nil { + fail(w, err) + return + } + writeJSON(w, 200, in) + })) + mux.HandleFunc("POST /api/v1/incidents/{id}/comments", s.auth(false, func(w http.ResponseWriter, r *http.Request) { + var in struct { + Text string `json:"text"` + } + decode(r, &in) + fail2(w, s.CommentIncident(r.PathValue("id"), userFrom(r.Context()).Name, in.Text)) + })) + mux.HandleFunc("POST /api/v1/incidents/{id}/postmortem-template", s.auth(false, func(w http.ResponseWriter, r *http.Request) { + in, err := getOf[Incident](s.st, "incident", r.PathValue("id")) + if err != nil { + fail(w, err) + return + } + writeJSON(w, 200, map[string]string{"template": s.postmortemTemplate(in)}) + })) + mux.HandleFunc("DELETE /api/v1/incidents/{id}", s.auth(true, func(w http.ResponseWriter, r *http.Request) { + fail2(w, s.st.del("incident", r.PathValue("id"))) + })) + + return secureHeaders(mux) +} + +var ok = map[string]bool{"ok": true} + +func servePage(w http.ResponseWriter, page []byte) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Write(page) +} + +func secureHeaders(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := w.Header() + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Referrer-Policy", "no-referrer") + h.Set("X-Frame-Options", "DENY") + h.Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:") + next.ServeHTTP(w, r) + }) +} + +// ---------- helpers ---------- + +func writeJSON(w http.ResponseWriter, code int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(code) + json.NewEncoder(w).Encode(v) +} + +// bad answers 400. Messages are capitalized here, in one place, so errors read as sentences. +func bad(w http.ResponseWriter, msg string) { + if msg != "" { + r, n := utf8.DecodeRuneInString(msg) + msg = string(unicode.ToUpper(r)) + msg[n:] + } + writeJSON(w, 400, map[string]string{"error": msg}) +} + +func fail(w http.ResponseWriter, err error) { + if errors.Is(err, errNotFound) { + writeJSON(w, 404, map[string]string{"error": "not found"}) + return + } + bad(w, err.Error()) +} + +// fail2 answers with an error, or with ok when err is nil. +func fail2(w http.ResponseWriter, err error) { + if err != nil { + fail(w, err) + return + } + writeJSON(w, 200, ok) +} + +func decode(r *http.Request, v any) bool { + return json.NewDecoder(http.MaxBytesReader(nil, r.Body, 1<<20)).Decode(v) == nil +} + +// auth wraps a handler: it needs a signed-in user (admin if adminOnly). Requests +// that change things with a cookie must be JSON, which a cross-site form can't send. +func (s *Server) auth(adminOnly bool, h http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + u := s.authenticate(r) + if u == nil { + w.Header().Set("WWW-Authenticate", `Basic realm="sandbar"`) + writeJSON(w, 401, map[string]string{"error": "sign in or send an API key"}) + return + } + if adminOnly && u.Role != "admin" { + writeJSON(w, 403, map[string]string{"error": "administrators only"}) + return + } + _, noCookie := r.Cookie(sessionCookie) + if noCookie == nil && r.Method != "GET" && strings.HasPrefix(r.URL.Path, "/api/") && + !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") { + bad(w, "send application/json") + return + } + h(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, u))) + } +} + +// crud registers list/create/update/delete for a kind of configuration document. +func (s *Server) crud(mux *http.ServeMux, path, kind string, adminWrite bool, newItem func() any, prepare func(v any, id string) error, redact func(any) any) { + base := "/api/v1/" + path + read := func(v any) any { + if redact != nil { + return redact(v) + } + return v + } + mux.HandleFunc("GET "+base, s.auth(false, func(w http.ResponseWriter, r *http.Request) { + var out []any + s.st.list(kind, func(raw []byte) error { + v := newItem() + if err := json.Unmarshal(raw, v); err != nil { + return err + } + out = append(out, read(v)) + return nil + }) + if out == nil { + out = []any{} + } + writeJSON(w, 200, out) + })) + save := func(w http.ResponseWriter, r *http.Request, id string) { + v := newItem() + if !decode(r, v) { + bad(w, "invalid request") + return + } + if err := prepare(v, id); err != nil { + bad(w, err.Error()) + return + } + if err := s.st.put(kind, id, v); err != nil { + fail(w, err) + return + } + writeJSON(w, 200, read(v)) + } + mux.HandleFunc("POST "+base, s.auth(adminWrite, func(w http.ResponseWriter, r *http.Request) { save(w, r, newID()) })) + mux.HandleFunc("PUT "+base+"/{id}", s.auth(adminWrite, func(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + if err := s.st.get(kind, id, newItem()); err != nil { + fail(w, err) + return + } + // A channel's secret target is never sent to the browser; an unchanged form sends the placeholder. + save(w, r, id) + })) + mux.HandleFunc("DELETE "+base+"/{id}", s.auth(adminWrite, func(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + if kind == "monitor" { + s.deleteMonitorData(id) + } + fail2(w, s.st.del(kind, id)) + })) +} + +func redactChannel(v any) any { + c := *(v.(*Channel)) + c.Target = redactedTarget // webhook URLs and addresses are secrets; re-enter to change + return c +} + +const redactedTarget = "••••••••" + +// ---------- session ---------- + +func (s *Server) getState(w http.ResponseWriter, r *http.Request) { + out := map[string]any{"needsSetup": s.countUsers() == 0, "user": nil, "url": s.opts.URL} + if u := s.authenticate(r); u != nil { + out["user"] = u + } + writeJSON(w, 200, out) +} + +func (s *Server) setup(w http.ResponseWriter, r *http.Request) { + var in struct{ Name, Email, Password string } + if !decode(r, &in) { + bad(w, "invalid request") + return + } + if s.countUsers() > 0 { + writeJSON(w, 403, map[string]string{"error": "already set up"}) + return + } + if _, err := s.createUser(in.Name, in.Email, in.Password, "admin", ""); err != nil { + bad(w, err.Error()) + return + } + u, err := s.login(w, r, in.Email, in.Password) + if err != nil { + bad(w, err.Error()) + return + } + writeJSON(w, 200, u) +} + +func (s *Server) apiLogin(w http.ResponseWriter, r *http.Request) { + var in struct{ Email, Password string } + if !decode(r, &in) { + bad(w, "invalid request") + return + } + u, err := s.login(w, r, in.Email, in.Password) + if err != nil { + code := 401 + if errors.Is(err, errThrottled) { + code = 429 + } + writeJSON(w, code, map[string]string{"error": err.Error()}) + return + } + writeJSON(w, 200, u) +} + +// ---------- people ---------- + +func (s *Server) createUserHTTP(w http.ResponseWriter, r *http.Request) { + var in struct{ Name, Email, Password, Role, Phone string } + if !decode(r, &in) { + bad(w, "invalid request") + return + } + if in.Role == "" { + in.Role = "member" + } + u, err := s.createUser(in.Name, in.Email, in.Password, in.Role, in.Phone) + if err != nil { + bad(w, err.Error()) + return + } + writeJSON(w, 200, u) +} + +func (s *Server) deleteUser(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + if id == userFrom(r.Context()).ID { + bad(w, "you can't delete yourself") + return + } + res, err := s.st.db.Exec(`DELETE FROM users WHERE id=?`, id) + if err != nil { + fail(w, err) + return + } + if n, _ := res.RowsAffected(); n == 0 { + fail(w, errNotFound) + return + } + writeJSON(w, 200, ok) +} + +func (s *Server) passwordHTTP(w http.ResponseWriter, r *http.Request) { + me := userFrom(r.Context()) + id := r.PathValue("id") + if id != me.ID && me.Role != "admin" { + writeJSON(w, 403, map[string]string{"error": "you can only change your own password"}) + return + } + var in struct{ Password string } + if !decode(r, &in) { + bad(w, "invalid request") + return + } + fail2(w, s.setPassword(id, in.Password)) +} + +func (s *Server) listKeys(w http.ResponseWriter, r *http.Request) { + out := []map[string]any{} + rows, err := s.st.db.Query(`SELECT id,name,created FROM apikeys WHERE user_id=? ORDER BY created`, userFrom(r.Context()).ID) + if err == nil { + defer rows.Close() + for rows.Next() { + var id, name string + var c int64 + if rows.Scan(&id, &name, &c) == nil { + out = append(out, map[string]any{"id": id, "name": name, "created": c}) + } + } + } + writeJSON(w, 200, out) +} + +func (s *Server) createKeyHTTP(w http.ResponseWriter, r *http.Request) { + var in struct{ Name string } + decode(r, &in) + id, tok, err := s.createAPIKey(userFrom(r.Context()).ID, in.Name) + if err != nil { + fail(w, err) + return + } + writeJSON(w, 200, map[string]string{"id": id, "token": tok}) // shown once +} + +func (s *Server) deleteKey(w http.ResponseWriter, r *http.Request) { + s.st.db.Exec(`DELETE FROM apikeys WHERE id=? AND user_id=?`, r.PathValue("id"), userFrom(r.Context()).ID) + writeJSON(w, 200, ok) +} + +// ---------- topics ---------- + +func (s *Server) publishHTTP(w http.ResponseWriter, r *http.Request) { + topic := r.PathValue("topic") + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64<<10)) + if err != nil { + bad(w, "message too large (limit 64 KB)") + return + } + h := func(names ...string) string { + for _, n := range names { + if v := r.Header.Get(n); v != "" { + return v + } + if v := r.URL.Query().Get(strings.ToLower(n)); v != "" { + return v + } + } + return "" + } + m, err := s.Publish(topic, h("Title", "X-Title", "t"), string(body), parsePriority(h("Priority", "X-Priority", "p")), parseTags(h("Tags", "X-Tags", "ta"))) + if err != nil { + bad(w, err.Error()) + return + } + writeJSON(w, 200, m) +} + +// subscribeHTTP streams a topic as server-sent events (/sse) or JSON lines (/json). +// ?since=|all replays stored messages first. +func (s *Server) subscribeHTTP(w http.ResponseWriter, r *http.Request) { + topic := r.PathValue("topic") + if !validTopic(topic) { + bad(w, "invalid topic") + return + } + fl, canFlush := w.(http.Flusher) + if !canFlush { + http.Error(w, "streaming not supported", 500) + return + } + sse := strings.HasSuffix(r.URL.Path, "/sse") + if sse { + w.Header().Set("Content-Type", "text/event-stream") + } else { + w.Header().Set("Content-Type", "application/x-ndjson") + } + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("X-Accel-Buffering", "no") + bw := bufio.NewWriter(w) + write := func(m Message) bool { + b, _ := json.Marshal(m) + var err error + if sse { + _, err = fmt.Fprintf(bw, "id: %s\ndata: %s\n\n", m.ID, b) + } else { + _, err = fmt.Fprintf(bw, "%s\n", b) + } + bw.Flush() + fl.Flush() + return err == nil + } + // Subscribe before replaying so nothing published in between is missed; duplicates are skipped by id. + ch, unsub := s.hub.subscribe(topic) + defer unsub() + seen := map[string]bool{} + if q := r.URL.Query().Get("since"); q != "" { + since := int64(0) + if q != "all" { + since, _ = strconv.ParseInt(q, 10, 64) + } + for _, m := range s.MessagesSince(topic, since, 500) { + seen[m.ID] = true + if !write(m) { + return + } + } + } + if sse { + fmt.Fprint(bw, ": connected\n\n") + bw.Flush() + fl.Flush() + } + keepalive := time.NewTicker(30 * time.Second) + defer keepalive.Stop() + for { + select { + case <-r.Context().Done(): + return + case <-s.stop: + return + case m := <-ch: + if seen[m.ID] { + continue + } + if !write(m) { + return + } + case <-keepalive.C: + if sse { + fmt.Fprint(bw, ": keepalive\n\n") + } else { + fmt.Fprint(bw, "\n") + } + bw.Flush() + fl.Flush() + } + } +} + +// ---------- alerts in ---------- + +func (s *Server) inboundAlert(w http.ResponseWriter, r *http.Request) { + var in struct { + Key string `json:"key"` + Summary string `json:"summary"` + Detail string `json:"detail"` + Severity string `json:"severity"` + Policy string `json:"policy"` + Status string `json:"status"` // firing (default) or resolved + Source string `json:"source"` + } + if !decode(r, &in) { + bad(w, "invalid request") + return + } + if in.Key == "" { + in.Key = in.Summary + } + if in.Key == "" { + bad(w, "send a key or a summary") + return + } + if in.Source == "" { + in.Source = "api" + } + in.Key = "ext:" + in.Key + if in.Status == "resolved" { + s.ResolveAlertKey(in.Key, in.Source) + writeJSON(w, 200, ok) + return + } + if in.Summary == "" { + in.Summary = in.Key + } + if in.Policy != "" { + if _, err := getOf[Policy](s.st, "policy", in.Policy); err != nil { + bad(w, "unknown escalation policy") + return + } + } + a, isNew, err := s.RaiseAlert(in.Key, in.Source, in.Summary, in.Detail, in.Severity, in.Policy) + if err != nil { + fail(w, err) + return + } + writeJSON(w, 200, map[string]any{"id": a.ID, "new": isNew}) +} + +// alertmanager accepts Prometheus Alertmanager's webhook (also Grafana's, which uses the same shape). +// ?policy= sets the escalation policy. +func (s *Server) alertmanager(w http.ResponseWriter, r *http.Request) { + var in struct { + Alerts []struct { + Status string `json:"status"` + Labels map[string]string `json:"labels"` + Annotations map[string]string `json:"annotations"` + Fingerprint string `json:"fingerprint"` + } `json:"alerts"` + } + if !decode(r, &in) { + bad(w, "invalid request") + return + } + policy := r.URL.Query().Get("policy") + if policy != "" { + if _, err := getOf[Policy](s.st, "policy", policy); err != nil { + bad(w, "unknown escalation policy") + return + } + } + n := 0 + for _, a := range in.Alerts { + key := a.Fingerprint + if key == "" { + key = a.Labels["alertname"] + "/" + a.Labels["instance"] + } + key = "am:" + key + if a.Status == "resolved" { + s.ResolveAlertKey(key, "alertmanager") + continue + } + sev := map[string]string{"critical": "critical", "warning": "warning", "info": "info"}[a.Labels["severity"]] + summary := firstNonEmpty(a.Annotations["summary"], a.Labels["alertname"], key) + if _, _, err := s.RaiseAlert(key, "alertmanager", summary, a.Annotations["description"], sev, policy); err == nil { + n++ + } + } + writeJSON(w, 200, map[string]int{"processed": n}) +} + +// ---------- misc ---------- + +func (s *Server) declareHTTP(w http.ResponseWriter, r *http.Request) { + var in struct { + Title string `json:"title"` + Severity string `json:"severity"` + Summary string `json:"summary"` + Lead string `json:"lead"` + AlertIDs []string `json:"alertIds"` + } + if !decode(r, &in) { + bad(w, "invalid request") + return + } + me := userFrom(r.Context()) + if in.Lead == "" { + in.Lead = me.ID + } + inc, err := s.DeclareIncident(in.Title, in.Severity, in.Summary, in.Lead, me.Name, in.AlertIDs) + if err != nil { + bad(w, err.Error()) + return + } + writeJSON(w, 200, inc) +} + +func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) { + ch, err := getOf[Channel](s.st, "channel", r.PathValue("id")) + if err != nil { + fail(w, err) + return + } + if err := s.sendChannel(*ch, Note{Status: "test", Kind: "alert", Title: "test", Time: s.now().Unix()}); err != nil { + bad(w, err.Error()) + return + } + writeJSON(w, 200, ok) +} + +func (s *Server) onCallNow(w http.ResponseWriter, r *http.Request) { + type row struct { + Schedule string `json:"schedule"` + ID string `json:"id"` + UserID string `json:"userId"` + User string `json:"user"` + Next string `json:"next"` // who is on call after the current handover + } + out := []row{} + scs, _ := listOf[Schedule](s.st, "schedule") + now := s.now() + for _, sc := range scs { + sc := sc + uid := sc.OnCall(now) + nx := sc.OnCall(now.Add(time.Duration(sc.RotationHours) * time.Hour)) + out = append(out, row{sc.Name, sc.ID, uid, s.userName(uid), s.userName(nx)}) + } + writeJSON(w, 200, out) +} + +func (s *Server) heartbeat(w http.ResponseWriter, r *http.Request) { + if !s.Heartbeat(r.PathValue("token")) { + http.NotFound(w, r) + return + } + io.WriteString(w, "ok") +} + +// statusJSON feeds the public status page: only monitors and incidents marked public. +func (s *Server) statusJSON(w http.ResponseWriter, r *http.Request) { + type mon struct { + Name string `json:"name"` + Status string `json:"status"` + Uptime float64 `json:"uptime"` + Since int64 `json:"since"` + } + type inc struct { + Title string `json:"title"` + Status string `json:"status"` + Severity string `json:"severity"` + Created int64 `json:"created"` + Resolved int64 `json:"resolved"` + Updates []Event `json:"updates"` + } + out := struct { + Monitors []mon `json:"monitors"` + Incidents []inc `json:"incidents"` + Overall string `json:"overall"` + }{[]mon{}, []inc{}, "operational"} + mons, _ := listOf[Monitor](s.st, "monitor") + for _, m := range mons { + if !m.Public || !m.Enabled { + continue + } + st := s.monitorState(m.ID) + out.Monitors = append(out.Monitors, mon{m.Name, st.Status, st.Uptime30, st.Since}) + if st.Status == "down" { + out.Overall = "outage" + } + } + incs, _ := listOf[Incident](s.st, "incident") + sortIncidents(incs) + cut := s.now().AddDate(0, 0, -14).Unix() + for _, in := range incs { + if !in.Public || (in.Status == "resolved" && in.Resolved < cut) { + continue + } + var ups []Event + for _, e := range s.st.events("incident", in.ID) { + if e.Kind == "update" || e.Kind == "declared" { + e.Actor = "" // staff names stay off the public page + ups = append(ups, e) + } + } + out.Incidents = append(out.Incidents, inc{in.Title, in.Status, in.Severity, in.Created, in.Resolved, ups}) + if in.Status != "resolved" && out.Overall == "operational" { + out.Overall = "degraded" + } + } + w.Header().Set("Cache-Control", "max-age=15") + writeJSON(w, 200, out) +} + +func sortIncidents(list []Incident) { + for i := 1; i < len(list); i++ { // newest first; lists are short + for j := i; j > 0 && list[j].Created > list[j-1].Created; j-- { + list[j], list[j-1] = list[j-1], list[j] + } + } +} + +func (s *Server) metrics(w http.ResponseWriter, r *http.Request) { + if s.opts.MetricsToken == "" { + http.NotFound(w, r) + return + } + if h := r.Header.Get("Authorization"); h != "Bearer "+s.opts.MetricsToken { + w.Header().Set("WWW-Authenticate", `Bearer realm="metrics"`) + http.Error(w, "unauthorized", 401) + return + } + var b strings.Builder + b.WriteString("# TYPE sandbar_monitor_up gauge\n") + mons, _ := listOf[Monitor](s.st, "monitor") + for _, m := range mons { + v := 0 + if s.monitorState(m.ID).Status == "up" { + v = 1 + } + fmt.Fprintf(&b, "sandbar_monitor_up{monitor=%q} %d\n", m.Name, v) + } + var firing, acked, open int + s.st.db.QueryRow(`SELECT COUNT(*) FROM alerts WHERE status='firing'`).Scan(&firing) + s.st.db.QueryRow(`SELECT COUNT(*) FROM alerts WHERE status='acked'`).Scan(&acked) + incs, _ := listOf[Incident](s.st, "incident") + for _, in := range incs { + if in.Status != "resolved" { + open++ + } + } + fmt.Fprintf(&b, "# TYPE sandbar_alerts gauge\nsandbar_alerts{status=\"firing\"} %d\nsandbar_alerts{status=\"acked\"} %d\n", firing, acked) + fmt.Fprintf(&b, "# TYPE sandbar_incidents_open gauge\nsandbar_incidents_open %d\n", open) + w.Header().Set("Content-Type", "text/plain; version=0.0.4") + io.WriteString(w, b.String()) +} diff --git a/internal/sandbar/auth.go b/internal/sandbar/auth.go new file mode 100644 index 0000000..e5c5ba3 --- /dev/null +++ b/internal/sandbar/auth.go @@ -0,0 +1,229 @@ +package sandbar + +import ( + "context" + "database/sql" + "errors" + "net" + "net/http" + "strings" + "time" + + "golang.org/x/crypto/bcrypt" +) + +type User struct { + ID string `json:"id"` + Name string `json:"name"` + Email string `json:"email"` + Role string `json:"role"` // admin or member + Phone string `json:"phone"` + Created int64 `json:"created"` + Topic string `json:"topic"` // the personal topic their phone subscribes to + hash string +} + +const ( + sessionCookie = "sandbar_session" + sessionTTL = 14 * 24 * time.Hour +) + +type ctxKey struct{} + +func (s *Server) countUsers() int { + var n int + s.st.db.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n) + return n +} + +func scanUser(r scanner) (*User, error) { + var u User + err := r.Scan(&u.ID, &u.Name, &u.Email, &u.hash, &u.Role, &u.Phone, &u.Created) + if errors.Is(err, sql.ErrNoRows) { + return nil, errNotFound + } + u.Topic = userTopic(u.ID) + return &u, err +} + +const userCols = `id,name,email,hash,role,phone,created` + +func (s *Server) userByID(id string) (*User, error) { + return scanUser(s.st.db.QueryRow(`SELECT `+userCols+` FROM users WHERE id=?`, id)) +} + +func (s *Server) userByEmail(email string) (*User, error) { + return scanUser(s.st.db.QueryRow(`SELECT `+userCols+` FROM users WHERE email=?`, strings.TrimSpace(email))) +} + +func (s *Server) listUsers() []User { + out := []User{} + rows, err := s.st.db.Query(`SELECT ` + userCols + ` FROM users ORDER BY name`) + if err != nil { + return out + } + defer rows.Close() + for rows.Next() { + if u, err := scanUser(rows); err == nil { + out = append(out, *u) + } + } + return out +} + +func validPassword(p string) error { + if len(p) < 10 { + return errors.New("use a password of at least 10 characters") + } + if len(p) > 72 { + return errors.New("passwords are limited to 72 characters") + } + return nil +} + +func (s *Server) createUser(name, email, password, role, phone string) (*User, error) { + name, email = strings.TrimSpace(name), strings.TrimSpace(email) + if name == "" || !strings.Contains(email, "@") || strings.ContainsAny(email, " \r\n<>") { + return nil, errors.New("a user needs a name and an email address") + } + if role != "admin" && role != "member" { + return nil, errors.New("role must be admin or member") + } + if err := validPassword(password); err != nil { + return nil, err + } + h, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return nil, err + } + u := &User{ID: newID(), Name: name, Email: email, Role: role, Phone: strings.TrimSpace(phone), Created: s.now().Unix()} + u.Topic = userTopic(u.ID) + _, err = s.st.db.Exec(`INSERT INTO users(`+userCols+`) VALUES(?,?,?,?,?,?,?)`, u.ID, u.Name, u.Email, string(h), u.Role, u.Phone, u.Created) + if err != nil { + if strings.Contains(err.Error(), "UNIQUE") { + return nil, errors.New("that email address is already registered") + } + return nil, err + } + return u, nil +} + +func (s *Server) setPassword(id, password string) error { + if err := validPassword(password); err != nil { + return err + } + h, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return err + } + _, err = s.st.db.Exec(`UPDATE users SET hash=? WHERE id=?`, string(h), id) + if err == nil { + s.st.db.Exec(`DELETE FROM sessions WHERE user_id=?`, id) // a password change signs everyone out + } + return err +} + +// throttled limits password guessing per client address: 10 tries per 10 minutes. +func (s *Server) throttled(ip string) bool { + s.loginMu.Lock() + defer s.loginMu.Unlock() + cut := s.now().Add(-10 * time.Minute) + var keep []time.Time + for _, t := range s.loginTry[ip] { + if t.After(cut) { + keep = append(keep, t) + } + } + s.loginTry[ip] = keep + return len(keep) >= 10 +} + +func (s *Server) noteFailure(ip string) { + s.loginMu.Lock() + s.loginTry[ip] = append(s.loginTry[ip], s.now()) + s.loginMu.Unlock() +} + +func clientIP(r *http.Request) string { + h, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return r.RemoteAddr + } + return h +} + +var errThrottled = errors.New("too many attempts, try again in a few minutes") + +// login checks credentials and starts a session. +func (s *Server) login(w http.ResponseWriter, r *http.Request, email, password string) (*User, error) { + ip := clientIP(r) + if s.throttled(ip) { + return nil, errThrottled + } + u, err := s.userByEmail(email) + hash := "$2a$10$7EqJtq98hPqEX7fNZaFWoOhi5BWYKTaYBwxwEGLMzRVr4qhCXWM9S" // so a wrong email costs the same time as a wrong password + if err == nil { + hash = u.hash + } + if bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) != nil || err != nil { + s.noteFailure(ip) + return nil, errors.New("wrong email or password") + } + tok := newToken() + exp := s.now().Add(sessionTTL) + if _, err := s.st.db.Exec(`INSERT INTO sessions(hash,user_id,expires) VALUES(?,?,?)`, hashToken(tok), u.ID, exp.Unix()); err != nil { + return nil, err + } + http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: tok, Path: "/", Expires: exp, HttpOnly: true, + SameSite: http.SameSiteStrictMode, Secure: strings.HasPrefix(s.opts.URL, "https://")}) + return u, nil +} + +func (s *Server) logout(w http.ResponseWriter, r *http.Request) { + if c, err := r.Cookie(sessionCookie); err == nil { + s.st.db.Exec(`DELETE FROM sessions WHERE hash=?`, hashToken(c.Value)) + } + http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: "", Path: "/", MaxAge: -1, HttpOnly: true}) +} + +// authenticate finds who is calling: a session cookie, or an API key given as a +// bearer token or as the password of HTTP basic auth (ntfy clients do the latter). +func (s *Server) authenticate(r *http.Request) *User { + if c, err := r.Cookie(sessionCookie); err == nil { + var uid string + var exp int64 + if s.st.db.QueryRow(`SELECT user_id,expires FROM sessions WHERE hash=?`, hashToken(c.Value)).Scan(&uid, &exp) == nil && exp > s.now().Unix() { + if u, err := s.userByID(uid); err == nil { + return u + } + } + } + key := "" + if h := r.Header.Get("Authorization"); strings.HasPrefix(h, "Bearer ") { + key = strings.TrimSpace(h[7:]) + } else if _, pw, ok := r.BasicAuth(); ok { + key = pw + } + if key == "" { + return nil + } + var uid string + if s.st.db.QueryRow(`SELECT user_id FROM apikeys WHERE hash=?`, hashToken(key)).Scan(&uid) == nil { + if u, err := s.userByID(uid); err == nil { + return u + } + } + return nil +} + +func userFrom(ctx context.Context) *User { + u, _ := ctx.Value(ctxKey{}).(*User) + return u +} + +func (s *Server) createAPIKey(userID, name string) (id, token string, err error) { + token = "sb_" + newToken() + id = newID() + _, err = s.st.db.Exec(`INSERT INTO apikeys(id,name,hash,user_id,created) VALUES(?,?,?,?,?)`, id, strings.TrimSpace(name), hashToken(token), userID, s.now().Unix()) + return +} diff --git a/internal/sandbar/incident.go b/internal/sandbar/incident.go new file mode 100644 index 0000000..265183f --- /dev/null +++ b/internal/sandbar/incident.go @@ -0,0 +1,200 @@ +package sandbar + +import ( + "errors" + "fmt" + "strings" + "time" +) + +// Incidents are the human side: something is wrong and people are working on it. +// An incident has a severity, a status that moves forward, a lead and a comms +// owner, a timeline of everything that happened, and a post-mortem. Every change +// is announced on the "incidents" topic and the broadcast channels. + +type Incident struct { + ID string `json:"id"` + Title string `json:"title"` + Severity string `json:"severity"` // sev1 (worst) to sev3 + Status string `json:"status"` // investigating, identified, monitoring, resolved + Lead string `json:"lead"` // user id + Comms string `json:"comms"` // user id + Summary string `json:"summary"` + Postmortem string `json:"postmortem"` + Public bool `json:"public"` // shown on the status page + Created int64 `json:"created"` + Resolved int64 `json:"resolved"` + AlertIDs []string `json:"alertIds"` + Timeline []Event `json:"timeline,omitempty"` +} + +var incidentStatuses = []string{"investigating", "identified", "monitoring", "resolved"} + +func validStatus(s string) bool { + for _, v := range incidentStatuses { + if v == s { + return true + } + } + return false +} + +func validSeverity(s string) bool { return s == "sev1" || s == "sev2" || s == "sev3" } + +func (s *Server) userName(id string) string { + if u, err := s.userByID(id); err == nil { + return u.Name + } + return "" +} + +func (s *Server) announceIncident(in *Incident, status, text string) { + s.broadcast(Note{Status: status, Kind: "incident", Title: in.Title, Message: fmt.Sprintf("[%s] %s: %s", strings.ToUpper(in.Severity), in.Status, text), + Severity: map[string]string{"sev1": "critical", "sev2": "warning"}[in.Severity], Link: s.link("/#incidents"), Time: s.now().Unix()}, "incidents") +} + +// DeclareIncident opens an incident, optionally linking the alerts that caused it. +func (s *Server) DeclareIncident(title, severity, summary, lead, actor string, alertIDs []string) (*Incident, error) { + title = strings.TrimSpace(title) + if title == "" { + return nil, errors.New("give the incident a title") + } + if severity == "" { + severity = "sev2" + } + if !validSeverity(severity) { + return nil, errors.New("severity must be sev1, sev2 or sev3") + } + now := s.now() + in := &Incident{ID: newID(), Title: title, Severity: severity, Status: "investigating", Lead: lead, Summary: summary, Created: now.Unix(), AlertIDs: []string{}} + for _, id := range alertIDs { + if a, err := s.getAlert(id); err == nil { + in.AlertIDs = append(in.AlertIDs, a.ID) + s.st.db.Exec(`UPDATE alerts SET incident_id=? WHERE id=?`, in.ID, a.ID) + s.st.addEvent("alert", a.ID, "incident", actor, "linked to incident "+title, now) + } + } + if err := s.st.put("incident", in.ID, in); err != nil { + return nil, err + } + s.st.addEvent("incident", in.ID, "declared", actor, fmt.Sprintf("declared %s: %s", severity, title), now) + if lead != "" { + s.st.addEvent("incident", in.ID, "role", actor, "lead: "+s.userName(lead), now) + } + s.announceIncident(in, "declared", firstNonEmpty(summary, "incident declared")) + return in, nil +} + +func firstNonEmpty(v ...string) string { + for _, s := range v { + if s != "" { + return s + } + } + return "" +} + +// IncidentPatch holds the fields an update may change; nil means unchanged. +type IncidentPatch struct { + Title *string `json:"title"` + Severity *string `json:"severity"` + Status *string `json:"status"` + Lead *string `json:"lead"` + Comms *string `json:"comms"` + Summary *string `json:"summary"` + Postmortem *string `json:"postmortem"` + Public *bool `json:"public"` + Note string `json:"note"` // text for the update announcement and timeline +} + +func (s *Server) UpdateIncident(id, actor string, p IncidentPatch) (*Incident, error) { + in, err := getOf[Incident](s.st, "incident", id) + if err != nil { + return nil, err + } + now := s.now() + var changes []string + if p.Severity != nil && *p.Severity != in.Severity { + if !validSeverity(*p.Severity) { + return nil, errors.New("severity must be sev1, sev2 or sev3") + } + changes = append(changes, "severity "+in.Severity+" to "+*p.Severity) + in.Severity = *p.Severity + } + if p.Status != nil && *p.Status != in.Status { + if !validStatus(*p.Status) { + return nil, errors.New("status must be investigating, identified, monitoring or resolved") + } + changes = append(changes, "status "+in.Status+" to "+*p.Status) + in.Status = *p.Status + if in.Status == "resolved" { + in.Resolved = now.Unix() + } else { + in.Resolved = 0 + } + } + if p.Lead != nil && *p.Lead != in.Lead { + in.Lead = *p.Lead + changes = append(changes, "lead: "+s.userName(in.Lead)) + } + if p.Comms != nil && *p.Comms != in.Comms { + in.Comms = *p.Comms + changes = append(changes, "comms: "+s.userName(in.Comms)) + } + if p.Title != nil && strings.TrimSpace(*p.Title) != "" && *p.Title != in.Title { + in.Title = strings.TrimSpace(*p.Title) + changes = append(changes, "renamed") + } + if p.Summary != nil { + in.Summary = *p.Summary + } + if p.Postmortem != nil { + in.Postmortem = *p.Postmortem + } + if p.Public != nil { + in.Public = *p.Public + } + if err := s.st.put("incident", in.ID, in); err != nil { + return nil, err + } + if len(changes) > 0 || p.Note != "" { + text := strings.Join(changes, "; ") + if p.Note != "" { + text = strings.TrimSpace(text + ": " + p.Note) + } + s.st.addEvent("incident", in.ID, "update", actor, text, now) + kind := "update" + if in.Status == "resolved" { + kind = "resolved" + } + s.announceIncident(in, kind, text) + } + return in, nil +} + +func (s *Server) CommentIncident(id, actor, text string) error { + if _, err := getOf[Incident](s.st, "incident", id); err != nil { + return err + } + if strings.TrimSpace(text) == "" { + return errors.New("write something") + } + s.st.addEvent("incident", id, "comment", actor, text, s.now()) + return nil +} + +// postmortemTemplate is a starting point, filled with what the timeline already knows. +func (s *Server) postmortemTemplate(in *Incident) string { + var b strings.Builder + fmt.Fprintf(&b, "# Post-mortem: %s\n\n", in.Title) + fmt.Fprintf(&b, "Severity: %s\nStarted: %s\n", in.Severity, time.Unix(in.Created, 0).UTC().Format(time.RFC1123)) + if in.Resolved > 0 { + fmt.Fprintf(&b, "Resolved: %s (%s)\n", time.Unix(in.Resolved, 0).UTC().Format(time.RFC1123), time.Duration(in.Resolved-in.Created)*time.Second) + } + b.WriteString("\n## Summary\n\n\n## Impact\n\n\n## Root cause\n\n\n## Timeline\n\n") + for _, e := range s.st.events("incident", in.ID) { + fmt.Fprintf(&b, "- %s %s\n", time.Unix(e.Time, 0).UTC().Format("15:04:05"), e.Text) + } + b.WriteString("\n## What went well\n\n\n## What went badly\n\n\n## Action items\n\n") + return b.String() +} diff --git a/internal/sandbar/monitor.go b/internal/sandbar/monitor.go new file mode 100644 index 0000000..1b6a725 --- /dev/null +++ b/internal/sandbar/monitor.go @@ -0,0 +1,390 @@ +package sandbar + +import ( + "context" + "crypto/tls" + "database/sql" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "git.veillax.com/Veillax/reef/netguard" +) + +// Monitors check that things are up. A check runs every interval; the monitor +// goes down after Retries failures in a row (so a blip is ignored) and raises an +// alert, and recovers on the first success. Heartbeat monitors work the other +// way round: your cron job or service calls /hb/, and the monitor goes +// down when the calls stop. + +type Monitor struct { + ID string `json:"id"` + Name string `json:"name"` + Kind string `json:"kind"` // http, tcp, dns, tls, heartbeat + Target string `json:"target"` // URL, host:port, hostname, or host[:port] for tls + IntervalS int `json:"intervalS"` + TimeoutS int `json:"timeoutS"` + Retries int `json:"retries"` // failures in a row before it is down (default 2) + Expect string `json:"expect"` // http: accepted status, e.g. "200-299" (default) + Keyword string `json:"keyword"` // http: text the body must contain + WarnDays int `json:"warnDays"` // tls: fail when the certificate expires within this many days (default 14) + GraceS int `json:"graceS"` // heartbeat: extra time allowed past the interval + Token string `json:"token"` // heartbeat: the secret in the ping URL + PolicyID string `json:"policyId"` // escalation policy for the alert it raises + Severity string `json:"severity"` // alert severity (default critical) + Public bool `json:"public"` // shown on the status page + AllowPrivate bool `json:"allowPrivate"` + Enabled bool `json:"enabled"` +} + +// MonitorState is what we know about a monitor right now. +type MonitorState struct { + MonitorID string `json:"monitorId"` + Status string `json:"status"` // pending, up, down + Since int64 `json:"since"` + LastCheck int64 `json:"lastCheck"` + LastMS int `json:"lastMs"` + Fails int `json:"fails"` + LastPing int64 `json:"lastPing"` + Detail string `json:"detail"` + Uptime30 float64 `json:"uptime30"` // percent of checks that passed in the retention window; -1 if none +} + +// interval is how often the monitor is checked. A heartbeat is evaluated often so +// a missed one is noticed soon after its deadline, not up to a whole interval later. +func (m *Monitor) interval() time.Duration { + if m.Kind == "heartbeat" { + return 15 * time.Second + } + if m.IntervalS < 10 { + return time.Minute + } + return time.Duration(m.IntervalS) * time.Second +} + +func (m *Monitor) timeout() time.Duration { + if m.TimeoutS <= 0 || m.TimeoutS > 120 { + return 10 * time.Second + } + return time.Duration(m.TimeoutS) * time.Second +} + +func (m *Monitor) retries() int { + if m.Retries < 1 { + return 2 + } + return m.Retries +} + +func validateMonitor(m *Monitor) error { + m.Name, m.Target = strings.TrimSpace(m.Name), strings.TrimSpace(m.Target) + if m.Name == "" { + return errors.New("give the monitor a name") + } + switch m.Kind { + case "http": + u, err := url.Parse(m.Target) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return errors.New("an http monitor needs an http:// or https:// URL") + } + case "tcp": + if _, _, err := net.SplitHostPort(m.Target); err != nil { + return errors.New("a tcp monitor needs host:port") + } + case "dns", "tls": + if m.Target == "" || strings.ContainsAny(m.Target, " /\\") { + return errors.New("enter a hostname") + } + case "heartbeat": + if m.IntervalS < 10 { + return errors.New("a heartbeat interval is at least 10 seconds") + } + if m.Token == "" { + m.Token = newToken() + } + default: + return errors.New("kind must be http, tcp, dns, tls or heartbeat") + } + if m.Severity == "" { + m.Severity = "critical" + } + if _, _, err := parseRange(m.Expect); err != nil { + return err + } + return nil +} + +// parseRange reads "200-299", "204" or "" (= 200-299). +func parseRange(s string) (lo, hi int, err error) { + s = strings.TrimSpace(s) + if s == "" { + return 200, 299, nil + } + a, b, found := strings.Cut(s, "-") + if lo, err = strconv.Atoi(strings.TrimSpace(a)); err != nil { + return 0, 0, errors.New(`expected status must look like "200-299" or "204"`) + } + hi = lo + if found { + if hi, err = strconv.Atoi(strings.TrimSpace(b)); err != nil || hi < lo { + return 0, 0, errors.New(`expected status must look like "200-299" or "204"`) + } + } + return lo, hi, nil +} + +// ---------- the checks ---------- + +// runCheck performs one probe and returns how long it took and an error if it failed. +func (s *Server) runCheck(ctx context.Context, m *Monitor) (time.Duration, error) { + ctx, cancel := context.WithTimeout(ctx, m.timeout()) + defer cancel() + start := time.Now() + var err error + switch m.Kind { + case "http": + err = s.checkHTTP(ctx, m) + case "tcp": + var c net.Conn + if c, err = netguard.DialContext(m.AllowPrivate)(ctx, "tcp", m.Target); err == nil { + c.Close() + } + case "dns": + var addrs []string + if addrs, err = net.DefaultResolver.LookupHost(ctx, m.Target); err == nil && len(addrs) == 0 { + err = errors.New("no addresses") + } + case "tls": + err = checkTLS(ctx, m, s.now()) + } + return time.Since(start), err +} + +func (s *Server) checkHTTP(ctx context.Context, m *Monitor) error { + req, err := http.NewRequestWithContext(ctx, "GET", m.Target, nil) + if err != nil { + return err + } + req.Header.Set("User-Agent", "Sandbar-Monitor/1") + c := *s.httpClient(m.AllowPrivate) + c.Timeout = 0 // the context carries the deadline + c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + resp, err := c.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + lo, hi, _ := parseRange(m.Expect) + if resp.StatusCode < lo || resp.StatusCode > hi { + return fmt.Errorf("status %d, expected %d-%d", resp.StatusCode, lo, hi) + } + if m.Keyword != "" { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if !strings.Contains(string(body), m.Keyword) { + return fmt.Errorf("the page doesn't contain %q", m.Keyword) + } + } + return nil +} + +func checkTLS(ctx context.Context, m *Monitor, now time.Time) error { + host, port, err := net.SplitHostPort(m.Target) + if err != nil { + host, port = m.Target, "443" + } + d := tls.Dialer{Config: &tls.Config{ServerName: host}} + conn, err := d.DialContext(ctx, "tcp", net.JoinHostPort(host, port)) + if err != nil { + return err + } + defer conn.Close() + certs := conn.(*tls.Conn).ConnectionState().PeerCertificates + if len(certs) == 0 { + return errors.New("no certificate") + } + warn := m.WarnDays + if warn <= 0 { + warn = 14 + } + left := certs[0].NotAfter.Sub(now) + if left < time.Duration(warn)*24*time.Hour { + return fmt.Errorf("the certificate expires in %d days (%s)", int(left.Hours()/24), certs[0].NotAfter.Format("2006-01-02")) + } + return nil +} + +// ---------- scheduling and state ---------- + +func (s *Server) monitorState(id string) MonitorState { + st := MonitorState{MonitorID: id, Status: "pending", Uptime30: -1} + s.st.db.QueryRow(`SELECT status,since,last_check,last_ms,fails,last_ping,detail FROM mstate WHERE monitor_id=?`, id). + Scan(&st.Status, &st.Since, &st.LastCheck, &st.LastMS, &st.Fails, &st.LastPing, &st.Detail) + var total, ok sql.NullInt64 + s.st.db.QueryRow(`SELECT COUNT(*), SUM(ok) FROM checks WHERE monitor_id=?`, id).Scan(&total, &ok) + if total.Int64 > 0 { + st.Uptime30 = float64(ok.Int64) * 100 / float64(total.Int64) + } + return st +} + +func (s *Server) saveState(st MonitorState) { + s.st.db.Exec(`INSERT INTO mstate(monitor_id,status,since,last_check,last_ms,fails,last_ping,detail) VALUES(?,?,?,?,?,?,?,?) + ON CONFLICT(monitor_id) DO UPDATE SET status=excluded.status, since=excluded.since, last_check=excluded.last_check, + last_ms=excluded.last_ms, fails=excluded.fails, last_ping=excluded.last_ping, detail=excluded.detail`, + st.MonitorID, st.Status, st.Since, st.LastCheck, st.LastMS, st.Fails, st.LastPing, st.Detail) +} + +// runDueMonitors starts a check for every enabled monitor whose interval has elapsed. +func (s *Server) runDueMonitors(now time.Time) { + mons, err := listOf[Monitor](s.st, "monitor") + if err != nil { + return + } + for i := range mons { + m := mons[i] + if !m.Enabled { + continue + } + st := s.monitorState(m.ID) + if now.Sub(time.Unix(st.LastCheck, 0)) < m.interval() { + continue + } + s.mu.Lock() + busy := s.running[m.ID] + s.running[m.ID] = true + s.mu.Unlock() + if busy { + continue + } + go func() { + defer func() { + s.mu.Lock() + delete(s.running, m.ID) + s.mu.Unlock() + }() + s.checkMonitor(&m, now) + }() + } +} + +// checkMonitor runs one probe (or evaluates a heartbeat) and moves state forward. +func (s *Server) checkMonitor(m *Monitor, now time.Time) { + st := s.monitorState(m.ID) + var dur time.Duration + var err error + if m.Kind == "heartbeat" { + if st.LastPing == 0 { + // Never pinged: give it a full interval from when we first looked. + if st.LastCheck == 0 { + st.LastCheck, st.Status = now.Unix(), "pending" + st.Since = now.Unix() + s.saveState(st) + return + } + if now.Unix()-st.Since < int64(m.IntervalS+m.GraceS) { + st.LastCheck = now.Unix() // still within the first interval: nothing to judge yet + s.saveState(st) + return + } + err = errors.New("no heartbeat received yet") + } else if now.Unix()-st.LastPing > int64(m.IntervalS+m.GraceS) { + err = fmt.Errorf("no heartbeat for %s", now.Sub(time.Unix(st.LastPing, 0)).Round(time.Second)) + } + } else { + dur, err = s.runCheck(context.Background(), m) + } + s.recordResult(m, st, now, dur, err) +} + +func (s *Server) recordResult(m *Monitor, st MonitorState, now time.Time, dur time.Duration, err error) { + ok := err == nil + okInt := 0 + if ok { + okInt = 1 + } + s.st.db.Exec(`INSERT INTO checks(monitor_id,time,ok,ms,detail) VALUES(?,?,?,?,?)`, m.ID, now.Unix(), okInt, dur.Milliseconds(), errText(err)) + st.LastCheck, st.LastMS, st.Detail = now.Unix(), int(dur.Milliseconds()), errText(err) + key := "monitor:" + m.ID + if ok { + wasDown := st.Status == "down" + if st.Status != "up" { + st.Status, st.Since = "up", now.Unix() + } + st.Fails = 0 + s.saveState(st) + if wasDown { + s.ResolveAlertKey(key, "monitor") + } + return + } + st.Fails++ + if st.Fails >= m.retries() && st.Status != "down" { + st.Status, st.Since = "down", now.Unix() + } + s.saveState(st) + if st.Status == "down" { + s.RaiseAlert(key, "monitor", m.Name+" is down", m.Name+" ("+m.Kind+" "+m.Target+"): "+st.Detail, m.Severity, m.PolicyID) + } +} + +func errText(err error) string { + if err == nil { + return "" + } + return err.Error() +} + +// Heartbeat records a ping for the monitor with this token. It returns false if there is none. +func (s *Server) Heartbeat(token string) bool { + if token == "" { + return false + } + mons, _ := listOf[Monitor](s.st, "monitor") + for i := range mons { + m := mons[i] + if m.Kind == "heartbeat" && m.Token == token && m.Enabled { + st := s.monitorState(m.ID) + st.LastPing = s.now().Unix() + if st.Since == 0 { + st.Since = st.LastPing + } + s.saveState(st) + // A ping on a down monitor recovers it at once rather than at the next check. + if st.Status == "down" { + s.recordResult(&m, st, s.now(), 0, nil) + } + return true + } + } + return false +} + +// deleteMonitorData drops what we keep about a monitor and closes its alert. +func (s *Server) deleteMonitorData(id string) { + s.st.db.Exec(`DELETE FROM mstate WHERE monitor_id=?`, id) + s.st.db.Exec(`DELETE FROM checks WHERE monitor_id=?`, id) + s.ResolveAlertKey("monitor:"+id, "monitor deleted") +} + +func (s *Server) recentChecks(id string, limit int) []map[string]any { + out := []map[string]any{} + rows, err := s.st.db.Query(`SELECT time,ok,ms,detail FROM checks WHERE monitor_id=? ORDER BY time DESC LIMIT ?`, id, limit) + if err != nil { + return out + } + defer rows.Close() + for rows.Next() { + var t, ok, ms int64 + var d string + if rows.Scan(&t, &ok, &ms, &d) == nil { + out = append(out, map[string]any{"time": t, "ok": ok == 1, "ms": ms, "detail": d}) + } + } + return out +} diff --git a/internal/sandbar/notify.go b/internal/sandbar/notify.go new file mode 100644 index 0000000..328c114 --- /dev/null +++ b/internal/sandbar/notify.go @@ -0,0 +1,342 @@ +package sandbar + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "log" + "net/http" + "net/smtp" + "net/url" + "regexp" + "strconv" + "strings" + "sync" + "time" + + "git.veillax.com/Veillax/reef/netguard" +) + +// Notify is the ntfy-shaped part: anything can publish a message to a topic with +// an HTTP request, and anything can subscribe to it (SSE, newline-delimited JSON, +// or the web UI). Alerts and incidents publish here too, so a phone with the ntfy +// app subscribed to "alerts" is a working pager with no other setup. + +type Message struct { + ID string `json:"id"` + Topic string `json:"topic"` + Time int64 `json:"time"` + Title string `json:"title,omitempty"` + Message string `json:"message"` + Priority int `json:"priority"` + Tags []string `json:"tags,omitempty"` +} + +var topicRe = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`) + +// reservedTopics are first path segments that belong to Sandbar itself. +var reservedTopics = map[string]bool{"api": true, "status": true, "hb": true, "metrics": true, "static": true, "healthz": true} + +func validTopic(t string) bool { return topicRe.MatchString(t) && !reservedTopics[t] } + +// hub fans published messages out to live subscribers. +type hub struct { + mu sync.Mutex + subs map[string]map[chan Message]bool +} + +func newHub() *hub { return &hub{subs: map[string]map[chan Message]bool{}} } + +func (h *hub) subscribe(topic string) (chan Message, func()) { + ch := make(chan Message, 64) + h.mu.Lock() + if h.subs[topic] == nil { + h.subs[topic] = map[chan Message]bool{} + } + h.subs[topic][ch] = true + h.mu.Unlock() + return ch, func() { + h.mu.Lock() + delete(h.subs[topic], ch) + h.mu.Unlock() + } +} + +func (h *hub) publish(m Message) { + h.mu.Lock() + defer h.mu.Unlock() + for ch := range h.subs[m.Topic] { + select { + case ch <- m: + default: // a stalled subscriber drops messages instead of blocking publishers + } + } +} + +func parsePriority(s string) int { + switch strings.ToLower(strings.TrimSpace(s)) { + case "5", "max", "urgent": + return 5 + case "4", "high": + return 4 + case "2", "low": + return 2 + case "1", "min": + return 1 + } + return 3 +} + +func parseTags(s string) []string { + var out []string + for _, t := range strings.Split(s, ",") { + if t = strings.TrimSpace(t); t != "" { + out = append(out, t) + } + } + return out +} + +// Publish stores a message and delivers it to live subscribers. +func (s *Server) Publish(topic, title, body string, prio int, tags []string) (Message, error) { + if !validTopic(topic) { + return Message{}, errors.New("a topic is 1-64 letters, digits, - or _") + } + m := Message{ID: newID(), Topic: topic, Time: s.now().Unix(), Title: title, Message: body, Priority: prio, Tags: tags} + tj, _ := json.Marshal(tags) + if _, err := s.st.db.Exec(`INSERT INTO messages(id,topic,time,title,body,priority,tags) VALUES(?,?,?,?,?,?,?)`, + m.ID, m.Topic, m.Time, m.Title, m.Message, m.Priority, string(tj)); err != nil { + return m, err + } + s.hub.publish(m) + return m, nil +} + +// MessagesSince returns stored messages for a topic after the given unix time, oldest first. +func (s *Server) MessagesSince(topic string, since int64, limit int) []Message { + out := []Message{} + rows, err := s.st.db.Query(`SELECT id,time,title,body,priority,tags FROM messages WHERE topic=? AND time>=? ORDER BY time, rowid LIMIT ?`, topic, since, limit) + if err != nil { + return out + } + defer rows.Close() + for rows.Next() { + m := Message{Topic: topic} + var tj string + if rows.Scan(&m.ID, &m.Time, &m.Title, &m.Message, &m.Priority, &tj) == nil { + json.Unmarshal([]byte(tj), &m.Tags) + out = append(out, m) + } + } + return out +} + +// ---------- outputs: email and webhooks ---------- + +// Channel is a place broadcast notifications go: an email address list or a webhook. +type Channel struct { + ID string `json:"id"` + Name string `json:"name"` + Kind string `json:"kind"` // "email" or "webhook" + Target string `json:"target"` // addresses, or a URL (secret: URLs often carry tokens) + Format string `json:"format"` // webhook body: json, slack, discord or ntfy + AllowPrivate bool `json:"allowPrivate"` + Enabled bool `json:"enabled"` +} + +// Note is what every notification is built from. +type Note struct { + Status string `json:"status"` // firing, resolved, acked, test, declared, update + Kind string `json:"kind"` // alert, monitor, incident + Title string `json:"title"` + Message string `json:"message"` + Severity string `json:"severity,omitempty"` + Link string `json:"link,omitempty"` + Time int64 `json:"time"` +} + +func (n Note) subject() string { + switch n.Status { + case "resolved": + return "[Sandbar] Resolved: " + n.Title + case "test": + return "[Sandbar] Test notification" + case "acked": + return "[Sandbar] Acknowledged: " + n.Title + } + return "[Sandbar] " + strings.ToUpper(n.Kind[:1]) + n.Kind[1:] + ": " + n.Title +} + +func (n Note) text() string { + if n.Status == "test" { + return "This is a test from Sandbar. If you can read this, the channel works." + } + t := n.Message + if n.Link != "" { + t += "\n" + n.Link + } + return t +} + +func (n Note) priority() int { + switch { + case n.Status == "resolved" || n.Status == "acked" || n.Status == "test": + return 3 + case n.Severity == "critical": + return 5 + } + return 4 +} + +func (n Note) tags() []string { + switch n.Status { + case "resolved": + return []string{"white_check_mark"} + case "acked": + return []string{"eyes"} + case "test": + return []string{"test_tube"} + } + return []string{"rotating_light"} +} + +func webhookBody(format string, n Note) (body []byte, ctype string, hdr map[string]string) { + text := n.subject() + "\n" + n.text() + switch format { + case "slack": + body, _ = json.Marshal(map[string]string{"text": text}) + case "discord": + body, _ = json.Marshal(map[string]string{"content": text}) + case "ntfy": + return []byte(n.text()), "text/plain", map[string]string{ + "Title": n.subject(), "Priority": strconv.Itoa(n.priority()), "Tags": strings.Join(n.tags(), ","), + } + default: + body, _ = json.Marshal(n) + } + return body, "application/json", nil +} + +func (s *Server) sendChannel(ch Channel, n Note) error { + switch ch.Kind { + case "email": + var errs []error + for _, to := range strings.Split(s.st.open(ch.Target), ",") { + if to = strings.TrimSpace(to); to != "" { + if err := s.Mail(to, n.subject(), n.text()); err != nil { + errs = append(errs, err) + } + } + } + return errors.Join(errs...) + case "webhook": + body, ctype, hdr := webhookBody(ch.Format, n) + req, err := http.NewRequest("POST", s.st.open(ch.Target), bytes.NewReader(body)) + if err != nil { + return err + } + req.Header.Set("Content-Type", ctype) + for k, v := range hdr { + req.Header.Set(k, v) + } + resp, err := s.httpClient(ch.AllowPrivate).Do(req) + if err != nil { + return err + } + resp.Body.Close() + if resp.StatusCode >= 300 { + return fmt.Errorf("the webhook answered %s", resp.Status) + } + return nil + } + return errors.New("unknown channel kind") +} + +func (s *Server) httpClient(allowPrivate bool) *http.Client { + if s.opts.HTTPClient != nil { + return s.opts.HTTPClient + } + c := netguard.Client(allowPrivate) + c.Timeout = 15 * time.Second + return c +} + +// Mail sends one plain-text email through the configured SMTP server. +func (s *Server) Mail(to, subject, body string) error { + if s.opts.Mailer != nil { + return s.opts.Mailer(to, subject, body) + } + c := s.opts.SMTP + if c.Host == "" { + return errors.New("no SMTP server configured (SANDBAR_SMTP_HOST)") + } + if strings.ContainsAny(to+subject, "\r\n") { + return errors.New("invalid header") + } + port := c.Port + if port == "" { + port = "587" + } + msg := "From: " + c.From + "\r\nTo: " + to + "\r\nSubject: " + subject + + "\r\nDate: " + s.now().Format(time.RFC1123Z) + "\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n" + body + "\r\n" + var auth smtp.Auth + if c.User != "" { + auth = smtp.PlainAuth("", c.User, c.Password, c.Host) + } + return smtp.SendMail(c.Host+":"+port, auth, c.From, []string{to}, []byte(msg)) +} + +// broadcast sends a note to the topic named by the source and every enabled channel. +func (s *Server) broadcast(n Note, topics ...string) { + for _, t := range topics { + if _, err := s.Publish(t, n.subject(), n.text(), n.priority(), n.tags()); err != nil { + log.Printf("publish %s: %v", t, err) + } + } + chans, _ := listOf[Channel](s.st, "channel") + for _, ch := range chans { + if !ch.Enabled { + continue + } + ch := ch + go func() { + if err := s.sendChannel(ch, n); err != nil { + log.Printf("channel %q: %v", ch.Name, err) + } + }() + } +} + +// validateChannel normalises ch. +func validateChannel(ch *Channel) error { + ch.Name = strings.TrimSpace(ch.Name) + ch.Target = strings.TrimSpace(ch.Target) + switch ch.Kind { + case "email": + for _, a := range strings.Split(ch.Target, ",") { + if a = strings.TrimSpace(a); !strings.Contains(a, "@") || strings.ContainsAny(a, " \r\n<>") { + return errors.New("enter one or more email addresses, separated by commas") + } + } + ch.Format, ch.AllowPrivate = "", false + case "webhook": + u, err := url.Parse(ch.Target) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return errors.New("the webhook must be an http:// or https:// URL") + } + switch ch.Format { + case "json", "slack", "discord", "ntfy": + case "": + ch.Format = "json" + default: + return errors.New("format must be json, slack, discord or ntfy") + } + default: + return errors.New("a channel is an email or a webhook") + } + if ch.Name == "" { + ch.Name = ch.Kind + } + return nil +} diff --git a/internal/sandbar/oncall.go b/internal/sandbar/oncall.go new file mode 100644 index 0000000..5c1a9a3 --- /dev/null +++ b/internal/sandbar/oncall.go @@ -0,0 +1,327 @@ +package sandbar + +import ( + "database/sql" + "errors" + "fmt" + "strings" + "time" +) + +// On-call: who is responsible right now, and what happens to an alert nobody has +// picked up. An alert follows its escalation policy, a list of steps, each of +// which waits a delay and then notifies people and/or whoever is on call for a +// schedule. Acknowledging or resolving the alert stops the walk. Alerts are kept +// in the database with the time the next step is due, so a restart neither loses +// nor repeats them. + +type Override struct { + UserID string `json:"userId"` + From int64 `json:"from"` + To int64 `json:"to"` +} + +// Schedule rotates through Members, handing over every RotationHours from Start. +type Schedule struct { + ID string `json:"id"` + Name string `json:"name"` + Members []string `json:"members"` // user ids, in rotation order + RotationHours int `json:"rotationHours"` + Start int64 `json:"start"` + Overrides []Override `json:"overrides"` +} + +// OnCall returns the user id on call at t, or "". +func (sc *Schedule) OnCall(t time.Time) string { + for i := len(sc.Overrides) - 1; i >= 0; i-- { + o := sc.Overrides[i] + if t.Unix() >= o.From && t.Unix() < o.To { + return o.UserID + } + } + if len(sc.Members) == 0 { + return "" + } + rot := int64(sc.RotationHours) * 3600 + if rot <= 0 { + return sc.Members[0] + } + elapsed := t.Unix() - sc.Start + if elapsed < 0 { + return sc.Members[0] + } + return sc.Members[(elapsed/rot)%int64(len(sc.Members))] +} + +type Step struct { + DelayMin int `json:"delayMin"` // wait this long after the previous step (0 = at once) + Users []string `json:"users"` + Schedules []string `json:"schedules"` +} + +type Policy struct { + ID string `json:"id"` + Name string `json:"name"` + Steps []Step `json:"steps"` + RepeatMin int `json:"repeatMin"` // after the last step, start over this many minutes later (0 = never) +} + +type Alert struct { + ID string `json:"id"` + Key string `json:"key"` + Source string `json:"source"` + Summary string `json:"summary"` + Detail string `json:"detail"` + Severity string `json:"severity"` // critical, warning, info + Status string `json:"status"` // firing, acked, resolved + PolicyID string `json:"policyId"` + Step int `json:"step"` + NextAt int64 `json:"nextAt"` + Created int64 `json:"created"` + Updated int64 `json:"updated"` + Count int `json:"count"` + AckedBy string `json:"ackedBy"` + AckedAt int64 `json:"ackedAt"` + SnoozeUntil int64 `json:"snoozeUntil"` + ResolvedAt int64 `json:"resolvedAt"` + IncidentID string `json:"incidentId"` + Timeline []Event `json:"timeline,omitempty"` +} + +const alertCols = `id,key,source,summary,detail,severity,status,policy_id,step,next_at,created,updated,count,acked_by,acked_at,snooze_until,resolved_at,incident_id` + +type scanner interface{ Scan(...any) error } + +func scanAlert(r scanner) (*Alert, error) { + var a Alert + err := r.Scan(&a.ID, &a.Key, &a.Source, &a.Summary, &a.Detail, &a.Severity, &a.Status, &a.PolicyID, &a.Step, &a.NextAt, + &a.Created, &a.Updated, &a.Count, &a.AckedBy, &a.AckedAt, &a.SnoozeUntil, &a.ResolvedAt, &a.IncidentID) + if errors.Is(err, sql.ErrNoRows) { + return nil, errNotFound + } + return &a, err +} + +func (s *Server) getAlert(id string) (*Alert, error) { + return scanAlert(s.st.db.QueryRow(`SELECT `+alertCols+` FROM alerts WHERE id=?`, id)) +} + +func (s *Server) listAlerts(status string, limit int) []Alert { + q := `SELECT ` + alertCols + ` FROM alerts` + var args []any + switch status { + case "open": + q += ` WHERE status IN ('firing','acked')` + case "firing", "acked", "resolved": + q += ` WHERE status=?` + args = append(args, status) + } + q += ` ORDER BY created DESC LIMIT ?` + args = append(args, limit) + out := []Alert{} + rows, err := s.st.db.Query(q, args...) + if err != nil { + return out + } + defer rows.Close() + for rows.Next() { + if a, err := scanAlert(rows); err == nil { + out = append(out, *a) + } + } + return out +} + +// RaiseAlert opens an alert for key, or bumps the open one with the same key +// (deduplication). It returns the alert and whether it is new. +func (s *Server) RaiseAlert(key, source, summary, detail, severity, policyID string) (*Alert, bool, error) { + now := s.now() + if severity == "" { + severity = "warning" + } + existing, err := scanAlert(s.st.db.QueryRow(`SELECT `+alertCols+` FROM alerts WHERE key=? AND status IN ('firing','acked') ORDER BY created DESC LIMIT 1`, key)) + if err == nil { + existing.Count++ + existing.Updated = now.Unix() + existing.Summary, existing.Detail = summary, detail + _, err := s.st.db.Exec(`UPDATE alerts SET count=?, updated=?, summary=?, detail=? WHERE id=?`, existing.Count, existing.Updated, summary, detail, existing.ID) + return existing, false, err + } + if !errors.Is(err, errNotFound) { + return nil, false, err + } + a := &Alert{ID: newID(), Key: key, Source: source, Summary: summary, Detail: detail, Severity: severity, Status: "firing", + PolicyID: policyID, NextAt: now.Unix(), Created: now.Unix(), Updated: now.Unix(), Count: 1} + if policyID == "" { + a.NextAt = 0 // nothing to escalate: it is only broadcast + } + _, err = s.st.db.Exec(`INSERT INTO alerts(`+alertCols+`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + a.ID, a.Key, a.Source, a.Summary, a.Detail, a.Severity, a.Status, a.PolicyID, a.Step, a.NextAt, a.Created, a.Updated, a.Count, + a.AckedBy, a.AckedAt, a.SnoozeUntil, a.ResolvedAt, a.IncidentID) + if err != nil { + return nil, false, err + } + s.st.addEvent("alert", a.ID, "created", source, summary, now) + s.broadcast(Note{Status: "firing", Kind: "alert", Title: summary, Message: s.alertText(a), Severity: severity, Link: s.link("/#alerts"), Time: now.Unix()}, "alerts") + return a, true, nil +} + +func (s *Server) alertText(a *Alert) string { + t := strings.ToUpper(a.Severity) + ": " + a.Summary + if a.Detail != "" { + t += "\n" + a.Detail + } + return t +} + +// ResolveAlertKey resolves the open alert for key, if any. +func (s *Server) ResolveAlertKey(key, actor string) { + var id string + if s.st.db.QueryRow(`SELECT id FROM alerts WHERE key=? AND status IN ('firing','acked') LIMIT 1`, key).Scan(&id) == nil { + s.ResolveAlert(id, actor) + } +} + +func (s *Server) ResolveAlert(id, actor string) error { + a, err := s.getAlert(id) + if err != nil { + return err + } + if a.Status == "resolved" { + return nil + } + now := s.now() + if _, err := s.st.db.Exec(`UPDATE alerts SET status='resolved', next_at=0, resolved_at=?, updated=? WHERE id=?`, now.Unix(), now.Unix(), id); err != nil { + return err + } + s.st.addEvent("alert", id, "resolved", actor, "resolved", now) + s.broadcast(Note{Status: "resolved", Kind: "alert", Title: a.Summary, Message: "Resolved: " + a.Summary, Severity: a.Severity, Link: s.link("/#alerts"), Time: now.Unix()}, "alerts") + return nil +} + +func (s *Server) AckAlert(id, actor string) error { + a, err := s.getAlert(id) + if err != nil { + return err + } + if a.Status != "firing" { + return errors.New("only a firing alert can be acknowledged") + } + now := s.now() + if _, err := s.st.db.Exec(`UPDATE alerts SET status='acked', next_at=0, acked_by=?, acked_at=?, updated=? WHERE id=?`, actor, now.Unix(), now.Unix(), id); err != nil { + return err + } + s.st.addEvent("alert", id, "acked", actor, "acknowledged", now) + s.broadcast(Note{Status: "acked", Kind: "alert", Title: a.Summary, Message: "Acknowledged by " + actor + ": " + a.Summary, Time: now.Unix()}, "alerts") + return nil +} + +// SnoozeAlert pauses escalation for d. When it ends the walk resumes at the step it was on. +func (s *Server) SnoozeAlert(id, actor string, d time.Duration) error { + a, err := s.getAlert(id) + if err != nil { + return err + } + if a.Status != "firing" { + return errors.New("only a firing alert can be snoozed") + } + until := s.now().Add(d).Unix() + if _, err := s.st.db.Exec(`UPDATE alerts SET next_at=?, snooze_until=? WHERE id=?`, until, until, id); err != nil { + return err + } + s.st.addEvent("alert", id, "snoozed", actor, "snoozed for "+d.String(), s.now()) + return nil +} + +// ---------- escalation ---------- + +// escalate runs every alert step that has come due. +func (s *Server) escalate(now time.Time) { + rows, err := s.st.db.Query(`SELECT id FROM alerts WHERE status='firing' AND next_at>0 AND next_at<=?`, now.Unix()) + if err != nil { + return + } + var ids []string + for rows.Next() { + var id string + if rows.Scan(&id) == nil { + ids = append(ids, id) + } + } + rows.Close() + for _, id := range ids { + s.runStep(id, now) + } +} + +func (s *Server) runStep(id string, now time.Time) { + a, err := s.getAlert(id) + if err != nil || a.Status != "firing" { + return + } + pol, err := getOf[Policy](s.st, "policy", a.PolicyID) + if err != nil || len(pol.Steps) == 0 { + s.st.db.Exec(`UPDATE alerts SET next_at=0 WHERE id=?`, id) // policy deleted: stop trying + s.st.addEvent("alert", id, "note", "sandbar", "its escalation policy is gone or empty", now) + return + } + if a.Step >= len(pol.Steps) { + a.Step = 0 + } + step := pol.Steps[a.Step] + var people []string + seen := map[string]bool{} + add := func(uid string) { + if uid != "" && !seen[uid] { + seen[uid] = true + people = append(people, uid) + } + } + for _, u := range step.Users { + add(u) + } + for _, scID := range step.Schedules { + if sc, err := getOf[Schedule](s.st, "schedule", scID); err == nil { + add(sc.OnCall(now)) + } + } + var names []string + for _, uid := range people { + if u, err := s.userByID(uid); err == nil { + s.notifyUser(u, Note{Status: "firing", Kind: "alert", Title: a.Summary, Message: s.alertText(a), Severity: a.Severity, + Link: s.link("/#alerts"), Time: now.Unix()}) + names = append(names, u.Name) + } + } + text := fmt.Sprintf("step %d: notified %s", a.Step+1, strings.Join(names, ", ")) + if len(names) == 0 { + text = fmt.Sprintf("step %d: nobody to notify (empty schedule or removed users)", a.Step+1) + } + s.st.addEvent("alert", id, "escalated", "sandbar", text, now) + + next := a.Step + 1 + var nextAt int64 + switch { + case next < len(pol.Steps): + nextAt = now.Add(time.Duration(pol.Steps[next].DelayMin) * time.Minute).Unix() + case pol.RepeatMin > 0: + next = 0 + nextAt = now.Add(time.Duration(pol.RepeatMin) * time.Minute).Unix() + } + s.st.db.Exec(`UPDATE alerts SET step=?, next_at=?, updated=? WHERE id=?`, next, nextAt, now.Unix(), id) +} + +// notifyUser reaches one person: a message on their personal topic (u-, which +// their phone subscribes to) and an email if the server can send mail. +func (s *Server) notifyUser(u *User, n Note) { + s.Publish(userTopic(u.ID), n.subject(), n.text(), n.priority(), n.tags()) + if u.Email != "" && (s.opts.SMTP.Host != "" || s.opts.Mailer != nil) { + go func() { + if err := s.Mail(u.Email, n.subject(), n.text()); err != nil { + s.st.addEvent("alert", "", "error", "sandbar", "email to "+u.Email+": "+err.Error(), s.now()) + } + }() + } +} + +func userTopic(id string) string { return "u-" + id } diff --git a/internal/sandbar/sandbar_test.go b/internal/sandbar/sandbar_test.go new file mode 100644 index 0000000..a58d204 --- /dev/null +++ b/internal/sandbar/sandbar_test.go @@ -0,0 +1,550 @@ +package sandbar + +import ( + "bufio" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "git.veillax.com/Veillax/reef/secretbox" +) + +type fakeClock struct { + mu sync.Mutex + t time.Time +} + +func (c *fakeClock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t } +func (c *fakeClock) Advance(d time.Duration) { + c.mu.Lock() + c.t = c.t.Add(d) + c.mu.Unlock() +} + +type mailLog struct { + mu sync.Mutex + sent []string +} + +func (m *mailLog) send(to, subject, body string) error { + m.mu.Lock() + m.sent = append(m.sent, to) + m.mu.Unlock() + return nil +} + +func (m *mailLog) to() []string { + m.mu.Lock() + defer m.mu.Unlock() + return append([]string(nil), m.sent...) +} + +func newTestServer(t *testing.T) (*Server, *fakeClock, *mailLog) { + t.Helper() + box, _ := secretbox.New(secretbox.GenerateKey()) + st, err := OpenStore(t.TempDir(), box) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { st.Close() }) + clk := &fakeClock{t: time.Date(2026, 1, 5, 9, 0, 0, 0, time.UTC)} + ml := &mailLog{} + return New(Options{Now: clk.Now, Mailer: ml.send, URL: "http://sandbar.test"}, st), clk, ml +} + +func mustUser(t *testing.T, s *Server, name string) *User { + t.Helper() + u, err := s.createUser(name, strings.ToLower(name)+"@example.com", "correct-horse-battery", "member", "") + if err != nil { + t.Fatal(err) + } + return u +} + +func TestScheduleRotationAndOverride(t *testing.T) { + start := time.Date(2026, 1, 5, 0, 0, 0, 0, time.UTC) + sc := &Schedule{Members: []string{"a", "b", "c"}, RotationHours: 24, Start: start.Unix()} + for day, want := range []string{"a", "b", "c", "a"} { + if got := sc.OnCall(start.Add(time.Duration(day)*24*time.Hour + time.Hour)); got != want { + t.Errorf("day %d: on call %q, want %q", day, got, want) + } + } + sc.Overrides = []Override{{UserID: "z", From: start.Add(2 * time.Hour).Unix(), To: start.Add(5 * time.Hour).Unix()}} + if got := sc.OnCall(start.Add(3 * time.Hour)); got != "z" { + t.Errorf("override: %q", got) + } + if got := sc.OnCall(start.Add(6 * time.Hour)); got != "a" { + t.Errorf("after override: %q", got) + } + if (&Schedule{}).OnCall(start) != "" { + t.Error("empty schedule should have nobody on call") + } +} + +func TestEscalationWalksStepsUntilAcked(t *testing.T) { + s, clk, mails := newTestServer(t) + alice, bob := mustUser(t, s, "Alice"), mustUser(t, s, "Bob") + s.st.put("schedule", "sch", &Schedule{ID: "sch", Name: "primary", Members: []string{alice.ID}, RotationHours: 24, Start: clk.Now().Unix()}) + s.st.put("policy", "pol", &Policy{ID: "pol", Name: "p", Steps: []Step{ + {Schedules: []string{"sch"}}, + {DelayMin: 5, Users: []string{bob.ID}}, + }}) + + a, isNew, err := s.RaiseAlert("k1", "test", "db down", "", "critical", "pol") + if err != nil || !isNew { + t.Fatalf("raise: %v new=%v", err, isNew) + } + s.escalate(clk.Now()) + if got := s.MessagesSince(userTopic(alice.ID), 0, 10); len(got) != 1 { + t.Fatalf("alice should be paged once, got %d", len(got)) + } + if len(s.MessagesSince(userTopic(bob.ID), 0, 10)) != 0 { + t.Fatal("bob must wait for step 2") + } + + clk.Advance(4 * time.Minute) + s.escalate(clk.Now()) + if len(s.MessagesSince(userTopic(bob.ID), 0, 10)) != 0 { + t.Fatal("step 2 fired early") + } + clk.Advance(2 * time.Minute) + s.escalate(clk.Now()) + if len(s.MessagesSince(userTopic(bob.ID), 0, 10)) != 1 { + t.Fatal("bob should be paged after the delay") + } + + // A second alert with the same key is deduplicated, not a new page. + b, isNew, _ := s.RaiseAlert("k1", "test", "db down", "still", "critical", "pol") + if isNew || b.ID != a.ID || b.Count != 2 { + t.Fatalf("dedupe: new=%v same=%v count=%d", isNew, b.ID == a.ID, b.Count) + } + + // Ack stops escalation entirely. + c, _, _ := s.RaiseAlert("k2", "test", "disk full", "", "warning", "pol") + s.escalate(clk.Now()) + if err := s.AckAlert(c.ID, "Alice"); err != nil { + t.Fatal(err) + } + clk.Advance(time.Hour) + before := len(s.MessagesSince(userTopic(bob.ID), 0, 50)) + s.escalate(clk.Now()) + if len(s.MessagesSince(userTopic(bob.ID), 0, 50)) != before { + t.Fatal("an acked alert kept escalating") + } + // Emails go out on a goroutine; give them a moment. + deadline := time.Now().Add(2 * time.Second) + for len(mails.to()) == 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if len(mails.to()) == 0 { + t.Fatal("expected email notifications to be sent") + } +} + +func TestSnoozeResumesAtSameStep(t *testing.T) { + s, clk, _ := newTestServer(t) + alice := mustUser(t, s, "Alice") + s.st.put("policy", "pol", &Policy{ID: "pol", Name: "p", Steps: []Step{{Users: []string{alice.ID}}}}) + a, _, _ := s.RaiseAlert("k", "test", "x", "", "info", "pol") + if err := s.SnoozeAlert(a.ID, "me", 30*time.Minute); err != nil { + t.Fatal(err) + } + s.escalate(clk.Now()) + if len(s.MessagesSince(userTopic(alice.ID), 0, 10)) != 0 { + t.Fatal("snoozed alert paged") + } + clk.Advance(31 * time.Minute) + s.escalate(clk.Now()) + if len(s.MessagesSince(userTopic(alice.ID), 0, 10)) != 1 { + t.Fatal("alert should page when the snooze ends") + } +} + +func TestMonitorHTTPDownAndRecover(t *testing.T) { + s, clk, _ := newTestServer(t) + var mu sync.Mutex + status := 200 + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + w.WriteHeader(status) + io.WriteString(w, "hello world") + })) + defer backend.Close() + m := &Monitor{ID: "m1", Name: "web", Kind: "http", Target: backend.URL, IntervalS: 30, Retries: 2, Enabled: true, AllowPrivate: true, Keyword: "hello"} + if err := validateMonitor(m); err != nil { + t.Fatal(err) + } + s.st.put("monitor", m.ID, m) + + step := func() { s.checkMonitor(m, clk.Now()); clk.Advance(30 * time.Second) } + setStatus := func(v int) { mu.Lock(); status = v; mu.Unlock() } + + step() + if st := s.monitorState("m1"); st.Status != "up" { + t.Fatalf("want up, got %s (%s)", st.Status, st.Detail) + } + setStatus(500) + step() + if st := s.monitorState("m1"); st.Status != "up" || st.Fails != 1 { + t.Fatalf("one failure must not flip it: %+v", st) + } + step() + if st := s.monitorState("m1"); st.Status != "down" { + t.Fatalf("want down after retries, got %+v", st) + } + if open := s.listAlerts("open", 10); len(open) != 1 || !strings.Contains(open[0].Summary, "web is down") { + t.Fatalf("expected one open alert, got %+v", open) + } + step() // still down: same alert, not a second one + if open := s.listAlerts("open", 10); len(open) != 1 { + t.Fatalf("alert duplicated: %d", len(open)) + } + setStatus(200) + step() + if st := s.monitorState("m1"); st.Status != "up" { + t.Fatalf("want recovered, got %+v", st) + } + if open := s.listAlerts("open", 10); len(open) != 0 { + t.Fatalf("alert should have resolved: %+v", open) + } + if up := s.monitorState("m1").Uptime30; up <= 0 || up >= 100 { + t.Fatalf("uptime should reflect the outage, got %v", up) + } +} + +func TestMonitorBlocksPrivateTargetsByDefault(t *testing.T) { + s, _, _ := newTestServer(t) + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer backend.Close() + m := &Monitor{Name: "x", Kind: "http", Target: backend.URL} + if _, err := s.runCheck(context.Background(), m); err == nil { + t.Fatal("a loopback target must be refused unless allowPrivate is set") + } +} + +func TestHeartbeatMissed(t *testing.T) { + s, clk, _ := newTestServer(t) + m := &Monitor{ID: "hb", Name: "backup", Kind: "heartbeat", IntervalS: 60, GraceS: 10, Enabled: true} + if err := validateMonitor(m); err != nil { + t.Fatal(err) + } + s.st.put("monitor", m.ID, m) + s.checkMonitor(m, clk.Now()) // first look: starts the clock + if s.monitorState("hb").Status != "pending" { + t.Fatal("a heartbeat that was never expected yet should be pending") + } + clk.Advance(30 * time.Second) + if !s.Heartbeat(m.Token) { + t.Fatal("ping rejected") + } + s.checkMonitor(m, clk.Now()) + if s.monitorState("hb").Status != "up" { + t.Fatal("want up after a ping") + } + clk.Advance(2 * time.Minute) + for i := 0; i < 2; i++ { + s.checkMonitor(m, clk.Now()) + clk.Advance(15 * time.Second) + } + if s.monitorState("hb").Status != "down" { + t.Fatalf("missed heartbeat should be down: %+v", s.monitorState("hb")) + } + if !s.Heartbeat(m.Token) { + t.Fatal("ping rejected") + } + if s.monitorState("hb").Status != "up" || len(s.listAlerts("open", 10)) != 0 { + t.Fatal("a ping should recover a down heartbeat immediately") + } + if s.Heartbeat("nope") { + t.Fatal("unknown token accepted") + } +} + +func TestIncidentLifecycle(t *testing.T) { + s, _, _ := newTestServer(t) + u := mustUser(t, s, "Alice") + a, _, _ := s.RaiseAlert("k", "t", "api 500s", "", "critical", "") + in, err := s.DeclareIncident("API outage", "sev1", "errors everywhere", u.ID, u.Name, []string{a.ID}) + if err != nil { + t.Fatal(err) + } + if got, _ := s.getAlert(a.ID); got.IncidentID != in.ID { + t.Fatal("alert not linked") + } + st := "identified" + if _, err := s.UpdateIncident(in.ID, u.Name, IncidentPatch{Status: &st, Note: "bad deploy"}); err != nil { + t.Fatal(err) + } + bogus := "exploding" + if _, err := s.UpdateIncident(in.ID, u.Name, IncidentPatch{Status: &bogus}); err == nil { + t.Fatal("invalid status accepted") + } + done := "resolved" + got, _ := s.UpdateIncident(in.ID, u.Name, IncidentPatch{Status: &done}) + if got.Resolved == 0 { + t.Fatal("resolved time not set") + } + s.CommentIncident(in.ID, u.Name, "rolled back") + ev := s.st.events("incident", in.ID) + if len(ev) < 4 { + t.Fatalf("timeline too short: %+v", ev) + } + if tpl := s.postmortemTemplate(got); !strings.Contains(tpl, "rolled back") || !strings.Contains(tpl, "API outage") { + t.Fatalf("template missing content:\n%s", tpl) + } + if n := len(s.MessagesSince("incidents", 0, 10)); n != 3 { + t.Fatalf("expected declare + 2 updates on the incidents topic, got %d", n) + } +} + +func TestChannelSecretsAreSealedAndRedacted(t *testing.T) { + s, _, _ := newTestServer(t) + ts := httptest.NewServer(s.Handler()) + defer ts.Close() + c := newAPIClient(t, ts) + c.setup() + var created map[string]any + c.do("POST", "/api/v1/channels", map[string]any{"name": "slack", "kind": "webhook", "target": "https://hooks.example.com/secret-token", "format": "slack", "enabled": true}, &created) + var raw string + s.st.db.QueryRow(`SELECT body FROM docs WHERE kind='channel'`).Scan(&raw) + if strings.Contains(raw, "secret-token") { + t.Fatal("webhook URL stored in clear text") + } + if created["target"] == "https://hooks.example.com/secret-token" { + t.Fatal("the API returned the secret") + } + // Editing without touching the target keeps the stored secret. + created["name"] = "slack2" + c.do("PUT", "/api/v1/channels/"+created["id"].(string), created, nil) + ch, _ := getOf[Channel](s.st, "channel", created["id"].(string)) + if s.st.open(ch.Target) != "https://hooks.example.com/secret-token" || ch.Name != "slack2" { + t.Fatalf("secret lost on edit: %+v", ch) + } +} + +// ---------- HTTP API end to end ---------- + +type apiClient struct { + t *testing.T + ts *httptest.Server + cookie *http.Cookie +} + +func newAPIClient(t *testing.T, ts *httptest.Server) *apiClient { return &apiClient{t: t, ts: ts} } + +func (c *apiClient) req(method, path string, body any, headers map[string]string) *http.Response { + c.t.Helper() + var rd io.Reader + if body != nil { + b, _ := json.Marshal(body) + rd = strings.NewReader(string(b)) + } + r, _ := http.NewRequest(method, c.ts.URL+path, rd) + if body != nil || method != "GET" { + r.Header.Set("Content-Type", "application/json") + } + if c.cookie != nil { + r.AddCookie(c.cookie) + } + for k, v := range headers { + r.Header.Set(k, v) + } + resp, err := http.DefaultClient.Do(r) + if err != nil { + c.t.Fatal(err) + } + return resp +} + +func (c *apiClient) do(method, path string, body any, out any) int { + c.t.Helper() + resp := c.req(method, path, body, nil) + defer resp.Body.Close() + if out != nil { + json.NewDecoder(resp.Body).Decode(out) + } + return resp.StatusCode +} + +func (c *apiClient) setup() { + c.t.Helper() + resp := c.req("POST", "/api/v1/setup", map[string]string{"name": "Root", "email": "root@example.com", "password": "correct-horse-battery"}, nil) + defer resp.Body.Close() + if resp.StatusCode != 200 { + c.t.Fatalf("setup: %d", resp.StatusCode) + } + for _, ck := range resp.Cookies() { + if ck.Name == sessionCookie { + c.cookie = ck + } + } + if c.cookie == nil { + c.t.Fatal("no session cookie") + } +} + +func TestAPIAuthSetupAndTopics(t *testing.T) { + s, _, _ := newTestServer(t) + ts := httptest.NewServer(s.Handler()) + defer ts.Close() + c := newAPIClient(t, ts) + + if code := c.do("GET", "/api/v1/alerts", nil, nil); code != 401 { + t.Fatalf("unauthenticated API call: %d", code) + } + if code := c.do("POST", "/mytopic", nil, nil); code != 401 { + t.Fatalf("unauthenticated publish: %d", code) + } + c.setup() + if code := c.do("POST", "/api/v1/setup", map[string]string{"name": "x", "email": "x@x.com", "password": "correct-horse-battery"}, nil); code != 403 { + t.Fatalf("second setup must be refused, got %d", code) + } + + var key map[string]string + c.do("POST", "/api/v1/apikeys", map[string]string{"name": "ci"}, &key) + if !strings.HasPrefix(key["token"], "sb_") { + t.Fatalf("api key: %v", key) + } + bearer := map[string]string{"Authorization": "Bearer " + key["token"]} + + // Subscribe with the API key, then publish ntfy-style with headers. + sub := make(chan string, 4) + go func() { + req, _ := http.NewRequest("GET", ts.URL+"/alerts-room/sse", nil) + req.Header.Set("Authorization", "Bearer "+key["token"]) + resp, err := http.DefaultClient.Do(req) + if err != nil { + return + } + defer resp.Body.Close() + sc := bufio.NewScanner(resp.Body) + for sc.Scan() { + if strings.HasPrefix(sc.Text(), "data: ") { + sub <- sc.Text()[6:] + return + } + } + }() + time.Sleep(300 * time.Millisecond) + r, _ := http.NewRequest("POST", ts.URL+"/alerts-room", strings.NewReader("disk is full")) + r.Header.Set("Authorization", "Bearer "+key["token"]) + r.Header.Set("Title", "Disk") + r.Header.Set("Priority", "urgent") + r.Header.Set("Tags", "warning,disk") + resp, err := http.DefaultClient.Do(r) + if err != nil || resp.StatusCode != 200 { + t.Fatalf("publish: %v %v", err, resp) + } + select { + case line := <-sub: + var m Message + json.Unmarshal([]byte(line), &m) + if m.Message != "disk is full" || m.Title != "Disk" || m.Priority != 5 || len(m.Tags) != 2 { + t.Fatalf("bad message: %+v", m) + } + case <-time.After(3 * time.Second): + t.Fatal("subscriber got nothing") + } + + // Reserved topics are refused. + for _, reserved := range []string{"/api", "/status"} { + r, _ := http.NewRequest("POST", ts.URL+reserved, strings.NewReader("x")) + r.Header.Set("Authorization", "Bearer "+key["token"]) + resp, _ := http.DefaultClient.Do(r) + if resp.StatusCode == 200 { + t.Errorf("publish to %s should not succeed", reserved) + } + } + + // Inbound alert -> ack -> resolve over the API with the key. + var out map[string]any + c.cookie = nil + if code := c.do("POST", "/api/v1/alerts", map[string]string{"key": "cpu", "summary": "CPU high"}, nil); code != 401 { + t.Fatalf("alert without credentials: %d", code) + } + resp = c.req("POST", "/api/v1/alerts", map[string]string{"key": "cpu", "summary": "CPU high", "severity": "warning"}, bearer) + json.NewDecoder(resp.Body).Decode(&out) + resp.Body.Close() + id, _ := out["id"].(string) + if id == "" { + t.Fatalf("no alert id: %v", out) + } + c.req("POST", "/api/v1/alerts/"+id+"/ack", nil, bearer).Body.Close() + a, _ := s.getAlert(id) + if a.Status != "acked" || a.AckedBy != "Root" { + t.Fatalf("ack: %+v", a) + } + c.req("POST", "/api/v1/alerts", map[string]string{"key": "cpu", "status": "resolved"}, bearer).Body.Close() + if a, _ = s.getAlert(id); a.Status != "resolved" { + t.Fatalf("resolve via key: %+v", a) + } +} + +func TestAlertmanagerWebhook(t *testing.T) { + s, _, _ := newTestServer(t) + ts := httptest.NewServer(s.Handler()) + defer ts.Close() + c := newAPIClient(t, ts) + c.setup() + payload := map[string]any{"alerts": []map[string]any{{"status": "firing", "fingerprint": "abc", + "labels": map[string]string{"alertname": "HighLatency", "severity": "critical"}, "annotations": map[string]string{"summary": "p99 > 2s"}}}} + c.do("POST", "/api/v1/integrations/alertmanager", payload, nil) + open := s.listAlerts("open", 10) + if len(open) != 1 || open[0].Summary != "p99 > 2s" || open[0].Severity != "critical" { + t.Fatalf("got %+v", open) + } + payload["alerts"].([]map[string]any)[0]["status"] = "resolved" + c.do("POST", "/api/v1/integrations/alertmanager", payload, nil) + if len(s.listAlerts("open", 10)) != 0 { + t.Fatal("not resolved") + } +} + +func TestStatusPageOnlyShowsPublic(t *testing.T) { + s, clk, _ := newTestServer(t) + s.st.put("monitor", "a", &Monitor{ID: "a", Name: "Public site", Kind: "http", Target: "http://x", Enabled: true, Public: true}) + s.st.put("monitor", "b", &Monitor{ID: "b", Name: "Internal DB", Kind: "tcp", Target: "x:1", Enabled: true}) + s.saveState(MonitorState{MonitorID: "a", Status: "up", Since: clk.Now().Unix()}) + s.st.put("incident", "i1", &Incident{ID: "i1", Title: "Public incident", Severity: "sev2", Status: "investigating", Public: true, Created: clk.Now().Unix()}) + s.st.put("incident", "i2", &Incident{ID: "i2", Title: "Private incident", Severity: "sev1", Status: "investigating", Created: clk.Now().Unix()}) + ts := httptest.NewServer(s.Handler()) + defer ts.Close() + resp, _ := http.Get(ts.URL + "/status.json") + b, _ := io.ReadAll(resp.Body) + body := string(b) + if !strings.Contains(body, "Public site") || strings.Contains(body, "Internal DB") { + t.Fatalf("monitor visibility wrong: %s", body) + } + if !strings.Contains(body, "Public incident") || strings.Contains(body, "Private incident") { + t.Fatalf("incident visibility wrong: %s", body) + } + if !strings.Contains(body, `"overall":"degraded"`) { + t.Fatalf("overall: %s", body) + } +} + +func TestLoginThrottle(t *testing.T) { + s, _, _ := newTestServer(t) + mustUser(t, s, "Alice") + ts := httptest.NewServer(s.Handler()) + defer ts.Close() + c := newAPIClient(t, ts) + var last int + for i := 0; i < 12; i++ { + last = c.do("POST", "/api/v1/login", map[string]string{"email": "alice@example.com", "password": "wrong-password-x"}, nil) + } + if last != 429 { + t.Fatalf("expected throttling after repeated failures, got %d", last) + } + // Even the right password is refused while throttled. + if code := c.do("POST", "/api/v1/login", map[string]string{"email": "alice@example.com", "password": "correct-horse-battery"}, nil); code != 429 { + t.Fatalf("throttle should apply to the right password too, got %d", code) + } +} diff --git a/internal/sandbar/server.go b/internal/sandbar/server.go new file mode 100644 index 0000000..b660441 --- /dev/null +++ b/internal/sandbar/server.go @@ -0,0 +1,119 @@ +package sandbar + +import ( + _ "embed" + "log" + "net/http" + "sync" + "time" +) + +//go:embed web/index.html +var indexHTML []byte + +//go:embed web/status.html +var statusHTML []byte + +type SMTPConfig struct{ Host, Port, User, Password, From string } + +// Options configures a Server. Zero values are sensible defaults. +type Options struct { + DataDir string + URL string // public URL, used for links in notifications + MasterKey string + MetricsToken string + SMTP SMTPConfig + MessageDays int // how long topic messages are kept (default 30) + CheckDays int // how long monitor results are kept (default 30) + + // Tests replace these. + Now func() time.Time + HTTPClient *http.Client + Mailer func(to, subject, body string) error +} + +type Server struct { + opts Options + st *Store + hub *hub + + // monitor runtime state + mu sync.Mutex + running map[string]bool // monitor ids with a check in flight + + loginMu sync.Mutex + loginTry map[string][]time.Time + + stop chan struct{} + wg sync.WaitGroup +} + +func New(opts Options, st *Store) *Server { + if opts.MessageDays <= 0 { + opts.MessageDays = 30 + } + if opts.CheckDays <= 0 { + opts.CheckDays = 30 + } + return &Server{opts: opts, st: st, hub: newHub(), running: map[string]bool{}, loginTry: map[string][]time.Time{}, stop: make(chan struct{})} +} + +func (s *Server) now() time.Time { + if s.opts.Now != nil { + return s.opts.Now() + } + return time.Now() +} + +// Start runs the background workers: monitor scheduler, escalation, pruning. +func (s *Server) Start() { + s.every(time.Second, func() { s.runDueMonitors(s.now()) }) + s.every(5*time.Second, func() { s.escalate(s.now()) }) + s.every(time.Hour, func() { s.st.prune(s.now(), s.opts.MessageDays, s.opts.CheckDays) }) +} + +func (s *Server) Close() { + close(s.stop) + s.wg.Wait() +} + +func (s *Server) every(d time.Duration, f func()) { + s.wg.Add(1) + go func() { + defer s.wg.Done() + t := time.NewTicker(d) + defer t.Stop() + for { + select { + case <-s.stop: + return + case <-t.C: + func() { + defer func() { + if r := recover(); r != nil { + log.Printf("worker panic: %v", r) + } + }() + f() + }() + } + } + }() +} + +func (s *Server) link(path string) string { + if s.opts.URL == "" { + return "" + } + return s.opts.URL + path +} + +// BootstrapAdmin creates the first administrator from the environment when there are no users yet. +func (s *Server) BootstrapAdmin(email, password string) { + if email == "" || password == "" || s.countUsers() > 0 { + return + } + if _, err := s.createUser("Admin", email, password, "admin", ""); err != nil { + log.Printf("SANDBAR_ADMIN_EMAIL: %v", err) + } +} diff --git a/internal/sandbar/store.go b/internal/sandbar/store.go new file mode 100644 index 0000000..5fb75c5 --- /dev/null +++ b/internal/sandbar/store.go @@ -0,0 +1,239 @@ +package sandbar + +import ( + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "os" + "path/filepath" + "time" + + "git.veillax.com/Veillax/reef/secretbox" + _ "modernc.org/sqlite" +) + +// Store is Sandbar's one SQLite file (pure Go, WAL mode). Configuration that is +// edited by hand and rarely queried (channels, monitors, schedules, policies, +// incidents) is kept as JSON documents in one table; things that grow or are +// searched (messages, checks, alerts, timeline events) have proper indexed tables. +type Store struct { + db *sql.DB + box *secretbox.Box +} + +var errNotFound = errors.New("not found") + +const schema = ` +CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE COLLATE NOCASE, + hash TEXT NOT NULL, role TEXT NOT NULL, phone TEXT NOT NULL DEFAULT '', created INTEGER NOT NULL); +CREATE TABLE IF NOT EXISTS sessions ( + hash TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, expires INTEGER NOT NULL); +CREATE TABLE IF NOT EXISTS apikeys ( + id TEXT PRIMARY KEY, name TEXT NOT NULL, hash TEXT NOT NULL UNIQUE, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, created INTEGER NOT NULL); +CREATE TABLE IF NOT EXISTS docs ( + kind TEXT NOT NULL, id TEXT NOT NULL, body TEXT NOT NULL, PRIMARY KEY (kind, id)); +CREATE TABLE IF NOT EXISTS messages ( + id TEXT PRIMARY KEY, topic TEXT NOT NULL, time INTEGER NOT NULL, title TEXT NOT NULL, + body TEXT NOT NULL, priority INTEGER NOT NULL, tags TEXT NOT NULL); +CREATE INDEX IF NOT EXISTS messages_topic ON messages(topic, time); +CREATE TABLE IF NOT EXISTS checks ( + monitor_id TEXT NOT NULL, time INTEGER NOT NULL, ok INTEGER NOT NULL, ms INTEGER NOT NULL, detail TEXT NOT NULL); +CREATE INDEX IF NOT EXISTS checks_monitor ON checks(monitor_id, time); +CREATE TABLE IF NOT EXISTS mstate ( + monitor_id TEXT PRIMARY KEY, status TEXT NOT NULL, since INTEGER NOT NULL, last_check INTEGER NOT NULL, + last_ms INTEGER NOT NULL, fails INTEGER NOT NULL, last_ping INTEGER NOT NULL, detail TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS alerts ( + id TEXT PRIMARY KEY, key TEXT NOT NULL, source TEXT NOT NULL, summary TEXT NOT NULL, detail TEXT NOT NULL, + severity TEXT NOT NULL, status TEXT NOT NULL, policy_id TEXT NOT NULL, step INTEGER NOT NULL, + next_at INTEGER NOT NULL, created INTEGER NOT NULL, updated INTEGER NOT NULL, count INTEGER NOT NULL, + acked_by TEXT NOT NULL DEFAULT '', acked_at INTEGER NOT NULL DEFAULT 0, snooze_until INTEGER NOT NULL DEFAULT 0, + resolved_at INTEGER NOT NULL DEFAULT 0, incident_id TEXT NOT NULL DEFAULT ''); +CREATE INDEX IF NOT EXISTS alerts_key ON alerts(key, status); +CREATE INDEX IF NOT EXISTS alerts_due ON alerts(status, next_at); +CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, scope TEXT NOT NULL, ref TEXT NOT NULL, time INTEGER NOT NULL, + kind TEXT NOT NULL, actor TEXT NOT NULL, text TEXT NOT NULL); +CREATE INDEX IF NOT EXISTS events_ref ON events(scope, ref, time); +` + +// OpenStore opens (creating if needed) the database in dir. +func OpenStore(dir string, box *secretbox.Box) (*Store, error) { + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, err + } + dsn := "file:" + filepath.ToSlash(filepath.Join(dir, "sandbar.db")) + + "?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_pragma=foreign_keys(1)&_pragma=synchronous(NORMAL)" + db, err := sql.Open("sqlite", dsn) + if err != nil { + return nil, err + } + db.SetMaxOpenConns(4) + if _, err := db.Exec(schema); err != nil { + db.Close() + return nil, err + } + return &Store{db: db, box: box}, nil +} + +func (s *Store) Close() error { return s.db.Close() } + +// ---------- ids and tokens ---------- + +func newID() string { + b := make([]byte, 9) + rand.Read(b) + return hex.EncodeToString(b) +} + +func newToken() string { + b := make([]byte, 32) + rand.Read(b) + return base64.RawURLEncoding.EncodeToString(b) +} + +func hashToken(t string) string { + sum := sha256.Sum256([]byte(t)) + return hex.EncodeToString(sum[:]) +} + +// ---------- JSON documents ---------- + +func (s *Store) put(kind, id string, v any) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + _, err = s.db.Exec(`INSERT INTO docs(kind,id,body) VALUES(?,?,?) ON CONFLICT(kind,id) DO UPDATE SET body=excluded.body`, kind, id, string(b)) + return err +} + +func (s *Store) get(kind, id string, v any) error { + var body string + err := s.db.QueryRow(`SELECT body FROM docs WHERE kind=? AND id=?`, kind, id).Scan(&body) + if errors.Is(err, sql.ErrNoRows) { + return errNotFound + } + if err != nil { + return err + } + return json.Unmarshal([]byte(body), v) +} + +// list decodes every document of a kind through add, which is called with a +// fresh pointer-to-value from newItem and then appended by the caller. +func (s *Store) list(kind string, each func(raw []byte) error) error { + rows, err := s.db.Query(`SELECT body FROM docs WHERE kind=? ORDER BY id`, kind) + if err != nil { + return err + } + var bodies []string + for rows.Next() { + var b string + if err := rows.Scan(&b); err != nil { + rows.Close() + return err + } + bodies = append(bodies, b) + } + rows.Close() + for _, b := range bodies { + if err := each([]byte(b)); err != nil { + return err + } + } + return nil +} + +func (s *Store) del(kind, id string) error { + res, err := s.db.Exec(`DELETE FROM docs WHERE kind=? AND id=?`, kind, id) + if err != nil { + return err + } + if n, _ := res.RowsAffected(); n == 0 { + return errNotFound + } + return nil +} + +func listOf[T any](s *Store, kind string) ([]T, error) { + out := []T{} + err := s.list(kind, func(raw []byte) error { + var v T + if err := json.Unmarshal(raw, &v); err != nil { + return err + } + out = append(out, v) + return nil + }) + return out, err +} + +func getOf[T any](s *Store, kind, id string) (*T, error) { + var v T + if err := s.get(kind, id, &v); err != nil { + return nil, err + } + return &v, nil +} + +// seal and open wrap secretbox so callers don't repeat the nil check. +func (s *Store) seal(v string) string { + if s.box == nil || v == "" { + return v + } + return s.box.Seal(v) +} + +func (s *Store) open(v string) string { + if s.box == nil { + return v + } + out, err := s.box.Open(v) + if err != nil { + return "" + } + return out +} + +// ---------- timeline events ---------- + +func (s *Store) addEvent(scope, ref, kind, actor, text string, at time.Time) { + s.db.Exec(`INSERT INTO events(scope,ref,time,kind,actor,text) VALUES(?,?,?,?,?,?)`, scope, ref, at.Unix(), kind, actor, text) +} + +type Event struct { + Time int64 `json:"time"` + Kind string `json:"kind"` + Actor string `json:"actor"` + Text string `json:"text"` +} + +func (s *Store) events(scope, ref string) []Event { + out := []Event{} + rows, err := s.db.Query(`SELECT time,kind,actor,text FROM events WHERE scope=? AND ref=? ORDER BY time, id`, scope, ref) + if err != nil { + return out + } + defer rows.Close() + for rows.Next() { + var e Event + if rows.Scan(&e.Time, &e.Kind, &e.Actor, &e.Text) == nil { + out = append(out, e) + } + } + return out +} + +// prune deletes data past its retention. +func (s *Store) prune(now time.Time, messageDays, checkDays int) { + s.db.Exec(`DELETE FROM messages WHERE time < ?`, now.AddDate(0, 0, -messageDays).Unix()) + s.db.Exec(`DELETE FROM checks WHERE time < ?`, now.AddDate(0, 0, -checkDays).Unix()) + s.db.Exec(`DELETE FROM sessions WHERE expires < ?`, now.Unix()) + s.db.Exec(`DELETE FROM alerts WHERE status='resolved' AND resolved_at < ? AND incident_id=''`, now.AddDate(0, 0, -90).Unix()) +} diff --git a/internal/sandbar/web/index.html b/internal/sandbar/web/index.html new file mode 100644 index 0000000..0b8eea3 --- /dev/null +++ b/internal/sandbar/web/index.html @@ -0,0 +1,775 @@ + + + + + + +Sandbar + + + +
+ + + diff --git a/internal/sandbar/web/status.html b/internal/sandbar/web/status.html new file mode 100644 index 0000000..6c7aca3 --- /dev/null +++ b/internal/sandbar/web/status.html @@ -0,0 +1,104 @@ + + + + + + +Status + + + +
+

Status

+ +

Services

+
+

Incidents

+
+
+ + + diff --git a/scripts/lint-design.mjs b/scripts/lint-design.mjs new file mode 100644 index 0000000..20e09c0 --- /dev/null +++ b/scripts/lint-design.mjs @@ -0,0 +1,57 @@ +// Style gate for the dashboard, following the Lightwell design language (see docs/design.md). +// Fails on em or en dashes, emoji, exclamation marks in interface copy, and raw colors outside the +// token block of web/index.html. Run with: node scripts/lint-design.mjs +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { extname, join, relative, sep } from "node:path"; + +const root = new URL("..", import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1"); +const targets = ["internal/sandbar/web", "internal/sandbar", "docs", "README.md", "scripts", "cmd", "."]; +const skipDirs = new Set(["node_modules", ".git"]); +const exts = new Set([".html", ".md", ".go", ".sh", ".mjs", ".example"]); + +const dash = /[–—−]/; +const emoji = /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}\u{1F900}-\u{1F9FF}\u{FE0F}\u{2B50}\u{2705}\u{274C}]/u; +const rawColor = /#[0-9a-fA-F]{3,8}\b|\brgba?\(|\bhsla?\(/; + +const seen = new Set(); +function* walk(p, top) { + const st = statSync(p, { throwIfNoEntry: false }); + if (!st || seen.has(p)) return; + if (st.isFile()) { seen.add(p); return yield p; } + for (const name of readdirSync(p)) { + if (skipDirs.has(name) || (top && name.startsWith("."))) continue; + const full = join(p, name); + // the "." target only contributes the files at the top level + if (p === root && statSync(full).isDirectory()) continue; + yield* walk(full, false); + } +} + +const problems = []; +for (const t of targets) { + for (const file of walk(join(root, t), true)) { + if (!exts.has(extname(file)) && !file.endsWith(".env.example")) continue; + const rel = relative(root, file).split(sep).join("/"); + if (rel.endsWith("go.sum") || rel === "scripts/lint-design.mjs") continue; + const isPage = rel.includes("/web/") && rel.endsWith(".html"); + let inTokens = false; + readFileSync(file, "utf8").split("\n").forEach((line, i) => { + const at = (msg) => problems.push(`${rel}:${i + 1}: ${msg}`); + if (line.includes("tokens:begin")) inTokens = true; + if (dash.test(line)) at("em dash, en dash or minus sign. Use a comma, colon, period or the word to."); + if (emoji.test(line)) at("emoji or pictographic symbol. Use an approved outline icon."); + if (isPage && !inTokens && rawColor.test(line.replace(/\/\*.*?\*\//g, "")) && !/placeholder|href="#|&#/.test(line)) { + at("raw color outside the token block. Use a token."); + } + if (isPage && /(?:toast|textContent\s*=|class:'(?:empty|notice)')[^;\n]*'[^']*[A-Za-z]![^']*'/.test(line)) at("exclamation mark in interface copy."); + if (line.includes("tokens:end")) inTokens = false; + }); + } +} + +if (problems.length) { + console.error(problems.join("\n")); + console.error(`\n${problems.length} style problem(s).`); + process.exit(1); +} +console.log("Style checks passed.");