Files
DriverVault/API Server/internal/plugins/builtin/toyota/toyota_test.go
T
tajniak81andClaude Opus 5.5 914aeeee23 Toyota Connected: Toyota, Lexus and Subaru as three plugins
One connector, registered once per brand with the brand fixed, so the
panel, the Web App and the Phone App each list Toyota, Lexus and Subaru
separately: own card, own account, own enable switch, own
/api/integrations/{brand} routes and vehicle provider. The brand picker
is gone.

Settings saved before the split under pluginSettings.toyota with brand
L or S move onto their brand's key on read, and are written back on the
next save. Cars linked as provider "toyota" read through their make's
brand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:32:35 +01:00

294 lines
11 KiB
Go

package toyota
import (
"context"
"encoding/base64"
"encoding/json"
"net/http"
"strings"
"testing"
"drivervault/apiserver/internal/plugins"
)
func TestDescriptor(t *testing.T) {
d := (&Plugin{}).Descriptor()
if d.Name != "toyota" {
t.Fatalf("name = %q, want toyota", d.Name)
}
if d.Kind != plugins.KindBuiltin {
t.Fatalf("kind = %q, want builtin", d.Kind)
}
if len(d.Capabilities) == 0 {
t.Fatal("expected capabilities")
}
// The credential fields must be advertised. They are intentionally NOT
// required at the global layer — credentials come from the per-user cascade —
// and the password field must be marked secret. There is no brand field: each
// brand is a registration of its own.
fields := map[string]plugins.ConfigField{}
for _, f := range d.ConfigFields {
fields[f.Key] = f
}
for _, k := range []string{"username", "password"} {
if _, ok := fields[k]; !ok {
t.Errorf("config field %q should be present", k)
}
}
if _, ok := fields["brand"]; ok {
t.Error("the brand is fixed per registration and must not be a config field")
}
if fields["username"].Required || fields["password"].Required {
t.Error("credentials must not be required at the global layer (per-user cascade)")
}
if !fields["password"].Secret {
t.Error("password field must be marked secret")
}
}
// TestBrandRegistrations pins the three faces of the one connector: each brand
// is its own plugin name with its brand fixed, so the panel and the apps list
// Toyota, Lexus and Subaru separately, and a config cannot move one onto
// another's login.
func TestBrandRegistrations(t *testing.T) {
want := map[string]string{"toyota": "T", "lexus": "L", "subaru": "S"}
if len(Brands) != len(want) {
t.Fatalf("Brands = %d entries, want %d", len(Brands), len(want))
}
for _, b := range Brands {
code, ok := want[b.Name]
if !ok || code != b.Code {
t.Errorf("brand %q has code %q, want %q", b.Name, b.Code, code)
}
p := &Plugin{fixedBrand: b.Code}
if d := p.Descriptor(); d.Name != b.Name || d.Category != plugins.CategoryVehicles {
t.Errorf("brand %q: descriptor name %q category %q", b.Name, d.Name, d.Category)
}
// A stray brand in config (a pre-split setting) must not win.
_ = p.Init(context.Background(), map[string]string{"username": "u", "password": "p", "brand": "T"})
if p.brand != b.Code {
t.Errorf("brand %q: Init with brand=T gave %q", b.Name, p.brand)
}
}
s := &Plugin{fixedBrand: "S"}
_ = s.Init(context.Background(), map[string]string{"username": "u", "password": "p"})
if s.auth.clientID != subaruAuth.clientID {
t.Errorf("subaru registration logs in as %q", s.auth.clientID)
}
}
// TestBrandAuth pins the per-brand login: Toyota and Lexus are the MyToyota app
// in the "tme" realm, Subaru is its own client in "alliance-subaru". A brand on
// the wrong realm authenticates against a user directory it is not in, which
// reads as a bad password.
func TestBrandAuth(t *testing.T) {
for _, brand := range []string{"", "T", "L"} {
a := authFor(brand)
if a.clientID != "oneapp" || !strings.Contains(a.authenticateURL, "/realms/tme/") {
t.Errorf("brand %q: expected the oneapp client in realm tme, got %q at %s", brand, a.clientID, a.authenticateURL)
}
}
s := authFor("S")
if !strings.HasSuffix(s.clientID, ".subaru.com") || !strings.Contains(s.accessTokenURL, "/realms/alliance-subaru/") {
t.Errorf("Subaru: expected its own client in realm alliance-subaru, got %q at %s", s.clientID, s.accessTokenURL)
}
if s.redirectURI != "com.subaru.oneapp:/oauth2Callback" {
t.Errorf("Subaru redirect = %q", s.redirectURI)
}
if !strings.Contains(s.authorizeURL, "client_id="+s.clientID+"&") || !strings.Contains(s.authorizeURL, "redirect_uri="+s.redirectURI+"&") {
t.Errorf("Subaru authorize URL does not carry its own client and redirect: %s", s.authorizeURL)
}
// The three URLs of one brand must share a realm.
if !strings.Contains(s.authorizeURL, "/realms/alliance-subaru/") || !strings.Contains(s.authenticateURL, "/realms/alliance-subaru/") {
t.Error("Subaru login URLs disagree on the realm")
}
if s.basicAuth == toyotaAuth.basicAuth {
t.Error("Subaru must present its own client credentials")
}
// Init picks the client for the configured brand.
p := &Plugin{}
_ = p.Init(context.Background(), map[string]string{"username": "u", "password": "p", "brand": "S"})
if p.auth.clientID != s.clientID {
t.Errorf("Init(brand=S) chose client %q", p.auth.clientID)
}
}
// TestHeadersFollowUpstream keeps the request headers in step with what the app
// sends: x-user-region on every call, and the brand named twice more for the
// non-Toyota brands only.
func TestHeadersFollowUpstream(t *testing.T) {
tok := tokenInfo{accessToken: "at", uuid: "uuid-1"}
headers := func(brand string) http.Header {
p := &Plugin{}
_ = p.Init(context.Background(), map[string]string{"username": "u", "password": "p", "brand": brand})
h := http.Header{}
p.applyHeaders(h, "VIN1", tok)
return h
}
for _, brand := range []string{"T", "L", "S"} {
h := headers(brand)
if got := h["x-user-region"]; len(got) != 1 || got[0] != "EU" {
t.Errorf("brand %s: x-user-region = %v, want [EU]", brand, got)
}
if got := h["x-brand"]; len(got) != 1 || got[0] != brand {
t.Errorf("brand %s: x-brand = %v", brand, got)
}
_, appbrand := h["x-appbrand"]
_, bare := h["brand"]
if brand == "T" && (appbrand || bare) {
t.Error("a Toyota account must not send x-appbrand/brand")
}
if brand != "T" && (!appbrand || !bare || h["x-appbrand"][0] != brand || h["brand"][0] != brand) {
t.Errorf("brand %s: x-appbrand=%v brand=%v, want both = %s", brand, h["x-appbrand"], h["brand"], brand)
}
}
}
// TestEndpointsFollowUpstream guards the mid-2026 migration: Toyota put the
// /v1/global/remote read routes behind AWS SigV4, where a Bearer token is
// answered with 403, and the app moved to /v1/vehicle/*. Falling back to the old
// paths would leave the cards permanently in error.
func TestEndpointsFollowUpstream(t *testing.T) {
retired := []string{
"/v1/global/remote/status",
"/v1/global/remote/climate-status",
"/v1/global/remote/climate-settings",
}
for _, c := range (&Plugin{}).Descriptor().Capabilities {
for _, dead := range retired {
if c.Endpoint == dead {
t.Errorf("capability %q still points at the retired %s", c.ID, dead)
}
}
}
if epRemoteStatus != "/v1/vehicle/status" {
t.Errorf("status endpoint = %q, want /v1/vehicle/status", epRemoteStatus)
}
// The electric read moved later than the rest, and keeps its old route only
// as the fallback for a gateway that has not caught up.
if epElectricStatus != "/v1/vehicle/electric/status" {
t.Errorf("electric endpoint = %q, want /v1/vehicle/electric/status", epElectricStatus)
}
if epElectricStatusLegacy != "/v1/global/remote/electric/status" {
t.Errorf("electric fallback = %q, want the old global route", epElectricStatusLegacy)
}
for status, want := range map[int]bool{403: true, 404: true, 401: false, 429: false, 500: false, 0: false} {
if got := electricFallback(status); got != want {
t.Errorf("electricFallback(%d) = %v, want %v", status, got, want)
}
}
}
// TestActionsCoverCapabilities keeps Invoke and the descriptor in step: every
// advertised capability must be callable, since the car tab drives the plugin by
// the ids the descriptor publishes.
func TestActionsCoverCapabilities(t *testing.T) {
p := &Plugin{}
_ = p.Init(context.Background(), map[string]string{"username": "u", "password": "p"})
for _, c := range p.Descriptor().Capabilities {
if c.ID == "vehicles" {
continue // the only action that takes no vin
}
// No vin, so the call is rejected before any network I/O — an "unknown
// action" here means the switch in Invoke was never extended.
_, err := p.Invoke(context.Background(), c.ID, nil)
if err == nil {
t.Errorf("action %q: expected an error without a vin", c.ID)
continue
}
if strings.Contains(err.Error(), "unknown action") {
t.Errorf("capability %q is advertised but not wired into Invoke", c.ID)
}
}
}
func TestRegistered(t *testing.T) {
// The plugin must self-register via init() so the manager can construct it.
var found bool
for _, v := range plugins.NewManager(plugins.NewMemoryStore(nil)).List() {
if v.Name == "toyota" {
found = true
}
}
if !found {
t.Fatal("toyota not registered with the plugin manager")
}
}
func TestHMACSHA256(t *testing.T) {
// Mirrors pytoyoda: hmac.new(b"2.14.0", b"abc", sha256).hexdigest().
got := hmacSHA256("2.14.0", "abc")
if len(got) != 64 {
t.Fatalf("hex digest length = %d, want 64", len(got))
}
// Deterministic: same key/message → same digest.
if got != hmacSHA256("2.14.0", "abc") {
t.Fatal("hmac not deterministic")
}
// Key matters: a different client version changes the digest.
if got == hmacSHA256("9.9.9", "abc") {
t.Fatal("hmac ignored the key")
}
}
func TestJWTUUID(t *testing.T) {
payload := base64.RawURLEncoding.EncodeToString([]byte(`{"uuid":"abc-123","aud":"oneappsdkclient"}`))
token := "header." + payload + ".sig"
uuid, err := jwtUUID(token)
if err != nil {
t.Fatalf("jwtUUID: %v", err)
}
if uuid != "abc-123" {
t.Fatalf("uuid = %q, want abc-123", uuid)
}
if _, err := jwtUUID("not-a-jwt"); err == nil {
t.Error("expected error for malformed token")
}
}
func TestExtractCode(t *testing.T) {
loc := "com.toyota.oneapp:/oauth2Callback?code=AUTHCODE123&state=xyz"
if got := extractCode(loc); got != "AUTHCODE123" {
t.Fatalf("code = %q, want AUTHCODE123", got)
}
if got := extractCode("com.toyota.oneapp:/oauth2Callback"); got != "" {
t.Fatalf("expected empty code, got %q", got)
}
}
func TestCallbackHelpers(t *testing.T) {
// A NameCallback shaped like ForgeRock's response.
var cb map[string]any
_ = json.Unmarshal([]byte(`{
"type":"NameCallback",
"output":[{"name":"prompt","value":"User Name"}],
"input":[{"name":"IDToken1","value":""}]
}`), &cb)
if output0(cb) != "User Name" {
t.Fatalf("output0 = %q", output0(cb))
}
setInput0(cb, "driver@example.com")
in := cb["input"].([]any)[0].(map[string]any)
if in["value"] != "driver@example.com" {
t.Fatalf("input value = %v, want driver@example.com", in["value"])
}
}
func TestInvokeRequiresVIN(t *testing.T) {
p := &Plugin{}
_ = p.Init(context.Background(), map[string]string{"username": "u", "password": "p"})
if _, err := p.Invoke(context.Background(), "telemetry", nil); err == nil ||
!strings.Contains(err.Error(), "requires a vin") {
t.Fatalf("expected vin-required error, got %v", err)
}
if _, err := p.Invoke(context.Background(), "bogus", nil); err == nil ||
!strings.Contains(err.Error(), "unknown action") {
t.Fatalf("expected unknown-action error, got %v", err)
}
}