diff --git a/API Server/internal/plugins/builtin/ankersolix/ankersolix.go b/API Server/internal/plugins/builtin/ankersolix/ankersolix.go index c02ddd6..1740757 100644 --- a/API Server/internal/plugins/builtin/ankersolix/ankersolix.go +++ b/API Server/internal/plugins/builtin/ankersolix/ankersolix.go @@ -225,6 +225,7 @@ type tokenInfo struct { gtoken string // md5(user_id) nickname string expiration time.Time + issued time.Time // when the login that returned it answered } // Plugin is the Anker Solix EV-charger connector. @@ -1067,6 +1068,13 @@ const ( // penalty out rather than spending attempts against a door that is shut. codeSignInLocked = 10019 loginLockoutWait = 10 * time.Minute + + // codeLoginBanned is "Hit max login error limit": Anker has banned the + // client's IP for 24 hours after too many logins (ha-anker-solix #659). + // Nothing but a new public IP lifts it early, so try once an hour rather + // than adding attempts to the count. + codeLoginBanned = 100041 + loginBanWait = time.Hour ) // loginRejected is the login endpoint answering with a non-zero API code. The @@ -1223,6 +1231,7 @@ func (p *Plugin) storeToken(body []byte) error { gtoken: md5hex(env.Data.UserID), nickname: env.Data.NickName, expiration: exp, + issued: time.Now(), } // A handshake belongs to the login it was run under; the next encrypted // request runs a fresh one. @@ -1359,28 +1368,29 @@ func (p *Plugin) apiCall(ctx context.Context, endpoint string, send func(tokenIn } // A rejected token surfaces as 401/403 or an auth error code; log in afresh - // and retry once. - if status == http.StatusUnauthorized || status == http.StatusForbidden || isAuthCode(body) { - p.sess.mu.Lock() - p.sess.tok = nil - p.sess.enc = nil // the handshake goes with the token it was run under - lerr := p.attemptLogin(ctx) - var newTok tokenInfo - if lerr == nil { - newTok = *p.sess.tok - } - p.sess.mu.Unlock() + // and retry once — unless the rejection cannot be about the token. Anker + // also answers 403 for an endpoint it has retired (ha-anker-solix #658, + // #659), and a fresh login per poll for one of those ends in a 24-hour IP + // ban. relogin decides; see there. + if rejected(status, body) { + newTok, again, lerr := p.relogin(ctx, endpoint, tok) if lerr != nil { return nil, lerr } - if p.encrypt { - if enc, err = p.ensureCipher(ctx, newTok); err != nil { + if again { + if p.encrypt { + if enc, err = p.ensureCipher(ctx, newTok); err != nil { + return nil, err + } + } + body, status, err = send(newTok, enc, gmt) + if err != nil { return nil, err } - } - body, status, err = send(newTok, enc, gmt) - if err != nil { - return nil, err + if rejected(status, body) { + // A token minutes old was refused too: the endpoint is saying no. + p.sess.noteRefused(endpoint) + } } } @@ -1393,6 +1403,44 @@ func (p *Plugin) apiCall(ctx context.Context, endpoint string, send func(tokenIn return body, nil } +// rejected reports whether a reply is the cloud refusing the token. +func rejected(status int, body []byte) bool { + return status == http.StatusUnauthorized || status == http.StatusForbidden || isAuthCode(body) +} + +// freshToken is how young a token is when a refusal of it is taken to be about +// the endpoint rather than the token: the mobile app evicting it, the one +// reason a valid token stops working, does not happen seconds after a login. +const freshToken = 2 * time.Minute + +// relogin answers a refused token. It returns the token to retry with and +// whether to retry at all. Three cases spend no login: the endpoint already +// refused a fresh token within the hour, the token used is itself fresh (so a +// new one would be refused the same way), and another request has already +// replaced the token meanwhile (so retry with that one). Otherwise the token +// is dropped, with the handshake run under it, and a new login is made. +func (p *Plugin) relogin(ctx context.Context, endpoint string, used tokenInfo) (tokenInfo, bool, error) { + s := p.sess + s.mu.Lock() + defer s.mu.Unlock() + if s.refusing(endpoint) { + return tokenInfo{}, false, nil + } + if s.tok != nil && s.tok.authToken != used.authToken && time.Now().Before(s.tok.expiration) { + return *s.tok, true, nil + } + if !used.issued.IsZero() && time.Since(used.issued) < freshToken { + s.noteRefusedLocked(endpoint) + return tokenInfo{}, false, nil + } + s.tok = nil + s.enc = nil // the handshake goes with the token it was run under + if err := p.attemptLogin(ctx); err != nil { + return tokenInfo{}, false, err + } + return *s.tok, true, nil +} + // doRequest issues a single POST to an endpoint with the common Anker headers. // When authToken is empty the auth headers are omitted (login request). A // non-nil enc sends the body sealed and signed, and opens the reply. diff --git a/API Server/internal/plugins/builtin/ankersolix/login_backoff_test.go b/API Server/internal/plugins/builtin/ankersolix/login_backoff_test.go index 37de5d7..1aafdf8 100644 --- a/API Server/internal/plugins/builtin/ankersolix/login_backoff_test.go +++ b/API Server/internal/plugins/builtin/ankersolix/login_backoff_test.go @@ -168,3 +168,90 @@ func TestPruneSessionsDropsIdle(t *testing.T) { t.Error("a session in use must not be pruned") } } + +// TestRetiredEndpointSpendsNoLoginLoop is the ha-anker-solix #659 regression: +// Anker retired an endpoint by answering it 403, and a client that took every +// 403 for an evicted token logged in afresh on each poll until the IP was banned +// for 24 hours. A token that is days old earns one fresh login; once a fresh +// token is refused too, the endpoint is left alone, and the polls that follow +// spend nothing on it. +func TestRetiredEndpointSpendsNoLoginLoop(t *testing.T) { + logins, gone := 0, 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, epLogin): + logins++ + _, _ = w.Write([]byte(`{"code":0,"msg":"success!","data":{"auth_token":"t` + strconv.Itoa(logins) + + `","user_id":"u","token_expires_at":` + strconv.FormatInt(time.Now().Add(24*time.Hour).Unix(), 10) + `}}`)) + case strings.HasSuffix(r.URL.Path, "/retired"): + gone++ + w.WriteHeader(http.StatusForbidden) + default: + _, _ = w.Write([]byte(`{"code":0,"msg":"success!","data":{}}`)) + } + })) + defer srv.Close() + + p := &Plugin{} + if err := p.Init(context.Background(), map[string]string{"email": "retired@example.com", "password": "pw"}); err != nil { + t.Fatal(err) + } + p.apiBase = srv.URL + p.sess = sessionFor(srv.URL, "retired@example.com", "pw") + // A token from days ago, as a long-running server holds. + p.sess.tok = &tokenInfo{authToken: "old", gtoken: "g", expiration: time.Now().Add(time.Hour), issued: time.Now().Add(-72 * time.Hour)} + + for i := 0; i < 5; i++ { + if _, err := p.apiRequest(context.Background(), "retired", map[string]any{}); err == nil { + t.Fatal("a refused endpoint must still fail") + } + } + if logins != 1 { + t.Errorf("logins over five polls = %d, want 1", logins) + } + if gone != 6 { + t.Errorf("requests to the endpoint = %d, want 6 (one retry, then one per poll)", gone) + } + // Other endpoints keep working on the token that login bought. + if _, err := p.apiRequest(context.Background(), "alive", map[string]any{}); err != nil { + t.Errorf("a working endpoint failed: %v", err) + } +} + +// TestFreshTokenRefusalIsTheEndpoint: a token a minute old was not evicted, so a +// 403 for it spends no login at all. +func TestFreshTokenRefusalIsTheEndpoint(t *testing.T) { + logins := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, epLogin) { + logins++ + } + w.WriteHeader(http.StatusForbidden) + })) + defer srv.Close() + + p := &Plugin{} + if err := p.Init(context.Background(), map[string]string{"email": "fresh@example.com", "password": "pw"}); err != nil { + t.Fatal(err) + } + p.apiBase = srv.URL + p.sess = sessionFor(srv.URL, "fresh@example.com", "pw") + p.sess.tok = &tokenInfo{authToken: "new", gtoken: "g", expiration: time.Now().Add(time.Hour), issued: time.Now().Add(-time.Minute)} + + if _, err := p.apiRequest(context.Background(), "anything", map[string]any{}); err == nil { + t.Fatal("expected the 403 to fail the request") + } + if logins != 0 { + t.Errorf("logins = %d, want 0", logins) + } +} + +// TestLoginBanWaitsAnHour: code 100041 is a 24-hour IP ban, and every attempt +// inside it is one more against the count. +func TestLoginBanWaitsAnHour(t *testing.T) { + s := &session{} + s.noteLogin(&loginRejected{code: codeLoginBanned, msg: "Hit max login error limit"}) + if wait := time.Until(s.loginRetryAt); wait < loginBanWait-time.Second { + t.Errorf("banned login waits %s, want at least %s", wait, loginBanWait) + } +} diff --git a/API Server/internal/plugins/builtin/ankersolix/payloadcrypto_test.go b/API Server/internal/plugins/builtin/ankersolix/payloadcrypto_test.go index 718012a..1f4c1ac 100644 --- a/API Server/internal/plugins/builtin/ankersolix/payloadcrypto_test.go +++ b/API Server/internal/plugins/builtin/ankersolix/payloadcrypto_test.go @@ -14,6 +14,7 @@ import ( "strings" "sync" "testing" + "time" ) // encryptedCloud is the server half of the scheme in payloadcrypto.go, written @@ -204,6 +205,9 @@ func TestPayloadEncryptionHandshakeFollowsLogin(t *testing.T) { if _, err := p.apiRequest(context.Background(), epSiteList, map[string]any{}); err != nil { t.Fatal(err) } + // An evicted token is an old one: a token refused minutes after its login + // is taken to be the endpoint saying no (relogin), so age it first. + p.sess.tok.issued = time.Now().Add(-72 * time.Hour) cloud.mu.Lock() cloud.rejectTok = "tok-01" // the first login's token cloud.mu.Unlock() diff --git a/API Server/internal/plugins/builtin/ankersolix/session.go b/API Server/internal/plugins/builtin/ankersolix/session.go index f367188..1c49db7 100644 --- a/API Server/internal/plugins/builtin/ankersolix/session.go +++ b/API Server/internal/plugins/builtin/ankersolix/session.go @@ -42,6 +42,10 @@ type session struct { loginRetryAt time.Time loginFails int + // refused holds endpoints that turned a token away minutes after the login + // that issued it, until when no login is spent on them again. Guarded by mu. + refused map[string]time.Time + // The cloud MQTT half (cloudmqtt.go), under its own lock: a broker connection // takes a TLS handshake and a fetched certificate to open, so it outlives the // plugin instance for the same reason the token does. mqttMu guards all four @@ -131,9 +135,43 @@ func (s *session) noteLogin(err error) { wait = loginRetryMax } var rejected *loginRejected - if errors.As(err, &rejected) && rejected.code == codeSignInLocked && wait < loginLockoutWait { - wait = loginLockoutWait + if errors.As(err, &rejected) { + switch { + case rejected.code == codeSignInLocked && wait < loginLockoutWait: + wait = loginLockoutWait + case rejected.code == codeLoginBanned && wait < loginBanWait: + wait = loginBanWait + } } s.loginRetryAt = time.Now().Add(wait) s.loginErr = &loginFailure{err: err, retryAt: s.loginRetryAt} } + +// endpointRefusal is how long an endpoint that refused a fresh token is left +// without a login spent on it. Its requests still go out, and fail on their own. +const endpointRefusal = time.Hour + +// noteRefused records that endpoint refused a token it had no reason to. +func (s *session) noteRefused(endpoint string) { + s.mu.Lock() + defer s.mu.Unlock() + s.noteRefusedLocked(endpoint) +} + +// noteRefusedLocked is noteRefused for a caller already holding s.mu. +func (s *session) noteRefusedLocked(endpoint string) { + if s.refused == nil { + s.refused = map[string]time.Time{} + } + s.refused[endpoint] = time.Now().Add(endpointRefusal) +} + +// refusing reports whether endpoint is inside its refusal window. Caller holds s.mu. +func (s *session) refusing(endpoint string) bool { + until, ok := s.refused[endpoint] + if ok && !time.Now().Before(until) { + delete(s.refused, endpoint) + return false + } + return ok +}