Initial commit

This commit is contained in:
Michael committed 2026-08-06 18:26:45 +12:00
commit b6014c6ffc
47 files changed
+4329

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
package main
import "embed"
// frontendFS holds the built Svelte SPA (frontend/dist contents, copied into
// ./web at build time — see backend/Dockerfile and scripts/build-frontend.sh).
// Embedding it means the whole app ships as one binary/container.
//
//go:embed all:web
var frontendFS embed.FS
+687
View File
@@ -0,0 +1,687 @@
package main
// End-to-end smoke test against SQLite + local-disk storage — the
// DB_DRIVER=sqlite / STORAGE_DRIVER=local combination that lets this app be
// tested with no external services at all. Exercises the real mux/handlers;
// only OIDC login/callback are skipped (they need a real provider), so the
// session cookie is minted directly the same way Callback would.
import (
"bytes"
"encoding/json"
"fmt"
"mime/multipart"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"github.com/google/uuid"
"vlog/internal/auth"
"vlog/internal/db"
"vlog/internal/handlers"
"vlog/internal/storage"
)
// a minimal valid 1x1 PNG.
var testPNG = []byte{
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00,
0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00,
0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49,
0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
}
func newTestApp(t *testing.T) (*http.ServeMux, string) {
t.Helper()
dir := t.TempDir()
database, err := db.Connect("sqlite", filepath.Join(dir, "test.db"))
if err != nil {
t.Fatalf("db.Connect: %v", err)
}
t.Cleanup(func() { database.Close() })
store, err := storage.NewLocal(filepath.Join(dir, "uploads"))
if err != nil {
t.Fatalf("storage.NewLocal: %v", err)
}
// Authenticator is nil — fine as long as the test never hits
// /api/auth/login or /api/auth/callback (OIDC needs a real provider).
h := handlers.New(database, store, nil, "test-jwt-secret", false)
mux := http.NewServeMux()
registerRoutes(mux, h)
// Simulate what Callback does on first login: JIT-provision a user row
// and mint the same session JWT.
userID := uuid.New().String()
if _, err := database.Exec(`INSERT INTO users (id, oidc_sub, email, name) VALUES (?, ?, ?, ?)`,
userID, "test-sub", "[email protected]", "Test User"); err != nil {
t.Fatalf("seed user: %v", err)
}
token, err := auth.MintSessionJWT("test-jwt-secret", userID, "[email protected]")
if err != nil {
t.Fatalf("mint session: %v", err)
}
return mux, token
}
func doJSON(t *testing.T, mux *http.ServeMux, token, method, path string, body interface{}) *httptest.ResponseRecorder {
t.Helper()
var buf bytes.Buffer
if body != nil {
if err := json.NewEncoder(&buf).Encode(body); err != nil {
t.Fatalf("encode body: %v", err)
}
}
req := httptest.NewRequest(method, path, &buf)
req.Header.Set("Content-Type", "application/json")
req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token})
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
return rec
}
func doUpload(t *testing.T, mux *http.ServeMux, token, path, fieldFile string, content []byte) *httptest.ResponseRecorder {
t.Helper()
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
part, err := w.CreateFormFile("file", fieldFile)
if err != nil {
t.Fatalf("create form file: %v", err)
}
if _, err := part.Write(content); err != nil {
t.Fatalf("write form file: %v", err)
}
w.Close()
req := httptest.NewRequest(http.MethodPost, path, &buf)
req.Header.Set("Content-Type", w.FormDataContentType())
req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token})
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
return rec
}
func TestFullFlow_SQLiteAndLocalStorage(t *testing.T) {
mux, token := newTestApp(t)
// Me
rec := doJSON(t, mux, token, http.MethodGet, "/api/me", nil)
if rec.Code != http.StatusOK {
t.Fatalf("GET /api/me: got %d, body %s", rec.Code, rec.Body.String())
}
// Create car
rec = doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{
"rego": "ABC123",
"make": "Toyota",
"model": "Corolla",
"year": 2018,
"regoExpiry": "2026-09-01",
"wofExpiry": "2026-08-20",
})
if rec.Code != http.StatusCreated {
t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String())
}
var car struct {
ID string `json:"id"`
Rego string `json:"rego"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &car); err != nil {
t.Fatalf("decode car: %v", err)
}
if car.Rego != "ABC123" {
t.Fatalf("expected rego ABC123, got %q", car.Rego)
}
// List cars
rec = doJSON(t, mux, token, http.MethodGet, "/api/cars", nil)
if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("ABC123")) {
t.Fatalf("GET /api/cars: got %d, body %s", rec.Code, rec.Body.String())
}
// Upload photo (local storage)
rec = doUpload(t, mux, token, fmt.Sprintf("/api/cars/%s/photo", car.ID), "photo.png", testPNG)
if rec.Code != http.StatusOK {
t.Fatalf("POST photo: got %d, body %s", rec.Code, rec.Body.String())
}
// Stream photo back
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/cars/%s/photo", car.ID), nil)
req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token})
rec2 := httptest.NewRecorder()
mux.ServeHTTP(rec2, req)
if rec2.Code != http.StatusOK {
t.Fatalf("GET photo: got %d", rec2.Code)
}
if got := rec2.Body.Bytes(); !bytes.Equal(got, testPNG) {
t.Fatalf("photo bytes round-trip mismatch: got %d bytes, want %d", len(got), len(testPNG))
}
if ct := rec2.Header().Get("Content-Type"); ct != "image/png" {
t.Fatalf("expected image/png content-type, got %q", ct)
}
// A renamed non-image file must be rejected (content-sniffing, not extension)
rec = doUpload(t, mux, token, fmt.Sprintf("/api/cars/%s/photo", car.ID), "fake.png", []byte("not actually a png"))
if rec.Code != http.StatusUnsupportedMediaType {
t.Fatalf("expected 415 for fake png, got %d, body %s", rec.Code, rec.Body.String())
}
// Add a service entry
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{
"entryDate": "2026-07-01",
"entryType": "Oil change",
"performedAt": "Bob's Garage",
"odometer": 45000,
})
if rec.Code != http.StatusCreated {
t.Fatalf("POST service-entries: got %d, body %s", rec.Code, rec.Body.String())
}
var entry struct {
ID string `json:"id"`
}
json.Unmarshal(rec.Body.Bytes(), &entry)
// Attach a PNG to it
rec = doUpload(t, mux, token, fmt.Sprintf("/api/service-entries/%s/files", entry.ID), "invoice.png", testPNG)
if rec.Code != http.StatusCreated {
t.Fatalf("POST service-entry file: got %d, body %s", rec.Code, rec.Body.String())
}
var file struct {
ID string `json:"id"`
}
json.Unmarshal(rec.Body.Bytes(), &file)
// Timeline shows the entry with its file
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), nil)
if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("invoice.png")) {
t.Fatalf("GET service-entries: got %d, body %s", rec.Code, rec.Body.String())
}
// Stream the attachment back
req = httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/files/%s", file.ID), nil)
req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token})
rec2 = httptest.NewRecorder()
mux.ServeHTTP(rec2, req)
if rec2.Code != http.StatusOK || !bytes.Equal(rec2.Body.Bytes(), testPNG) {
t.Fatalf("GET file: got %d, %d bytes", rec2.Code, rec2.Body.Len())
}
// Add a custom reminder due soon, and one far in the future
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/reminders", car.ID), map[string]interface{}{
"reminderType": "custom",
"label": "Spark plugs",
"dueDate": "2026-08-20",
})
if rec.Code != http.StatusCreated {
t.Fatalf("POST reminders: got %d, body %s", rec.Code, rec.Body.String())
}
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/reminders", car.ID), map[string]interface{}{
"reminderType": "service",
"dueDate": "2030-01-01",
})
if rec.Code != http.StatusCreated {
t.Fatalf("POST reminders (far future): got %d, body %s", rec.Code, rec.Body.String())
}
// Dashboard should surface: the near-due custom reminder, rego expiry,
// and WoF expiry (all within 30 days) — but not the 2030 reminder.
rec = doJSON(t, mux, token, http.MethodGet, "/api/dashboard", nil)
if rec.Code != http.StatusOK {
t.Fatalf("GET dashboard: got %d, body %s", rec.Code, rec.Body.String())
}
var items []map[string]interface{}
if err := json.Unmarshal(rec.Body.Bytes(), &items); err != nil {
t.Fatalf("decode dashboard: %v", err)
}
kinds := map[string]bool{}
for _, it := range items {
kinds[it["reminderType"].(string)] = true
}
for _, want := range []string{"custom", "rego", "wof"} {
if !kinds[want] {
t.Errorf("expected dashboard to include kind %q, items: %+v", want, items)
}
}
if len(items) != 3 {
t.Errorf("expected exactly 3 dashboard items (not the 2030 reminder), got %d: %+v", len(items), items)
}
// Delete the car — must cascade to entries/files/reminders.
rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/cars/%s", car.ID), nil)
if rec.Code != http.StatusOK {
t.Fatalf("DELETE car: got %d, body %s", rec.Code, rec.Body.String())
}
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s", car.ID), nil)
if rec.Code != http.StatusNotFound {
t.Fatalf("GET deleted car: expected 404, got %d", rec.Code)
}
// The attached file should also be gone from local disk (best-effort
// delete on cascade) — GET should now 404.
req = httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/files/%s", file.ID), nil)
req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token})
rec2 = httptest.NewRecorder()
mux.ServeHTTP(rec2, req)
if rec2.Code != http.StatusNotFound {
t.Fatalf("GET file after car delete: expected 404, got %d", rec2.Code)
}
}
func TestKnowledgeBase(t *testing.T) {
mux, token := newTestApp(t)
rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "KB001"})
if rec.Code != http.StatusCreated {
t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String())
}
var car struct {
ID string `json:"id"`
}
json.Unmarshal(rec.Body.Bytes(), &car)
// Create
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), map[string]interface{}{
"title": "Coolant type",
"body": "Use Toyota Super Long Life Coolant, pink, diluted 50/50.",
})
if rec.Code != http.StatusCreated {
t.Fatalf("POST knowledge: got %d, body %s", rec.Code, rec.Body.String())
}
var entry struct {
ID string `json:"id"`
Title string `json:"title"`
}
json.Unmarshal(rec.Body.Bytes(), &entry)
if entry.Title != "Coolant type" {
t.Fatalf("expected title Coolant type, got %q", entry.Title)
}
// List
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), nil)
if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("Coolant type")) {
t.Fatalf("GET knowledge: got %d, body %s", rec.Code, rec.Body.String())
}
// Update
rec = doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/knowledge/%s", entry.ID), map[string]interface{}{
"title": "Coolant type (updated)",
"body": "Use Toyota Super Long Life Coolant, pink, diluted 50/50. Bleed via the top-left nipple.",
})
if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("Bleed via")) {
t.Fatalf("PUT knowledge: got %d, body %s", rec.Code, rec.Body.String())
}
// Delete
rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/knowledge/%s", entry.ID), nil)
if rec.Code != http.StatusOK {
t.Fatalf("DELETE knowledge: got %d, body %s", rec.Code, rec.Body.String())
}
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), nil)
if rec.Code != http.StatusOK || string(rec.Body.Bytes()) != `{"items":[],"hasMore":false}`+"\n" {
t.Fatalf("expected empty knowledge list after delete, got %d: %s", rec.Code, rec.Body.String())
}
}
// TestListPagination covers both paginated list endpoints (service entries
// and knowledge entries) — the thing that matters for a car with a very
// long history: a page at a time, never the whole thing in one response.
func TestListPagination(t *testing.T) {
mux, token := newTestApp(t)
rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "PAGE001"})
if rec.Code != http.StatusCreated {
t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String())
}
var car struct {
ID string `json:"id"`
}
json.Unmarshal(rec.Body.Bytes(), &car)
const total = 25
for i := 0; i < total; i++ {
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{
"entryDate": fmt.Sprintf("2020-01-%02d", (i%28)+1),
"entryType": fmt.Sprintf("Entry %d", i),
})
if rec.Code != http.StatusCreated {
t.Fatalf("seed service entry %d: got %d, body %s", i, rec.Code, rec.Body.String())
}
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), map[string]interface{}{
"title": fmt.Sprintf("KB %d", i),
"body": "body",
})
if rec.Code != http.StatusCreated {
t.Fatalf("seed knowledge entry %d: got %d, body %s", i, rec.Code, rec.Body.String())
}
}
for _, endpoint := range []string{"service-entries", "knowledge"} {
// Default page (no ?limit=) should cap at 20 and report more available.
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/%s", car.ID, endpoint), nil)
var firstPage struct {
Items []json.RawMessage `json:"items"`
HasMore bool `json:"hasMore"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &firstPage); err != nil {
t.Fatalf("%s first page: decode failed: %v, body %s", endpoint, err, rec.Body.String())
}
if len(firstPage.Items) != 20 || !firstPage.HasMore {
t.Fatalf("%s first page: expected 20 items + hasMore=true, got %d items, hasMore=%v",
endpoint, len(firstPage.Items), firstPage.HasMore)
}
// Second page (offset=20) should return the remaining 5, hasMore=false.
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/%s?limit=20&offset=20", car.ID, endpoint), nil)
var secondPage struct {
Items []json.RawMessage `json:"items"`
HasMore bool `json:"hasMore"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &secondPage); err != nil {
t.Fatalf("%s second page: decode failed: %v, body %s", endpoint, err, rec.Body.String())
}
if len(secondPage.Items) != total-20 || secondPage.HasMore {
t.Fatalf("%s second page: expected %d items + hasMore=false, got %d items, hasMore=%v",
endpoint, total-20, len(secondPage.Items), secondPage.HasMore)
}
// A tiny explicit page size still respects hasMore correctly.
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/%s?limit=3&offset=0", car.ID, endpoint), nil)
var smallPage struct {
Items []json.RawMessage `json:"items"`
HasMore bool `json:"hasMore"`
}
json.Unmarshal(rec.Body.Bytes(), &smallPage)
if len(smallPage.Items) != 3 || !smallPage.HasMore {
t.Fatalf("%s small page: expected 3 items + hasMore=true, got %d items, hasMore=%v",
endpoint, len(smallPage.Items), smallPage.HasMore)
}
}
}
func TestSecondUserCannotSeeFirstUsersCar(t *testing.T) {
mux, token1 := newTestApp(t)
rec := doJSON(t, mux, token1, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "PRIVATE1"})
if rec.Code != http.StatusCreated {
t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String())
}
var car struct {
ID string `json:"id"`
}
json.Unmarshal(rec.Body.Bytes(), &car)
// Mint a second user's session against the SAME app/db (simulating a
// second OIDC-authenticated user).
// newTestApp already seeded one user in its own fresh DB, so instead we
// reuse the mux but mint a token for a brand-new, never-provisioned user.
req := httptest.NewRequest(http.MethodGet, "/api/cars", nil)
badToken, err := auth.MintSessionJWT("test-jwt-secret", "00000000-0000-0000-0000-000000000000", "[email protected]")
if err != nil {
t.Fatalf("mint: %v", err)
}
req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: badToken})
rec2 := httptest.NewRecorder()
mux.ServeHTTP(rec2, req)
if rec2.Code != http.StatusOK || string(rec2.Body.Bytes()) != "[]\n" {
// (also guards against regressing to encoding an empty list as
// JSON null, which would crash the frontend's cars.length checks)
t.Fatalf("second user's garage should be empty, got %d: %s", rec2.Code, rec2.Body.String())
}
// And can't reach the first user's car by ID either.
rec3 := doJSON(t, mux, badToken, http.MethodGet, fmt.Sprintf("/api/cars/%s", car.ID), nil)
if rec3.Code != http.StatusNotFound {
t.Fatalf("expected 404 for other user's car, got %d", rec3.Code)
}
}
func TestSharingPublicEndpoints(t *testing.T) {
mux, token := newTestApp(t)
rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "SHARE1", "make": "Honda"})
if rec.Code != http.StatusCreated {
t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String())
}
var car struct {
ID string `json:"id"`
}
json.Unmarshal(rec.Body.Bytes(), &car)
// Not shared yet — public endpoint 404s.
req := httptest.NewRequest(http.MethodGet, "/api/public/cars/nonexistent-token", nil)
rec2 := httptest.NewRecorder()
mux.ServeHTTP(rec2, req)
if rec2.Code != http.StatusNotFound {
t.Fatalf("expected 404 for unknown share token, got %d", rec2.Code)
}
// Turn sharing on.
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/share", car.ID), nil)
if rec.Code != http.StatusOK {
t.Fatalf("POST share: got %d, body %s", rec.Code, rec.Body.String())
}
var shared struct {
ShareToken string `json:"shareToken"`
}
json.Unmarshal(rec.Body.Bytes(), &shared)
if shared.ShareToken == "" {
t.Fatal("expected a non-empty shareToken")
}
// Add a service entry with an attachment, to confirm docs are included
// in the public view (the whole point of sharing when selling a car).
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{
"entryDate": "2026-01-01",
"entryType": "Oil change",
})
var entry struct {
ID string `json:"id"`
}
json.Unmarshal(rec.Body.Bytes(), &entry)
rec = doUpload(t, mux, token, fmt.Sprintf("/api/service-entries/%s/files", entry.ID), "invoice.png", testPNG)
var file struct {
ID string `json:"id"`
}
json.Unmarshal(rec.Body.Bytes(), &file)
// Public car info — no auth cookie needed at all.
req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken, nil)
rec2 = httptest.NewRecorder()
mux.ServeHTTP(rec2, req)
if rec2.Code != http.StatusOK || !bytes.Contains(rec2.Body.Bytes(), []byte("SHARE1")) {
t.Fatalf("public car: got %d, body %s", rec2.Code, rec2.Body.String())
}
// Public service history — should include the attachment.
req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken+"/service-entries", nil)
rec2 = httptest.NewRecorder()
mux.ServeHTTP(rec2, req)
if rec2.Code != http.StatusOK || !bytes.Contains(rec2.Body.Bytes(), []byte("invoice.png")) {
t.Fatalf("public service-entries: got %d, body %s", rec2.Code, rec2.Body.String())
}
// Public file download.
req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken+"/files/"+file.ID, nil)
rec2 = httptest.NewRecorder()
mux.ServeHTTP(rec2, req)
if rec2.Code != http.StatusOK || !bytes.Equal(rec2.Body.Bytes(), testPNG) {
t.Fatalf("public file: got %d, %d bytes", rec2.Code, rec2.Body.Len())
}
// Revoke — public endpoint 404s again.
rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/cars/%s/share", car.ID), nil)
if rec.Code != http.StatusOK {
t.Fatalf("DELETE share: got %d, body %s", rec.Code, rec.Body.String())
}
req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken, nil)
rec2 = httptest.NewRecorder()
mux.ServeHTTP(rec2, req)
if rec2.Code != http.StatusNotFound {
t.Fatalf("expected 404 after revoke, got %d", rec2.Code)
}
}
func TestFuelEntries(t *testing.T) {
mux, token := newTestApp(t)
rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "FUEL1"})
var car struct {
ID string `json:"id"`
}
json.Unmarshal(rec.Body.Bytes(), &car)
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/fuel-entries", car.ID), map[string]interface{}{
"entryDate": "2026-07-01",
"litres": 45.5,
"cost": 98.20,
"odometer": 50000,
"location": "BP",
})
if rec.Code != http.StatusCreated {
t.Fatalf("POST fuel-entries: got %d, body %s", rec.Code, rec.Body.String())
}
var entry struct {
ID string `json:"id"`
Litres float64 `json:"litres"`
}
json.Unmarshal(rec.Body.Bytes(), &entry)
if entry.Litres != 45.5 {
t.Fatalf("expected litres 45.5, got %v", entry.Litres)
}
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/fuel-entries", car.ID), nil)
if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("BP")) {
t.Fatalf("GET fuel-entries: got %d, body %s", rec.Code, rec.Body.String())
}
rec = doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/fuel-entries/%s", entry.ID), map[string]interface{}{
"entryDate": "2026-07-01",
"litres": 46,
"cost": 100,
"location": "Z Energy",
})
if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("Z Energy")) {
t.Fatalf("PUT fuel-entries: got %d, body %s", rec.Code, rec.Body.String())
}
rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/fuel-entries/%s", entry.ID), nil)
if rec.Code != http.StatusOK {
t.Fatalf("DELETE fuel-entries: got %d, body %s", rec.Code, rec.Body.String())
}
}
func TestMileageAndMilestone(t *testing.T) {
mux, token := newTestApp(t)
rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "MILE1", "odometer": 68420})
var car struct {
ID string `json:"id"`
}
json.Unmarshal(rec.Body.Bytes(), &car)
// With no history points yet, still reports current reading, just no
// rate/throughput estimate.
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/mileage", car.ID), nil)
var m struct {
CurrentOdometer int `json:"currentOdometer"`
KmPerYear *float64 `json:"kmPerYear"`
YearsPer100k *float64 `json:"yearsPer100k"`
Next100kEta *string `json:"next100kEta"`
}
json.Unmarshal(rec.Body.Bytes(), &m)
if m.KmPerYear != nil || m.YearsPer100k != nil {
t.Fatalf("expected no rate/throughput with <2 data points, got kmPerYear=%v yearsPer100k=%v", m.KmPerYear, m.YearsPer100k)
}
// Add a historical fuel entry a year ago at a lower reading — now there
// are two points and a rate/throughput estimate should compute.
yearAgo := "2025-08-06"
doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/fuel-entries", car.ID), map[string]interface{}{
"entryDate": yearAgo, "litres": 40, "cost": 80, "odometer": 50000,
})
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/mileage", car.ID), nil)
json.Unmarshal(rec.Body.Bytes(), &m)
if m.KmPerYear == nil || *m.KmPerYear < 17000 || *m.KmPerYear > 19500 {
t.Fatalf("expected ~18,420 km/year, got %v", m.KmPerYear)
}
// 100,000km / ~18,420km per year is ~5.4 years — a throughput figure
// from today, unrelated to the odometer's current position (68,420km
// is nowhere near a "100,000km" round number, and that's the point).
if m.YearsPer100k == nil || *m.YearsPer100k < 5.0 || *m.YearsPer100k > 6.0 {
t.Fatalf("expected ~5.4 years per 100,000km, got %v", m.YearsPer100k)
}
if m.Next100kEta == nil {
t.Fatal("expected a next100kEta date once a rate is known")
}
}
func TestSynthesizedReminders(t *testing.T) {
mux, token := newTestApp(t)
rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{
"rego": "REM001", "regoExpiry": "2026-08-20", "wofExpiry": "2026-08-15",
})
var car struct {
ID string `json:"id"`
}
json.Unmarshal(rec.Body.Bytes(), &car)
// Even with zero real reminders, rego/WoF show up automatically.
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders", car.ID), nil)
var views []map[string]interface{}
json.Unmarshal(rec.Body.Bytes(), &views)
types := map[string]bool{}
for _, v := range views {
types[v["reminderType"].(string)] = true
if v["id"] != nil && v["reminderType"] == "rego" {
t.Fatalf("synthesized rego reminder should have a nil id, got %v", v["id"])
}
}
if !types["rego"] || !types["wof"] {
t.Fatalf("expected synthesized rego+wof reminders, got %+v", views)
}
// Configure a service interval and log a qualifying service entry —
// a synthesized "service" reminder should now also appear.
doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/cars/%s", car.ID), map[string]interface{}{
"rego": "REM001", "serviceIntervalKm": 10000, "serviceIntervalMonths": 6,
})
doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{
"entryDate": "2026-01-01", "entryType": "Full service", "odometer": 40000, "isService": true,
})
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders", car.ID), nil)
json.Unmarshal(rec.Body.Bytes(), &views)
types = map[string]bool{}
for _, v := range views {
types[v["reminderType"].(string)] = true
}
if !types["service"] {
t.Fatalf("expected synthesized service reminder after logging a qualifying entry, got %+v", views)
}
// A completed real reminder is hidden by default, shown with ?completed=1.
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/reminders", car.ID), map[string]interface{}{
"reminderType": "custom", "label": "Test reminder", "dueDate": "2026-09-01",
})
var reminder struct {
ID string `json:"id"`
}
json.Unmarshal(rec.Body.Bytes(), &reminder)
doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/reminders/%s", reminder.ID), map[string]interface{}{"completed": true})
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders", car.ID), nil)
if bytes.Contains(rec.Body.Bytes(), []byte("Test reminder")) {
t.Fatalf("completed reminder should be hidden by default, got %s", rec.Body.String())
}
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders?completed=1", car.ID), nil)
if !bytes.Contains(rec.Body.Bytes(), []byte("Test reminder")) {
t.Fatalf("completed reminder should show with ?completed=1, got %s", rec.Body.String())
}
}
+85
View File
@@ -0,0 +1,85 @@
// Command server is the whole app: it serves the JSON API and the embedded
// Svelte SPA from one binary, and applies DB migrations on startup.
package main
import (
"context"
"fmt"
"io/fs"
"log"
"net/http"
"strings"
"time"
"vlog/internal/auth"
"vlog/internal/config"
"vlog/internal/db"
"vlog/internal/handlers"
"vlog/internal/storage"
)
func main() {
cfg, err := config.Load()
if err != nil {
log.Fatalf("config: %v", err)
}
ctx := context.Background()
database, err := db.Connect(cfg.DBDriver, cfg.DatabaseURL)
if err != nil {
log.Fatalf("database: %v", err)
}
defer database.Close()
store, err := newStorage(ctx, cfg)
if err != nil {
log.Fatalf("storage: %v", err)
}
// Only require Secure cookies when we're actually serving over https —
// lets this run over plain http for local dev.
secureCookies := strings.HasPrefix(cfg.PublicBaseURL, "https://")
authenticator, err := auth.NewAuthenticator(ctx, cfg.OIDCIssuerURL, cfg.OIDCClientID, cfg.OIDCClientSecret, cfg.OIDCRedirectURL, secureCookies)
if err != nil {
log.Fatalf("oidc: %v", err)
}
h := handlers.New(database, store, authenticator, cfg.JWTSigningSecret, secureCookies)
mux := http.NewServeMux()
registerRoutes(mux, h)
staticFS, err := fs.Sub(frontendFS, "web")
if err != nil {
log.Fatalf("frontend assets: %v", err)
}
mux.Handle("/", spaHandler(staticFS))
srv := &http.Server{
Addr: ":" + cfg.Port,
Handler: logMiddleware(mux),
ReadHeaderTimeout: 10 * time.Second,
}
log.Printf("listening on :%s", cfg.Port)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("server: %v", err)
}
}
// newStorage picks the file storage backend based on STORAGE_DRIVER: "s3"
// (production) or "local" (writes to disk — for testing without a real S3
// bucket). Handlers depend only on the storage.Storage interface, so
// nothing else in the app needs to know which one is active.
func newStorage(ctx context.Context, cfg *config.Config) (storage.Storage, error) {
switch cfg.StorageDriver {
case "s3":
return storage.NewS3(ctx, cfg.AWSRegion, cfg.S3Bucket)
case "local":
return storage.NewLocal(cfg.LocalStoragePath)
default:
return nil, fmt.Errorf("invalid STORAGE_DRIVER %q (must be s3 or local)", cfg.StorageDriver)
}
}
+24
View File
@@ -0,0 +1,24 @@
package main
import (
"log"
"net/http"
"time"
)
// logMiddleware and recovery in one small wrapper — no need for a whole
// middleware package for two stdlib one-liners.
func logMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
log.Printf("panic handling %s %s: %v", r.Method, r.URL.Path, rec)
http.Error(w, "internal server error", http.StatusInternalServerError)
}
}()
start := time.Now()
next.ServeHTTP(w, r)
log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start))
})
}
+70
View File
@@ -0,0 +1,70 @@
package main
import (
"net/http"
"vlog/internal/auth"
"vlog/internal/handlers"
)
// registerRoutes wires up the whole JSON API. Auth login/callback/logout
// and the /api/public/... share endpoints are public; everything else
// requires the session cookie.
func registerRoutes(mux *http.ServeMux, h *handlers.Handlers) {
mux.HandleFunc("GET /api/auth/login", h.Login)
mux.HandleFunc("GET /api/auth/callback", h.Callback)
mux.HandleFunc("POST /api/auth/logout", h.Logout)
// Public, unauthenticated share view (QR code / link, no login) — a
// deliberately narrow read-only surface, see internal/handlers/public.go.
mux.HandleFunc("GET /api/public/cars/{shareToken}", h.PublicCar)
mux.HandleFunc("GET /api/public/cars/{shareToken}/photo", h.PublicCarPhoto)
mux.HandleFunc("GET /api/public/cars/{shareToken}/service-entries", h.PublicServiceEntries)
mux.HandleFunc("GET /api/public/cars/{shareToken}/files/{fileId}", h.PublicFile)
protected := http.NewServeMux()
protected.HandleFunc("GET /api/me", h.Me)
protected.HandleFunc("GET /api/cars", h.ListCars)
protected.HandleFunc("POST /api/cars", h.CreateCar)
protected.HandleFunc("GET /api/cars/{carId}", h.GetCar)
protected.HandleFunc("PUT /api/cars/{carId}", h.UpdateCar)
protected.HandleFunc("DELETE /api/cars/{carId}", h.DeleteCar)
protected.HandleFunc("POST /api/cars/{carId}/photo", h.UploadCarPhoto)
protected.HandleFunc("GET /api/cars/{carId}/photo", h.GetCarPhoto)
protected.HandleFunc("PATCH /api/cars/{carId}/odometer", h.UpdateOdometer)
protected.HandleFunc("POST /api/cars/{carId}/share", h.GenerateShareLink)
protected.HandleFunc("DELETE /api/cars/{carId}/share", h.RevokeShareLink)
protected.HandleFunc("GET /api/cars/{carId}/mileage", h.Mileage)
protected.HandleFunc("GET /api/cars/{carId}/service-entries", h.ListServiceEntries)
protected.HandleFunc("POST /api/cars/{carId}/service-entries", h.CreateServiceEntry)
protected.HandleFunc("GET /api/service-entries/{entryId}", h.GetServiceEntry)
protected.HandleFunc("PUT /api/service-entries/{entryId}", h.UpdateServiceEntry)
protected.HandleFunc("DELETE /api/service-entries/{entryId}", h.DeleteServiceEntry)
protected.HandleFunc("POST /api/service-entries/{entryId}/files", h.UploadServiceEntryFile)
protected.HandleFunc("GET /api/files/{fileId}", h.GetFile)
protected.HandleFunc("DELETE /api/files/{fileId}", h.DeleteFile)
protected.HandleFunc("GET /api/cars/{carId}/reminders", h.ListReminders)
protected.HandleFunc("POST /api/cars/{carId}/reminders", h.CreateReminder)
protected.HandleFunc("PUT /api/reminders/{reminderId}", h.UpdateReminder)
protected.HandleFunc("DELETE /api/reminders/{reminderId}", h.DeleteReminder)
protected.HandleFunc("GET /api/cars/{carId}/knowledge", h.ListKnowledge)
protected.HandleFunc("POST /api/cars/{carId}/knowledge", h.CreateKnowledge)
protected.HandleFunc("PUT /api/knowledge/{knowledgeId}", h.UpdateKnowledge)
protected.HandleFunc("DELETE /api/knowledge/{knowledgeId}", h.DeleteKnowledge)
protected.HandleFunc("GET /api/cars/{carId}/fuel-entries", h.ListFuelEntries)
protected.HandleFunc("POST /api/cars/{carId}/fuel-entries", h.CreateFuelEntry)
protected.HandleFunc("PUT /api/fuel-entries/{entryId}", h.UpdateFuelEntry)
protected.HandleFunc("DELETE /api/fuel-entries/{entryId}", h.DeleteFuelEntry)
protected.HandleFunc("GET /api/dashboard", h.Dashboard)
// Mounted as a subtree on the outer mux; Go's ServeMux does not strip
// the prefix, so the protected mux's patterns include the full "/api/..."
// path and match the original request untouched.
mux.Handle("/api/", auth.RequireAuth(h.JWTSecret)(protected))
}
+30
View File
@@ -0,0 +1,30 @@
package main
import (
"io/fs"
"net/http"
"strings"
)
// spaHandler serves the embedded Svelte build, falling back to index.html
// for any path that isn't a real static asset — this is what lets the
// client-side router handle "deep" URLs like /cars/123 on a hard refresh.
func spaHandler(staticFS fs.FS) http.Handler {
fileServer := http.FileServer(http.FS(staticFS))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/")
if path == "" {
path = "index.html"
}
if _, err := fs.Stat(staticFS, path); err != nil {
indexReq := r.Clone(r.Context())
indexReq.URL.Path = "/"
fileServer.ServeHTTP(w, indexReq)
return
}
fileServer.ServeHTTP(w, r)
})
}
View File
Whitespace-only changes.