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>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-18 10:32:35 +01:00
1 parent 9d8636ee73
commit 914aeeee23
21 files changed
+837 -471

No files matched your search

+172 -84
View File
@@ -6,6 +6,8 @@ import (
"net/http"
"net/url"
"strings"
"drivervault/apiserver/internal/plugins/builtin/toyota"
)
// Integrations exposes the Toyota Connected Europe plugin to end users under a
@@ -13,14 +15,20 @@ import (
// account, while a superadmin (and, in an organization, an org admin) can impose
// settings from above.
//
// The one connector serves three brands — Toyota, Lexus and Subaru — and each is
// a plugin of its own to the user (toyota.Brands): its own panel entry, its own
// settings card, its own credentials and enable flag under its own
// pluginSettings key, and its own /api/integrations/{brand} routes. Everything
// below is written once and parameterized by the brand.
//
// Resolution is a cascade: the top layer wins, and a lower layer only fills a
// field the layers above left blank.
//
// - global (L1): pluginSettings on the app_settings singleton, set in the API
// Server panel by a superadmin. This is the top of the cascade for everyone.
// - org (L2): pluginSettings.toyota on the caller's organization record,
// - org (L2): pluginSettings.{brand} on the caller's organization record,
// editable by an org admin. Present only for users who belong to an org.
// - user (L3): pluginSettings.toyota on the caller's own user record.
// - user (L3): pluginSettings.{brand} on the caller's own user record.
//
// So the effective cascade is:
// - org user: global → org → user
@@ -28,7 +36,7 @@ import (
//
// The MyToyota username + password resolve together as a *pair* from the highest
// layer that supplies a username, so credential halves are never mixed across
// layers. The brand resolves on its own. Enablement is strictly per-user (L3),
// layers. Enablement is strictly per-user (L3),
// gated by the global master switch (the plugin being enabled in the panel) and,
// for org users, by the org gate.
//
@@ -36,19 +44,34 @@ import (
// client: the effective config is resolved server-side and only masked values
// leave the API. The live probe runs server-side against the resolved config.
const (
toyotaPlugin = "toyota"
toyotaSecretMask = "••••••••"
)
const toyotaSecretMask = "••••••••"
// toyotaConfig is one layer's Toyota settings.
// vehicleBrand is one face of the Toyota Connected Europe connector.
type vehicleBrand = toyota.Brand
// toyotaBrand is the MyToyota face, the one that predates the split.
var toyotaBrand = toyota.Brands[0]
// brandByName finds a registered brand by its plugin name.
func brandByName(name string) (vehicleBrand, bool) {
for _, b := range toyota.Brands {
if b.Name == name {
return b, true
}
}
return vehicleBrand{}, false
}
// toyotaConfig is one layer's settings for one brand.
type toyotaConfig struct {
Username string `json:"username"`
Password string `json:"password"`
Brand string `json:"brand"`
// Brand is read only from settings saved before the brands were split, to
// move them onto their own key (see splitLegacyBrand); nothing writes it.
Brand string `json:"brand,omitempty"`
}
// toyotaStored is what we persist per user/org under pluginSettings.toyota.
// toyotaStored is what we persist per user/org under pluginSettings.{brand}.
type toyotaStored struct {
Config toyotaConfig `json:"config"`
// Enabled is the personal per-user opt-in (user layer). Default false.
@@ -58,9 +81,62 @@ type toyotaStored struct {
Disabled bool `json:"disabled,omitempty"`
}
// toyotaSettingsDoc is the pluginSettings JSON shape (only toyota today).
type toyotaSettingsDoc struct {
Toyota toyotaStored `json:"toyota"`
// decodePluginSettings reads a pluginSettings blob into its per-plugin entries,
// with any pre-split brand entry already moved onto its own key. Never nil.
func decodePluginSettings(raw json.RawMessage) map[string]json.RawMessage {
doc := map[string]json.RawMessage{}
if len(raw) > 0 {
_ = json.Unmarshal(raw, &doc)
}
if doc == nil {
doc = map[string]json.RawMessage{} // raw was JSON null
}
splitLegacyBrand(doc)
return doc
}
// splitLegacyBrand moves a pre-split entry onto its brand. Before Lexus and
// Subaru were plugins of their own, all three brands lived under
// pluginSettings.toyota with a brand field picking the login; an entry there
// that names L or S is that brand's account, so it belongs under that brand's
// key — left under toyota it would show a Lexus login on the Toyota card. The
// move happens on every read, so it needs no migration step, and is written
// back the first time the record is saved for any brand.
func splitLegacyBrand(doc map[string]json.RawMessage) {
raw, ok := doc[toyotaBrand.Name]
if !ok {
return
}
var ts toyotaStored
if json.Unmarshal(raw, &ts) != nil {
return
}
code := strings.ToUpper(strings.TrimSpace(ts.Config.Brand))
var target vehicleBrand
for _, b := range toyota.Brands {
if b.Code == code && b.Name != toyotaBrand.Name {
target = b
}
}
if target.Name == "" {
return // a Toyota entry, or one from before the brand field existed
}
if _, taken := doc[target.Name]; !taken {
ts.Config.Brand = ""
moved, _ := json.Marshal(ts)
doc[target.Name] = moved
}
delete(doc, toyotaBrand.Name)
}
// storedFor is one brand's entry in a pluginSettings blob.
func storedFor(raw json.RawMessage, b vehicleBrand) toyotaStored {
var ts toyotaStored
if entry, ok := decodePluginSettings(raw)[b.Name]; ok {
_ = json.Unmarshal(entry, &ts)
}
ts.Config.Brand = ""
return ts
}
// toyotaFieldView is one field's resolved state for the UI.
@@ -71,7 +147,7 @@ type toyotaFieldView struct {
Locked bool `json:"locked"` // set above the caller's editable layer
}
// toyotaResolution is the fully-resolved Toyota state for one caller. It captures
// toyotaResolution is the fully-resolved state of one brand for one caller. It captures
// the effective cascade plus both editable layers (personal + organization), so
// an org admin can manage each independently.
type toyotaResolution struct {
@@ -89,24 +165,19 @@ type toyotaResolution struct {
// toyotaLayerRank orders the cascade layers; a higher number is lower priority.
var toyotaLayerRank = map[string]int{"global": 1, "org": 2, "user": 3}
// resolveToyota computes the cascade for a caller. userRaw is the caller's
// pluginSettings blob (read from their user record).
func (s *Server) resolveToyota(ctx context.Context, who *callerIdentity, userRaw json.RawMessage) toyotaResolution {
g, masterEnabled, _ := s.plugins.RawConfig(toyotaPlugin)
gc := toyotaConfig{Username: g["username"], Password: g["password"], Brand: g["brand"]}
// resolveToyota computes one brand's cascade for a caller. userRaw is the
// caller's pluginSettings blob (read from their user record).
func (s *Server) resolveToyota(ctx context.Context, who *callerIdentity, userRaw json.RawMessage, b vehicleBrand) toyotaResolution {
g, masterEnabled, _ := s.plugins.RawConfig(b.Name)
gc := toyotaConfig{Username: g["username"], Password: g["password"]}
var oStored toyotaStored
if who.OrgID != "" {
oStored, _ = s.orgToyota(ctx, who.OrgID)
oStored, _ = s.orgToyota(ctx, who.OrgID, b)
}
oc := oStored.Config
var uStored toyotaStored
if len(userRaw) > 0 {
var d toyotaSettingsDoc
_ = json.Unmarshal(userRaw, &d)
uStored = d.Toyota
}
uStored := storedFor(userRaw, b)
uc := uStored.Config
res := toyotaResolution{
@@ -133,15 +204,6 @@ func (s *Server) resolveToyota(ctx context.Context, who *callerIdentity, userRaw
}
layers = append(layers, layer{"user", uc})
// Brand resolves independently: the highest layer that sets it wins.
res.source["brand"] = "unset"
for _, l := range layers {
if v := strings.TrimSpace(l.c.Brand); v != "" {
res.eff.Brand, res.source["brand"] = v, l.name
break
}
}
// Credentials resolve as a pair from the highest layer with a username, so
// the username and password never come from different layers.
credSrc := "unset"
@@ -177,10 +239,11 @@ func toyotaMaskPresent(v string) string {
return ""
}
// orgToyota reads an organization's stored Toyota settings (config + the org
// gate) and its raw pluginSettings blob via the service account. Best effort:
// zero values on any miss so callers proceed as if the org layer were empty.
func (s *Server) orgToyota(ctx context.Context, orgID string) (toyotaStored, json.RawMessage) {
// orgToyota reads an organization's stored settings for one brand (config + the
// org gate) and its raw pluginSettings blob via the service account. Best
// effort: zero values on any miss so callers proceed as if the org layer were
// empty.
func (s *Server) orgToyota(ctx context.Context, orgID string, b vehicleBrand) (toyotaStored, json.RawMessage) {
if orgID == "" || !s.pb.Configured() {
return toyotaStored{}, nil
}
@@ -193,11 +256,7 @@ func (s *Server) orgToyota(ctx context.Context, orgID string) (toyotaStored, jso
PluginSettings json.RawMessage `json:"pluginSettings"`
}
_ = json.Unmarshal(data, &rec)
var doc toyotaSettingsDoc
if len(rec.PluginSettings) > 0 {
_ = json.Unmarshal(rec.PluginSettings, &doc)
}
return doc.Toyota, rec.PluginSettings
return storedFor(rec.PluginSettings, b), rec.PluginSettings
}
// userPluginSettings reads a user's raw pluginSettings blob via the service
@@ -215,23 +274,19 @@ func (s *Server) userPluginSettings(ctx context.Context, id string) json.RawMess
return rec.PluginSettings
}
// mergeToyota applies a mutation to the toyota entry of a pluginSettings blob,
// preserving any other plugin keys, and returns the new blob.
func mergeToyota(existing json.RawMessage, apply func(*toyotaStored)) json.RawMessage {
doc := map[string]json.RawMessage{}
if len(existing) > 0 {
_ = json.Unmarshal(existing, &doc)
}
if doc == nil {
doc = map[string]json.RawMessage{} // existing was JSON null
}
// mergeToyota applies a mutation to one brand's entry of a pluginSettings blob,
// preserving any other plugin keys, and returns the new blob. A pre-split entry
// is moved onto its brand on the way through, so the save also migrates it.
func mergeToyota(existing json.RawMessage, b vehicleBrand, apply func(*toyotaStored)) json.RawMessage {
doc := decodePluginSettings(existing)
var ts toyotaStored
if raw, ok := doc["toyota"]; ok {
if raw, ok := doc[b.Name]; ok {
_ = json.Unmarshal(raw, &ts)
}
apply(&ts)
b, _ := json.Marshal(ts)
doc["toyota"] = b
ts.Config.Brand = ""
entry, _ := json.Marshal(ts)
doc[b.Name] = entry
out, _ := json.Marshal(doc)
return out
}
@@ -265,7 +320,6 @@ func (s *Server) toyotaScopeView(res toyotaResolution, editable string) map[stri
"fields": map[string]toyotaFieldView{
"username": field("username", res.eff.Username, own.Username, false),
"password": field("password", res.eff.Password, own.Password, true),
"brand": field("brand", res.eff.Brand, own.Brand, false),
},
}
}
@@ -273,8 +327,11 @@ func (s *Server) toyotaScopeView(res toyotaResolution, editable string) map[stri
// toyotaView builds the masked, client-safe response body from a resolution. It
// exposes a "user" scope for everyone plus, for org admins, an "org" scope — each
// with its own locked-field state — so the UI can present the two independently.
func (s *Server) toyotaView(who *callerIdentity, res toyotaResolution) map[string]any {
func (s *Server) toyotaView(who *callerIdentity, res toyotaResolution, b vehicleBrand) map[string]any {
out := map[string]any{
"brand": b.Name,
"make": b.Make,
"app": b.App,
"available": res.available,
"orgEnabled": res.orgEnabled,
"enabled": res.enabled,
@@ -297,28 +354,52 @@ func (s *Server) toyotaView(who *callerIdentity, res toyotaResolution) map[strin
return out
}
// GET /api/integrations/toyota — resolved Toyota view for the caller.
// integrationBrand reads the brand segment of /api/integrations/{brand}. The
// routes are registered once per brand, so a miss is a wiring mistake; it still
// answers 404 rather than falling back to Toyota.
func integrationBrand(w http.ResponseWriter, r *http.Request) (vehicleBrand, bool) {
name := strings.TrimPrefix(r.URL.Path, "/api/integrations/")
if i := strings.IndexByte(name, '/'); i >= 0 {
name = name[:i]
}
b, ok := brandByName(name)
if !ok {
writeError(w, http.StatusNotFound, "unknown integration")
}
return b, ok
}
// GET /api/integrations/{toyota|lexus|subaru} — resolved view of one brand for
// the caller.
func (s *Server) handleGetToyota(w http.ResponseWriter, r *http.Request) {
who := caller(r)
if who == nil {
writeError(w, http.StatusUnauthorized, "not authenticated")
return
}
b, ok := integrationBrand(w, r)
if !ok {
return
}
userRaw := s.userPluginSettings(r.Context(), who.ID)
res := s.resolveToyota(r.Context(), who, userRaw)
writeJSON(w, http.StatusOK, s.toyotaView(who, res))
res := s.resolveToyota(r.Context(), who, userRaw, b)
writeJSON(w, http.StatusOK, s.toyotaView(who, res, b))
}
// PUT /api/integrations/toyota — save the caller's editable layer. Body:
// {enabled?: bool, scope?: "user"|"org", config?: {username, password, brand}}.
// Fields locked above the caller are ignored; a password left at the mask is
// preserved.
// PUT /api/integrations/{toyota|lexus|subaru} — save the caller's editable layer
// of one brand. Body: {enabled?: bool, scope?: "user"|"org", config?: {username,
// password}}. Fields locked above the caller are ignored; a password left at the
// mask is preserved.
func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) {
who := caller(r)
if who == nil {
writeError(w, http.StatusUnauthorized, "not authenticated")
return
}
b, ok := integrationBrand(w, r)
if !ok {
return
}
if !s.pb.Configured() {
writeError(w, http.StatusServiceUnavailable, "integration settings not configured on the server")
return
@@ -334,7 +415,7 @@ func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) {
}
userRaw := s.userPluginSettings(r.Context(), who.ID)
res := s.resolveToyota(r.Context(), who, userRaw)
res := s.resolveToyota(r.Context(), who, userRaw, b)
// Resolve which layer this write targets. Everyone edits their own personal
// (user) layer by default; an org admin may target the organization layer by
@@ -370,12 +451,11 @@ func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) {
}
applyField("username", func(c *toyotaConfig, v string) { c.Username = v })
applyField("password", func(c *toyotaConfig, v string) { c.Password = v })
applyField("brand", func(c *toyotaConfig, v string) { c.Brand = v })
// Persist the organization layer (admins) via the service account.
if editable == "org" {
_, orgRaw := s.orgToyota(r.Context(), who.OrgID)
newDoc := mergeToyota(orgRaw, func(ts *toyotaStored) {
_, orgRaw := s.orgToyota(r.Context(), who.OrgID, b)
newDoc := mergeToyota(orgRaw, b, func(ts *toyotaStored) {
ts.Config = newOwn
// In the org scope the enable flag is the org master switch, stored
// inverted (disabled) so absent means enabled.
@@ -401,7 +481,7 @@ func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) {
// so does the personal config layer when this write targets the user scope.
personalEnable := body.Enabled != nil && editable != "org"
if personalEnable || editable == "user" {
newDoc := mergeToyota(userRaw, func(ts *toyotaStored) {
newDoc := mergeToyota(userRaw, b, func(ts *toyotaStored) {
if personalEnable {
ts.Enabled = *body.Enabled
}
@@ -418,42 +498,45 @@ func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) {
// Re-resolve and return the fresh view.
fresh := s.userPluginSettings(r.Context(), who.ID)
res2 := s.resolveToyota(r.Context(), who, fresh)
writeJSON(w, http.StatusOK, s.toyotaView(who, res2))
res2 := s.resolveToyota(r.Context(), who, fresh, b)
writeJSON(w, http.StatusOK, s.toyotaView(who, res2, b))
}
// POST /api/integrations/toyota/health — live probe using the caller's resolved
// config. Never returns secrets.
// POST /api/integrations/{toyota|lexus|subaru}/health — live probe using the
// caller's resolved config for that brand. Never returns secrets.
func (s *Server) handleToyotaHealth(w http.ResponseWriter, r *http.Request) {
who := caller(r)
if who == nil {
writeError(w, http.StatusUnauthorized, "not authenticated")
return
}
b, ok := integrationBrand(w, r)
if !ok {
return
}
userRaw := s.userPluginSettings(r.Context(), who.ID)
res := s.resolveToyota(r.Context(), who, userRaw)
res := s.resolveToyota(r.Context(), who, userRaw, b)
down := func(detail string) {
writeJSON(w, http.StatusOK, map[string]any{"health": map[string]any{"status": "down", "detail": detail}})
}
switch {
case !res.available:
down("The Toyota integration is disabled by the administrator")
down("The " + b.Make + " integration is disabled by the administrator")
return
case !res.orgEnabled:
down("The Toyota integration is disabled for your organization")
down("The " + b.Make + " integration is disabled for your organization")
return
case strings.TrimSpace(res.eff.Username) == "" || strings.TrimSpace(res.eff.Password) == "":
down("Enter your MyToyota email and password to connect")
down("Enter your " + b.App + " email and password to connect")
return
}
cfg := map[string]string{
"username": res.eff.Username,
"password": res.eff.Password,
"brand": res.eff.Brand,
}
h, err := s.plugins.HealthCheckWith(r.Context(), toyotaPlugin, cfg)
h, err := s.plugins.HealthCheckWith(r.Context(), b.Name, cfg)
if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()})
return
@@ -461,7 +544,8 @@ func (s *Server) handleToyotaHealth(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"health": h})
}
// GET /api/integrations/toyota/vehicles — the caller's Toyota vehicles as the
// GET /api/integrations/{toyota|lexus|subaru}/vehicles — the caller's vehicles
// on that brand's account as the
// upstream returned them, fetched server-side under their resolved credentials.
// Gated by the same switches as the settings view (global master, org gate,
// personal opt-in, credentials present); when any gate is off it returns 200 with
@@ -477,14 +561,18 @@ func (s *Server) handleToyotaVehicles(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusUnauthorized, "not authenticated")
return
}
b, found := integrationBrand(w, r)
if !found {
return
}
userRaw := s.userPluginSettings(r.Context(), who.ID)
cfg, ok, detail := toyotaSource{}.gate(r.Context(), s, who, userRaw)
cfg, ok, detail := toyotaSource{b}.gate(r.Context(), s, who, userRaw)
if !ok {
writeJSON(w, http.StatusOK, map[string]any{"vehicles": []any{}, "unavailable": true, "detail": detail})
return
}
raw, err := s.plugins.InvokeWith(r.Context(), toyotaPlugin, cfg, "vehicles", nil)
raw, err := s.plugins.InvokeWith(r.Context(), b.Name, cfg, "vehicles", nil)
if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()})
return
@@ -0,0 +1,131 @@
package api
import (
"encoding/json"
"net/http"
"strings"
"testing"
)
// Toyota, Lexus and Subaru are one connector shown as three integrations, so
// each brand must be a vehicle provider of its own, labelled with its app.
func TestEveryBrandIsAVehicleProvider(t *testing.T) {
want := map[string]string{"toyota": "MyToyota", "lexus": "Lexus Link+", "subaru": "MySubaru"}
for id, label := range want {
src, ok := vehicleSourceByID(id)
if !ok {
t.Errorf("%q is not a vehicle provider", id)
continue
}
if src.label() != label {
t.Errorf("%q label = %q, want %q", id, src.label(), label)
}
}
if n := len(vehicleSources()); n != len(want) {
t.Errorf("vehicle providers = %d, want %d", n, len(want))
}
}
// Before the split every brand lived under pluginSettings.toyota with a brand
// field. A Lexus or Subaru entry there belongs to that brand now, and must leave
// the Toyota card empty rather than show the other brand's login.
func TestLegacyBrandEntryMovesToItsBrand(t *testing.T) {
lexus, _ := brandByName("lexus")
subaru, _ := brandByName("subaru")
raw := json.RawMessage(`{"toyota":{"config":{"username":"me@x","password":"pw","brand":"L"},"enabled":true},"anker-solix":{"enabled":true}}`)
if got := storedFor(raw, lexus); got.Config.Username != "me@x" || got.Config.Password != "pw" || !got.Enabled {
t.Errorf("lexus entry = %+v, want the legacy login, enabled", got)
}
if got := storedFor(raw, toyotaBrand); got.Config.Username != "" || got.Enabled {
t.Errorf("toyota entry = %+v, want empty — the legacy login was a Lexus one", got)
}
if got := storedFor(raw, subaru); got.Config.Username != "" {
t.Errorf("subaru entry = %+v, want empty", got)
}
// Saving any brand writes the move back and keeps unrelated plugins.
out := mergeToyota(raw, toyotaBrand, func(ts *toyotaStored) { ts.Config.Username = "t@x" })
var doc map[string]map[string]any
_ = json.Unmarshal(out, &doc)
if doc["lexus"] == nil || doc["anker-solix"] == nil {
t.Fatalf("merged doc lost an entry: %s", out)
}
if cfg, _ := doc["toyota"]["config"].(map[string]any); cfg["username"] != "t@x" || cfg["brand"] != nil {
t.Errorf("toyota entry after save = %v", doc["toyota"])
}
// A plain Toyota entry, with or without the old field, stays where it is.
for _, plain := range []string{
`{"toyota":{"config":{"username":"t@x","brand":"T"}}}`,
`{"toyota":{"config":{"username":"t@x"}}}`,
} {
if got := storedFor(json.RawMessage(plain), toyotaBrand); got.Config.Username != "t@x" {
t.Errorf("%s: toyota entry = %+v", plain, got)
}
}
// A brand that already has its own entry keeps it; the legacy one is dropped.
both := json.RawMessage(`{"toyota":{"config":{"username":"old","brand":"S"}},"subaru":{"config":{"username":"new"}}}`)
if got := storedFor(both, subaru); got.Config.Username != "new" {
t.Errorf("subaru entry = %+v, want its own", got)
}
}
// A car linked before the split says provider "toyota" whatever its make; it
// must read through its own brand's account.
func TestLegacyCarLinkFollowsItsMake(t *testing.T) {
cases := []struct{ provider, make, want string }{
{"toyota", "Lexus", "lexus"},
{"toyota", "SUBARU", "subaru"},
{"toyota", "Toyota", "toyota"},
{"toyota", "", "toyota"},
{"lexus", "Lexus", "lexus"},
}
for _, c := range cases {
src, ok := carVehicleSource(c.provider, c.make)
if !ok || src.id() != c.want {
t.Errorf("carVehicleSource(%q, %q) = %v, want %q", c.provider, c.make, src, c.want)
}
}
}
// Each brand answers on its own route with its own identity, and the provider
// listing offers all three — the server end of "three plugins in the apps".
func TestEveryBrandHasItsOwnIntegrationRoutes(t *testing.T) {
srv := newProviderTestServer(t, &fakeProviderPB{})
for _, c := range []struct{ brand, make, app string }{
{"toyota", "Toyota", "MyToyota"},
{"lexus", "Lexus", "Lexus Link+"},
{"subaru", "Subaru", "MySubaru"},
} {
status, body := call(t, srv, http.MethodGet, "/api/integrations/"+c.brand, "")
if status != http.StatusOK {
t.Errorf("GET %s: status %d", c.brand, status)
continue
}
if body["brand"] != c.brand || body["make"] != c.make || body["app"] != c.app {
t.Errorf("GET %s: identity = %v/%v/%v", c.brand, body["brand"], body["make"], body["app"])
}
scopes, _ := body["scopes"].(map[string]any)
user, _ := scopes["user"].(map[string]any)
fields, _ := user["fields"].(map[string]any)
if _, hasBrand := fields["brand"]; hasBrand || fields["username"] == nil {
t.Errorf("GET %s: fields = %v, want username/password and no brand picker", c.brand, fields)
}
// Plugin not enabled for lexus/subaru in this store: the probe says so,
// naming the brand rather than Toyota.
status, body = call(t, srv, http.MethodPost, "/api/integrations/"+c.brand+"/health", "")
h, _ := body["health"].(map[string]any)
if status != http.StatusOK || h["status"] != "down" || !strings.Contains(h["detail"].(string), c.make) {
t.Errorf("POST %s/health: %d %v", c.brand, status, body)
}
}
_, body := call(t, srv, http.MethodGet, "/api/vehicle-providers", "")
if list, _ := body["providers"].([]any); len(list) != 3 {
t.Errorf("providers = %v, want three", body["providers"])
}
}
+13 -7
View File
@@ -45,9 +45,9 @@
// DELETE /api/admin/plugins/{name} POST /api/admin/plugins/{name}/health
//
// # integrations (per-user plugin settings; superadmin → org admin → user cascade)
// GET /api/integrations/toyota PUT /api/integrations/toyota
// POST /api/integrations/toyota/health
// GET /api/integrations/toyota/vehicles
// GET /api/integrations/{toyota|lexus|subaru} PUT (same)
// POST /api/integrations/{toyota|lexus|subaru}/health
// GET /api/integrations/{toyota|lexus|subaru}/vehicles
// GET /api/integrations/anker-solix PUT /api/integrations/anker-solix
// POST /api/integrations/anker-solix/health
// GET /api/integrations/anker-solix/chargers
@@ -142,6 +142,7 @@ import (
"drivervault/apiserver/internal/ocpp"
"drivervault/apiserver/internal/pb"
"drivervault/apiserver/internal/plugins"
"drivervault/apiserver/internal/plugins/builtin/toyota"
_ "drivervault/apiserver/internal/plugins/builtin" // register built-in plugins
)
@@ -444,10 +445,15 @@ func (s *Server) Handler() http.Handler {
// Integrations — per-user plugin settings under the superadmin → org admin →
// user cascade (see integrations.go). Any authenticated user manages their
// own layer; an org admin may also target their organization's layer.
mux.HandleFunc("GET /api/integrations/toyota", s.handleGetToyota)
mux.HandleFunc("PUT /api/integrations/toyota", s.handlePutToyota)
mux.HandleFunc("POST /api/integrations/toyota/health", s.handleToyotaHealth)
mux.HandleFunc("GET /api/integrations/toyota/vehicles", s.handleToyotaVehicles)
// Toyota, Lexus and Subaru are one connector registered once per brand; each
// gets its own routes, so the apps can show them as three integrations.
for _, b := range toyota.Brands {
base := "/api/integrations/" + b.Name
mux.HandleFunc("GET "+base, s.handleGetToyota)
mux.HandleFunc("PUT "+base, s.handlePutToyota)
mux.HandleFunc("POST "+base+"/health", s.handleToyotaHealth)
mux.HandleFunc("GET "+base+"/vehicles", s.handleToyotaVehicles)
}
mux.HandleFunc("GET /api/integrations/anker-solix", s.handleGetAnker)
mux.HandleFunc("PUT /api/integrations/anker-solix", s.handlePutAnker)
mux.HandleFunc("POST /api/integrations/anker-solix/health", s.handleAnkerHealth)
+32 -5
View File
@@ -49,6 +49,7 @@ import (
"drivervault/apiserver/internal/models"
"drivervault/apiserver/internal/plugins"
"drivervault/apiserver/internal/plugins/builtin/toyota"
)
// vehicleSource adapts one plugin that can enumerate the caller's vehicles and
@@ -73,9 +74,30 @@ type vehicleSource interface {
sections() []providerSection
}
// vehicleSources are the registered providers, in menu order.
// vehicleSources are the registered providers, in menu order: one per brand of
// the Toyota Connected Europe connector.
func vehicleSources() []vehicleSource {
return []vehicleSource{toyotaSource{}}
out := make([]vehicleSource, 0, len(toyota.Brands))
for _, b := range toyota.Brands {
out = append(out, toyotaSource{b})
}
return out
}
// carVehicleSource is the provider a linked car reads from. A Lexus or a Subaru
// linked before the brands were split carries provider "toyota" — there was only
// the one — so its make picks the brand it now belongs to; reading it through
// the Toyota account would log in to the wrong app.
func carVehicleSource(provider, carMake string) (vehicleSource, bool) {
if provider == toyotaBrand.Name && strings.TrimSpace(carMake) != "" {
mk := toyotaMake(carMake)
for _, b := range toyota.Brands {
if b.Make == mk {
return toyotaSource{b}, true
}
}
}
return vehicleSourceByID(provider)
}
func vehicleSourceByID(id string) (vehicleSource, bool) {
@@ -282,8 +304,13 @@ func (s *Server) linkedVehicles(ctx context.Context, userID, provider string) ma
if userID == "" || provider == "" {
return out
}
filter := fmt.Sprintf("provider='%s'", provider)
if b, ok := brandByName(provider); ok && b.Name != toyotaBrand.Name {
// Cars of this brand linked before the split are under "toyota".
filter = fmt.Sprintf("(%s || (provider='%s' && make='%s'))", filter, toyotaBrand.Name, b.Make)
}
res, err := s.pb.List(ctx, colCars, url.Values{
"filter": {fmt.Sprintf("owner='%s' && provider='%s'", userID, provider)},
"filter": {fmt.Sprintf("owner='%s' && %s", userID, filter)},
"perPage": {"200"},
})
if err != nil {
@@ -531,7 +558,7 @@ func (s *Server) handleCarProvider(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "this car is not linked to a connected service")
return
}
src, found := vehicleSourceByID(rec.Provider)
src, found := carVehicleSource(rec.Provider, rec.Make)
if !found {
writeError(w, http.StatusNotFound, "unknown vehicle provider")
return
@@ -822,7 +849,7 @@ func (s *Server) handleSyncCarProvider(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "this car is not linked to a connected service")
return
}
src, found := vehicleSourceByID(rec.Provider)
src, found := carVehicleSource(rec.Provider, rec.Make)
if !found {
writeError(w, http.StatusNotFound, "unknown vehicle provider")
return
@@ -1,7 +1,9 @@
package api
// toyotaSource is the first vehicleSource: Toyota Connected Europe, the backend
// behind the MyToyota app (see internal/plugins/builtin/toyota). It contributes
// behind the MyToyota app (see internal/plugins/builtin/toyota), and behind the
// Lexus and Subaru apps too. There is one source per brand, so each shows up as
// a provider of its own, labelled with the app its owner knows. It contributes
// nothing but wiring — credentials come from the cascade already in
// integrations.go, and the payload walking lives in vehicleproviders.go — which
// is the shape the next manufacturer's adapter should copy.
@@ -12,14 +14,13 @@ import (
"strings"
)
// toyotaLabel is what the user sees: the app they know the account by, not the
// corporate service name behind it. It titles the car's provider tab.
const toyotaLabel = "MyToyota"
// toyotaSource serves one brand. Its label is what the user sees: the app they
// know the account by ("MyToyota", "Lexus Link+"), not the corporate service
// name behind it. It titles the car's provider tab.
type toyotaSource struct{ brand vehicleBrand }
type toyotaSource struct{}
func (toyotaSource) id() string { return toyotaPlugin }
func (toyotaSource) label() string { return toyotaLabel }
func (t toyotaSource) id() string { return t.brand.Name }
func (t toyotaSource) label() string { return t.brand.App }
func (toyotaSource) service() string { return "Toyota Connected Europe" }
func (toyotaSource) listAction() string { return "vehicles" }
@@ -40,25 +41,25 @@ func (toyotaSource) sections() []providerSection {
}
}
// gate resolves the caller's MyToyota credentials through the global → org → user
// cascade and reports what is missing when they cannot be used. It is the single
// place those messages are written: handleToyotaVehicles calls it too.
func (toyotaSource) gate(ctx context.Context, s *Server, who *callerIdentity, userRaw json.RawMessage) (map[string]string, bool, string) {
res := s.resolveToyota(ctx, who, userRaw)
// gate resolves the caller's credentials for this brand through the global → org
// → user cascade and reports what is missing when they cannot be used. It is the
// single place those messages are written: handleToyotaVehicles calls it too.
func (t toyotaSource) gate(ctx context.Context, s *Server, who *callerIdentity, userRaw json.RawMessage) (map[string]string, bool, string) {
b := t.brand
res := s.resolveToyota(ctx, who, userRaw, b)
switch {
case !res.available:
return nil, false, "The Toyota integration is disabled by the administrator"
return nil, false, "The " + b.Make + " integration is disabled by the administrator"
case !res.orgEnabled:
return nil, false, "The Toyota integration is disabled for your organization"
return nil, false, "The " + b.Make + " integration is disabled for your organization"
case !res.enabled:
return nil, false, "Enable the Toyota integration in Settings to load your vehicles"
return nil, false, "Enable the " + b.Make + " integration in Settings to load your vehicles"
case strings.TrimSpace(res.eff.Username) == "" || strings.TrimSpace(res.eff.Password) == "":
return nil, false, "Enter your MyToyota email and password to connect"
return nil, false, "Enter your " + b.App + " email and password to connect"
}
return map[string]string{
"username": res.eff.Username,
"password": res.eff.Password,
"brand": res.eff.Brand,
}, true, ""
}
+2 -1
View File
@@ -177,7 +177,8 @@ Restart the server. The plugin appears in the panel's **Plugins** card,
**disabled** by default.
> DriverVault ships four built-in connectors today — `toyota` (Toyota Connected /
> MyToyota, read-only vehicle data), `anker-solix` (Anker Solix V1 EV charger),
> MyToyota, read-only vehicle data; registered three times, as `toyota`, `lexus`
> and `subaru`, so each brand shows up as a plugin of its own), `anker-solix` (Anker Solix V1 EV charger),
> `greencell` (Greencell HabuDen EV charger, read over the owner's MQTT broker
> rather than a cloud API) and `apprise` (notifications, through an apprise-api
> gateway the operator runs) — all blank-imported from `builtin/builtin.go`. The
@@ -24,6 +24,9 @@ func TestEveryBuiltinIsRegistered(t *testing.T) {
"apprise": plugins.CategoryNotifications,
"greencell": plugins.CategoryChargers,
"toyota": plugins.CategoryVehicles,
// One connector, three registrations: see toyota.Brands.
"lexus": plugins.CategoryVehicles,
"subaru": plugins.CategoryVehicles,
}
for name, category := range want {
v, ok := seen[name]
@@ -138,8 +138,41 @@ const (
// never fires with a token that expires mid-flight.
const tokenExpiryMargin = 30 * time.Second
// Brand is one of the three makes this connector serves. The apps show each as
// a plugin of its own — its own panel entry, its own settings card, its own
// credentials — because an owner thinks of "my Lexus account", not of the
// Toyota Connected Europe backend the three happen to share. The code is one
// connector; only the login realm and a few headers differ (see authFor).
type Brand struct {
Name string // plugin name, also the key under pluginSettings: "toyota"
Code string // the one-letter code the API uses on the wire: "T"
Make string // "Toyota"
App string // the app the owner knows the account by: "MyToyota"
Provider string // the panel's provider line
}
// Brands are the registered makes, in menu order.
var Brands = []Brand{
{Name: "toyota", Code: "T", Make: "Toyota", App: "MyToyota", Provider: "Toyota Connected Europe"},
{Name: "lexus", Code: "L", Make: "Lexus", App: "Lexus Link+", Provider: "Lexus (Toyota Connected Europe)"},
{Name: "subaru", Code: "S", Make: "Subaru", App: "MySubaru", Provider: "Subaru (Toyota Connected Europe)"},
}
// brandByCode finds a brand by its wire code; Toyota for anything unknown.
func brandByCode(code string) Brand {
for _, b := range Brands {
if b.Code == code {
return b
}
}
return Brands[0]
}
func init() {
plugins.Register("toyota", func() plugins.Plugin { return &Plugin{} })
for _, b := range Brands {
code := b.Code
plugins.Register(b.Name, func() plugins.Plugin { return &Plugin{fixedBrand: code} })
}
}
// tokenInfo holds the currently-held OAuth tokens and the derived account UUID.
@@ -154,8 +187,11 @@ type tokenInfo struct {
type Plugin struct {
username string
password string
brand string // "T" (Toyota), "L" (Lexus) or "S" (Subaru)
auth brandAuth // the OAuth client for brand, fixed at Init
// fixedBrand is the brand this registration serves, set by its factory. A
// bare &Plugin{} (tests) has none and takes the brand from config instead.
fixedBrand string
brand string // "T" (Toyota), "L" (Lexus) or "S" (Subaru)
auth brandAuth // the OAuth client for brand, fixed at Init
mu sync.Mutex // guards tok and the login flow
tok *tokenInfo
@@ -169,9 +205,10 @@ type Plugin struct {
// Descriptor returns the plugin's static metadata for the admin panel.
func (p *Plugin) Descriptor() plugins.Descriptor {
b := brandByCode(p.fixedBrand)
return plugins.Descriptor{
Name: "toyota",
Provider: "Toyota Connected Europe",
Name: b.Name,
Provider: b.Provider,
Version: "0.4.0",
Kind: plugins.KindBuiltin,
Category: plugins.CategoryVehicles,
@@ -190,21 +227,15 @@ func (p *Plugin) Descriptor() plugins.Descriptor {
},
ConfigFields: []plugins.ConfigField{
// Credentials are intentionally NOT required at the global (panel) layer:
// this connector runs under each user's own MyToyota account, supplied in
// the Web App's per-user integration settings. A superadmin/org admin may
// this connector runs under each user's own account, supplied in the
// Web App's per-user integration settings. A superadmin/org admin may
// still set a shared (e.g. fleet) account here that users inherit. See the
// cascade in internal/api/integrations.go.
{Key: "username", Label: "MyToyota email", Type: "text",
Help: "The email address for your MyToyota (Toyota Connected Europe) account."},
{Key: "password", Label: "MyToyota password", Type: "password", Secret: true,
Help: "Your MyToyota account password. Stored locally, sent only to Toyota's login endpoint."},
{Key: "brand", Label: "Brand", Type: "select", Default: "T",
Help: "Vehicle brand tied to the account. Subaru accounts (Solterra) log in through their own realm on the same service.",
Options: []plugins.SelectOption{
{Value: "T", Label: "Toyota"},
{Value: "L", Label: "Lexus"},
{Value: "S", Label: "Subaru"},
}},
// cascade in internal/api/integrations.go. There is no brand field: each
// brand is its own registration.
{Key: "username", Label: b.App + " email", Type: "text",
Help: "The email address for your " + b.App + " account."},
{Key: "password", Label: b.App + " password", Type: "password", Secret: true,
Help: "Your " + b.App + " account password. Stored locally, sent only to the " + b.Make + " login endpoint."},
},
}
}
@@ -217,7 +248,10 @@ func (p *Plugin) Init(_ context.Context, config map[string]string) error {
p.username = strings.TrimSpace(config["username"])
p.password = config["password"]
p.brand = strings.TrimSpace(config["brand"])
p.brand = p.fixedBrand
if p.brand == "" {
p.brand = strings.TrimSpace(config["brand"])
}
if p.brand == "" {
p.brand = "T"
}
@@ -22,34 +22,58 @@ func TestDescriptor(t *testing.T) {
if len(d.Capabilities) == 0 {
t.Fatal("expected capabilities")
}
// The credential + brand 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.
// 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", "brand"} {
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")
}
// The three brands that share the backend must all be offered: a value the
// select does not list cannot be chosen from the panel.
brands := map[string]bool{}
for _, o := range fields["brand"].Options {
brands[o.Value] = true
}
// 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 []string{"T", "L", "S"} {
if !brands[b] {
t.Errorf("brand option %q should be offered", b)
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)
}
}