Files
mg4/server/api_test.go
T
nilsandClaude Opus 5.5 d5f68e1bd9 Server 2.1.0: pair cars by QR code instead of typing the token
Modelled on the OAuth device authorization grant (RFC 8628) and on
only when APPROVAL_PASSWORD is set (at least 12 characters):

- POST /v1/pair/start opens a request for an installation and returns
  a short user code and the /pair URL for the car's QR code;
  POST /v1/pair/poll returns pending, the car's own token (once),
  denied or expired. Requests live 10 minutes, in memory.
- GET/POST /pair is a script-free approval page for the phone
  (strict CSP, no framing). Five wrong passwords lock approvals for a
  minute.
- Each car gets its own 43-character token; only its SHA-256 is stored
  (measurement "device"), and the device is persisted before the car
  can collect the token. Tokens are loaded at startup, so a restart
  keeps paired cars working; the server refuses to start if they cannot
  be loaded.
- GET /v1/devices and POST /v1/devices/{id}/revoke, authenticated with
  the approval password, list and revoke cars.
- The shared INGEST_TOKEN keeps working.

31 tests (race detector clean), govulncheck clean. Tested end to end
against InfluxDB 2.7.12: pairing, wrong password, single collection,
persistence across restarts, revocation (also across a restart), and
that InfluxDB holds only the hash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QLJfZQZeAKAwSqViTmLzki
2026-10-17 16:16:19 +02:00

192 lines
5.6 KiB
Go

package main
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
)
type fakeStore struct {
mu sync.Mutex
telemetry []TelemetrySample
chunks []ConsumptionChunk
sessions []ChargingSession
devices []Device
fail error
}
func (f *fakeStore) WriteTelemetry(_ context.Context, _ string, s []TelemetrySample) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.fail != nil {
return f.fail
}
f.telemetry = append(f.telemetry, s...)
return nil
}
func (f *fakeStore) WriteConsumptionChunk(_ context.Context, c ConsumptionChunk) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.fail != nil {
return f.fail
}
f.chunks = append(f.chunks, c)
return nil
}
func (f *fakeStore) WriteChargingSession(_ context.Context, s ChargingSession) error {
f.mu.Lock()
defer f.mu.Unlock()
f.sessions = append(f.sessions, s)
return f.fail
}
func (f *fakeStore) SaveDevice(_ context.Context, d Device) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.fail != nil {
return f.fail
}
f.devices = append(f.devices, d)
return nil
}
func (f *fakeStore) LoadDevices(context.Context) ([]Device, error) {
f.mu.Lock()
defer f.mu.Unlock()
return f.devices, f.fail
}
func (f *fakeStore) ReadConsumptionChunks(context.Context, string) ([]ConsumptionChunk, error) {
f.mu.Lock()
defer f.mu.Unlock()
return f.chunks, f.fail
}
const (
testToken = "ingest-test-token-0123456789abcdef"
testApprovalPassword = "approval-password-123"
)
func newTestAPI() (*API, *fakeStore) {
store := &fakeStore{}
return &API{Store: store, IngestToken: testToken, Forwarder: &Forwarder{},
Pairing: NewPairing(testApprovalPassword, nil), PublicURL: "https://car.example.com"}, store
}
func do(t *testing.T, h http.Handler, method, path, token, body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func TestHealthNeedsNoToken(t *testing.T) {
api, _ := newTestAPI()
rec := do(t, api.Routes(), "GET", "/v1/health", "", "")
if rec.Code != 200 || strings.TrimSpace(rec.Body.String()) != `{"status":"ok"}` {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
}
func TestEveryOtherEndpointNeedsTheIngestToken(t *testing.T) {
api, _ := newTestAPI()
h := api.Routes()
for _, c := range []struct{ method, path string }{
{"POST", "/v1/telemetry"},
{"PUT", "/v1/consumption/daily"},
{"PUT", "/v1/charging-sessions/" + testSession},
{"GET", "/v1/consumption/history/" + testInstallation},
} {
for _, token := range []string{"", "wrong-token-0123456789abcdef", testToken + "x"} {
if rec := do(t, h, c.method, c.path, token, "{}"); rec.Code != 401 {
t.Errorf("%s %s with %q: want 401, got %d", c.method, c.path, token, rec.Code)
}
}
}
}
func TestTelemetryIsStoredAndBadInputIsA400(t *testing.T) {
api, store := newTestAPI()
h := api.Routes()
rec := do(t, h, "POST", "/v1/telemetry", testToken, string(telemetryBody(`{"utc":1790000000,"soc":80}`)))
if rec.Code != 204 || len(store.telemetry) != 1 {
t.Fatalf("%d, stored %d", rec.Code, len(store.telemetry))
}
rec = do(t, h, "POST", "/v1/telemetry", testToken, string(telemetryBody(`{"utc":1790000000,"soc":120}`)))
if rec.Code != 400 || !strings.Contains(rec.Body.String(), "samples[0].soc is invalid") {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
if rec := do(t, h, "GET", "/v1/telemetry", testToken, ""); rec.Code != 405 {
t.Fatalf("GET on a POST route: want 405, got %d", rec.Code)
}
}
func TestAFailedWriteIsA500WithoutDetail(t *testing.T) {
api, store := newTestAPI()
store.fail = errors.New("influx says: token xyz rejected")
rec := do(t, api.Routes(), "POST", "/v1/telemetry", testToken, string(telemetryBody(`{"utc":1790000000,"soc":80}`)))
if rec.Code != 500 || strings.Contains(rec.Body.String(), "xyz") {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
}
func TestOversizedBodiesAreRejected(t *testing.T) {
api, _ := newTestAPI()
big := `{"x":"` + strings.Repeat("a", maxBodyBytes) + `"}`
if rec := do(t, api.Routes(), "PUT", "/v1/consumption/daily", testToken, big); rec.Code != 400 {
t.Fatalf("want 400, got %d", rec.Code)
}
}
func TestHistoryReturnsDaysNewestFirstAndTheLifetime(t *testing.T) {
api, _ := newTestAPI()
h := api.Routes()
day := func(date string, at int64) string {
return `{"installationId":"` + testInstallation + `","date":"` + date + `","recordedAt":` +
jsonInt(at) + `,"day":{"km":2.5,"kwh":0.4,"hours":0.03,"socDrop":0.6}}`
}
// Two chunks on one day and one on the next. Retry dedupe is InfluxDB's overwrite and is
// covered by the end-to-end check, not this fake.
for _, body := range []string{day("2026-10-16", 1000), day("2026-10-16", 2000), day("2026-10-17", 3000)} {
if rec := do(t, h, "PUT", "/v1/consumption/daily", testToken, body); rec.Code != 204 {
t.Fatalf("chunk: %d %s", rec.Code, rec.Body)
}
}
rec := do(t, h, "GET", "/v1/consumption/history/"+testInstallation, testToken, "")
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
var got struct {
Records []struct {
Date string `json:"date"`
Day Totals `json:"day"`
} `json:"records"`
Lifetime Totals `json:"lifetime"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if len(got.Records) != 2 || got.Records[0].Date != "2026-10-17" || got.Records[1].Day.Km != 5 || got.Lifetime.Km != 7.5 {
t.Fatalf("%s", rec.Body)
}
if rec := do(t, h, "GET", "/v1/consumption/history/not-a-uuid", testToken, ""); rec.Code != 400 {
t.Fatalf("bad id: want 400, got %d", rec.Code)
}
}
func jsonInt(v int64) string {
b, _ := json.Marshal(v)
return string(b)
}