From 15211e32b087c13f66197bfdccf875cf645598ff Mon Sep 17 00:00:00 2001 From: Alexander Heldt Date: Tue, 29 Sep 2026 19:13:28 +0000 Subject: [PATCH] Add a read-only integration feed of walks and meals GET /api/integration/events?since= returns one account's walk starts and meals that happened or changed since then, tombstones included, for other services on the same host. It is authenticated with a bearer token rather than a session and cannot write anything. Enabled with -integration-token-file (services.puppy-tracker .integration.tokenFile); -integration-user picks the account, and defaults to the only one. --- module.nix | 30 ++++++++++- server/integration.go | 105 +++++++++++++++++++++++++++++++++++++ server/integration_test.go | 71 +++++++++++++++++++++++++ server/main.go | 15 ++++++ 4 files changed, 220 insertions(+), 1 deletion(-) create mode 100644 server/integration.go create mode 100644 server/integration_test.go diff --git a/module.nix b/module.nix index 3523cda..3fd21eb 100644 --- a/module.nix +++ b/module.nix @@ -63,6 +63,24 @@ 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; @@ -90,7 +108,17 @@ 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"); + ] ++ 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}"; # 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 diff --git a/server/integration.go b/server/integration.go new file mode 100644 index 0000000..891ff29 --- /dev/null +++ b/server/integration.go @@ -0,0 +1,105 @@ +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= 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}) +} diff --git a/server/integration_test.go b/server/integration_test.go new file mode 100644 index 0000000..ddd06ce --- /dev/null +++ b/server/integration_test.go @@ -0,0 +1,71 @@ +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) + } +} diff --git a/server/main.go b/server/main.go index 1c2ab64..d914c22 100644 --- a/server/main.go +++ b/server/main.go @@ -864,6 +864,10 @@ 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) @@ -1096,6 +1100,17 @@ 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")) })