mirror of
https://github.com/yibaiba/hideck.git
synced 2026-12-06 08:02:21 +00:00
fix(device): converge strict SIM identity before using the card
This commit is contained in:
11 files changed
+463
-28
No files matched your search
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/iniwex5/vowifi-go/runtimehost/messaging"
|
||||
"github.com/iniwex5/vowifi-go/runtimehost/voicehost"
|
||||
"github.com/yibaiba/hideck/internal/config"
|
||||
"github.com/yibaiba/hideck/internal/modem"
|
||||
"github.com/yibaiba/hideck/internal/outbound"
|
||||
"github.com/yibaiba/hideck/pkg/smscodec"
|
||||
)
|
||||
@@ -143,3 +144,54 @@ func TestQueuedSMSSIMReplacementStopsBeforeNewRuntimeSend(t *testing.T) {
|
||||
t.Fatalf("queued send crossed SIM: err=%v sent=%d", err, newRuntime.sendCount())
|
||||
}
|
||||
}
|
||||
|
||||
func TestML307CCSSMSChecksLiveSIMBeforeSubmitting(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
iccid, imsi string
|
||||
simErr, want error
|
||||
simAbsent bool
|
||||
}{
|
||||
{name: "matching", iccid: "card-old", imsi: "imsi-old"},
|
||||
{name: "different_card", iccid: "card-new", imsi: "imsi-new", want: ErrSMSIdentityConflict},
|
||||
{name: "same_iccid_different_imsi", iccid: "card-old", imsi: "imsi-new", want: ErrSMSIdentityConflict},
|
||||
{name: "incomplete", iccid: "card-old", want: ErrSMSIdentityUnknown},
|
||||
{name: "absent", simAbsent: true, want: ErrSMSIdentityUnknown},
|
||||
{name: "pin_required", iccid: "card-old", imsi: "imsi-old", simErr: modem.ErrSIMPINRequired, want: modem.ErrSIMPINRequired},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
p, w, be := newML307CIdentityWorker(t)
|
||||
limiter := &recordingOutboundLimiter{}
|
||||
p.SetOutboundLimiter(limiter)
|
||||
be.liveICCID, be.liveIMSI, be.simErr, be.simAbsent = tc.iccid, tc.imsi, tc.simErr, tc.simAbsent
|
||||
if err := w.SendSMS("10010", "test"); !errors.Is(err, tc.want) {
|
||||
t.Fatalf("SendSMS() = %v, want %v", err, tc.want)
|
||||
}
|
||||
count := 0
|
||||
if tc.want == nil {
|
||||
count = 1
|
||||
}
|
||||
if be.sends != count || len(limiter.requests) != 1 || limiter.requests[0].ICCID != "card-old" {
|
||||
t.Fatalf("sends=%d want %d; charges=%+v want one on intended card", be.sends, count, limiter.requests)
|
||||
}
|
||||
if tc.want != nil && !w.SIMIdentityConvergenceMatches("", 0) {
|
||||
t.Fatal("confirmed SIM state did not invalidate cached readiness")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestML307CCSSMSRejectsSilentSIMSwapDuringAuthorization(t *testing.T) {
|
||||
p, w, be := newML307CIdentityWorker(t)
|
||||
be.liveICCID, be.liveIMSI = "card-old", "imsi-old"
|
||||
limiter := &recordingOutboundLimiter{after: func() {
|
||||
be.liveICCID, be.liveIMSI = "card-new", "imsi-new"
|
||||
}}
|
||||
p.SetOutboundLimiter(limiter)
|
||||
if err := w.SendSMS("10010", "test"); !errors.Is(err, ErrSMSIdentityConflict) {
|
||||
t.Fatalf("SendSMS() = %v, want SIM conflict", err)
|
||||
}
|
||||
if be.sends != 0 || len(limiter.requests) != 1 || limiter.requests[0].ICCID != "card-old" {
|
||||
t.Fatalf("wrong send or quota owner: sends=%d charges=%+v", be.sends, limiter.requests)
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,7 @@ func TestML307CPhonePolicyKeepsExplicitRadioSettings(t *testing.T) {
|
||||
t.Cleanup(p.cancel)
|
||||
w := p.GetWorker("ml307c")
|
||||
w.Modem = newML307CPhoneTestModem(t, w.ID)
|
||||
w.state.Identity.Phase = simIdentityPhaseReady
|
||||
radio := &esimSwitchRestoreBackendStub{mode: backend.BackendAT, getMode: backend.ModeOnline}
|
||||
w.Backend = radio
|
||||
pol := cardpolicy.Policy{
|
||||
@@ -124,6 +125,7 @@ func TestML307COneNZWiFiPolicyStillStarts(t *testing.T) {
|
||||
t.Cleanup(p.cancel)
|
||||
w := p.GetWorker("ml307c")
|
||||
w.Modem = newML307CPhoneTestModem(t, w.ID)
|
||||
w.state.Identity.Phase = simIdentityPhaseReady
|
||||
p.SetPolicyResolver(&stubPolicyResolver{pol: cardpolicy.Policy{
|
||||
ICCID: w.CurrentICCID(), PhoneMode: PhoneModeWiFi, VoWiFiEnabled: true,
|
||||
}})
|
||||
@@ -156,6 +158,7 @@ func TestML307CLebaraSavedVoLTERecoversEffectiveWiFi(t *testing.T) {
|
||||
t.Cleanup(p.cancel)
|
||||
w := p.GetWorker("ml307c")
|
||||
w.Modem = newML307CPhoneTestModem(t, w.ID)
|
||||
w.state.Identity.Phase = simIdentityPhaseReady
|
||||
pol := cardpolicy.Policy{
|
||||
ICCID: w.CurrentICCID(), PhoneMode: PhoneModeVoLTE, VoWiFiEnabled: true,
|
||||
}
|
||||
|
||||
@@ -60,6 +60,10 @@ func (p *Pool) validatePolicyOwner(owner policyOwner, transition *policyTransiti
|
||||
if strings.TrimSpace(identity.ICCID) != owner.iccid || identity.Generation != owner.identityGeneration {
|
||||
return errPolicyOwnerChanged
|
||||
}
|
||||
if w.atDeviceRules().strictSIMIdentity && (!identity.Ready || identity.Phase != simIdentityPhaseReady ||
|
||||
strings.TrimSpace(identity.ICCID) == "" || strings.TrimSpace(identity.IMSI) == "") {
|
||||
return errPolicyOwnerChanged
|
||||
}
|
||||
p.switchMu.Lock()
|
||||
switching, snapshot := p.switchingDevices[w.ID], p.switchContexts[w.ID]
|
||||
p.switchMu.Unlock()
|
||||
|
||||
+26
-12
@@ -685,19 +685,20 @@ func (w *Worker) refreshIdentityLiveWithPresence(ctx context.Context, reason str
|
||||
}
|
||||
|
||||
strictSIMIdentity := w.atDeviceRules().strictSIMIdentity
|
||||
var generation uint64
|
||||
if strictSIMIdentity {
|
||||
generation = w.SIMIdentityGeneration()
|
||||
}
|
||||
if strictSIMIdentity && !presenceConfirmed {
|
||||
generation := w.SIMIdentityGeneration()
|
||||
inserted, err := w.Backend.IsSimInserted(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, modem.ErrSIMPINRequired) && (w.Pool == nil || !w.Pool.IsESIMSwitching(w.ID)) {
|
||||
if w.markSIMPINRequired(generation) && w.Pool != nil {
|
||||
owner := workerLifecycleOwner{worker: w, generation: w.generation}
|
||||
w.Pool.handleSIMStatusEventForOwner(owner, reason, nil, "SIM PIN")
|
||||
}
|
||||
if errors.Is(err, modem.ErrSIMPINRequired) {
|
||||
w.recordStrictSIMLock(generation, reason)
|
||||
}
|
||||
return liveSIMIdentityRefreshResult{}, err
|
||||
}
|
||||
if !inserted {
|
||||
w.recordStrictSIMAbsence(generation, reason)
|
||||
return liveSIMIdentityRefreshResult{}, errATNoSIM
|
||||
}
|
||||
}
|
||||
@@ -708,6 +709,9 @@ func (w *Worker) refreshIdentityLiveWithPresence(ctx context.Context, reason str
|
||||
if snapshotReader, supported := w.Backend.(liveSIMIdentitySnapshotReader); supported {
|
||||
snapshot, err := snapshotReader.ReadSIMIdentityLive(ctx)
|
||||
if err != nil {
|
||||
if strictSIMIdentity {
|
||||
w.degradeStrictSIMIdentity(generation, reason, err)
|
||||
}
|
||||
return liveSIMIdentityRefreshResult{}, err
|
||||
}
|
||||
iccid = strings.TrimSpace(snapshot.ICCID)
|
||||
@@ -749,7 +753,9 @@ func (w *Worker) refreshIdentityLiveWithPresence(ctx context.Context, reason str
|
||||
}
|
||||
}
|
||||
if strictSIMIdentity && (iccid == "" || imsi == "") {
|
||||
return liveSIMIdentityRefreshResult{}, errors.New("live_identity_incomplete")
|
||||
err := errors.New("live_identity_incomplete")
|
||||
w.degradeStrictSIMIdentity(generation, reason, err)
|
||||
return liveSIMIdentityRefreshResult{}, err
|
||||
}
|
||||
_, snapshotSupported := w.Backend.(liveSIMIdentitySnapshotReader)
|
||||
if !snapshotSupported && (simMetadata == nil ||
|
||||
@@ -813,6 +819,10 @@ func (w *Worker) refreshIdentityLiveWithPresence(ctx context.Context, reason str
|
||||
|
||||
now := time.Now()
|
||||
w.cacheMu.Lock()
|
||||
if strictSIMIdentity && w.state.Identity.Generation != generation {
|
||||
w.cacheMu.Unlock()
|
||||
return liveSIMIdentityRefreshResult{}, ErrSMSIdentityTransitioning
|
||||
}
|
||||
identityIncomplete := (iccid == "") != (imsi == "")
|
||||
hasCachedIdentity := strings.TrimSpace(w.state.Identity.ICCID) != "" ||
|
||||
strings.TrimSpace(w.state.Identity.IMSI) != ""
|
||||
@@ -841,8 +851,10 @@ func (w *Worker) refreshIdentityLiveWithPresence(ctx context.Context, reason str
|
||||
(imsi != "" && imsi != strings.TrimSpace(w.state.Identity.IMSI))
|
||||
// Physical swaps do not necessarily pass through the eSIM transition hook.
|
||||
// Retain a generation change even if the original ICCID later returns.
|
||||
if iccid != "" && w.state.Identity.ICCID != "" &&
|
||||
normalizeSIMIdentityForCompare(iccid) != normalizeSIMIdentityForCompare(w.state.Identity.ICCID) {
|
||||
iccidChanged := iccid != "" && w.state.Identity.ICCID != "" &&
|
||||
normalizeSIMIdentityForCompare(iccid) != normalizeSIMIdentityForCompare(w.state.Identity.ICCID)
|
||||
if iccidChanged || (strictSIMIdentity && imsi != "" && w.state.Identity.IMSI != "" &&
|
||||
imsi != strings.TrimSpace(w.state.Identity.IMSI)) {
|
||||
w.state.Identity.Generation++
|
||||
}
|
||||
if iccid != "" {
|
||||
@@ -1259,7 +1271,7 @@ func (p *Pool) confirmSIMStatusForOwner(owner workerLifecycleOwner, source strin
|
||||
p.finishConfirmedSIMInsertion(owner, source, result)
|
||||
return
|
||||
}
|
||||
p.handleConfirmedSIMRemoval(owner, source, baseCtx)
|
||||
p.handleConfirmedSIMRemoval(owner, source, baseCtx, generation)
|
||||
transition.Unlock()
|
||||
}
|
||||
|
||||
@@ -1323,7 +1335,7 @@ func (p *Pool) finishConfirmedSIMInsertion(owner workerLifecycleOwner, source st
|
||||
}
|
||||
|
||||
// Caller holds the device policy transition lock.
|
||||
func (p *Pool) handleConfirmedSIMRemoval(owner workerLifecycleOwner, source string, baseCtx context.Context) {
|
||||
func (p *Pool) handleConfirmedSIMRemoval(owner workerLifecycleOwner, source string, baseCtx context.Context, generation uint64) {
|
||||
if !p.workerLifecycleOwnerCurrent(owner) {
|
||||
return
|
||||
}
|
||||
@@ -1332,7 +1344,9 @@ func (p *Pool) handleConfirmedSIMRemoval(owner workerLifecycleOwner, source stri
|
||||
refreshCtx, cancel := context.WithTimeout(baseCtx, 3*time.Second)
|
||||
_ = w.RefreshRuntime(refreshCtx, "sim_removed")
|
||||
cancel()
|
||||
w.markSIMRemoved("sim_removed")
|
||||
if !w.markSIMRemoved("sim_removed", generation) {
|
||||
return
|
||||
}
|
||||
p.detachPersistedSIMBinding(w)
|
||||
p.broadcastVoWiFiStateChange(deviceID)
|
||||
p.clearDesiredVoWiFiRecoverState(deviceID)
|
||||
|
||||
@@ -410,10 +410,17 @@ func (w *Worker) SendSMSWithOptions(phone, message string, opts smscodec.SubmitO
|
||||
}
|
||||
defer release()
|
||||
check := w.Pool.outboundOwnerCheck(w)
|
||||
var intended SMSIdentity
|
||||
if w.atDeviceRules().strictSIMIdentity {
|
||||
intended, err = w.strictSMSSendIdentity()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := w.Pool.authorizeSMS(context.Background(), outboundSMSRequest{Worker: w, To: phone, Text: message, Options: opts}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := check(); err != nil {
|
||||
if err := w.confirmCSSMSIdentity(context.Background(), intended, check); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.sendSMSWithOptions(phone, message, opts)
|
||||
|
||||
@@ -11,15 +11,17 @@ import (
|
||||
"github.com/yibaiba/hideck/pkg/logger"
|
||||
)
|
||||
|
||||
func (w *Worker) markSIMRemoved(reason string) {
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
func (w *Worker) markSIMRemoved(reason string, generation uint64) bool {
|
||||
now := time.Now()
|
||||
w.cacheMu.Lock()
|
||||
defer w.cacheMu.Unlock()
|
||||
strict := w.atDeviceRules().strictSIMIdentity
|
||||
if strict && w.state.Identity.Generation != generation {
|
||||
return false
|
||||
}
|
||||
hadIdentity := strings.TrimSpace(w.state.Identity.ICCID) != "" ||
|
||||
strings.TrimSpace(w.state.Identity.IMSI) != "" || w.state.Identity.Ready
|
||||
if hadIdentity {
|
||||
if hadIdentity || (strict && w.state.Identity.LastError != "sim_removed") {
|
||||
w.state.Identity.Generation++
|
||||
}
|
||||
w.state.Identity.ICCID = ""
|
||||
@@ -35,7 +37,43 @@ func (w *Worker) markSIMRemoved(reason string) {
|
||||
w.state.Meta.IdentityUpdatedAt = now
|
||||
w.state.Meta.RuntimeUpdatedAt = now
|
||||
w.state.Meta.UpdatedAt = now
|
||||
w.cacheMu.Unlock()
|
||||
return true
|
||||
}
|
||||
|
||||
func (w *Worker) scheduleSIMStatusCheck(source string, inserted *bool, state string) {
|
||||
if w.Pool == nil {
|
||||
return
|
||||
}
|
||||
owner := workerLifecycleOwner{worker: w, generation: w.generation}
|
||||
w.Pool.handleSIMStatusEventForOwner(owner, source, inserted, state)
|
||||
}
|
||||
|
||||
func (w *Worker) recordStrictSIMAbsence(generation uint64, source string) {
|
||||
w.degradeStrictSIMIdentity(generation, source, errATNoSIM)
|
||||
inserted := false
|
||||
w.scheduleSIMStatusCheck(source, &inserted, "")
|
||||
}
|
||||
|
||||
func (w *Worker) recordStrictSIMLock(generation uint64, source string) {
|
||||
if w.Pool != nil && w.Pool.IsESIMSwitching(w.ID) {
|
||||
return
|
||||
}
|
||||
if w.markSIMPINRequired(generation) {
|
||||
w.scheduleSIMStatusCheck(source, nil, "SIM PIN")
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) degradeStrictSIMIdentity(generation uint64, reason string, err error) bool {
|
||||
now := time.Now()
|
||||
w.cacheMu.Lock()
|
||||
defer w.cacheMu.Unlock()
|
||||
if w.state.Identity.Generation != generation || !w.state.Identity.Ready ||
|
||||
w.state.Identity.Phase == simIdentityPhaseTransitioning {
|
||||
return false
|
||||
}
|
||||
w.markSIMIdentityDegradedLocked(reason, err, now)
|
||||
w.state.Identity.Generation++
|
||||
return true
|
||||
}
|
||||
|
||||
func (w *Worker) markSIMPINRequired(generation uint64) bool {
|
||||
|
||||
@@ -2,6 +2,7 @@ package device
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -178,14 +179,160 @@ func TestConfirmedSIMRemovalCancelsStartingVoWiFi(t *testing.T) {
|
||||
type ml307cSIMBackendStub struct {
|
||||
workerStartupIdentityBackendStub
|
||||
simErr error
|
||||
simAbsent bool
|
||||
onSIMQuery func()
|
||||
onICCID func()
|
||||
sends int
|
||||
}
|
||||
|
||||
func (s *ml307cSIMBackendStub) IsSimInserted(context.Context) (bool, error) {
|
||||
if s.onSIMQuery != nil {
|
||||
s.onSIMQuery()
|
||||
}
|
||||
return s.simErr == nil, s.simErr
|
||||
return !s.simAbsent && s.simErr == nil, s.simErr
|
||||
}
|
||||
|
||||
func (s *ml307cSIMBackendStub) GetICCIDLive(context.Context) (string, error) {
|
||||
if s.onICCID != nil {
|
||||
s.onICCID()
|
||||
}
|
||||
return s.liveICCID, nil
|
||||
}
|
||||
|
||||
func (s *ml307cSIMBackendStub) SendSMS(context.Context, string, string) error {
|
||||
s.sends++
|
||||
return nil
|
||||
}
|
||||
|
||||
func newML307CIdentityWorker(t *testing.T) (*Pool, *Worker, *ml307cSIMBackendStub) {
|
||||
t.Helper()
|
||||
p := NewPool(&config.Config{})
|
||||
t.Cleanup(func() { _ = p.Shutdown() })
|
||||
cfg := config.DeviceConfig{ID: "c", DeviceBackend: "at", ATPort: "/dev/ttyUSB8"}
|
||||
m, err := modem.NewWithATProfile(cfg, modem.ATProfileML307C)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
be := &ml307cSIMBackendStub{}
|
||||
w := &Worker{ID: cfg.ID, Pool: p, Config: cfg, Modem: m, Backend: be}
|
||||
setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-old", IMSI: "imsi-old"})
|
||||
p.AttachWorkerForTest(w)
|
||||
t.Cleanup(func() { p.cancelWorkerLifecycleTimers(w.ID) })
|
||||
return p, w, be
|
||||
}
|
||||
|
||||
func TestML307CIncompleteReadyIdentityBlocksOldCardAndRetries(t *testing.T) {
|
||||
p, w, be := newML307CIdentityWorker(t)
|
||||
before := w.SIMIdentityGeneration()
|
||||
be.liveICCID = "card-new"
|
||||
p.confirmSIMRemovedAndStopVoWiFi(w.ID, "test")
|
||||
if !w.SIMIdentityConvergenceMatches("", 0) || w.SIMIdentityGeneration() <= before {
|
||||
t.Fatal("incomplete live identity left the previous SIM ready")
|
||||
}
|
||||
p.SetPolicyResolver(&stubPolicyResolver{pol: cardpolicy.Policy{ICCID: "card-old"}})
|
||||
if result := p.resolveAndApplyPolicy(w, "test"); result.Applied || !errors.Is(result.Err, errPolicyOwnerChanged) {
|
||||
t.Fatalf("unready SIM applied cached policy: %+v", result)
|
||||
}
|
||||
p.SetPolicyResolver(nil)
|
||||
be.liveIMSI = "imsi-new"
|
||||
owner := p.captureWorkerLifecycleOwner(w.ID)
|
||||
ready := true
|
||||
p.handleSIMStatusEventForOwner(owner, "test", &ready, "")
|
||||
p.simEventMu.Lock()
|
||||
timer := p.simEventTimers[w.ID]
|
||||
p.simEventMu.Unlock()
|
||||
if timer == nil || !timer.Stop() {
|
||||
t.Fatal("subsequent READY did not schedule an identity retry")
|
||||
}
|
||||
p.confirmSIMRemovedForOwner(owner, "test", timer)
|
||||
if w.SIMIdentityConvergenceMatches("", 0) || w.CurrentICCID() != "card-new" || w.GetCachedIMSI() != "imsi-new" {
|
||||
t.Fatal("subsequent READY did not settle on the new identity")
|
||||
}
|
||||
before = w.SIMIdentityGeneration()
|
||||
be.liveIMSI = "imsi-rotated"
|
||||
if err := w.RefreshIdentityLive(context.Background(), "test"); err != nil || w.SIMIdentityGeneration() <= before {
|
||||
t.Fatalf("changed IMSI on a stable ICCID did not retire the old generation: %v", err)
|
||||
}
|
||||
|
||||
w.BeginSIMIdentityTransition("target", "test")
|
||||
be.liveICCID, be.liveIMSI = "", ""
|
||||
if err := w.RefreshIdentityLive(context.Background(), "test"); err == nil {
|
||||
t.Fatal("incomplete identity unexpectedly succeeded during the switch")
|
||||
}
|
||||
w.cacheMu.RLock()
|
||||
phase, target := w.state.Identity.Phase, w.state.Identity.TargetICCID
|
||||
w.cacheMu.RUnlock()
|
||||
if phase != simIdentityPhaseTransitioning || target != "target" {
|
||||
t.Fatalf("incomplete read interrupted eSIM identity transition: phase=%s target=%s", phase, target)
|
||||
}
|
||||
}
|
||||
|
||||
func TestML307CAbsentIdentityBlocksOldCardBeforeDebouncedCleanup(t *testing.T) {
|
||||
p, w, be := newML307CIdentityWorker(t)
|
||||
be.simAbsent = true
|
||||
if err := w.RefreshIdentityLive(context.Background(), "test"); !errors.Is(err, errATNoSIM) {
|
||||
t.Fatalf("absent SIM returned %v", err)
|
||||
}
|
||||
if !w.SIMIdentityConvergenceMatches("", 0) || w.CurrentICCID() != "card-old" {
|
||||
t.Fatal("absent SIM should immediately become unready and keep its binding until confirmation")
|
||||
}
|
||||
p.simEventMu.Lock()
|
||||
timer := p.simEventTimers[w.ID]
|
||||
p.simEventMu.Unlock()
|
||||
if timer == nil || !timer.Stop() {
|
||||
t.Fatal("absent SIM did not schedule debounced cleanup")
|
||||
}
|
||||
p.confirmSIMRemovedForOwner(p.captureWorkerLifecycleOwner(w.ID), "test", timer)
|
||||
if w.CurrentICCID() != "" {
|
||||
t.Fatal("confirmed absence retained the previous identity")
|
||||
}
|
||||
}
|
||||
|
||||
func TestML307CAbsentConfirmationDoesNotClearNewerSIM(t *testing.T) {
|
||||
p, w, be := newML307CIdentityWorker(t)
|
||||
be.simAbsent = true
|
||||
be.onSIMQuery = func() {
|
||||
w.cacheMu.Lock()
|
||||
defer w.cacheMu.Unlock()
|
||||
setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-new", IMSI: "imsi-new"})
|
||||
w.state.Identity.Generation++
|
||||
}
|
||||
p.confirmSIMRemovedAndStopVoWiFi(w.ID, "test")
|
||||
if w.CurrentICCID() != "card-new" || w.SIMIdentityConvergenceMatches("", 0) {
|
||||
t.Fatal("stale absence cleared the live SIM generation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestML307CSlowIdentityCannotReviveOlderSIMGeneration(t *testing.T) {
|
||||
for _, before := range []bool{false, true} {
|
||||
name := "probe_presence"
|
||||
if before {
|
||||
name = "confirmed_presence"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
_, w, be := newML307CIdentityWorker(t)
|
||||
be.liveICCID, be.liveIMSI = "card-old", "imsi-old"
|
||||
started, finish := make(chan struct{}), make(chan struct{})
|
||||
be.onICCID = func() {
|
||||
close(started)
|
||||
<-finish
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := w.refreshIdentityLiveWithPresence(context.Background(), "old-read", before)
|
||||
done <- err
|
||||
}()
|
||||
<-started
|
||||
generation := w.BeginSIMIdentityTransition("target", "test")
|
||||
close(finish)
|
||||
if err := <-done; !errors.Is(err, ErrSMSIdentityTransitioning) {
|
||||
t.Fatalf("superseded identity read returned %v", err)
|
||||
}
|
||||
if !w.SIMIdentityConvergenceMatches("target", generation) || currentSIMOwnership(w).iccid != "" {
|
||||
t.Fatal("superseded read reset the current identity transition")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func confirmScheduledSIMPIN(t *testing.T, p *Pool, owner workerLifecycleOwner) {
|
||||
|
||||
@@ -54,30 +54,49 @@ func (owner storedSMSOwner) check() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type storedSMSIdentityReader interface {
|
||||
QuerySIMInserted() (bool, error)
|
||||
QueryICCID() (string, error)
|
||||
QueryIMSI() (string, error)
|
||||
}
|
||||
|
||||
func (owner storedSMSOwner) verifyLive() error {
|
||||
return owner.verifyLiveFrom(owner.worker.Modem)
|
||||
}
|
||||
|
||||
func (owner storedSMSOwner) verifyLiveFrom(reader storedSMSIdentityReader) error {
|
||||
if err := owner.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
w := owner.worker
|
||||
inserted, err := w.Modem.QuerySIMInserted()
|
||||
inserted, err := reader.QuerySIMInserted()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !inserted {
|
||||
return ErrSMSIdentityUnknown
|
||||
}
|
||||
iccid, err := w.Modem.QueryICCID()
|
||||
iccid, err := reader.QueryICCID()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
imsi, err := w.Modem.QueryIMSI()
|
||||
imsi, err := reader.QueryIMSI()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if normalizeSMSIdentity(SMSIdentity{ICCID: iccid, IMSI: imsi}) != owner.SMSIdentity {
|
||||
return ErrSMSIdentityConflict
|
||||
if err := owner.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
return owner.check()
|
||||
live := normalizeSMSIdentity(SMSIdentity{ICCID: iccid, IMSI: imsi})
|
||||
switch {
|
||||
case live.ICCID == "" || live.IMSI == "":
|
||||
err = ErrSMSIdentityUnknown
|
||||
case live != owner.SMSIdentity:
|
||||
err = ErrSMSIdentityConflict
|
||||
}
|
||||
if err != nil && owner.worker.atDeviceRules().strictSIMIdentity {
|
||||
return owner.worker.rejectLiveCSSMSIdentity(owner.simGeneration, "at_sms_inbox_identity", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// A CMTI only proves provenance within the current worker and SIM generation.
|
||||
|
||||
@@ -3,6 +3,7 @@ package device
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -384,3 +385,81 @@ func TestATStoredSMSDuplicateRequiresReceiptIMSIForDeletion(t *testing.T) {
|
||||
t.Fatalf("replay recreated removed history: count=%d, err=%v", count, err)
|
||||
}
|
||||
}
|
||||
|
||||
type storedSMSIdentityTestReader struct {
|
||||
SMSIdentity
|
||||
onIMSI func()
|
||||
}
|
||||
|
||||
func (r storedSMSIdentityTestReader) QuerySIMInserted() (bool, error) { return true, nil }
|
||||
func (r storedSMSIdentityTestReader) QueryICCID() (string, error) { return r.ICCID, nil }
|
||||
func (r storedSMSIdentityTestReader) QueryIMSI() (string, error) {
|
||||
if r.onIMSI != nil {
|
||||
r.onIMSI()
|
||||
}
|
||||
return r.IMSI, nil
|
||||
}
|
||||
|
||||
func TestATStoredSMSLiveSwapSchedulesSIMConvergence(t *testing.T) {
|
||||
p, w, be := newML307CIdentityWorker(t)
|
||||
configureWorkerATSMS(w)
|
||||
owner, err := w.storedSMSOwner()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
live := SMSIdentity{ICCID: "card-new", IMSI: "imsi-new"}
|
||||
be.liveICCID, be.liveIMSI = live.ICCID, live.IMSI
|
||||
if err := owner.verifyLiveFrom(storedSMSIdentityTestReader{SMSIdentity: live}); !errors.Is(err, ErrSMSIdentityConflict) {
|
||||
t.Fatalf("live swap returned %v", err)
|
||||
}
|
||||
if !w.SIMIdentityConvergenceMatches("", 0) || w.SIMIdentityGeneration() != owner.simGeneration+1 {
|
||||
t.Fatal("live swap left old cached identity ready")
|
||||
}
|
||||
var messages []InboundSMS
|
||||
if err := w.readStoredSMSInbox(owner, nil, &messages); !errors.Is(err, ErrSMSIdentityTransitioning) || len(messages) != 0 {
|
||||
t.Fatalf("old owner could enter the inbox: messages=%+v, err=%v", messages, err)
|
||||
}
|
||||
p.simEventMu.Lock()
|
||||
timer := p.simEventTimers[w.ID]
|
||||
p.simEventMu.Unlock()
|
||||
if timer == nil || !timer.Stop() {
|
||||
t.Fatal("inbox mismatch did not schedule SIM status convergence")
|
||||
}
|
||||
p.confirmSIMRemovedForOwner(owner.workerLifecycleOwner, "test", timer)
|
||||
current, err := w.storedSMSOwner()
|
||||
if err != nil || current.SMSIdentity != live || current.simGeneration <= owner.simGeneration {
|
||||
t.Fatalf("inbox did not converge to the live identity: %+v, %v", current.SMSIdentity, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestATStoredSMSStaleLiveReadLeavesNewerSIMReady(t *testing.T) {
|
||||
p, w, _ := newML307CIdentityWorker(t)
|
||||
configureWorkerATSMS(w)
|
||||
owner, err := w.storedSMSOwner()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
live := SMSIdentity{ICCID: "card-new", IMSI: "imsi-new"}
|
||||
reader := storedSMSIdentityTestReader{
|
||||
SMSIdentity: SMSIdentity{ICCID: "card-intermediate", IMSI: "imsi-intermediate"},
|
||||
onIMSI: func() {
|
||||
w.cacheMu.Lock()
|
||||
defer w.cacheMu.Unlock()
|
||||
setWorkerSMSIdentity(w, live)
|
||||
w.state.Identity.Generation++
|
||||
},
|
||||
}
|
||||
if err := owner.verifyLiveFrom(reader); !errors.Is(err, ErrSMSIdentityTransitioning) {
|
||||
t.Fatalf("superseded read returned %v", err)
|
||||
}
|
||||
current, err := w.storedSMSOwner()
|
||||
if err != nil || current.SMSIdentity != live || current.simGeneration != owner.simGeneration+1 {
|
||||
t.Fatalf("superseded read altered the newer generation: %+v, %v", current.SMSIdentity, err)
|
||||
}
|
||||
p.simEventMu.Lock()
|
||||
timer := p.simEventTimers[w.ID]
|
||||
p.simEventMu.Unlock()
|
||||
if timer != nil {
|
||||
t.Fatal("superseded read scheduled a new SIM status check")
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
@@ -9,6 +10,7 @@ import (
|
||||
"github.com/yibaiba/hideck/internal/backend"
|
||||
"github.com/yibaiba/hideck/internal/config"
|
||||
"github.com/yibaiba/hideck/internal/db"
|
||||
"github.com/yibaiba/hideck/internal/modem"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -130,6 +132,76 @@ func (p *Pool) runtimeSMSIdentity(deviceID string) (smsIdentityCandidate, error)
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (w *Worker) strictSMSSendIdentity() (SMSIdentity, error) {
|
||||
w.cacheMu.RLock()
|
||||
state := w.state.Identity
|
||||
w.cacheMu.RUnlock()
|
||||
identity := normalizeSMSIdentity(SMSIdentity{ICCID: state.ICCID, IMSI: state.IMSI})
|
||||
if !state.Ready || state.Phase != simIdentityPhaseReady || identity.ICCID == "" || identity.IMSI == "" {
|
||||
return SMSIdentity{}, ErrSMSIdentityUnknown
|
||||
}
|
||||
return identity, nil
|
||||
}
|
||||
|
||||
// Caller holds the outbound operation through confirmation and submission.
|
||||
func (w *Worker) confirmCSSMSIdentity(ctx context.Context, intended SMSIdentity, checkOwner func() error) error {
|
||||
if err := checkOwner(); err != nil || !w.atDeviceRules().strictSIMIdentity {
|
||||
return err
|
||||
}
|
||||
reader, ok := w.Backend.(liveSIMIdentityReader)
|
||||
if !ok {
|
||||
return ErrSMSIdentityUnknown
|
||||
}
|
||||
const source = "cs_sms_identity"
|
||||
generation := w.SIMIdentityGeneration()
|
||||
ctx, cancel := context.WithTimeout(contextOrBackground(ctx), 8*time.Second)
|
||||
defer cancel()
|
||||
inserted, err := w.Backend.IsSimInserted(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, modem.ErrSIMPINRequired) {
|
||||
w.recordStrictSIMLock(generation, source)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if !inserted {
|
||||
w.recordStrictSIMAbsence(generation, source)
|
||||
return ErrSMSIdentityUnknown
|
||||
}
|
||||
iccid, err := reader.GetICCIDLive(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
imsi, err := reader.GetIMSILive(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
live := normalizeSMSIdentity(SMSIdentity{ICCID: iccid, IMSI: imsi})
|
||||
cached, err := w.strictSMSSendIdentity()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkOwner(); err != nil {
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case live.ICCID == "" || live.IMSI == "":
|
||||
err = ErrSMSIdentityUnknown
|
||||
case live != intended || cached != intended:
|
||||
err = ErrSMSIdentityConflict
|
||||
}
|
||||
if err != nil {
|
||||
return w.rejectLiveCSSMSIdentity(generation, source, err)
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func (w *Worker) rejectLiveCSSMSIdentity(generation uint64, source string, err error) error {
|
||||
if w.degradeStrictSIMIdentity(generation, source, err) {
|
||||
w.scheduleSIMStatusCheck(source, nil, "READY")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// smsIMSIAliasChecker is implemented by stores that remember every IMSI read on a
|
||||
// card, so a multi-IMSI SIM switching EF_IMSI is not treated as a different card.
|
||||
type smsIMSIAliasChecker interface {
|
||||
|
||||
@@ -146,7 +146,7 @@ func (p *Pool) SendRoutedSMS(
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if err := checkOwner(); err != nil {
|
||||
if err := worker.confirmCSSMSIdentity(ctx, identity, checkOwner); err != nil {
|
||||
return err
|
||||
}
|
||||
if sendCSHook != nil {
|
||||
|
||||
Reference in new issue
Block a user