Repository navigation
Add Reddit FCM push registration #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Fizzadar
wants to merge
1
commit into
main
Choose a base branch
from
codex/reddit-push-registration
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| package connector | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "strings" | ||
|
|
||
| "github.com/google/uuid" | ||
| "maunium.net/go/mautrix/bridgev2" | ||
|
|
||
| "github.com/beeper/reddit/pkg/redditchat" | ||
| ) | ||
|
|
||
| var _ bridgev2.PushableNetworkAPI = (*RedditClient)(nil) | ||
|
|
||
| var pushConfig = &bridgev2.PushConfig{ | ||
| FCM: &bridgev2.FCMPushConfig{SenderID: redditchat.FCMSenderID}, | ||
| } | ||
|
|
||
| func (r *RedditClient) GetPushConfigs() *bridgev2.PushConfig { | ||
| return pushConfig | ||
| } | ||
|
|
||
| func (r *RedditClient) RegisterPushNotifications(ctx context.Context, pushType bridgev2.PushType, token string) error { | ||
| if pushType != bridgev2.PushTypeFCM { | ||
| return fmt.Errorf("unsupported push type: %s", pushType) | ||
| } | ||
| if !r.IsLoggedIn() { | ||
| return bridgev2.ErrNotLoggedIn | ||
| } | ||
| if strings.TrimSpace(token) == "" { | ||
| return errors.New("reddit push: FCM token is required") | ||
| } | ||
| if err := ctx.Err(); err != nil { | ||
| return err | ||
| } | ||
| r.pushMu.Lock() | ||
| defer r.pushMu.Unlock() | ||
| deviceID, err := r.pushDeviceID(ctx) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| err = r.remote().RegisterFCMPush(ctx, token, deviceID) | ||
| if errors.Is(err, redditchat.ErrPushAuthentication) && r.session != nil { | ||
| if refreshErr := r.refreshChatToken(ctx); refreshErr != nil { | ||
| return fmt.Errorf("refresh Reddit credentials for push registration: %w", refreshErr) | ||
| } | ||
| err = r.remote().RegisterFCMPush(ctx, token, deviceID) | ||
| } | ||
| return err | ||
| } | ||
|
|
||
| func (r *RedditClient) pushDeviceID(ctx context.Context) (string, error) { | ||
| r.saveMu.Lock() | ||
| defer r.saveMu.Unlock() | ||
| if r.meta.PushDeviceID == "" { | ||
| r.meta.PushDeviceID = uuid.NewString() | ||
| if err := r.userLogin.Save(ctx); err != nil { | ||
| r.meta.PushDeviceID = "" | ||
| return "", fmt.Errorf("save Reddit push device ID: %w", err) | ||
| } | ||
| } | ||
| return r.meta.PushDeviceID, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,191 @@ | ||
| package connector | ||
|
|
||
| import ( | ||
| "encoding/base64" | ||
| "encoding/json" | ||
| "errors" | ||
| "io" | ||
| "net/http" | ||
| "path/filepath" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/google/uuid" | ||
| "go.mau.fi/util/dbutil" | ||
| _ "go.mau.fi/util/dbutil/litestream" | ||
| "maunium.net/go/mautrix/bridgev2" | ||
| "maunium.net/go/mautrix/bridgev2/database" | ||
|
|
||
| "github.com/beeper/reddit/pkg/redditchat" | ||
| ) | ||
|
|
||
| type pushTransport func(*http.Request) (*http.Response, error) | ||
|
|
||
| func (f pushTransport) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } | ||
|
|
||
| func TestPushRegistrationFromWrapper(t *testing.T) { | ||
| r := testClient(t, func(http.ResponseWriter, *http.Request) { t.Fatal("unexpected Matrix request") }) | ||
| r.meta.PushDeviceID = "persistent-bridge-device" | ||
| calls := 0 | ||
| r.matrix().Client.Transport = pushTransport(func(req *http.Request) (*http.Response, error) { | ||
| calls++ | ||
| var body struct { | ||
| Variables struct { | ||
| PushToken string `json:"pushToken"` | ||
| DeviceID string `json:"deviceId"` | ||
| } `json:"variables"` | ||
| } | ||
| if err := json.NewDecoder(req.Body).Decode(&body); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| wantToken := "first-token" | ||
| if calls == 2 { | ||
| wantToken = "rotated-token" | ||
| } | ||
| if body.Variables.PushToken != wantToken || body.Variables.DeviceID != "persistent-bridge-device" { | ||
| t.Fatal("wrong token or device changed on token rotation") | ||
| } | ||
| return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`{"data":{"registerMobilePushToken":{"ok":true}}}`))}, nil | ||
| }) | ||
| var pushable bridgev2.PushableNetworkAPI = r | ||
| cfg := pushable.GetPushConfigs() | ||
| if cfg.FCM == nil || cfg.FCM.SenderID != "933360113277" || cfg.Web != nil || cfg.APNs != nil || cfg.Native { | ||
| t.Fatalf("wrong relay configuration: %+v", cfg) | ||
| } | ||
| for _, token := range []string{"first-token", "rotated-token"} { | ||
| if err := pushable.RegisterPushNotifications(t.Context(), bridgev2.PushTypeFCM, token); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| } | ||
| if calls != 2 { | ||
| t.Fatalf("got %d registrations", calls) | ||
| } | ||
| } | ||
|
|
||
| func TestPushRegistrationRejectsUnsupportedRequests(t *testing.T) { | ||
| r := testClient(t, func(http.ResponseWriter, *http.Request) { t.Fatal("unexpected request") }) | ||
| for _, pushType := range []bridgev2.PushType{bridgev2.PushTypeUnknown, bridgev2.PushTypeWeb, bridgev2.PushTypeAPNs} { | ||
| if err := r.RegisterPushNotifications(t.Context(), pushType, "token"); err == nil { | ||
| t.Fatalf("accepted unsupported type: %s", pushType) | ||
| } | ||
| } | ||
| if err := r.RegisterPushNotifications(t.Context(), bridgev2.PushTypeFCM, " "); err == nil { | ||
| t.Fatal("accepted blank token") | ||
| } | ||
| r.rc = nil | ||
| if err := r.RegisterPushNotifications(t.Context(), bridgev2.PushTypeFCM, "token"); !errors.Is(err, bridgev2.ErrNotLoggedIn) { | ||
| t.Fatalf("wrong missing-login error: %v", err) | ||
| } | ||
| } | ||
|
|
||
| func TestPushRegistrationWithoutRenewableSession(t *testing.T) { | ||
| r := testClient(t, func(http.ResponseWriter, *http.Request) { t.Fatal("unexpected Matrix request") }) | ||
| r.meta.PushDeviceID = "device" | ||
| calls := 0 | ||
| r.matrix().Client.Transport = pushTransport(func(req *http.Request) (*http.Response, error) { | ||
| calls++ | ||
| return &http.Response{StatusCode: http.StatusUnauthorized, Body: io.NopCloser(strings.NewReader(`{}`))}, nil | ||
| }) | ||
| err := r.RegisterPushNotifications(t.Context(), bridgev2.PushTypeFCM, "token") | ||
| if !errors.Is(err, redditchat.ErrPushAuthentication) || calls != 1 { | ||
| t.Fatalf("wrong auth failure: %v (%d calls)", err, calls) | ||
| } | ||
| } | ||
|
|
||
| func pushTestDatabase(t *testing.T, r *RedditClient) { | ||
| t.Helper() | ||
| db, err := dbutil.NewWithDialect(filepath.Join(t.TempDir(), "push.db"), "sqlite3") | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| t.Cleanup(func() { _ = db.Close() }) | ||
| r.main.Bridge.DB = database.New("", r.main.GetDBMetaTypes(), db) | ||
| if err = db.Upgrade(t.Context()); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| r.userLogin.Bridge = r.main.Bridge | ||
| r.userLogin.Metadata = r.meta | ||
| r.userLogin.UserMXID = "@test:example.com" | ||
| if err = r.main.Bridge.DB.User.Insert(t.Context(), &database.User{MXID: r.userLogin.UserMXID}); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if err = r.main.Bridge.DB.UserLogin.Insert(t.Context(), r.userLogin.UserLogin); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| } | ||
|
|
||
| func TestPushDeviceIDPersistenceAndSaveFailure(t *testing.T) { | ||
| r := testClient(t, func(http.ResponseWriter, *http.Request) { t.Fatal("unexpected request") }) | ||
| pushTestDatabase(t, r) | ||
| deviceID, err := r.pushDeviceID(t.Context()) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if _, err = uuid.Parse(deviceID); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| stored, err := r.main.Bridge.DB.UserLogin.GetByID(t.Context(), r.userLogin.ID) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if stored.Metadata.(*UserLoginMetadata).PushDeviceID != deviceID { | ||
| t.Fatal("push device ID was not persisted") | ||
| } | ||
| if err = r.main.Bridge.DB.Close(); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if reused, err := r.pushDeviceID(t.Context()); err != nil || reused != deviceID { | ||
| t.Fatalf("existing device ID was not reused: %v", err) | ||
| } | ||
| r.meta.PushDeviceID = "" | ||
| err = r.RegisterPushNotifications(t.Context(), bridgev2.PushTypeFCM, "token") | ||
| if err == nil || r.meta.PushDeviceID != "" { | ||
| t.Fatal("failed save retained an unpersisted device ID") | ||
| } | ||
| } | ||
|
|
||
| func TestPushRegistrationRefreshesExpiredCredentials(t *testing.T) { | ||
| r := testClient(t, func(http.ResponseWriter, *http.Request) { t.Fatal("unexpected request") }) | ||
| pushTestDatabase(t, r) | ||
| freshToken := "header." + base64.RawURLEncoding.EncodeToString([]byte(`{"lid":"t2_a"}`)) + ".signature" | ||
| registrationCalls, refreshCalls := 0, 0 | ||
| transport := pushTransport(func(req *http.Request) (*http.Response, error) { | ||
| status, body := http.StatusOK, "" | ||
| switch req.URL.Host + req.URL.Path { | ||
| case "gql-fed.reddit.com/": | ||
| registrationCalls++ | ||
| if registrationCalls == 1 { | ||
| status, body = http.StatusUnauthorized, `{}` | ||
| } else { | ||
| if req.Header.Get("Authorization") != "Bearer "+freshToken { | ||
| t.Fatal("registration retry used expired credentials") | ||
| } | ||
| body = `{"data":{"registerMobilePushToken":{"ok":true}}}` | ||
| } | ||
| case "www.reddit.com/svc/shreddit/token": | ||
| refreshCalls++ | ||
| body = `{"token":"` + freshToken + `","expires":1900000000}` | ||
| case "matrix.redditspace.com/_matrix/client/v3/account/whoami": | ||
| body = `{"device_id":"matrix-device"}` | ||
| default: | ||
| t.Fatalf("unexpected request: %s", req.URL) | ||
| } | ||
| return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil | ||
| }) | ||
| previousTransport := http.DefaultTransport | ||
| http.DefaultTransport = transport | ||
| t.Cleanup(func() { http.DefaultTransport = previousTransport }) | ||
| r.matrix().Client.Transport = transport | ||
| var err error | ||
| r.session, err = redditchat.NewRedditSession(&http.Client{Transport: transport}, "", "") | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| r.session.CSRFToken = "csrf" | ||
| if err = r.RegisterPushNotifications(t.Context(), bridgev2.PushTypeFCM, "push-token"); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if registrationCalls != 2 || refreshCalls != 1 || r.meta.Credentials.AccessToken != freshToken { | ||
| t.Fatalf("incorrect refresh: registrations=%d refreshes=%d", registrationCalls, refreshCalls) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Bug · Push registration saves user-login metadata concurrently with the sync loop's unlocked map writes
userLogin.Savemarshals the wholeUserLoginMetadata, including theHiddenRoomsmap, butsaveMuonly serializes saves against each other. The sync loop inchatsync.gomutatesNextBatch,RoomStateVersionandHiddenRoomswithout holding it.RegisterPushNotificationsruns on a separate goroutine, so a first registration, or any registration that refreshes credentials viasaveMeta, can overlap a sync write. That can hit Go's fatalconcurrent map iteration and map writeand crash the bridge. It can also persist a sync cursor that the sync loop later rolls back in memory. Guard allr.metaaccess with one mutex, or clone the metadata under the lock before marshaling.Ref:
pkg/connector/chatsync.golines ~103 and ~200-208.Found by Indent Review Agent