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