The control-mode picker offered all five paths to everyone, always. When one of them is broken in a deployment — OCPP is, right now — there was nothing to do about it: the superadmin could pick a different mode for the global layer, but the option stayed in every organization's and every user's dropdown, waiting to be chosen. The cascade could impose a mode. It could not withdraw one. So each layer now carries a second, separate thing: a list of the modes it hides from the layers below it. controlModesDisabled sits beside controlMode, on the global layer as a plugin config field and on an organization as part of the same pluginSettings blob its credentials already live in. A superadmin ticking Own CSMS and Proxy CSMS takes both OCPP paths out of every picker underneath; an org admin ticking Modbus takes it out of their own users'. Three decisions are worth naming. A hide-list governs the layers below, not the layer holding it. The superadmin can keep running Proxy globally while hiding it from everyone else, which is what you want while a mode is being repaired rather than retired: the operator testing the fix is the one person who still needs to select it. The alternative, a list that also invalidates its own layer's choice, would have made the panel contradict itself — a mode chosen in one field and switched off in the one below it. But a hidden mode really is hidden, not merely absent from a dropdown. A user who had picked Proxy last month stops resolving to Proxy the moment the superadmin hides it, and falls back to monitoring only. Filtering the picker alone would have left every existing charger on the broken path and quietly disagreed with the list the operator had just filled in. Resolution now walks the layers accumulating what each hides from the next, so a stored value only takes effect if the layers above it still permit it. And off is never hideable. It is what a charger falls back to and what an empty cascade resolves to, so a layer that could take it away could leave the layer below with a picker holding no valid choice at all. It is not among the checkboxes in any of the three clients, and the parser drops it if it arrives anyway. The panel needed a field shape it did not have — several options, any number chosen — so ConfigField grows a "multiselect" type, stored as the comma-separated string that fits the flat map every other field already uses. That is generic: any plugin can declare one now, and the PUT body is unchanged. The phone's field specs grew the same way, a scopeOptions hook that narrows a declared option list to what the server still offers, rather than teaching the integration card about control modes specifically. Both clients clamp a stored mode that has since been hidden back to off before drawing the picker, so the box shows what will actually happen rather than a choice that would be dropped on save. Verified: Go tests pass, both frontends build, flutter analyze is clean, and the panel's new checkbox field was rendered against the real stylesheet. The end-to-end path — superadmin hides a mode, an org admin and then a user reload and find it gone — has not been walked on a live stack; the panel is embedded in the Go binary, so the remote deployment needs a rebuild before any of this is visible there. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
324 lines
10 KiB
Go
324 lines
10 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"drivervault/apiserver/internal/config"
|
|
"drivervault/apiserver/internal/pb"
|
|
)
|
|
|
|
func TestNormalizeControlMode(t *testing.T) {
|
|
cases := map[string]string{
|
|
"off": "off",
|
|
"own": "own",
|
|
"proxy": "proxy",
|
|
"modbus": "modbus",
|
|
"mqtt": "mqtt",
|
|
"OWN": "own",
|
|
" Proxy": "proxy",
|
|
"Modbus ": "modbus",
|
|
" MQTT ": "mqtt",
|
|
"": "", // unset — cascade continues to the next layer
|
|
"bogus": "", // unknown — treated as unset
|
|
}
|
|
for in, want := range cases {
|
|
if got := normalizeControlMode(in); got != want {
|
|
t.Errorf("normalizeControlMode(%q) = %q, want %q", in, got, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
// binding builds a hashed binding the way handleAnkerControlToken does, so the
|
|
// index tests exercise the real hash-at-rest path.
|
|
func binding(token string) ankerChargerBinding {
|
|
return ankerChargerBinding{TokenHash: hashToken(token), TokenHint: tokenHint(token)}
|
|
}
|
|
|
|
func TestControlIndexSetUserInvalidatesOldToken(t *testing.T) {
|
|
ci := newControlIndex()
|
|
ci.setUser("u1", map[string]ankerChargerBinding{"SN1": binding("tok-old")})
|
|
if _, ok := ci.lookup("tok-old"); !ok {
|
|
t.Fatal("tok-old should resolve after first set")
|
|
}
|
|
// Regenerate: same charger, new token. The old token must stop resolving.
|
|
ci.setUser("u1", map[string]ankerChargerBinding{"SN1": binding("tok-new")})
|
|
if _, ok := ci.lookup("tok-old"); ok {
|
|
t.Error("tok-old should be invalidated after regeneration")
|
|
}
|
|
b, ok := ci.lookup("tok-new")
|
|
if !ok || b.UserID != "u1" || b.Serial != "SN1" {
|
|
t.Errorf("tok-new resolves to %+v (ok=%v), want u1/SN1", b, ok)
|
|
}
|
|
}
|
|
|
|
func TestControlIndexRevoke(t *testing.T) {
|
|
ci := newControlIndex()
|
|
ci.setUser("u1", map[string]ankerChargerBinding{"SN1": binding("tok")})
|
|
// Revoke = setUser with the charger removed.
|
|
ci.setUser("u1", map[string]ankerChargerBinding{})
|
|
if _, ok := ci.lookup("tok"); ok {
|
|
t.Error("token should not resolve after revocation")
|
|
}
|
|
}
|
|
|
|
func TestControlIndexIsolatesUsers(t *testing.T) {
|
|
ci := newControlIndex()
|
|
ci.setUser("u1", map[string]ankerChargerBinding{"SN1": binding("a")})
|
|
ci.setUser("u2", map[string]ankerChargerBinding{"SN2": binding("b")})
|
|
// Re-setting u1 must not touch u2's token.
|
|
ci.setUser("u1", map[string]ankerChargerBinding{"SN1": binding("a2")})
|
|
if _, ok := ci.lookup("b"); !ok {
|
|
t.Error("u2's token should be untouched when u1 is updated")
|
|
}
|
|
}
|
|
|
|
func TestControlIndexStoresNoPlaintext(t *testing.T) {
|
|
ci := newControlIndex()
|
|
ci.setUser("u1", map[string]ankerChargerBinding{"SN1": binding("super-secret-token")})
|
|
// The plaintext must never appear as an index key.
|
|
ci.mu.RLock()
|
|
defer ci.mu.RUnlock()
|
|
if _, ok := ci.byHash["super-secret-token"]; ok {
|
|
t.Fatal("index must key on the hash, never the plaintext token")
|
|
}
|
|
}
|
|
|
|
func TestAnkerBindingFor(t *testing.T) {
|
|
raw := json.RawMessage(`{"ankerSolix":{"controlChargers":{"SN1":{"tokenHash":"abc","tokenHint":"1234"}}}}`)
|
|
if got := ankerBindingFor(raw, "SN1").TokenHash; got != "abc" {
|
|
t.Errorf("binding hash = %q, want abc", got)
|
|
}
|
|
if got := ankerBindingFor(raw, "other").TokenHash; got != "" {
|
|
t.Errorf("unknown charger should have empty hash, got %q", got)
|
|
}
|
|
if got := ankerBindingFor(nil, "SN1").TokenHash; got != "" {
|
|
t.Errorf("nil settings should have empty hash, got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestHashAndHint(t *testing.T) {
|
|
tok := "0123456789abcdef"
|
|
if h := hashToken(tok); len(h) != 64 || h == tok {
|
|
t.Errorf("hashToken should be a 64-char hex digest distinct from input, got %q", h)
|
|
}
|
|
if hashToken("a") == hashToken("b") {
|
|
t.Error("distinct tokens must hash differently")
|
|
}
|
|
if got := tokenHint(tok); got != "cdef" {
|
|
t.Errorf("tokenHint = %q, want cdef", got)
|
|
}
|
|
if got := tokenHint("ab"); got != "ab" {
|
|
t.Errorf("short-token hint = %q, want ab", got)
|
|
}
|
|
}
|
|
|
|
func TestIsDestructiveAction(t *testing.T) {
|
|
for _, a := range []string{"reset", "unlock"} {
|
|
if !isDestructiveAction(a) {
|
|
t.Errorf("%q should be destructive", a)
|
|
}
|
|
}
|
|
for _, a := range []string{"start", "stop", "limit", "clear-limit", "availability", "trigger", "config"} {
|
|
if isDestructiveAction(a) {
|
|
t.Errorf("%q should not be destructive", a)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRateLimiter(t *testing.T) {
|
|
rl := newRateLimiter(2, time.Minute)
|
|
if !rl.allow("k") || !rl.allow("k") {
|
|
t.Fatal("first two calls should be allowed")
|
|
}
|
|
if rl.allow("k") {
|
|
t.Error("third call in the window should be blocked")
|
|
}
|
|
if !rl.allow("other") {
|
|
t.Error("a different key must have its own budget")
|
|
}
|
|
}
|
|
|
|
func TestReauthenticateGuards(t *testing.T) {
|
|
// With PocketBase unconfigured, re-auth must fail closed regardless of input,
|
|
// and never treat a missing password/email as success.
|
|
s := &Server{pb: pb.New("", "", "")}
|
|
ctx := context.Background()
|
|
cases := []struct {
|
|
name string
|
|
who *callerIdentity
|
|
pass string
|
|
}{
|
|
{"nil caller", nil, "pw"},
|
|
{"empty email", &callerIdentity{ID: "u1"}, "pw"},
|
|
{"empty password", &callerIdentity{ID: "u1", Email: "a@b.c"}, ""},
|
|
{"pb unconfigured", &callerIdentity{ID: "u1", Email: "a@b.c"}, "pw"},
|
|
}
|
|
for _, c := range cases {
|
|
if s.reauthenticate(ctx, c.who, c.pass) {
|
|
t.Errorf("%s: reauthenticate should fail closed", c.name)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestAnkerUpstreamAllowed(t *testing.T) {
|
|
ok := []string{
|
|
"wss://ankerpower-api-eu.anker.com/ocpp/CP1",
|
|
"wss://ankerpower-api.anker.com/x",
|
|
"ws://anker.com/y",
|
|
}
|
|
bad := []string{
|
|
"wss://evil.example.com/ocpp/CP1",
|
|
"wss://anker.com.evil.net/x",
|
|
"not a url at all ::::",
|
|
"",
|
|
}
|
|
for _, u := range ok {
|
|
if !ankerUpstreamAllowed(u) {
|
|
t.Errorf("%q should be allowed", u)
|
|
}
|
|
}
|
|
for _, u := range bad {
|
|
if ankerUpstreamAllowed(u) {
|
|
t.Errorf("%q should be rejected", u)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestExtractWSURL(t *testing.T) {
|
|
cases := map[string]string{
|
|
`{"data":{"ocppUrl":"wss://ocpp.anker.com/CP1"}}`: "wss://ocpp.anker.com/CP1",
|
|
`{"a":{"b":[{"endpoint":"ws://x/y"}]}}`: "ws://x/y",
|
|
`{"data":{"note":"https://not-a-ws-url"}}`: "",
|
|
`{"empty":true}`: "",
|
|
}
|
|
for in, want := range cases {
|
|
if got := extractWSURL(json.RawMessage(in)); got != want {
|
|
t.Errorf("extractWSURL(%s) = %q, want %q", in, got, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestOCPPEndpoint(t *testing.T) {
|
|
s := &Server{}
|
|
// Plain HTTP request → ws://
|
|
r := httptest.NewRequest("GET", "http://host.example/x", nil)
|
|
r.Host = "host.example"
|
|
if got := s.ocppEndpoint(r, "SN 1"); got != "ws://host.example/ocpp/SN%201" {
|
|
t.Errorf("endpoint = %q", got)
|
|
}
|
|
// Behind a TLS-terminating proxy → wss://
|
|
r2 := httptest.NewRequest("GET", "http://host.example/x", nil)
|
|
r2.Host = "host.example"
|
|
r2.Header.Set("X-Forwarded-Proto", "https")
|
|
if got := s.ocppEndpoint(r2, "SN1"); got != "wss://host.example/ocpp/SN1" {
|
|
t.Errorf("tls endpoint = %q", got)
|
|
}
|
|
}
|
|
|
|
// The four card routes are reachable at all. A capability the plugin implements
|
|
// and the action catalogue advertises is still unusable if nothing routes to it,
|
|
// and that is not a failure any other test here would notice: the plugin's own
|
|
// tests pass, and the panel simply has no button. Each route is asked for
|
|
// without a token, so what is being checked is that the request reached the
|
|
// authentication middleware rather than a 404.
|
|
func TestAnkerCardRoutesAreRegistered(t *testing.T) {
|
|
h := New(config.Config{}, nil).Handler()
|
|
for _, tc := range []struct{ method, path string }{
|
|
{"POST", "/api/integrations/anker-solix/chargers/SN1/rfid-cards"},
|
|
{"POST", "/api/integrations/anker-solix/chargers/SN1/rfid-cards/scan"},
|
|
{"GET", "/api/integrations/anker-solix/chargers/SN1/rfid-cards/charger"},
|
|
{"DELETE", "/api/integrations/anker-solix/chargers/SN1/rfid-cards/AABBCCDD"},
|
|
} {
|
|
rr := httptest.NewRecorder()
|
|
h.ServeHTTP(rr, httptest.NewRequest(tc.method, tc.path, nil))
|
|
if rr.Code == http.StatusNotFound {
|
|
t.Errorf("%s %s is not routed", tc.method, tc.path)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestParseControlModes(t *testing.T) {
|
|
got := parseControlModes(" Proxy , own ,bogus,, off ")
|
|
// off is never hideable: monitoring only is what a charger falls back to.
|
|
want := map[string]bool{"proxy": true, "own": true}
|
|
if len(got) != len(want) {
|
|
t.Fatalf("parseControlModes = %v, want %v", got, want)
|
|
}
|
|
for m := range want {
|
|
if !got[m] {
|
|
t.Errorf("parseControlModes is missing %q", m)
|
|
}
|
|
}
|
|
if s := joinControlModes(got); s != "own,proxy" {
|
|
t.Errorf("joinControlModes = %q, want own,proxy (canonical order)", s)
|
|
}
|
|
}
|
|
|
|
func TestControlModesOffered(t *testing.T) {
|
|
got := controlModesOffered(map[string]bool{"own": true, "proxy": true})
|
|
want := []string{"off", "mqtt", "modbus"}
|
|
if len(got) != len(want) {
|
|
t.Fatalf("controlModesOffered = %v, want %v", got, want)
|
|
}
|
|
for i, m := range want {
|
|
if got[i] != m {
|
|
t.Errorf("controlModesOffered[%d] = %q, want %q", i, got[i], m)
|
|
}
|
|
}
|
|
}
|
|
|
|
// A mode the global layer hides is not merely absent from a lower picker: a
|
|
// value stored below before it was hidden stops taking effect too.
|
|
func TestHiddenControlModeDoesNotTakeEffect(t *testing.T) {
|
|
res := ankerResolution{
|
|
hiddenForOrg: map[string]bool{"own": true, "proxy": true},
|
|
hiddenForUser: map[string]bool{"own": true, "proxy": true},
|
|
}
|
|
if !res.hiddenAt("user")["proxy"] {
|
|
t.Error("proxy should be hidden from the user layer")
|
|
}
|
|
if res.hiddenAt("global")["proxy"] {
|
|
t.Error("nothing is hidden from the global layer — it is the one hiding")
|
|
}
|
|
view := (&Server{}).ankerScopeView(res, "user")
|
|
for _, m := range view["controlModes"].([]string) {
|
|
if m == "own" || m == "proxy" {
|
|
t.Errorf("hidden mode %q is still offered to the user scope", m)
|
|
}
|
|
}
|
|
if _, ok := view["controlModesDisabled"]; ok {
|
|
t.Error("the user scope has nobody below it and must carry no hide-list")
|
|
}
|
|
}
|
|
|
|
// An organization narrows the set once more for its own users, and its admin
|
|
// edits that list in the org scope.
|
|
func TestOrgScopeCarriesItsOwnHideList(t *testing.T) {
|
|
res := ankerResolution{
|
|
hiddenForOrg: map[string]bool{"proxy": true},
|
|
hiddenForUser: map[string]bool{"proxy": true, "own": true},
|
|
orgHidden: map[string]bool{"own": true},
|
|
}
|
|
org := (&Server{}).ankerScopeView(res, "org")
|
|
offered := org["controlModes"].([]string)
|
|
var sawOwn, sawProxy bool
|
|
for _, m := range offered {
|
|
sawOwn = sawOwn || m == "own"
|
|
sawProxy = sawProxy || m == "proxy"
|
|
}
|
|
if !sawOwn {
|
|
t.Error("an org may still choose a mode it only hides from its users")
|
|
}
|
|
if sawProxy {
|
|
t.Error("a mode the global layer hid must not reach the org picker")
|
|
}
|
|
if got := org["controlModesDisabled"].([]string); len(got) != 1 || got[0] != "own" {
|
|
t.Errorf("org hide-list = %v, want [own]", got)
|
|
}
|
|
}
|