fix: persist unsupported IMS subscriptions

This commit is contained in:
yibaiba committed 2026-09-08 17:01:51 +08:00
1 parent 510b634a70
commit 72bd58db1d
20 files changed
+544 -47

No files matched your search

+1
View File
@@ -177,6 +177,7 @@ func Init(dbPath string) error {
&VoiceCallRecord{},
&PhoneContact{},
&DisclaimerAcceptance{},
&IMSSubscriptionRejection{},
); err != nil {
return err
}
+126
View File
@@ -0,0 +1,126 @@
package db
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
"gorm.io/gorm"
)
const maxIMSSubscriptionIdentityBytes = 4096
type IMSSubscriptionRejection struct {
IdentityHash string `gorm:"column:identity_hash;primaryKey;size:64"`
EventPackage string `gorm:"column:event_package;primaryKey;size:32"`
StatusCode int `gorm:"column:status_code;not null"`
ExpiresAt time.Time `gorm:"column:expires_at;index;not null"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
func LoadIMSSubscriptionRejection(
identity, eventPackage string,
now time.Time,
) (int, time.Time, error) {
identityHash, eventPackage, err := normalizeIMSSubscriptionRejectionKey(identity, eventPackage)
if err != nil {
return 0, time.Time{}, err
}
if DB == nil {
return 0, time.Time{}, gorm.ErrInvalidDB
}
var row IMSSubscriptionRejection
err = DB.Where("identity_hash = ? AND event_package = ?", identityHash, eventPackage).First(&row).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return 0, time.Time{}, nil
}
return 0, time.Time{}, err
}
if !now.Before(row.ExpiresAt) {
err = DB.Delete(&row).Error
return 0, time.Time{}, err
}
if !validPersistentSubscriptionStatus(row.StatusCode) {
return 0, time.Time{}, fmt.Errorf("invalid persisted IMS subscription status %d", row.StatusCode)
}
return row.StatusCode, row.ExpiresAt, nil
}
func SaveIMSSubscriptionRejection(
identity, eventPackage string,
status int,
expiresAt time.Time,
) error {
identityHash, eventPackage, err := normalizeIMSSubscriptionRejectionKey(identity, eventPackage)
if err != nil {
return err
}
if !validPersistentSubscriptionStatus(status) {
return fmt.Errorf("IMS subscription status %d is not persistable", status)
}
if expiresAt.IsZero() {
return fmt.Errorf("IMS subscription rejection expiration is required")
}
if DB == nil {
return gorm.ErrInvalidDB
}
return DB.Transaction(func(tx *gorm.DB) error {
return upsertIMSSubscriptionRejection(tx, IMSSubscriptionRejection{
IdentityHash: identityHash, EventPackage: eventPackage,
StatusCode: status, ExpiresAt: expiresAt,
})
})
}
func DeleteIMSSubscriptionRejections(identity string) error {
identityHash, _, err := normalizeIMSSubscriptionRejectionKey(identity, "reg")
if err != nil {
return err
}
if DB == nil {
return gorm.ErrInvalidDB
}
return DB.Where("identity_hash = ?", identityHash).Delete(&IMSSubscriptionRejection{}).Error
}
func upsertIMSSubscriptionRejection(tx *gorm.DB, row IMSSubscriptionRejection) error {
var current IMSSubscriptionRejection
err := tx.Where(
"identity_hash = ? AND event_package = ?", row.IdentityHash, row.EventPackage,
).First(&current).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return tx.Create(&row).Error
}
if err != nil {
return err
}
if current.ExpiresAt.After(row.ExpiresAt) {
row.ExpiresAt = current.ExpiresAt
}
return tx.Model(&current).Updates(map[string]any{
"status_code": row.StatusCode,
"expires_at": row.ExpiresAt,
}).Error
}
func normalizeIMSSubscriptionRejectionKey(identity, eventPackage string) (string, string, error) {
identity = strings.TrimSpace(identity)
if identity == "" || len(identity) > maxIMSSubscriptionIdentityBytes {
return "", "", fmt.Errorf("invalid IMS subscription identity length %d", len(identity))
}
eventPackage = strings.ToLower(strings.TrimSpace(eventPackage))
if eventPackage != "reg" && eventPackage != "message-summary" {
return "", "", fmt.Errorf("unsupported IMS event package %q", eventPackage)
}
digest := sha256.Sum256([]byte(identity))
return hex.EncodeToString(digest[:]), eventPackage, nil
}
func validPersistentSubscriptionStatus(status int) bool {
return status == 405 || status == 489
}
@@ -0,0 +1,74 @@
package db
import (
"path/filepath"
"testing"
"time"
)
func TestIMSSubscriptionRejectionPersistence(t *testing.T) {
previousDB := DB
if err := Init(filepath.Join(t.TempDir(), "subscription-rejections.db")); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if sqlDB, err := DB.DB(); err == nil {
_ = sqlDB.Close()
}
DB = previousDB
})
identity := "wwan0\x00user@ims.example\x00ims.example"
now := time.Now().UTC().Truncate(time.Second)
expiresAt := now.Add(time.Hour)
if err := SaveIMSSubscriptionRejection(identity, "reg", 489, expiresAt); err != nil {
t.Fatal(err)
}
status, loadedExpiry, err := LoadIMSSubscriptionRejection(identity, "reg", now)
if err != nil || status != 489 || !loadedExpiry.Equal(expiresAt) {
t.Fatalf("loaded status=%d expiry=%s err=%v", status, loadedExpiry, err)
}
if err := SaveIMSSubscriptionRejection(identity, "reg", 405, now.Add(time.Minute)); err != nil {
t.Fatal(err)
}
status, loadedExpiry, err = LoadIMSSubscriptionRejection(identity, "reg", now)
if err != nil || status != 405 || !loadedExpiry.Equal(expiresAt) {
t.Fatalf("short update status=%d expiry=%s err=%v", status, loadedExpiry, err)
}
if err := DeleteIMSSubscriptionRejections(identity); err != nil {
t.Fatal(err)
}
status, _, err = LoadIMSSubscriptionRejection(identity, "reg", now)
if err != nil || status != 0 {
t.Fatalf("deleted status=%d err=%v", status, err)
}
}
func TestIMSSubscriptionRejectionExpiresAndValidatesBoundary(t *testing.T) {
previousDB := DB
if err := Init(filepath.Join(t.TempDir(), "subscription-rejections.db")); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if sqlDB, err := DB.DB(); err == nil {
_ = sqlDB.Close()
}
DB = previousDB
})
now := time.Now().UTC().Truncate(time.Second)
if err := SaveIMSSubscriptionRejection("identity", "message-summary", 405, now.Add(-time.Second)); err != nil {
t.Fatal(err)
}
status, _, err := LoadIMSSubscriptionRejection("identity", "message-summary", now)
if err != nil || status != 0 {
t.Fatalf("expired status=%d err=%v", status, err)
}
if err := SaveIMSSubscriptionRejection("identity", "reg", 503, now.Add(time.Hour)); err == nil {
t.Fatal("transient status was persisted")
}
if _, _, err := LoadIMSSubscriptionRejection("identity", "unknown", now); err == nil {
t.Fatal("unknown event package was accepted")
}
}
+20 -1
View File
@@ -4,13 +4,32 @@ import (
"errors"
"time"
"github.com/yibaiba/hideck/internal/db"
"github.com/iniwex5/vowifi-go/runtimehost/messaging"
"github.com/yibaiba/hideck/internal/db"
"gorm.io/gorm"
)
type vowifiDeliveryStore struct{}
func (vowifiDeliveryStore) LoadIMSSubscriptionRejection(
identity, eventPackage string,
now time.Time,
) (int, time.Time, error) {
return db.LoadIMSSubscriptionRejection(identity, eventPackage, now)
}
func (vowifiDeliveryStore) SaveIMSSubscriptionRejection(
identity, eventPackage string,
status int,
expiresAt time.Time,
) error {
return db.SaveIMSSubscriptionRejection(identity, eventPackage, status, expiresAt)
}
func (vowifiDeliveryStore) DeleteIMSSubscriptionRejections(identity string) error {
return db.DeleteIMSSubscriptionRejections(identity)
}
func (vowifiDeliveryStore) CreateSMSDelivery(messageID, imsi, deviceID, peer, content string, partsTotal int, at time.Time) error {
return db.CreateSMSDelivery(messageID, imsi, deviceID, peer, content, partsTotal, at)
}
@@ -12,6 +12,7 @@ import (
var _ messaging.InboundFragmentStore = vowifiDeliveryStore{}
var _ messaging.InboundFragmentLifecycleStore = vowifiDeliveryStore{}
var _ messaging.SubscriptionRejectionStore = vowifiDeliveryStore{}
func TestVoWiFiDeliveryStoreReportsMatchedPart(t *testing.T) {
previousDB := db.DB
@@ -34,10 +34,11 @@ func (s *Service) subscriptionAttemptBlockedLocked(mwi, unsubscribe bool) error
}
lifecycle := s.subscriptionFieldsLocked(mwi).lifecycle
status := lifecycle.rejectedStatus
if mwi {
if rejected := s.subscriptionRegistrations.mwiRejected(s.subscriptionBinding); rejected != 0 {
status = rejected
}
if rejected := s.subscriptionRegistrations.rejected(
s.subscriptionBinding,
subscriptionEventPackage(mwi),
); rejected != 0 {
status = rejected
}
if status != 0 {
return fmt.Errorf("imscore: subscription previously rejected with status %d", status)
@@ -109,7 +109,7 @@ func TestSubscriptionLateResponseCannotChangeReopenedUsage(t *testing.T) {
if !reflect.DeepEqual(*f.lifecycle, lifecycle) || !reflect.DeepEqual(*f.dialog, dialog) || *f.lastErr != lastErr || *f.closed {
t.Fatal("stale response changed the new usage")
}
if s.subscriptionRegistrations.mwiRejected(s.subscriptionBinding) != 0 {
if s.subscriptionRegistrations.rejected(s.subscriptionBinding, subscriptionEventPackage(mwi)) != 0 {
t.Fatal("retired response marked the current identity unsupported")
}
completeProtocolSubscription(t, s, mwi, next)
@@ -208,7 +208,7 @@ func TestMWISharedRejectionBlocksAlreadyBuiltAttempt(t *testing.T) {
t.Fatal(err)
}
}
s.subscriptionRegistrations.rejectMWI(s.subscriptionBinding, status)
s.subscriptionRegistrations.reject(s.subscriptionBinding, mwiEventPackage, status)
if queued {
attempt.err = s.subscriptionSent(attempt, true)
} else {
@@ -123,9 +123,11 @@ func (s *Service) failSubscriptionUsageLocked(f subscriptionFields, result subsc
if subscriptionPermanentlyRejected(result.response) {
f.terminate(result.err.Error())
f.lifecycle.rejectedStatus = result.response.StatusCode
if f.mwi {
s.subscriptionRegistrations.rejectMWI(result.context.binding, result.response.StatusCode)
}
s.subscriptionRegistrations.reject(
result.context.binding,
subscriptionEventPackage(f.mwi),
result.response.StatusCode,
)
return result.err
}
if *f.closed {
@@ -68,8 +68,8 @@ func (s *Service) trackSubscriptionRegistrationLocked(expires time.Duration) {
s.subscriptionBinding = s.subscriptionRegistrations.registered(binding, time.Now().Add(expires))
}
// A normal REGISTER refresh preserves dialogs and negative subscription results.
// MWI 405/489 is scoped to identity deregistration (TS 24.606 4.7.2.1), not a flow.
// A normal REGISTER refresh preserves dialogs and explicit event-package
// rejections. A 405/489 is scoped to identity deregistration, not a TCP flow.
func (s *Service) prepareSubscriptionStart(mwi bool) (bool, string) {
s.mu.Lock()
defer s.mu.Unlock()
@@ -78,13 +78,17 @@ func (s *Service) prepareSubscriptionStart(mwi bool) (bool, string) {
}
lifecycle := s.alignSubscriptionContextLocked(mwi)
current := lifecycle.context
if mwi {
if status := s.subscriptionRegistrations.mwiRejected(current.binding); status != 0 {
if status := s.subscriptionRegistrations.rejected(current.binding, subscriptionEventPackage(mwi)); status != 0 {
if mwi {
s.mwiSubscriptionClosed = true
s.mwiSubscriptionRefreshAt = time.Time{}
s.mwiSubscriptionLastErr = fmt.Sprintf("MWI rejected with status %d; waiting for IMS identity deregistration", status)
return false, s.mwiSubscriptionLastErr
}
s.subscriptionClosed = true
s.subscriptionRefreshAt = time.Time{}
s.subscriptionLastErr = fmt.Sprintf("registration event subscription rejected with status %d; waiting for IMS identity deregistration", status)
return false, s.subscriptionLastErr
}
if lifecycle.rejectedStatus != 0 {
return false, fmt.Sprintf("subscription previously rejected with status %d", lifecycle.rejectedStatus)
@@ -113,7 +113,7 @@ func TestRegisteredSubscriptionDialogSurvivesRegisterRefresh(t *testing.T) {
}
}
func TestSubscriptionNewContactRetriesRegButPreservesMWIRejection(t *testing.T) {
func TestSubscriptionNewContactPreservesExplicitRejections(t *testing.T) {
store := NewSubscriptionRegistrationStore()
s := newSubscriptionLifecycleTestService(t, store)
rejectSubscriptionForTest(t, s, false)
@@ -123,15 +123,17 @@ func TestSubscriptionNewContactRetriesRegButPreservesMWIRejection(t *testing.T)
s.subscriptionGeneration++
s.trackSubscriptionRegistrationLocked(time.Hour)
s.mu.Unlock()
if start, _ := s.prepareSubscriptionStart(false); !start {
t.Fatal("new Contact did not initiate reg subscription")
if start, _ := s.prepareSubscriptionStart(false); start {
t.Fatal("new Contact cleared registration event rejection")
}
if start, _ := s.prepareSubscriptionStart(true); start {
t.Fatal("new Contact cleared MWI rejection")
}
replacement := newSubscriptionLifecycleTestService(t, store)
if start, _ := replacement.prepareSubscriptionStart(true); start {
t.Fatal("Service rebuild cleared MWI rejection")
for _, mwi := range []bool{false, true} {
if start, _ := replacement.prepareSubscriptionStart(mwi); start {
t.Fatalf("Service rebuild cleared rejection for mwi=%t", mwi)
}
}
}
@@ -200,7 +202,7 @@ func TestSubscriptionDeregistrationAllowsNewMWIAttempt(t *testing.T) {
}
func storeMWIRejection(s *Service) int {
return s.subscriptionRegistrations.mwiRejected(s.subscriptionBinding)
return s.subscriptionRegistrations.rejected(s.subscriptionBinding, mwiEventPackage)
}
func Test2degreesMWIRejectionDoesNotChangeOnDemandSMSReadiness(t *testing.T) {
@@ -3,20 +3,32 @@ package imscore
import (
"sync"
"time"
"github.com/iniwex5/vowifi-go/internal/vowifi/logging"
)
// SubscriptionRejectionPersistence stores only explicit, durable event-package
// rejections. Transport failures and timeouts must never implement this interface
// as negative capability evidence.
type SubscriptionRejectionPersistence interface {
LoadIMSSubscriptionRejection(identity, eventPackage string, now time.Time) (status int, expiresAt time.Time, err error)
SaveIMSSubscriptionRejection(identity, eventPackage string, status int, expiresAt time.Time) error
DeleteIMSSubscriptionRejections(identity string) error
}
// SubscriptionRegistrationStore follows IMS identity registration lifetimes,
// not TCP or Service lifetimes. It is shared across runtime recovery attempts.
type SubscriptionRegistrationStore struct {
mu sync.Mutex
nextEpoch uint64
identities map[string]*subscriptionRegistrationEntry
mu sync.Mutex
nextEpoch uint64
identities map[string]*subscriptionRegistrationEntry
persistence SubscriptionRejectionPersistence
}
type subscriptionRegistrationEntry struct {
epoch uint64
bindings map[string]time.Time
mwiRejection int
epoch uint64
bindings map[string]time.Time
rejections map[string]int
}
type subscriptionRegistration struct {
@@ -29,6 +41,14 @@ func NewSubscriptionRegistrationStore() *SubscriptionRegistrationStore {
return &SubscriptionRegistrationStore{identities: make(map[string]*subscriptionRegistrationEntry)}
}
func NewPersistentSubscriptionRegistrationStore(
persistence SubscriptionRejectionPersistence,
) *SubscriptionRegistrationStore {
store := NewSubscriptionRegistrationStore()
store.persistence = persistence
return store
}
func (store *SubscriptionRegistrationStore) registered(binding subscriptionRegistration, expiresAt time.Time) subscriptionRegistration {
store.mu.Lock()
defer store.mu.Unlock()
@@ -37,15 +57,47 @@ func (store *SubscriptionRegistrationStore) registered(binding subscriptionRegis
}
entry := store.activeLocked(binding.identity, time.Now())
if entry == nil {
store.nextEpoch++
entry = &subscriptionRegistrationEntry{epoch: store.nextEpoch, bindings: make(map[string]time.Time)}
entry = store.newEntryLocked(binding.identity, time.Now())
store.identities[binding.identity] = entry
}
entry.bindings[binding.contact] = expiresAt
store.extendRejectionsLocked(binding.identity, entry, expiresAt)
binding.epoch = entry.epoch
return binding
}
func (store *SubscriptionRegistrationStore) newEntryLocked(
identity string,
now time.Time,
) *subscriptionRegistrationEntry {
store.nextEpoch++
entry := &subscriptionRegistrationEntry{
epoch: store.nextEpoch, bindings: make(map[string]time.Time), rejections: make(map[string]int),
}
for _, eventPackage := range []string{registrationEventPackage, mwiEventPackage} {
status, expiresAt, err := store.loadRejectionLocked(identity, eventPackage, now)
if err == nil && now.Before(expiresAt) && persistentSubscriptionRejection(status) {
entry.rejections[eventPackage] = status
}
}
return entry
}
func (store *SubscriptionRegistrationStore) loadRejectionLocked(
identity, eventPackage string,
now time.Time,
) (int, time.Time, error) {
if store.persistence == nil {
return 0, time.Time{}, nil
}
status, expiresAt, err := store.persistence.LoadIMSSubscriptionRejection(identity, eventPackage, now)
if err != nil {
logging.WarnRate("ims-subscription-rejection-load-"+eventPackage, time.Minute,
"IMS subscription rejection persistence load failed", "event_package", eventPackage, "err", err)
}
return status, expiresAt, err
}
func (store *SubscriptionRegistrationStore) activeLocked(identity string, now time.Time) *subscriptionRegistrationEntry {
entry := store.identities[identity]
if entry == nil {
@@ -63,26 +115,34 @@ func (store *SubscriptionRegistrationStore) activeLocked(identity string, now ti
return entry
}
func (store *SubscriptionRegistrationStore) rejectMWI(binding subscriptionRegistration, status int) {
if status != 405 && status != 489 {
func (store *SubscriptionRegistrationStore) reject(
binding subscriptionRegistration,
eventPackage string,
status int,
) {
if !persistentSubscriptionRejection(status) {
return
}
store.mu.Lock()
defer store.mu.Unlock()
entry := store.activeLocked(binding.identity, time.Now())
if entry != nil && entry.epoch == binding.epoch {
entry.mwiRejection = status
entry.rejections[eventPackage] = status
store.saveRejectionLocked(binding.identity, eventPackage, status, latestBindingExpiry(entry))
}
}
func (store *SubscriptionRegistrationStore) mwiRejected(binding subscriptionRegistration) int {
func (store *SubscriptionRegistrationStore) rejected(
binding subscriptionRegistration,
eventPackage string,
) int {
store.mu.Lock()
defer store.mu.Unlock()
entry := store.activeLocked(binding.identity, time.Now())
if entry == nil || entry.epoch != binding.epoch {
return 0
}
return entry.mwiRejection
return entry.rejections[eventPackage]
}
func (store *SubscriptionRegistrationStore) deregistered(binding subscriptionRegistration, all bool) {
@@ -95,5 +155,61 @@ func (store *SubscriptionRegistrationStore) deregistered(binding subscriptionReg
delete(entry.bindings, binding.contact)
if all || len(entry.bindings) == 0 {
delete(store.identities, binding.identity)
store.deleteRejectionsLocked(binding.identity)
}
}
func (store *SubscriptionRegistrationStore) extendRejectionsLocked(
identity string,
entry *subscriptionRegistrationEntry,
expiresAt time.Time,
) {
for eventPackage, status := range entry.rejections {
store.saveRejectionLocked(identity, eventPackage, status, expiresAt)
}
}
func (store *SubscriptionRegistrationStore) saveRejectionLocked(
identity, eventPackage string,
status int,
expiresAt time.Time,
) {
if store.persistence == nil || expiresAt.IsZero() {
return
}
if err := store.persistence.SaveIMSSubscriptionRejection(identity, eventPackage, status, expiresAt); err != nil {
logging.WarnRate("ims-subscription-rejection-save-"+eventPackage, time.Minute,
"IMS subscription rejection persistence save failed", "event_package", eventPackage, "err", err)
}
}
func (store *SubscriptionRegistrationStore) deleteRejectionsLocked(identity string) {
if store.persistence == nil {
return
}
if err := store.persistence.DeleteIMSSubscriptionRejections(identity); err != nil {
logging.WarnRate("ims-subscription-rejection-delete", time.Minute,
"IMS subscription rejection persistence delete failed", "err", err)
}
}
func latestBindingExpiry(entry *subscriptionRegistrationEntry) time.Time {
latest := time.Time{}
for _, expiresAt := range entry.bindings {
if expiresAt.After(latest) {
latest = expiresAt
}
}
return latest
}
func persistentSubscriptionRejection(status int) bool {
return status == 405 || status == 489
}
func subscriptionEventPackage(mwi bool) string {
if mwi {
return mwiEventPackage
}
return registrationEventPackage
}
@@ -5,26 +5,60 @@ import (
"time"
)
type persistedSubscriptionRejection struct {
status int
expiresAt time.Time
}
type memorySubscriptionRejectionStore struct {
values map[string]persistedSubscriptionRejection
}
func (store *memorySubscriptionRejectionStore) LoadIMSSubscriptionRejection(
identity, eventPackage string,
_ time.Time,
) (int, time.Time, error) {
value := store.values[identity+"\x00"+eventPackage]
return value.status, value.expiresAt, nil
}
func (store *memorySubscriptionRejectionStore) SaveIMSSubscriptionRejection(
identity, eventPackage string,
status int,
expiresAt time.Time,
) error {
store.values[identity+"\x00"+eventPackage] = persistedSubscriptionRejection{
status: status, expiresAt: expiresAt,
}
return nil
}
func (store *memorySubscriptionRejectionStore) DeleteIMSSubscriptionRejections(identity string) error {
delete(store.values, identity+"\x00"+registrationEventPackage)
delete(store.values, identity+"\x00"+mwiEventPackage)
return nil
}
func TestMWIRejectionFollowsIdentityNotServiceOrContact(t *testing.T) {
store := NewSubscriptionRegistrationStore()
first := store.registered(subscriptionRegistration{identity: "sim-a/user", contact: "old-contact"}, time.Now().Add(time.Hour))
store.rejectMWI(first, 405)
store.reject(first, mwiEventPackage, 405)
replacement := store.registered(subscriptionRegistration{identity: first.identity, contact: "new-contact"}, time.Now().Add(time.Hour))
if got := store.mwiRejected(replacement); got != 405 {
if got := store.rejected(replacement, mwiEventPackage); got != 405 {
t.Fatalf("replacement lost MWI rejection: %d", got)
}
store.deregistered(first, false)
if got := store.mwiRejected(replacement); got != 405 {
if got := store.rejected(replacement, mwiEventPackage); got != 405 {
t.Fatalf("retiring old contact cleared active identity rejection: %d", got)
}
other := store.registered(subscriptionRegistration{identity: "sim-b/user", contact: "other"}, time.Now().Add(time.Hour))
if store.mwiRejected(other) != 0 {
if store.rejected(other, mwiEventPackage) != 0 {
t.Fatal("rejection leaked to another identity")
}
store.deregistered(replacement, false)
next := store.registered(subscriptionRegistration{identity: first.identity, contact: "third-contact"}, time.Now().Add(time.Hour))
store.rejectMWI(first, 489)
if store.mwiRejected(next) != 0 {
store.reject(first, mwiEventPackage, 489)
if store.rejected(next, mwiEventPackage) != 0 {
t.Fatal("late rejection crossed deregistration boundary")
}
}
@@ -32,12 +66,12 @@ func TestMWIRejectionFollowsIdentityNotServiceOrContact(t *testing.T) {
func TestMWIRejectionExpiresWithLastKnownRegistration(t *testing.T) {
store := NewSubscriptionRegistrationStore()
ref := store.registered(subscriptionRegistration{identity: "sim/user", contact: "contact"}, time.Now().Add(time.Hour))
store.rejectMWI(ref, 489)
store.reject(ref, mwiEventPackage, 489)
store.mu.Lock()
store.identities[ref.identity].bindings[ref.contact] = time.Now().Add(-time.Second)
store.mu.Unlock()
next := store.registered(ref, time.Now().Add(time.Hour))
if next.epoch == ref.epoch || store.mwiRejected(next) != 0 {
if next.epoch == ref.epoch || store.rejected(next, mwiEventPackage) != 0 {
t.Fatal("expired registration retained rejection")
}
}
@@ -46,13 +80,59 @@ func TestMWITransientFailuresAreNotUnsupported(t *testing.T) {
store := NewSubscriptionRegistrationStore()
ref := store.registered(subscriptionRegistration{identity: "sim/user", contact: "contact"}, time.Now().Add(time.Hour))
for _, status := range []int{403, 408, 500, 503} {
store.rejectMWI(ref, status)
if store.mwiRejected(ref) != 0 {
store.reject(ref, mwiEventPackage, status)
if store.rejected(ref, mwiEventPackage) != 0 {
t.Fatalf("status %d became network unsupported", status)
}
}
}
func TestExplicitRejectionsSurviveProcessStoreReplacement(t *testing.T) {
persistence := &memorySubscriptionRejectionStore{
values: make(map[string]persistedSubscriptionRejection),
}
identity := "device\x00impi\x00domain\x00impu"
expiresAt := time.Now().Add(time.Hour)
firstStore := NewPersistentSubscriptionRegistrationStore(persistence)
first := firstStore.registered(subscriptionRegistration{
identity: identity, contact: "first",
}, expiresAt)
firstStore.reject(first, registrationEventPackage, 489)
firstStore.reject(first, mwiEventPackage, 405)
restartedStore := NewPersistentSubscriptionRegistrationStore(persistence)
restarted := restartedStore.registered(subscriptionRegistration{
identity: identity, contact: "replacement",
}, expiresAt.Add(time.Hour))
if got := restartedStore.rejected(restarted, registrationEventPackage); got != 489 {
t.Fatalf("registration rejection after restart = %d", got)
}
if got := restartedStore.rejected(restarted, mwiEventPackage); got != 405 {
t.Fatalf("MWI rejection after restart = %d", got)
}
for _, eventPackage := range []string{registrationEventPackage, mwiEventPackage} {
value := persistence.values[identity+"\x00"+eventPackage]
if !value.expiresAt.Equal(expiresAt.Add(time.Hour)) {
t.Fatalf("%s expiration was not extended: %s", eventPackage, value.expiresAt)
}
}
}
func TestExplicitDeregistrationClearsPersistedRejections(t *testing.T) {
persistence := &memorySubscriptionRejectionStore{
values: make(map[string]persistedSubscriptionRejection),
}
store := NewPersistentSubscriptionRegistrationStore(persistence)
binding := store.registered(subscriptionRegistration{
identity: "sim/user", contact: "contact",
}, time.Now().Add(time.Hour))
store.reject(binding, mwiEventPackage, 405)
store.deregistered(binding, false)
if len(persistence.values) != 0 {
t.Fatalf("deregistration left persisted rejections: %#v", persistence.values)
}
}
func TestSubscriptionRefreshUsesNegotiatedLifetime(t *testing.T) {
for _, test := range []struct{ expires, want time.Duration }{
{time.Minute, 30 * time.Second},
@@ -13,7 +13,7 @@ func (s *Service) subscriptionDueLocked(mwi bool, now time.Time) bool {
if !eligible || f.retryBlocked() || !f.lifecycle.notifyDeadline.IsZero() {
return false
}
if mwi && s.subscriptionRegistrations.mwiRejected(s.subscriptionBinding) != 0 {
if s.subscriptionRegistrations.rejected(s.subscriptionBinding, subscriptionEventPackage(mwi)) != 0 {
return false
}
if (mwi && s.mwiSubscriptionInFlight.Load()) || (!mwi && s.subscriptionInFlight.Load()) {
@@ -36,7 +36,9 @@ func (Runtime) Start(
req.fastReauth = &FastReauthStore{}
}
if req.subscriptionRegistrations == nil {
req.subscriptionRegistrations = imscore.NewSubscriptionRegistrationStore()
req.subscriptionRegistrations = imscore.NewPersistentSubscriptionRegistrationStore(
req.SubscriptionStore,
)
}
if req.Options.Voice != nil && req.voiceBinding == nil {
req.voiceBinding = &voiceLifecycleBinding{deviceID: req.DeviceID, voice: req.Options.Voice}
@@ -168,6 +168,7 @@ type RuntimeStartRequest struct {
Proxy *ProxyConfig
DNSServer string
DeliveryStore smsdelivery.Store
SubscriptionStore imscore.SubscriptionRejectionPersistence
Dispatch events.EventDispatcher
Reconnect bool
ReconnectDelay func(int) int64
+47
View File
@@ -508,6 +508,33 @@ type fragmentOnlyDeliveryStore struct {
fragments messaging.InboundFragmentStore
}
type subscriptionRejectionDeliveryStore struct {
messaging.DeliveryStore
status int
expiresAt time.Time
}
func (store *subscriptionRejectionDeliveryStore) LoadIMSSubscriptionRejection(
_, _ string,
_ time.Time,
) (int, time.Time, error) {
return store.status, store.expiresAt, nil
}
func (store *subscriptionRejectionDeliveryStore) SaveIMSSubscriptionRejection(
_, _ string,
status int,
expiresAt time.Time,
) error {
store.status, store.expiresAt = status, expiresAt
return nil
}
func (store *subscriptionRejectionDeliveryStore) DeleteIMSSubscriptionRejections(string) error {
store.status, store.expiresAt = 0, time.Time{}
return nil
}
func (store fragmentOnlyDeliveryStore) LoadInboundFragments(
owner messaging.InboundFragmentOwner,
) ([]messaging.StoredInboundFragment, error) {
@@ -659,6 +686,26 @@ func TestRuntimeCoreDeliveryStorePreservesOptionalSIPResults(t *testing.T) {
}
}
func TestRuntimeCoreAdapterPreservesSubscriptionRejectionStore(t *testing.T) {
store := &subscriptionRejectionDeliveryStore{DeliveryStore: &memDeliveryStore{}}
persistence := runtimeCoreSubscriptionRejectionStore(store)
if persistence == nil {
t.Fatal("subscription rejection store was dropped")
}
expiresAt := time.Now().Add(time.Hour)
if err := persistence.SaveIMSSubscriptionRejection(
"identity", "reg", 489, expiresAt,
); err != nil {
t.Fatal(err)
}
status, loadedExpiry, err := persistence.LoadIMSSubscriptionRejection(
"identity", "reg", time.Now(),
)
if err != nil || status != 489 || !loadedExpiry.Equal(expiresAt) {
t.Fatalf("status=%d expiry=%s err=%v", status, loadedExpiry, err)
}
}
func TestDeliveryStoreAdaptersDoNotInventFragmentLifecycleCapability(t *testing.T) {
underlying := &memDeliveryStore{}
store := fragmentOnlyDeliveryStore{DeliveryStore: underlying, fragments: underlying}
+9
View File
@@ -151,6 +151,15 @@ type DeliveryStore interface {
GetSMSDeliveryStatus(messageID string) (*DeliveryStatus, error)
}
// SubscriptionRejectionStore persists explicit IMS event-package rejections
// across runtime and process restarts. Expiration follows the associated IMS
// registration lifetime so a genuinely new registration may probe again.
type SubscriptionRejectionStore interface {
LoadIMSSubscriptionRejection(identity, eventPackage string, now time.Time) (status int, expiresAt time.Time, err error)
SaveIMSSubscriptionRejection(identity, eventPackage string, status int, expiresAt time.Time) error
DeleteIMSSubscriptionRejections(identity string) error
}
// SIPResultStore is an optional delivery-store capability used to preserve
// the initial SIP MESSAGE result while the part is still waiting for RP-ACK.
type SIPResultStore interface {
@@ -4,6 +4,7 @@ import (
"time"
"github.com/iniwex5/vowifi-go/internal/vowifi/events"
"github.com/iniwex5/vowifi-go/internal/vowifi/imscore"
"github.com/iniwex5/vowifi-go/internal/vowifi/smsdelivery"
"github.com/iniwex5/vowifi-go/runtimehost/eventhost"
"github.com/iniwex5/vowifi-go/runtimehost/messaging"
@@ -16,6 +17,13 @@ func runtimeCoreDispatcher(dispatcher eventhost.Dispatcher) events.EventDispatch
return eventDispatcherAdapter{dispatch: dispatcher}
}
func runtimeCoreSubscriptionRejectionStore(
store messaging.DeliveryStore,
) imscore.SubscriptionRejectionPersistence {
persistence, _ := store.(messaging.SubscriptionRejectionStore)
return persistence
}
type runtimeCoreDeliveryStoreAdapter struct{ store messaging.DeliveryStore }
type runtimeCoreSIPDeliveryStoreAdapter struct {
+3 -2
View File
@@ -42,8 +42,9 @@ func (req StartRequest) coreRequest() runtimecore.RuntimeStartRequest {
Mode: req.Dataplane.Mode, TUNName: req.Dataplane.TUNName,
},
Proxy: runtimeCoreProxy(req.Proxy), DNSServer: req.DNSServer,
DeliveryStore: runtimeCoreDeliveryStore(req.DeliveryStore),
Dispatch: runtimeCoreDispatcher(req.Dispatch), ShouldRun: req.ShouldRun,
DeliveryStore: runtimeCoreDeliveryStore(req.DeliveryStore),
SubscriptionStore: runtimeCoreSubscriptionRejectionStore(req.DeliveryStore),
Dispatch: runtimeCoreDispatcher(req.Dispatch), ShouldRun: req.ShouldRun,
}
if req.BeforeStart != nil {
hook := req.BeforeStart
+3
View File
@@ -491,6 +491,9 @@ func imscoreFromPrepared(req StartRequest, tunnel Tunnel) (*imscore.Service, err
}
if req.DeliveryStore != nil {
cfg.DeliveryStore = newDeliveryStoreAdapter(req.DeliveryStore)
cfg.SubscriptionRegistrations = imscore.NewPersistentSubscriptionRegistrationStore(
runtimeCoreSubscriptionRejectionStore(req.DeliveryStore),
)
}
svc, err := imscore.New(cfg)
if err != nil {