Add a read-only integration feed of walks and meals
GET /api/integration/events?since=<unix ms> 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.
This commit is contained in:
1 parent
b572371666
commit
15211e32b0
4 files changed
+220
-1
No files matched your search
@@ -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=<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})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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"))
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user