Remove the integration feed for schema

schema no longer reads walks and meals from puppy-tracker, so the
read-only /api/integration/events feed, its flags and the module's
integration options go. A config still setting them is told they were
removed.
This commit is contained in:
Alexander Heldt committed 2026-10-04 18:18:14 +00:00
1 parent ffa15ff2e7
commit 7b1b0889c6
4 files changed
+7 -220

No files matched your search

+7 -29
View File
@@ -6,6 +6,12 @@ let
serverPkg = self.packages.${pkgs.system}.server;
in
{
# The feed schema read walks from is gone; a config that still sets it
# is told so, rather than getting an unknown-option error.
imports = [
(lib.mkRemovedOptionModule [ "services" "puppy-tracker" "integration" ] "The integration feed for schema was removed.")
];
options.services.puppy-tracker = {
enable = lib.mkEnableOption "Puppy Tracker (offline-first puppy tracking app with sync server)";
@@ -63,24 +69,6 @@ in
'';
};
integration = {
tokenFile = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
example = "/run/agenix/schema-puppy-token";
description = ''
File holding a bearer token (just the token) that unlocks the
read-only GET /api/integration/events feed of walks and meals, used by
other services on this host. When null the endpoint doesn't exist.
'';
};
user = lib.mkOption {
type = lib.types.str;
default = "";
description = "Email of the account the feed exposes. Empty means the only account.";
};
};
package = lib.mkOption {
type = lib.types.package;
default = serverPkg;
@@ -108,17 +96,7 @@ in
"-addr ${cfg.address}:${toString cfg.port}"
"-static ${cfg.staticPackage}/share/puppy-tracker"
"-data /var/lib/puppy-tracker/puppy.db"
] ++ lib.optional cfg.secureCookies "-secure-cookies"
# %d is the unit's credentials directory (see LoadCredential below).
++ lib.optionals (cfg.integration.tokenFile != null) [
"-integration-token-file %d/integration-token"
"-integration-user ${lib.escapeShellArg cfg.integration.user}"
]);
# DynamicUser can't own the secret, so systemd reads it as root and
# hands the service a private copy.
LoadCredential = lib.optional (cfg.integration.tokenFile != null)
"integration-token:${toString cfg.integration.tokenFile}";
] ++ lib.optional cfg.secureCookies "-secure-cookies");
# Secrets (registration code, Web Push key) are read from env files kept
# out of the store, exposed to the server as PUPPY_INVITE_CODE and
-105
View File
@@ -1,105 +0,0 @@
package main
import (
"crypto/subtle"
"database/sql"
"encoding/json"
"errors"
"log"
"net/http"
"strconv"
"strings"
)
// Integration is a read-only, token-authenticated view of one account's walks
// and meals, for other services on the same host (the household planner,
// schema, ticks off its dog duties from it). It is not a session: there is no
// cookie, it sees one configured account, and it can't write anything.
type Integration struct {
db *sql.DB
token string
// email picks the account whose events are exposed. Empty means "the only
// account", and refuses to guess once there are several.
email string
}
type integrationEvent struct {
ID string `json:"id"`
Type string `json:"type"`
At int64 `json:"at"`
Deleted bool `json:"deleted,omitempty"`
}
func (in *Integration) userID() (string, error) {
if in.email != "" {
var id string
err := in.db.QueryRow(`SELECT id FROM users WHERE email = ? COLLATE NOCASE`, in.email).Scan(&id)
return id, err
}
rows, err := in.db.Query(`SELECT id FROM users LIMIT 2`)
if err != nil {
return "", err
}
defer rows.Close()
var ids []string
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return "", err
}
ids = append(ids, id)
}
if len(ids) != 1 {
return "", errors.New("set -integration-user: there is not exactly one account")
}
return ids[0], nil
}
// GET /api/integration/events?since=<unix ms> returns the account's walk
// starts and meals that happened, or were changed, since then — tombstones
// included, so a consumer can undo what a deleted event did.
func (in *Integration) handleEvents(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || subtle.ConstantTimeCompare([]byte(got), []byte(in.token)) != 1 {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
since, err := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
if err != nil {
http.Error(w, "since: want unix milliseconds", http.StatusBadRequest)
return
}
uid, err := in.userID()
if err != nil {
log.Printf("integration: %v", err)
http.Error(w, "no account to read from", http.StatusConflict)
return
}
rows, err := in.db.Query(`
SELECT id, type, at, deleted FROM events
WHERE user_id = ? AND type IN ('walk-start', 'eat') AND (at >= ? OR updated >= ?)
ORDER BY at`, uid, since, since)
if err != nil {
log.Printf("integration: %v", err)
http.Error(w, "server error", http.StatusInternalServerError)
return
}
defer rows.Close()
out := []integrationEvent{}
for rows.Next() {
var e integrationEvent
if err := rows.Scan(&e.ID, &e.Type, &e.At, &e.Deleted); err != nil {
log.Printf("integration: %v", err)
http.Error(w, "server error", http.StatusInternalServerError)
return
}
out = append(out, e)
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(map[string]any{"events": out})
}
-71
View File
@@ -1,71 +0,0 @@
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
)
func TestIntegrationEvents(t *testing.T) {
db, err := openDB(filepath.Join(t.TempDir(), "puppy.db"))
if err != nil {
t.Fatal(err)
}
defer db.Close()
db.Exec(`INSERT INTO users (id, email, password, created) VALUES ('u1', 'a@x', 'h', 0)`)
db.Exec(`INSERT INTO users (id, email, password, created) VALUES ('u2', 'b@x', 'h', 0)`)
store := newStore(db)
store.sync("u1", "", "", []Event{
{ID: "walk", Type: "walk-start", At: 1000, UpdatedAt: 1000},
{ID: "meal", Type: "eat", At: 2000, UpdatedAt: 2000},
{ID: "pee", Type: "pee", At: 2000, UpdatedAt: 2000},
{ID: "old", Type: "eat", At: 10, UpdatedAt: 10},
{ID: "gone", Type: "eat", At: 10, UpdatedAt: 3000, Deleted: true},
})
store.sync("u2", "", "", []Event{{ID: "theirs", Type: "eat", At: 2000, UpdatedAt: 2000}})
get := func(in *Integration, auth, since string) (int, []integrationEvent) {
req := httptest.NewRequest("GET", "/api/integration/events?since="+since, nil)
if auth != "" {
req.Header.Set("Authorization", "Bearer "+auth)
}
rec := httptest.NewRecorder()
in.handleEvents(rec, req)
var body struct{ Events []integrationEvent }
json.NewDecoder(rec.Body).Decode(&body)
return rec.Code, body.Events
}
in := &Integration{db: db, token: "tok", email: "A@x"}
if code, _ := get(in, "", "0"); code != http.StatusUnauthorized {
t.Errorf("no token = %d", code)
}
if code, _ := get(in, "nope", "0"); code != http.StatusUnauthorized {
t.Errorf("wrong token = %d", code)
}
code, evs := get(in, "tok", "500")
if code != 200 {
t.Fatalf("code = %d", code)
}
got := map[string]bool{}
for _, e := range evs {
got[e.ID] = e.Deleted
}
// Recent walks and meals, plus the tombstone updated since; not the pee,
// not the old meal, not the other account's.
if len(got) != 3 || !got["gone"] {
t.Errorf("events = %+v", evs)
}
for _, id := range []string{"walk", "meal"} {
if _, ok := got[id]; !ok {
t.Errorf("missing %s", id)
}
}
// With two accounts, no configured user is ambiguous.
if code, _ := get(&Integration{db: db, token: "tok"}, "tok", "0"); code != http.StatusConflict {
t.Errorf("ambiguous = %d", code)
}
}
-15
View File
@@ -864,10 +864,6 @@ func main() {
"mark session cookies Secure (enable when served over HTTPS / behind a TLS proxy)")
vapidKey := flag.String("vapid-key", os.Getenv("PUPPY_VAPID_KEY"),
"base64url P-256 private key for Web Push (env PUPPY_VAPID_KEY); generated next to the DB when unset")
integrationTokenFile := flag.String("integration-token-file", "",
"file holding the bearer token for the read-only /api/integration/events; unset disables it")
integrationUser := flag.String("integration-user", "",
"email of the account /api/integration/events exposes; empty means the only account")
flag.Parse()
db, err := openDB(*dataPath)
@@ -1100,17 +1096,6 @@ func main() {
mux.HandleFunc("/api/reminders", auth.requireOwner(scheduler.handleReminders))
}
// Read-only feed of walks and meals for other services on this host.
if *integrationTokenFile != "" {
raw, err := os.ReadFile(*integrationTokenFile)
token := strings.TrimSpace(string(raw))
if err != nil || token == "" {
log.Fatalf("integration token file %s: unreadable or empty (%v)", *integrationTokenFile, err)
}
in := &Integration{db: db, token: token, email: *integrationUser}
mux.HandleFunc("/api/integration/events", in.handleEvents)
}
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})