Merge https://git.base.ovh/Silverfish/proton-bridge
All checks were successful
nogui build / try & test (push) Successful in 2m45s

This commit is contained in:
yesBad
2024-12-16 20:00:44 +02:00
101 changed files with 2019 additions and 2700 deletions

View File

@ -97,18 +97,21 @@ const (
appShortName = "bridge"
)
// the two flags below have been deprecated by BRIDGE-281. We however keep them so that bridge does not error if they are passed on startup.
var cliFlagEnableKeychainTest = &cli.BoolFlag{ //nolint:gochecknoglobals
Name: flagEnableKeychainTest,
Usage: "Enable the keychain test for the current and future executions of the application",
Usage: "This flag is deprecated and does nothing",
Value: false,
DisableDefaultText: true,
} //nolint:gochecknoglobals
Hidden: true,
}
var cliFlagDisableKeychainTest = &cli.BoolFlag{ //nolint:gochecknoglobals
Name: flagDisableKeychainTest,
Usage: "Disable the keychain test for the current and future executions of the application",
Usage: "This flag is deprecated and does nothing",
Value: false,
DisableDefaultText: true,
Hidden: true,
}
func New() *cli.App {
@ -205,12 +208,14 @@ func New() *cli.App {
// We override the default help value because we want "Show" to be capitalized
cli.HelpFlag = &cli.BoolFlag{
Name: "help",
Aliases: []string{"h"},
Usage: "Show help",
DisableDefaultText: true,
}
if onMacOS() {
// The two flags below were introduced for BRIDGE-116, and are available only on macOS.
// They have been later removed fro BRIDGE-281.
app.Flags = append(app.Flags, cliFlagEnableKeychainTest, cliFlagDisableKeychainTest)
}
@ -282,8 +287,7 @@ func run(c *cli.Context) error {
return withSingleInstance(settings, locations.GetLockFile(), version, func() error {
// Look for available keychains
skipKeychainTest := checkSkipKeychainTest(c, settings)
return WithKeychainList(crashHandler, skipKeychainTest, func(keychains *keychain.List) error {
return WithKeychainList(crashHandler, func(keychains *keychain.List) error {
// Unlock the encrypted vault.
return WithVault(reporter, locations, keychains, crashHandler, func(v *vault.Vault, insecure, corrupt bool) error {
if !v.Migrated() {
@ -547,11 +551,11 @@ func withCookieJar(vault *vault.Vault, fn func(http.CookieJar) error) error {
}
// WithKeychainList init the list of usable keychains.
func WithKeychainList(panicHandler async.PanicHandler, skipKeychainTest bool, fn func(*keychain.List) error) error {
func WithKeychainList(panicHandler async.PanicHandler, fn func(*keychain.List) error) error {
logrus.Debug("Creating keychain list")
defer logrus.Debug("Keychain list stop")
defer async.HandlePanic(panicHandler)
return fn(keychain.NewList(skipKeychainTest))
return fn(keychain.NewList())
}
func setDeviceCookies(jar *cookies.Jar) error {
@ -572,38 +576,6 @@ func setDeviceCookies(jar *cookies.Jar) error {
return nil
}
func checkSkipKeychainTest(c *cli.Context, settingsDir string) bool {
if !onMacOS() {
return false
}
enable := c.Bool(flagEnableKeychainTest)
disable := c.Bool(flagDisableKeychainTest)
skip, err := vault.GetShouldSkipKeychainTest(settingsDir)
if err != nil {
logrus.WithError(err).Error("Could not load keychain settings.")
}
if (!enable) && (!disable) {
return skip
}
// if both switches are passed, 'enable' has priority
if disable {
skip = true
}
if enable {
skip = false
}
if err := vault.SetShouldSkipKeychainTest(settingsDir, skip); err != nil {
logrus.WithError(err).Error("Could not save keychain settings.")
}
return skip
}
func onMacOS() bool {
return runtime.GOOS == "darwin"
}

View File

@ -1,64 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package app
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/urfave/cli/v2"
)
func TestCheckSkipKeychainTest(t *testing.T) {
var expectedResult bool
dir := t.TempDir()
app := cli.App{
Flags: []cli.Flag{
cliFlagEnableKeychainTest,
cliFlagDisableKeychainTest,
},
Action: func(c *cli.Context) error {
require.Equal(t, expectedResult, checkSkipKeychainTest(c, dir))
return nil
},
}
noArgs := []string{"appName"}
enableArgs := []string{"appName", "-" + flagEnableKeychainTest}
disableArgs := []string{"appName", "-" + flagDisableKeychainTest}
bothArgs := []string{"appName", "-" + flagDisableKeychainTest, "-" + flagEnableKeychainTest}
onMac := onMacOS()
expectedResult = false
require.NoError(t, app.Run(noArgs))
expectedResult = onMac
require.NoError(t, app.Run(disableArgs))
require.NoError(t, app.Run(noArgs))
expectedResult = false
require.NoError(t, app.Run(enableArgs))
require.NoError(t, app.Run(noArgs))
expectedResult = onMac
require.NoError(t, app.Run(disableArgs))
expectedResult = false
require.NoError(t, app.Run(bothArgs))
}

View File

@ -636,14 +636,6 @@ func loadTLSConfig(vault *vault.Vault) (*tls.Config, error) {
}, nil
}
func min(a, b time.Duration) time.Duration { //nolint:predeclared
if a < b {
return a
}
return b
}
func (bridge *Bridge) HasAPIConnection() bool {
return bridge.api.GetStatus() == proton.StatusUp
}
@ -723,3 +715,18 @@ func (bridge *Bridge) PushDistinctObservabilityMetrics(errType observability.Dis
func (bridge *Bridge) ModifyObservabilityHeartbeatInterval(duration time.Duration) {
bridge.observabilityService.ModifyHeartbeatInterval(duration)
}
func (bridge *Bridge) ReportMessageWithContext(message string, messageCtx reporter.Context) {
if err := bridge.reporter.ReportMessageWithContext(message, messageCtx); err != nil {
logPkg.WithFields(logrus.Fields{
"err": err,
"sentryMessage": message,
"messageCtx": messageCtx,
}).Info("Error occurred when sending Report to Sentry")
}
}
// GetUsers is only used for testing purposes.
func (bridge *Bridge) GetUsers() map[string]*user.User {
return bridge.users
}

View File

@ -25,7 +25,6 @@ import (
"github.com/ProtonMail/go-proton-api"
"github.com/ProtonMail/proton-bridge/v3/internal/constants"
"github.com/ProtonMail/proton-bridge/v3/internal/logging"
"github.com/ProtonMail/proton-bridge/v3/internal/safe"
"github.com/ProtonMail/proton-bridge/v3/internal/vault"
)
@ -80,12 +79,6 @@ func (bridge *Bridge) ReportBug(ctx context.Context, report *ReportBugReq) error
return err
}
safe.RLock(func() {
for _, user := range bridge.users {
user.ReportBugSent()
}
}, bridge.usersLock)
// if we have a token we can append more attachment to the bugReport
for i, att := range attachments {
if i == 0 && report.IncludeLogs {

View File

@ -1,46 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package bridge
import (
"github.com/ProtonMail/proton-bridge/v3/internal/safe"
)
func (bridge *Bridge) ReportBugClicked() {
safe.RLock(func() {
for _, user := range bridge.users {
user.ReportBugClicked()
}
}, bridge.usersLock)
}
func (bridge *Bridge) AutoconfigUsed(client string) {
safe.RLock(func() {
for _, user := range bridge.users {
user.AutoconfigUsed(client)
}
}, bridge.usersLock)
}
func (bridge *Bridge) ExternalLinkClicked(article string) {
safe.RLock(func() {
for _, user := range bridge.users {
user.ExternalLinkClicked(article)
}
}, bridge.usersLock)
}

View File

@ -73,15 +73,15 @@ func (h *heartBeatState) init(bridge *Bridge, manager telemetry.HeartbeatManager
for _, user := range bridge.users {
if user.GetAddressMode() == vault.SplitMode {
splitMode = true
break
}
h.SetUserPlan(user.GetUserPlanName())
}
var nbAccount = len(bridge.users)
h.SetNbAccount(nbAccount)
var numberConnectedAccounts = len(bridge.users)
h.SetNumberConnectedAccounts(numberConnectedAccounts)
h.SetSplitMode(splitMode)
// Do not try to send if there is no user yet.
if nbAccount > 0 {
if numberConnectedAccounts > 0 {
defer h.start()
}
}, bridge.usersLock)

View File

@ -17,7 +17,9 @@
package bridge
import "github.com/sirupsen/logrus"
import (
"github.com/sirupsen/logrus"
)
func (bridge *Bridge) GetCurrentUserAgent() string {
return bridge.identifier.GetUserAgent()
@ -30,6 +32,8 @@ func (bridge *Bridge) SetCurrentPlatform(platform string) {
func (bridge *Bridge) setUserAgent(name, version string) {
currentUserAgent := bridge.identifier.GetClientString()
bridge.heartbeat.SetContactedByAppleNotes(name)
bridge.identifier.SetClient(name, version)
newUserAgent := bridge.identifier.GetClientString()
@ -54,6 +58,7 @@ func (b *bridgeUserAgentUpdater) HasClient() bool {
}
func (b *bridgeUserAgentUpdater) SetClient(name, version string) {
b.heartbeat.SetContactedByAppleNotes(name)
b.identifier.SetClient(name, version)
}

View File

@ -26,6 +26,7 @@ import (
imapEvents "github.com/ProtonMail/gluon/events"
"github.com/ProtonMail/proton-bridge/v3/internal/events"
"github.com/ProtonMail/proton-bridge/v3/internal/services/imapsmtpserver"
"github.com/ProtonMail/proton-bridge/v3/internal/unleash"
"github.com/ProtonMail/proton-bridge/v3/internal/useragent"
"github.com/sirupsen/logrus"
)
@ -93,6 +94,10 @@ func (b *bridgeIMAPSettings) LogServer() bool {
return b.b.logIMAPServer
}
func (b *bridgeIMAPSettings) DisableIMAPAuthenticate() bool {
return b.b.unleashService.GetFlagValue(unleash.IMAPAuthenticateCommandDisabled)
}
func (b *bridgeIMAPSettings) Port() int {
return b.b.vault.GetIMAPPort()
}

View File

@ -318,11 +318,10 @@ func (bridge *Bridge) GetKnowledgeBaseSuggestions(userInput string) (kb.ArticleL
// Note: it does not clear the keychain. The only entry in the keychain is the vault password,
// which we need at next startup to decrypt the vault.
func (bridge *Bridge) FactoryReset(ctx context.Context) {
useTelemetry := !bridge.GetTelemetryDisabled()
// Delete all the users.
safe.Lock(func() {
for _, user := range bridge.users {
bridge.logoutUser(ctx, user, true, true, useTelemetry)
bridge.logoutUser(ctx, user, true, true)
}
}, bridge.usersLock)

View File

@ -28,7 +28,6 @@ type Locator interface {
ProvideLogsPath() (string, error)
ProvideGluonCachePath() (string, error)
ProvideGluonDataPath() (string, error)
ProvideStatsPath() (string, error)
GetLicenseFilePath() string
GetDependencyLicensesLink() string
Clear(...string) error

View File

@ -33,6 +33,7 @@ import (
"github.com/ProtonMail/proton-bridge/v3/internal/safe"
"github.com/ProtonMail/proton-bridge/v3/internal/services/imapservice"
"github.com/ProtonMail/proton-bridge/v3/internal/try"
"github.com/ProtonMail/proton-bridge/v3/internal/unleash"
"github.com/ProtonMail/proton-bridge/v3/internal/user"
"github.com/ProtonMail/proton-bridge/v3/internal/vault"
"github.com/go-resty/resty/v2"
@ -255,7 +256,7 @@ func (bridge *Bridge) LogoutUser(ctx context.Context, userID string) error {
return ErrNoSuchUser
}
bridge.logoutUser(ctx, user, true, false, false)
bridge.logoutUser(ctx, user, true, false)
bridge.publish(events.UserLoggedOut{
UserID: userID,
@ -280,7 +281,7 @@ func (bridge *Bridge) DeleteUser(ctx context.Context, userID string) error {
}
if user, ok := bridge.users[userID]; ok {
bridge.logoutUser(ctx, user, true, true, !bridge.GetTelemetryDisabled())
bridge.logoutUser(ctx, user, true, true)
}
if err := imapservice.DeleteSyncState(syncConfigDir, userID); err != nil {
@ -358,7 +359,7 @@ func (bridge *Bridge) SendBadEventUserFeedback(_ context.Context, userID string,
return user.BadEventFeedbackResync(ctx)
}
bridge.logoutUser(ctx, user, true, false, false)
bridge.logoutUser(ctx, user, true, false)
bridge.publish(events.UserLoggedOut{
UserID: userID,
@ -527,11 +528,6 @@ func (bridge *Bridge) addUserWithVault(
vault *vault.User,
isNew bool,
) error {
statsPath, err := bridge.locator.ProvideStatsPath()
if err != nil {
return fmt.Errorf("failed to get Statistics directory: %w", err)
}
syncSettingsPath, err := bridge.locator.ProvideIMAPSyncConfigPath()
if err != nil {
return fmt.Errorf("failed to get IMAP sync config path: %w", err)
@ -546,7 +542,6 @@ func (bridge *Bridge) addUserWithVault(
bridge.panicHandler,
bridge.vault.GetShowAllMail(),
bridge.vault.GetMaxSyncMemory(),
statsPath,
bridge,
bridge.serverManager,
bridge.serverManager,
@ -589,9 +584,12 @@ func (bridge *Bridge) addUserWithVault(
// Finally, save the user in the bridge.
safe.Lock(func() {
bridge.users[apiUser.ID] = user
bridge.heartbeat.SetNbAccount(len(bridge.users))
bridge.heartbeat.SetNumberConnectedAccounts(len(bridge.users))
}, bridge.usersLock)
// Set user plan if its of a higher rank.
bridge.heartbeat.SetUserPlan(user.GetUserPlanName())
// As we need at least one user to send heartbeat, try to send it.
bridge.heartbeat.start()
@ -610,26 +608,21 @@ func (bridge *Bridge) newVaultUser(
return bridge.vault.GetOrAddUser(apiUser.ID, apiUser.Name, apiUser.Email, authUID, authRef, saltedKeyPass)
}
// logout logs out the given user, optionally logging them out from the API too.
func (bridge *Bridge) logoutUser(ctx context.Context, user *user.User, withAPI, withData, withTelemetry bool) {
// logoutUser logs out the given user, optionally logging them out from the API and deleting user related gluon data.
func (bridge *Bridge) logoutUser(ctx context.Context, user *user.User, withAPI, withData bool) {
defer delete(bridge.users, user.ID())
// if this is actually a remove account
if withData && withAPI {
user.SendConfigStatusAbort(ctx, withTelemetry)
}
logUser.WithFields(logrus.Fields{
"userID": user.ID(),
"withAPI": withAPI,
"withData": withData,
}).Debug("Logging out user")
if err := user.Logout(ctx, withAPI); err != nil {
if err := user.Logout(ctx, withAPI, withData, bridge.unleashService.GetFlagValue(unleash.UserRemovalGluonDataCleanupDisabled)); err != nil {
logUser.WithError(err).Error("Failed to logout user")
}
bridge.heartbeat.SetNbAccount(len(bridge.users))
bridge.heartbeat.SetNumberConnectedAccounts(len(bridge.users) - 1)
user.Close()
}

View File

@ -43,8 +43,7 @@ func (bridge *Bridge) handleUserEvent(ctx context.Context, user *user.User, even
func (bridge *Bridge) handleUserDeauth(ctx context.Context, user *user.User) {
safe.Lock(func() {
bridge.logoutUser(ctx, user, false, false, false)
user.ReportConfigStatusFailure("User deauth.")
bridge.logoutUser(ctx, user, false, false)
}, bridge.usersLock)
}

View File

@ -1,228 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package configstatus
import (
"encoding/json"
"fmt"
"os"
"strconv"
"time"
"github.com/ProtonMail/proton-bridge/v3/internal/safe"
"github.com/sirupsen/logrus"
)
const version = "1.0.0"
func LoadConfigurationStatus(filepath string) (*ConfigurationStatus, error) {
status := ConfigurationStatus{
FilePath: filepath,
DataLock: safe.NewRWMutex(),
Data: &ConfigurationStatusData{},
}
if _, err := os.Stat(filepath); err == nil {
if err := status.Load(); err == nil {
return &status, nil
}
logrus.WithError(err).Warn("Cannot load configuration status file. Reset it.")
}
status.Data.init()
if err := status.Save(); err != nil {
return &status, err
}
return &status, nil
}
func (status *ConfigurationStatus) Load() error {
bytes, err := os.ReadFile(status.FilePath)
if err != nil {
return err
}
var metadata MetadataOnly
if err := json.Unmarshal(bytes, &metadata); err != nil {
return err
}
if metadata.Metadata.Version != version {
return fmt.Errorf("unsupported configstatus file version %s", metadata.Metadata.Version)
}
return json.Unmarshal(bytes, status.Data)
}
func (status *ConfigurationStatus) Save() error {
temp := status.FilePath + "_temp"
f, err := os.Create(temp) //nolint:gosec
if err != nil {
return err
}
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
err = enc.Encode(status.Data)
if err := f.Close(); err != nil {
logrus.WithError(err).Error("Error while closing configstatus file.")
}
if err != nil {
return err
}
return os.Rename(temp, status.FilePath)
}
func (status *ConfigurationStatus) IsPending() bool {
status.DataLock.RLock()
defer status.DataLock.RUnlock()
return !status.Data.DataV1.PendingSince.IsZero()
}
func (status *ConfigurationStatus) isPendingSinceMin() int {
if min := int(time.Since(status.Data.DataV1.PendingSince).Minutes()); min > 0 { //nolint:predeclared
return min
}
return 0
}
func (status *ConfigurationStatus) IsFromFailure() bool {
status.DataLock.RLock()
defer status.DataLock.RUnlock()
return status.Data.DataV1.FailureDetails != ""
}
func (status *ConfigurationStatus) ApplySuccess() error {
status.DataLock.Lock()
defer status.DataLock.Unlock()
status.Data.init()
status.Data.DataV1.PendingSince = time.Time{}
return status.Save()
}
func (status *ConfigurationStatus) ApplyFailure(err string) error {
status.DataLock.Lock()
defer status.DataLock.Unlock()
status.Data.init()
status.Data.DataV1.FailureDetails = err
return status.Save()
}
func (status *ConfigurationStatus) ApplyProgress() error {
status.DataLock.Lock()
defer status.DataLock.Unlock()
status.Data.DataV1.LastProgress = time.Now()
return status.Save()
}
func (status *ConfigurationStatus) RecordLinkClicked(link uint64) error {
status.DataLock.Lock()
defer status.DataLock.Unlock()
if !status.Data.hasLinkClicked(link) {
status.Data.setClickedLink(link)
return status.Save()
}
return nil
}
func (status *ConfigurationStatus) ReportClicked() error {
status.DataLock.Lock()
defer status.DataLock.Unlock()
if !status.Data.DataV1.ReportClick {
status.Data.DataV1.ReportClick = true
return status.Save()
}
return nil
}
func (status *ConfigurationStatus) ReportSent() error {
status.DataLock.Lock()
defer status.DataLock.Unlock()
if !status.Data.DataV1.ReportSent {
status.Data.DataV1.ReportSent = true
return status.Save()
}
return nil
}
func (status *ConfigurationStatus) AutoconfigUsed(client string) error {
status.DataLock.Lock()
defer status.DataLock.Unlock()
if client != status.Data.DataV1.Autoconf {
status.Data.DataV1.Autoconf = client
return status.Save()
}
return nil
}
func (status *ConfigurationStatus) Remove() error {
status.DataLock.Lock()
defer status.DataLock.Unlock()
return os.Remove(status.FilePath)
}
func (data *ConfigurationStatusData) init() {
data.Metadata = Metadata{
Version: version,
}
data.DataV1.PendingSince = time.Now()
data.DataV1.LastProgress = time.Time{}
data.DataV1.Autoconf = ""
data.DataV1.ClickedLink = 0
data.DataV1.ReportSent = false
data.DataV1.ReportClick = false
data.DataV1.FailureDetails = ""
}
func (data *ConfigurationStatusData) setClickedLink(pos uint64) {
data.DataV1.ClickedLink |= 1 << pos
}
func (data *ConfigurationStatusData) hasLinkClicked(pos uint64) bool {
val := data.DataV1.ClickedLink & (1 << pos)
return val > 0
}
func (data *ConfigurationStatusData) clickedLinkToString() string {
var str = ""
var first = true
for i := 0; i < 64; i++ {
if data.hasLinkClicked(uint64(i)) { //nolint:gosec // disable G115
if !first {
str += ","
} else {
first = false
str += "["
}
str += strconv.Itoa(i)
}
}
if str != "" {
str += "]"
}
return str
}

View File

@ -1,252 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package configstatus_test
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"time"
"github.com/ProtonMail/proton-bridge/v3/internal/configstatus"
"github.com/stretchr/testify/require"
)
func TestConfigStatus_init_virgin(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, "1.0.0", config.Data.Metadata.Version)
require.Equal(t, false, config.Data.DataV1.PendingSince.IsZero())
require.Equal(t, true, config.Data.DataV1.LastProgress.IsZero())
require.Equal(t, "", config.Data.DataV1.Autoconf)
require.Equal(t, uint64(0), config.Data.DataV1.ClickedLink)
require.Equal(t, false, config.Data.DataV1.ReportSent)
require.Equal(t, false, config.Data.DataV1.ReportClick)
require.Equal(t, "", config.Data.DataV1.FailureDetails)
}
func TestConfigStatus_init_existing(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
var data = configstatus.ConfigurationStatusData{
Metadata: configstatus.Metadata{Version: "1.0.0"},
DataV1: configstatus.DataV1{Autoconf: "Mr TBird"},
}
require.NoError(t, dumpConfigStatusInFile(&data, file))
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, "1.0.0", config.Data.Metadata.Version)
require.Equal(t, "Mr TBird", config.Data.DataV1.Autoconf)
}
func TestConfigStatus_init_bad_version(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
var data = configstatus.ConfigurationStatusData{
Metadata: configstatus.Metadata{Version: "2.0.0"},
DataV1: configstatus.DataV1{Autoconf: "Mr TBird"},
}
require.NoError(t, dumpConfigStatusInFile(&data, file))
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, "1.0.0", config.Data.Metadata.Version)
require.Equal(t, "", config.Data.DataV1.Autoconf)
}
func TestConfigStatus_IsPending(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, true, config.IsPending())
config.Data.DataV1.PendingSince = time.Time{}
require.Equal(t, false, config.IsPending())
}
func TestConfigStatus_IsFromFailure(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, false, config.IsFromFailure())
config.Data.DataV1.FailureDetails = "test"
require.Equal(t, true, config.IsFromFailure())
}
func TestConfigStatus_ApplySuccess(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, true, config.IsPending())
require.NoError(t, config.ApplySuccess())
require.Equal(t, false, config.IsPending())
config2, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, "1.0.0", config2.Data.Metadata.Version)
require.Equal(t, true, config2.Data.DataV1.PendingSince.IsZero())
require.Equal(t, true, config2.Data.DataV1.LastProgress.IsZero())
require.Equal(t, "", config2.Data.DataV1.Autoconf)
require.Equal(t, uint64(0), config2.Data.DataV1.ClickedLink)
require.Equal(t, false, config2.Data.DataV1.ReportSent)
require.Equal(t, false, config2.Data.DataV1.ReportClick)
require.Equal(t, "", config2.Data.DataV1.FailureDetails)
}
func TestConfigStatus_ApplyFailure(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.NoError(t, config.ApplySuccess())
require.NoError(t, config.ApplyFailure("Big Failure"))
require.Equal(t, true, config.IsFromFailure())
require.Equal(t, true, config.IsPending())
config2, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, "1.0.0", config2.Data.Metadata.Version)
require.Equal(t, false, config2.Data.DataV1.PendingSince.IsZero())
require.Equal(t, true, config2.Data.DataV1.LastProgress.IsZero())
require.Equal(t, "", config2.Data.DataV1.Autoconf)
require.Equal(t, uint64(0), config2.Data.DataV1.ClickedLink)
require.Equal(t, false, config2.Data.DataV1.ReportSent)
require.Equal(t, false, config2.Data.DataV1.ReportClick)
require.Equal(t, "Big Failure", config2.Data.DataV1.FailureDetails)
}
func TestConfigStatus_ApplyProgress(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, true, config.IsPending())
require.Equal(t, true, config.Data.DataV1.LastProgress.IsZero())
require.NoError(t, config.ApplyProgress())
config2, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, "1.0.0", config2.Data.Metadata.Version)
require.Equal(t, false, config2.Data.DataV1.PendingSince.IsZero())
require.Equal(t, false, config2.Data.DataV1.LastProgress.IsZero())
require.Equal(t, "", config2.Data.DataV1.Autoconf)
require.Equal(t, uint64(0), config2.Data.DataV1.ClickedLink)
require.Equal(t, false, config2.Data.DataV1.ReportSent)
require.Equal(t, false, config2.Data.DataV1.ReportClick)
require.Equal(t, "", config2.Data.DataV1.FailureDetails)
}
func TestConfigStatus_RecordLinkClicked(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, uint64(0), config.Data.DataV1.ClickedLink)
require.NoError(t, config.RecordLinkClicked(0))
require.Equal(t, uint64(1), config.Data.DataV1.ClickedLink)
require.NoError(t, config.RecordLinkClicked(1))
require.Equal(t, uint64(3), config.Data.DataV1.ClickedLink)
config2, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, "1.0.0", config2.Data.Metadata.Version)
require.Equal(t, false, config2.Data.DataV1.PendingSince.IsZero())
require.Equal(t, true, config2.Data.DataV1.LastProgress.IsZero())
require.Equal(t, "", config2.Data.DataV1.Autoconf)
require.Equal(t, uint64(3), config2.Data.DataV1.ClickedLink)
require.Equal(t, false, config2.Data.DataV1.ReportSent)
require.Equal(t, false, config2.Data.DataV1.ReportClick)
require.Equal(t, "", config2.Data.DataV1.FailureDetails)
}
func TestConfigStatus_ReportClicked(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, false, config.Data.DataV1.ReportClick)
require.NoError(t, config.ReportClicked())
require.Equal(t, true, config.Data.DataV1.ReportClick)
config2, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, "1.0.0", config2.Data.Metadata.Version)
require.Equal(t, false, config2.Data.DataV1.PendingSince.IsZero())
require.Equal(t, true, config2.Data.DataV1.LastProgress.IsZero())
require.Equal(t, "", config2.Data.DataV1.Autoconf)
require.Equal(t, uint64(0), config2.Data.DataV1.ClickedLink)
require.Equal(t, false, config2.Data.DataV1.ReportSent)
require.Equal(t, true, config2.Data.DataV1.ReportClick)
require.Equal(t, "", config2.Data.DataV1.FailureDetails)
}
func TestConfigStatus_ReportSent(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, false, config.Data.DataV1.ReportSent)
require.NoError(t, config.ReportSent())
require.Equal(t, true, config.Data.DataV1.ReportSent)
config2, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
require.Equal(t, "1.0.0", config2.Data.Metadata.Version)
require.Equal(t, false, config2.Data.DataV1.PendingSince.IsZero())
require.Equal(t, true, config2.Data.DataV1.LastProgress.IsZero())
require.Equal(t, "", config2.Data.DataV1.Autoconf)
require.Equal(t, uint64(0), config2.Data.DataV1.ClickedLink)
require.Equal(t, true, config2.Data.DataV1.ReportSent)
require.Equal(t, false, config2.Data.DataV1.ReportClick)
require.Equal(t, "", config2.Data.DataV1.FailureDetails)
}
func dumpConfigStatusInFile(data *configstatus.ConfigurationStatusData, file string) error {
f, err := os.Create(file)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
return json.NewEncoder(f).Encode(data)
}

View File

@ -1,59 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package configstatus
import (
"strconv"
)
type ConfigAbortValues struct {
Duration int `json:"duration"`
}
type ConfigAbortDimensions struct {
ReportClick string `json:"report_click"`
ReportSent string `json:"report_sent"`
ClickedLink string `json:"clicked_link"`
}
type ConfigAbortData struct {
MeasurementGroup string
Event string
Values ConfigSuccessValues
Dimensions ConfigSuccessDimensions
}
type ConfigAbortBuilder struct{}
func (*ConfigAbortBuilder) New(config *ConfigurationStatus) ConfigAbortData {
config.DataLock.RLock()
defer config.DataLock.RUnlock()
return ConfigAbortData{
MeasurementGroup: "bridge.any.configuration",
Event: "bridge_config_abort",
Values: ConfigSuccessValues{
Duration: config.isPendingSinceMin(),
},
Dimensions: ConfigSuccessDimensions{
ReportClick: strconv.FormatBool(config.Data.DataV1.ReportClick),
ReportSent: strconv.FormatBool(config.Data.DataV1.ReportSent),
ClickedLink: config.Data.clickedLinkToString(),
},
}
}

View File

@ -1,75 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package configstatus_test
import (
"path/filepath"
"testing"
"time"
"github.com/ProtonMail/proton-bridge/v3/internal/configstatus"
"github.com/stretchr/testify/require"
)
func TestConfigurationAbort_default(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
var builder = configstatus.ConfigAbortBuilder{}
req := builder.New(config)
require.Equal(t, "bridge.any.configuration", req.MeasurementGroup)
require.Equal(t, "bridge_config_abort", req.Event)
require.Equal(t, 0, req.Values.Duration)
require.Equal(t, "false", req.Dimensions.ReportClick)
require.Equal(t, "false", req.Dimensions.ReportSent)
require.Equal(t, "", req.Dimensions.ClickedLink)
}
func TestConfigurationAbort_fed(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
var data = configstatus.ConfigurationStatusData{
Metadata: configstatus.Metadata{Version: "1.0.0"},
DataV1: configstatus.DataV1{
PendingSince: time.Now().Add(-10 * time.Minute),
LastProgress: time.Time{},
Autoconf: "Mr TBird",
ClickedLink: 42,
ReportSent: false,
ReportClick: true,
FailureDetails: "Not an error",
},
}
require.NoError(t, dumpConfigStatusInFile(&data, file))
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
var builder = configstatus.ConfigAbortBuilder{}
req := builder.New(config)
require.Equal(t, "bridge.any.configuration", req.MeasurementGroup)
require.Equal(t, "bridge_config_abort", req.Event)
require.Equal(t, 10, req.Values.Duration)
require.Equal(t, "true", req.Dimensions.ReportClick)
require.Equal(t, "false", req.Dimensions.ReportSent)
require.Equal(t, "[1,3,5]", req.Dimensions.ClickedLink)
}

View File

@ -1,60 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package configstatus
import "time"
type ConfigProgressValues struct {
NbDay int `json:"nb_day"`
NbDaySinceLast int `json:"nb_day_since_last"`
}
type ConfigProgressData struct {
MeasurementGroup string
Event string
Values ConfigProgressValues
Dimensions struct{}
}
type ConfigProgressBuilder struct{}
func (*ConfigProgressBuilder) New(config *ConfigurationStatus) ConfigProgressData {
config.DataLock.RLock()
defer config.DataLock.RUnlock()
return ConfigProgressData{
MeasurementGroup: "bridge.any.configuration",
Event: "bridge_config_progress",
Values: ConfigProgressValues{
NbDay: numberOfDay(time.Now(), config.Data.DataV1.PendingSince),
NbDaySinceLast: numberOfDay(time.Now(), config.Data.DataV1.LastProgress),
},
}
}
func numberOfDay(now, prev time.Time) int {
if now.IsZero() || prev.IsZero() {
return 1
}
if now.Year() > prev.Year() {
return (365 * (now.Year() - prev.Year())) + now.YearDay() - prev.YearDay()
} else if now.YearDay() > prev.YearDay() {
return now.YearDay() - prev.YearDay()
}
return 0
}

View File

@ -1,100 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package configstatus_test
import (
"path/filepath"
"testing"
"time"
"github.com/ProtonMail/proton-bridge/v3/internal/configstatus"
"github.com/stretchr/testify/require"
)
func TestConfigurationProgress_default(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
var builder = configstatus.ConfigProgressBuilder{}
req := builder.New(config)
require.Equal(t, "bridge.any.configuration", req.MeasurementGroup)
require.Equal(t, "bridge_config_progress", req.Event)
require.Equal(t, 0, req.Values.NbDay)
require.Equal(t, 1, req.Values.NbDaySinceLast)
}
func TestConfigurationProgress_fed(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
var data = configstatus.ConfigurationStatusData{
Metadata: configstatus.Metadata{Version: "1.0.0"},
DataV1: configstatus.DataV1{
PendingSince: time.Now().AddDate(0, 0, -5),
LastProgress: time.Now().AddDate(0, 0, -2),
Autoconf: "Mr TBird",
ClickedLink: 42,
ReportSent: false,
ReportClick: true,
FailureDetails: "Not an error",
},
}
require.NoError(t, dumpConfigStatusInFile(&data, file))
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
var builder = configstatus.ConfigProgressBuilder{}
req := builder.New(config)
require.Equal(t, "bridge.any.configuration", req.MeasurementGroup)
require.Equal(t, "bridge_config_progress", req.Event)
require.Equal(t, 5, req.Values.NbDay)
require.Equal(t, 2, req.Values.NbDaySinceLast)
}
func TestConfigurationProgress_fed_year_change(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
var data = configstatus.ConfigurationStatusData{
Metadata: configstatus.Metadata{Version: "1.0.0"},
DataV1: configstatus.DataV1{
PendingSince: time.Now().AddDate(-1, 0, -5),
LastProgress: time.Now().AddDate(0, 0, -2),
Autoconf: "Mr TBird",
ClickedLink: 42,
ReportSent: false,
ReportClick: true,
FailureDetails: "Not an error",
},
}
require.NoError(t, dumpConfigStatusInFile(&data, file))
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
var builder = configstatus.ConfigProgressBuilder{}
req := builder.New(config)
require.Equal(t, "bridge.any.configuration", req.MeasurementGroup)
require.Equal(t, "bridge_config_progress", req.Event)
require.True(t, (req.Values.NbDay == 370) || (req.Values.NbDay == 371)) // leap year is accounted for in the simplest manner.
require.Equal(t, 2, req.Values.NbDaySinceLast)
}

View File

@ -1,63 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package configstatus
import (
"strconv"
)
type ConfigRecoveryValues struct {
Duration int `json:"duration"`
}
type ConfigRecoveryDimensions struct {
Autoconf string `json:"autoconf"`
ReportClick string `json:"report_click"`
ReportSent string `json:"report_sent"`
ClickedLink string `json:"clicked_link"`
FailureDetails string `json:"failure_details"`
}
type ConfigRecoveryData struct {
MeasurementGroup string
Event string
Values ConfigRecoveryValues
Dimensions ConfigRecoveryDimensions
}
type ConfigRecoveryBuilder struct{}
func (*ConfigRecoveryBuilder) New(config *ConfigurationStatus) ConfigRecoveryData {
config.DataLock.RLock()
defer config.DataLock.RUnlock()
return ConfigRecoveryData{
MeasurementGroup: "bridge.any.configuration",
Event: "bridge_config_recovery",
Values: ConfigRecoveryValues{
Duration: config.isPendingSinceMin(),
},
Dimensions: ConfigRecoveryDimensions{
Autoconf: config.Data.DataV1.Autoconf,
ReportClick: strconv.FormatBool(config.Data.DataV1.ReportClick),
ReportSent: strconv.FormatBool(config.Data.DataV1.ReportSent),
ClickedLink: config.Data.clickedLinkToString(),
FailureDetails: config.Data.DataV1.FailureDetails,
},
}
}

View File

@ -1,79 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package configstatus_test
import (
"path/filepath"
"testing"
"time"
"github.com/ProtonMail/proton-bridge/v3/internal/configstatus"
"github.com/stretchr/testify/require"
)
func TestConfigurationRecovery_default(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
var builder = configstatus.ConfigRecoveryBuilder{}
req := builder.New(config)
require.Equal(t, "bridge.any.configuration", req.MeasurementGroup)
require.Equal(t, "bridge_config_recovery", req.Event)
require.Equal(t, 0, req.Values.Duration)
require.Equal(t, "", req.Dimensions.Autoconf)
require.Equal(t, "false", req.Dimensions.ReportClick)
require.Equal(t, "false", req.Dimensions.ReportSent)
require.Equal(t, "", req.Dimensions.ClickedLink)
require.Equal(t, "", req.Dimensions.FailureDetails)
}
func TestConfigurationRecovery_fed(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
var data = configstatus.ConfigurationStatusData{
Metadata: configstatus.Metadata{Version: "1.0.0"},
DataV1: configstatus.DataV1{
PendingSince: time.Now().Add(-10 * time.Minute),
LastProgress: time.Time{},
Autoconf: "Mr TBird",
ClickedLink: 42,
ReportSent: false,
ReportClick: true,
FailureDetails: "Not an error",
},
}
require.NoError(t, dumpConfigStatusInFile(&data, file))
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
var builder = configstatus.ConfigRecoveryBuilder{}
req := builder.New(config)
require.Equal(t, "bridge.any.configuration", req.MeasurementGroup)
require.Equal(t, "bridge_config_recovery", req.Event)
require.Equal(t, 10, req.Values.Duration)
require.Equal(t, "Mr TBird", req.Dimensions.Autoconf)
require.Equal(t, "true", req.Dimensions.ReportClick)
require.Equal(t, "false", req.Dimensions.ReportSent)
require.Equal(t, "[1,3,5]", req.Dimensions.ClickedLink)
require.Equal(t, "Not an error", req.Dimensions.FailureDetails)
}

View File

@ -1,61 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package configstatus
import (
"strconv"
)
type ConfigSuccessValues struct {
Duration int `json:"duration"`
}
type ConfigSuccessDimensions struct {
Autoconf string `json:"autoconf"`
ReportClick string `json:"report_click"`
ReportSent string `json:"report_sent"`
ClickedLink string `json:"clicked_link"`
}
type ConfigSuccessData struct {
MeasurementGroup string
Event string
Values ConfigSuccessValues
Dimensions ConfigSuccessDimensions
}
type ConfigSuccessBuilder struct{}
func (*ConfigSuccessBuilder) New(config *ConfigurationStatus) ConfigSuccessData {
config.DataLock.RLock()
defer config.DataLock.RUnlock()
return ConfigSuccessData{
MeasurementGroup: "bridge.any.configuration",
Event: "bridge_config_success",
Values: ConfigSuccessValues{
Duration: config.isPendingSinceMin(),
},
Dimensions: ConfigSuccessDimensions{
Autoconf: config.Data.DataV1.Autoconf,
ReportClick: strconv.FormatBool(config.Data.DataV1.ReportClick),
ReportSent: strconv.FormatBool(config.Data.DataV1.ReportSent),
ClickedLink: config.Data.clickedLinkToString(),
},
}
}

View File

@ -1,77 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package configstatus_test
import (
"path/filepath"
"testing"
"time"
"github.com/ProtonMail/proton-bridge/v3/internal/configstatus"
"github.com/stretchr/testify/require"
)
func TestConfigurationSuccess_default(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
var builder = configstatus.ConfigSuccessBuilder{}
req := builder.New(config)
require.Equal(t, "bridge.any.configuration", req.MeasurementGroup)
require.Equal(t, "bridge_config_success", req.Event)
require.Equal(t, 0, req.Values.Duration)
require.Equal(t, "", req.Dimensions.Autoconf)
require.Equal(t, "false", req.Dimensions.ReportClick)
require.Equal(t, "false", req.Dimensions.ReportSent)
require.Equal(t, "", req.Dimensions.ClickedLink)
}
func TestConfigurationSuccess_fed(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "dummy.json")
var data = configstatus.ConfigurationStatusData{
Metadata: configstatus.Metadata{Version: "1.0.0"},
DataV1: configstatus.DataV1{
PendingSince: time.Now().Add(-10 * time.Minute),
LastProgress: time.Time{},
Autoconf: "Mr TBird",
ClickedLink: 42,
ReportSent: false,
ReportClick: true,
FailureDetails: "Not an error",
},
}
require.NoError(t, dumpConfigStatusInFile(&data, file))
config, err := configstatus.LoadConfigurationStatus(file)
require.NoError(t, err)
var builder = configstatus.ConfigSuccessBuilder{}
req := builder.New(config)
require.Equal(t, "bridge.any.configuration", req.MeasurementGroup)
require.Equal(t, "bridge_config_success", req.Event)
require.Equal(t, 10, req.Values.Duration)
require.Equal(t, "Mr TBird", req.Dimensions.Autoconf)
require.Equal(t, "true", req.Dimensions.ReportClick)
require.Equal(t, "false", req.Dimensions.ReportSent)
require.Equal(t, "[1,3,5]", req.Dimensions.ClickedLink)
}

View File

@ -1,56 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package configstatus
import (
"time"
"github.com/ProtonMail/proton-bridge/v3/internal/safe"
)
const ProgressCheckInterval = time.Hour
type Metadata struct {
Version string `json:"version"`
}
type MetadataOnly struct {
Metadata Metadata `json:"metadata"`
}
type DataV1 struct {
PendingSince time.Time `json:"pending_since"`
LastProgress time.Time `json:"last_progress"`
Autoconf string `json:"auto_conf"`
ClickedLink uint64 `json:"clicked_link"`
ReportSent bool `json:"report_sent"`
ReportClick bool `json:"report_click"`
FailureDetails string `json:"failure_details"`
}
type ConfigurationStatusData struct {
Metadata Metadata `json:"metadata"`
DataV1 DataV1 `json:"dataV1"`
}
type ConfigurationStatus struct {
FilePath string
DataLock safe.RWMutex
Data *ConfigurationStatusData
}

View File

@ -30,7 +30,7 @@ using namespace bridgepp;
namespace {
QString const defaultKeychain = "defaultKeychain"; ///< The default keychain.
QString const HV_ERROR_TEMPLATE = "failed to create new API client: 422 POST https://mail-api.proton.me/auth/v4: CAPTCHA validation failed (Code=12087, Status=422)";
QString const HV_ERROR_TEMPLATE = "Human verification failed. Please try again.";
}
@ -846,32 +846,6 @@ Status GRPCService::InstallTLSCertificate(ServerContext *, Empty const *, Empty
}
//****************************************************************************************************************************************************
/// \param[in] request The request.
//****************************************************************************************************************************************************
Status GRPCService::ExternalLinkClicked(::grpc::ServerContext *, ::google::protobuf::StringValue const *request, ::google::protobuf::Empty *) {
app().log().debug(QString("%1 - URL = %2").arg(__FUNCTION__, QString::fromStdString(request->value())));
return Status::OK;
}
//****************************************************************************************************************************************************
//
//****************************************************************************************************************************************************
Status GRPCService::ReportBugClicked(::grpc::ServerContext *, ::google::protobuf::Empty const *, ::google::protobuf::Empty *) {
app().log().debug(__FUNCTION__);
return Status::OK;
}
//****************************************************************************************************************************************************
/// \param[in] request The request.
//****************************************************************************************************************************************************
Status GRPCService::AutoconfigClicked(::grpc::ServerContext *, ::google::protobuf::StringValue const *request, ::google::protobuf::Empty *response) {
app().log().debug(QString("%1 - Client = %2").arg(__FUNCTION__, QString::fromStdString(request->value())));
return Status::OK;
}
//****************************************************************************************************************************************************
/// \param[in] request The request
/// \param[in] writer The writer

View File

@ -97,9 +97,6 @@ public: // member functions.
grpc::Status IsTLSCertificateInstalled(::grpc::ServerContext *, ::google::protobuf::Empty const*, ::google::protobuf::BoolValue *response) override;
grpc::Status InstallTLSCertificate(::grpc::ServerContext *, ::google::protobuf::Empty const*, ::google::protobuf::Empty *) override;
grpc::Status ExportTLSCertificates(::grpc::ServerContext *, ::google::protobuf::StringValue const *request, ::google::protobuf::Empty *) override;
grpc::Status ReportBugClicked(::grpc::ServerContext *context, ::google::protobuf::Empty const *request, ::google::protobuf::Empty *) override;
grpc::Status AutoconfigClicked(::grpc::ServerContext *context, ::google::protobuf::StringValue const *request, ::google::protobuf::Empty *) override;
grpc::Status ExternalLinkClicked(::grpc::ServerContext *, ::google::protobuf::StringValue const *request, ::google::protobuf::Empty *) override;
grpc::Status RunEventStream(::grpc::ServerContext *ctx, ::grpc::EventStreamRequest const *request, ::grpc::ServerWriter<::grpc::StreamEvent> *writer) override;
grpc::Status StopEventStream(::grpc::ServerContext *, ::google::protobuf::Empty const *, ::google::protobuf::Empty *) override;
bool sendEvent(bridgepp::SPStreamEvent const &event); ///< Queue an event for sending through the event stream.

View File

@ -303,7 +303,6 @@ void QMLBackend::openExternalLink(QString const &url) {
HANDLE_EXCEPTION(
QString const u = url.isEmpty() ? bridgeKBUrl : url;
QDesktopServices::openUrl(u);
emit notifyExternalLinkClicked(u);
)
}
@ -1095,33 +1094,6 @@ void QMLBackend::sendBadEventUserFeedback(QString const &userID, bool doResync)
)
}
//****************************************************************************************************************************************************
///
//****************************************************************************************************************************************************
void QMLBackend::notifyReportBugClicked() const {
HANDLE_EXCEPTION(
app().grpc().reportBugClicked();
)
}
//****************************************************************************************************************************************************
/// \param[in] client The selected Mail client for autoconfig.
//****************************************************************************************************************************************************
void QMLBackend::notifyAutoconfigClicked(QString const &client) const {
HANDLE_EXCEPTION(
app().grpc().autoconfigClicked(client);
)
}
//****************************************************************************************************************************************************
/// \param[in] article The url of the KB article.
//****************************************************************************************************************************************************
void QMLBackend::notifyExternalLinkClicked(QString const &article) const {
HANDLE_EXCEPTION(
app().grpc().externalLinkClicked(article);
)
}
//****************************************************************************************************************************************************
//
//****************************************************************************************************************************************************

View File

@ -213,9 +213,6 @@ public slots: // slot for signals received from QML -> To be forwarded to Bridge
void onVersionChanged(); ///< Slot for the version change signal.
void setMailServerSettings(int imapPort, int smtpPort, bool useSSLForIMAP, bool useSSLForSMTP) const; ///< Forwards a connection mode change request from QML to gRPC
void sendBadEventUserFeedback(QString const &userID, bool doResync); ///< Slot the providing user feedback for a bad event.
void notifyReportBugClicked() const; ///< Slot for the ReportBugClicked gRPC event.
void notifyAutoconfigClicked(QString const &client) const; ///< Slot for gAutoconfigClicked gRPC event.
void notifyExternalLinkClicked(QString const &article) const; ///< Slot for KBArticleClicked gRPC event.
void triggerRepair() const; ///< Slot for the triggering of the bridge repair function i.e. 'resync'.
void userNotificationDismissed(); ///< Slot to pop the notification from the stack and display the rest.

View File

@ -83,7 +83,6 @@ SettingsView {
onClicked: {
Backend.updateCurrentMailClient();
Backend.notifyReportBugClicked();
root.parent.showBugReport();
}
}

View File

@ -29,6 +29,7 @@ FocusScope {
property alias username: usernameTextField.text
property var wizard
property string hvLinkUrl: ""
property bool hvLinkClicked: false
signal loginAbort(string username, bool wasSignedOut)
@ -49,6 +50,7 @@ FocusScope {
}
passwordTextField.hidePassword();
secondPasswordTextField.hidePassword();
hvLinkClicked = false;
}
function resetViaHv() {
usernameTextField.enabled = false;
@ -56,6 +58,7 @@ FocusScope {
signInButton.loading = true;
secondPasswordButton.loading = false;
secondPasswordTextField.enabled = true;
hvLinkClicked = false;
totpLayout.reset();
}
@ -562,6 +565,7 @@ FocusScope {
cursorShape: Qt.PointingHandCursor
onClicked: {
Qt.openUrlExternally(hvLinkUrl);
hvLinkClicked = true;
}
}
}
@ -574,7 +578,8 @@ FocusScope {
id: hVContinueButton
Layout.fillWidth: true
colorScheme: wizard.colorScheme
text: qsTr("Continue")
text: qsTr("Ive completed the verification")
enabled: hvLinkClicked
function checkAndSignInHv() {
console.assert(stackLayout.currentIndex === Login.RootStack.HV || stackLayout.currentIndex === Login.RootStack.MailboxPassword, "Unexpected checkInAndSignInHv")

View File

@ -1572,32 +1572,6 @@ UPClientContext GRPCClient::clientContext() const {
return ctx;
}
//****************************************************************************************************************************************************
/// \return the status for the gRPC call.
//****************************************************************************************************************************************************
grpc::Status GRPCClient::reportBugClicked() {
return this->logGRPCCallStatus(stub_->ReportBugClicked(this->clientContext().get(), empty, &empty), __FUNCTION__);
}
//****************************************************************************************************************************************************
/// \param[in] client The client string.
/// \return the status for the gRPC call.
//****************************************************************************************************************************************************
grpc::Status GRPCClient::autoconfigClicked(QString const &client) {
StringValue s;
s.set_value(client.toStdString());
return this->logGRPCCallStatus(stub_->AutoconfigClicked(this->clientContext().get(), s, &empty), __FUNCTION__);
}
//****************************************************************************************************************************************************
/// \param[in] link The clicked link.
/// \return the status for the gRPC call.
//****************************************************************************************************************************************************
grpc::Status GRPCClient::externalLinkClicked(QString const &link) {
StringValue s;
s.set_value(link.toStdString());
return this->logGRPCCallStatus(stub_->ExternalLinkClicked(this->clientContext().get(), s, &empty), __FUNCTION__);
}
//****************************************************************************************************************************************************
//

View File

@ -232,11 +232,6 @@ signals:
void syncFinished(QString const &userID);
void syncProgress(QString const &userID, double progress, qint64 elapsedMs, qint64 remainingMs);
public: // telemetry related calls
grpc::Status reportBugClicked(); ///< Performs the 'reportBugClicked' call.
grpc::Status autoconfigClicked(QString const &userID); ///< Performs the 'AutoconfigClicked' call.
grpc::Status externalLinkClicked(QString const &userID); ///< Performs the 'KBArticleClicked' call.
public: // keychain related calls
grpc::Status availableKeychains(QStringList &outKeychains);
grpc::Status currentKeychain(QString &outKeychain);

View File

@ -159,7 +159,10 @@ func (f *frontendCLI) loginAccount(c *ishell.Context) {
hvDetails, hvErr := hv.VerifyAndExtractHvRequest(err)
if hvErr != nil || hvDetails != nil {
if hvErr != nil {
f.printAndLogError("Cannot login", hvErr)
f.printAndLogError("Cannot login:", hv.ExtractionErrorMsg)
f.bridge.ReportMessageWithContext("Unable to extract HV request details", map[string]any{
"error": err.Error(),
})
return
}
f.promptHvURL(hvDetails)

View File

@ -5425,7 +5425,7 @@ var file_bridge_proto_rawDesc = []byte{
0x4c, 0x53, 0x5f, 0x43, 0x45, 0x52, 0x54, 0x5f, 0x45, 0x58, 0x50, 0x4f, 0x52, 0x54, 0x5f, 0x45,
0x52, 0x52, 0x4f, 0x52, 0x10, 0x01, 0x12, 0x18, 0x0a, 0x14, 0x54, 0x4c, 0x53, 0x5f, 0x4b, 0x45,
0x59, 0x5f, 0x45, 0x58, 0x50, 0x4f, 0x52, 0x54, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02,
0x32, 0x99, 0x23, 0x0a, 0x06, 0x42, 0x72, 0x69, 0x64, 0x67, 0x65, 0x12, 0x49, 0x0a, 0x0b, 0x43,
0x32, 0xbd, 0x21, 0x0a, 0x06, 0x42, 0x72, 0x69, 0x64, 0x67, 0x65, 0x12, 0x49, 0x0a, 0x0b, 0x43,
0x68, 0x65, 0x63, 0x6b, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x73, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x6f,
0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72,
0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
@ -5666,51 +5666,37 @@ var file_bridge_proto_rawDesc = []byte{
0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x65, 0x41, 0x70, 0x70, 0x6c, 0x65, 0x4d,
0x61, 0x69, 0x6c, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f,
0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70,
0x74, 0x79, 0x12, 0x42, 0x0a, 0x10, 0x52, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x42, 0x75, 0x67, 0x43,
0x6c, 0x69, 0x63, 0x6b, 0x65, 0x64, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x16,
0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66,
0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x49, 0x0a, 0x11, 0x41, 0x75, 0x74, 0x6f, 0x63, 0x6f,
0x6e, 0x66, 0x69, 0x67, 0x43, 0x6c, 0x69, 0x63, 0x6b, 0x65, 0x64, 0x12, 0x1c, 0x2e, 0x67, 0x6f,
0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74,
0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67,
0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74,
0x79, 0x12, 0x4b, 0x0a, 0x13, 0x45, 0x78, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x4c, 0x69, 0x6e,
0x6b, 0x43, 0x6c, 0x69, 0x63, 0x6b, 0x65, 0x64, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e,
0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x4f,
0x0a, 0x19, 0x49, 0x73, 0x54, 0x4c, 0x53, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61,
0x74, 0x65, 0x49, 0x6e, 0x73, 0x74, 0x61, 0x6c, 0x6c, 0x65, 0x64, 0x12, 0x16, 0x2e, 0x67, 0x6f,
0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d,
0x70, 0x74, 0x79, 0x1a, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12,
0x47, 0x0a, 0x15, 0x49, 0x6e, 0x73, 0x74, 0x61, 0x6c, 0x6c, 0x54, 0x4c, 0x53, 0x43, 0x65, 0x72,
0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79,
0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x4d, 0x0a, 0x15, 0x45, 0x78, 0x70, 0x6f,
0x72, 0x74, 0x54, 0x4c, 0x53, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65,
0x73, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a,
0x74, 0x79, 0x12, 0x4f, 0x0a, 0x19, 0x49, 0x73, 0x54, 0x4c, 0x53, 0x43, 0x65, 0x72, 0x74, 0x69,
0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x49, 0x6e, 0x73, 0x74, 0x61, 0x6c, 0x6c, 0x65, 0x64, 0x12,
0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75,
0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3f, 0x0a, 0x0e, 0x52, 0x75, 0x6e, 0x45, 0x76,
0x65, 0x6e, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x18, 0x2e, 0x67, 0x72, 0x70, 0x63,
0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x71, 0x75,
0x65, 0x73, 0x74, 0x1a, 0x11, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61,
0x6d, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x30, 0x01, 0x12, 0x41, 0x0a, 0x0f, 0x53, 0x74, 0x6f, 0x70,
0x45, 0x76, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x16, 0x2e, 0x67, 0x6f,
0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d,
0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3f, 0x0a, 0x0d, 0x54,
0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x52, 0x65, 0x70, 0x61, 0x69, 0x72, 0x12, 0x16, 0x2e, 0x67,
0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61,
0x6c, 0x75, 0x65, 0x12, 0x47, 0x0a, 0x15, 0x49, 0x6e, 0x73, 0x74, 0x61, 0x6c, 0x6c, 0x54, 0x4c,
0x53, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x12, 0x16, 0x2e, 0x67,
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45,
0x6d, 0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x42, 0x36, 0x5a, 0x34,
0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x50, 0x72, 0x6f, 0x74, 0x6f,
0x6e, 0x4d, 0x61, 0x69, 0x6c, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x6e, 0x2d, 0x62, 0x72, 0x69,
0x64, 0x67, 0x65, 0x2f, 0x76, 0x33, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f,
0x67, 0x72, 0x70, 0x63, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x4d, 0x0a, 0x15,
0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, 0x4c, 0x53, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69,
0x63, 0x61, 0x74, 0x65, 0x73, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61,
0x6c, 0x75, 0x65, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3f, 0x0a, 0x0e, 0x52,
0x75, 0x6e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x18, 0x2e,
0x67, 0x72, 0x70, 0x63, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x11, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x53,
0x74, 0x72, 0x65, 0x61, 0x6d, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x30, 0x01, 0x12, 0x41, 0x0a, 0x0f,
0x53, 0x74, 0x6f, 0x70, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12,
0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75,
0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12,
0x3f, 0x0a, 0x0d, 0x54, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x52, 0x65, 0x70, 0x61, 0x69, 0x72,
0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79,
0x42, 0x36, 0x5a, 0x34, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x50,
0x72, 0x6f, 0x74, 0x6f, 0x6e, 0x4d, 0x61, 0x69, 0x6c, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x6e,
0x2d, 0x62, 0x72, 0x69, 0x64, 0x67, 0x65, 0x2f, 0x76, 0x33, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72,
0x6e, 0x61, 0x6c, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
@ -5938,81 +5924,75 @@ var file_bridge_proto_depIdxs = []int32{
80, // 121: grpc.Bridge.LogoutUser:input_type -> google.protobuf.StringValue
80, // 122: grpc.Bridge.RemoveUser:input_type -> google.protobuf.StringValue
18, // 123: grpc.Bridge.ConfigureUserAppleMail:input_type -> grpc.ConfigureAppleMailRequest
81, // 124: grpc.Bridge.ReportBugClicked:input_type -> google.protobuf.Empty
80, // 125: grpc.Bridge.AutoconfigClicked:input_type -> google.protobuf.StringValue
80, // 126: grpc.Bridge.ExternalLinkClicked:input_type -> google.protobuf.StringValue
81, // 127: grpc.Bridge.IsTLSCertificateInstalled:input_type -> google.protobuf.Empty
81, // 128: grpc.Bridge.InstallTLSCertificate:input_type -> google.protobuf.Empty
80, // 129: grpc.Bridge.ExportTLSCertificates:input_type -> google.protobuf.StringValue
19, // 130: grpc.Bridge.RunEventStream:input_type -> grpc.EventStreamRequest
81, // 131: grpc.Bridge.StopEventStream:input_type -> google.protobuf.Empty
81, // 132: grpc.Bridge.TriggerRepair:input_type -> google.protobuf.Empty
80, // 133: grpc.Bridge.CheckTokens:output_type -> google.protobuf.StringValue
81, // 134: grpc.Bridge.AddLogEntry:output_type -> google.protobuf.Empty
8, // 135: grpc.Bridge.GuiReady:output_type -> grpc.GuiReadyResponse
81, // 136: grpc.Bridge.Quit:output_type -> google.protobuf.Empty
81, // 137: grpc.Bridge.Restart:output_type -> google.protobuf.Empty
82, // 138: grpc.Bridge.ShowOnStartup:output_type -> google.protobuf.BoolValue
81, // 139: grpc.Bridge.SetIsAutostartOn:output_type -> google.protobuf.Empty
82, // 140: grpc.Bridge.IsAutostartOn:output_type -> google.protobuf.BoolValue
81, // 141: grpc.Bridge.SetIsBetaEnabled:output_type -> google.protobuf.Empty
82, // 142: grpc.Bridge.IsBetaEnabled:output_type -> google.protobuf.BoolValue
81, // 143: grpc.Bridge.SetIsAllMailVisible:output_type -> google.protobuf.Empty
82, // 144: grpc.Bridge.IsAllMailVisible:output_type -> google.protobuf.BoolValue
81, // 145: grpc.Bridge.SetIsTelemetryDisabled:output_type -> google.protobuf.Empty
82, // 146: grpc.Bridge.IsTelemetryDisabled:output_type -> google.protobuf.BoolValue
80, // 147: grpc.Bridge.GoOs:output_type -> google.protobuf.StringValue
81, // 148: grpc.Bridge.TriggerReset:output_type -> google.protobuf.Empty
80, // 149: grpc.Bridge.Version:output_type -> google.protobuf.StringValue
80, // 150: grpc.Bridge.LogsPath:output_type -> google.protobuf.StringValue
80, // 151: grpc.Bridge.LicensePath:output_type -> google.protobuf.StringValue
80, // 152: grpc.Bridge.ReleaseNotesPageLink:output_type -> google.protobuf.StringValue
80, // 153: grpc.Bridge.DependencyLicensesLink:output_type -> google.protobuf.StringValue
80, // 154: grpc.Bridge.LandingPageLink:output_type -> google.protobuf.StringValue
81, // 155: grpc.Bridge.SetColorSchemeName:output_type -> google.protobuf.Empty
80, // 156: grpc.Bridge.ColorSchemeName:output_type -> google.protobuf.StringValue
80, // 157: grpc.Bridge.CurrentEmailClient:output_type -> google.protobuf.StringValue
81, // 158: grpc.Bridge.ReportBug:output_type -> google.protobuf.Empty
81, // 159: grpc.Bridge.ForceLauncher:output_type -> google.protobuf.Empty
81, // 160: grpc.Bridge.SetMainExecutable:output_type -> google.protobuf.Empty
81, // 161: grpc.Bridge.RequestKnowledgeBaseSuggestions:output_type -> google.protobuf.Empty
81, // 162: grpc.Bridge.Login:output_type -> google.protobuf.Empty
81, // 163: grpc.Bridge.Login2FA:output_type -> google.protobuf.Empty
81, // 164: grpc.Bridge.Login2Passwords:output_type -> google.protobuf.Empty
81, // 165: grpc.Bridge.LoginAbort:output_type -> google.protobuf.Empty
81, // 166: grpc.Bridge.CheckUpdate:output_type -> google.protobuf.Empty
81, // 167: grpc.Bridge.InstallUpdate:output_type -> google.protobuf.Empty
81, // 168: grpc.Bridge.SetIsAutomaticUpdateOn:output_type -> google.protobuf.Empty
82, // 169: grpc.Bridge.IsAutomaticUpdateOn:output_type -> google.protobuf.BoolValue
80, // 170: grpc.Bridge.DiskCachePath:output_type -> google.protobuf.StringValue
81, // 171: grpc.Bridge.SetDiskCachePath:output_type -> google.protobuf.Empty
81, // 172: grpc.Bridge.SetIsDoHEnabled:output_type -> google.protobuf.Empty
82, // 173: grpc.Bridge.IsDoHEnabled:output_type -> google.protobuf.BoolValue
12, // 174: grpc.Bridge.MailServerSettings:output_type -> grpc.ImapSmtpSettings
81, // 175: grpc.Bridge.SetMailServerSettings:output_type -> google.protobuf.Empty
80, // 176: grpc.Bridge.Hostname:output_type -> google.protobuf.StringValue
82, // 177: grpc.Bridge.IsPortFree:output_type -> google.protobuf.BoolValue
13, // 178: grpc.Bridge.AvailableKeychains:output_type -> grpc.AvailableKeychainsResponse
81, // 179: grpc.Bridge.SetCurrentKeychain:output_type -> google.protobuf.Empty
80, // 180: grpc.Bridge.CurrentKeychain:output_type -> google.protobuf.StringValue
17, // 181: grpc.Bridge.GetUserList:output_type -> grpc.UserListResponse
14, // 182: grpc.Bridge.GetUser:output_type -> grpc.User
81, // 183: grpc.Bridge.SetUserSplitMode:output_type -> google.protobuf.Empty
81, // 184: grpc.Bridge.SendBadEventUserFeedback:output_type -> google.protobuf.Empty
81, // 185: grpc.Bridge.LogoutUser:output_type -> google.protobuf.Empty
81, // 186: grpc.Bridge.RemoveUser:output_type -> google.protobuf.Empty
81, // 187: grpc.Bridge.ConfigureUserAppleMail:output_type -> google.protobuf.Empty
81, // 188: grpc.Bridge.ReportBugClicked:output_type -> google.protobuf.Empty
81, // 189: grpc.Bridge.AutoconfigClicked:output_type -> google.protobuf.Empty
81, // 190: grpc.Bridge.ExternalLinkClicked:output_type -> google.protobuf.Empty
82, // 191: grpc.Bridge.IsTLSCertificateInstalled:output_type -> google.protobuf.BoolValue
81, // 192: grpc.Bridge.InstallTLSCertificate:output_type -> google.protobuf.Empty
81, // 193: grpc.Bridge.ExportTLSCertificates:output_type -> google.protobuf.Empty
20, // 194: grpc.Bridge.RunEventStream:output_type -> grpc.StreamEvent
81, // 195: grpc.Bridge.StopEventStream:output_type -> google.protobuf.Empty
81, // 196: grpc.Bridge.TriggerRepair:output_type -> google.protobuf.Empty
133, // [133:197] is the sub-list for method output_type
69, // [69:133] is the sub-list for method input_type
81, // 124: grpc.Bridge.IsTLSCertificateInstalled:input_type -> google.protobuf.Empty
81, // 125: grpc.Bridge.InstallTLSCertificate:input_type -> google.protobuf.Empty
80, // 126: grpc.Bridge.ExportTLSCertificates:input_type -> google.protobuf.StringValue
19, // 127: grpc.Bridge.RunEventStream:input_type -> grpc.EventStreamRequest
81, // 128: grpc.Bridge.StopEventStream:input_type -> google.protobuf.Empty
81, // 129: grpc.Bridge.TriggerRepair:input_type -> google.protobuf.Empty
80, // 130: grpc.Bridge.CheckTokens:output_type -> google.protobuf.StringValue
81, // 131: grpc.Bridge.AddLogEntry:output_type -> google.protobuf.Empty
8, // 132: grpc.Bridge.GuiReady:output_type -> grpc.GuiReadyResponse
81, // 133: grpc.Bridge.Quit:output_type -> google.protobuf.Empty
81, // 134: grpc.Bridge.Restart:output_type -> google.protobuf.Empty
82, // 135: grpc.Bridge.ShowOnStartup:output_type -> google.protobuf.BoolValue
81, // 136: grpc.Bridge.SetIsAutostartOn:output_type -> google.protobuf.Empty
82, // 137: grpc.Bridge.IsAutostartOn:output_type -> google.protobuf.BoolValue
81, // 138: grpc.Bridge.SetIsBetaEnabled:output_type -> google.protobuf.Empty
82, // 139: grpc.Bridge.IsBetaEnabled:output_type -> google.protobuf.BoolValue
81, // 140: grpc.Bridge.SetIsAllMailVisible:output_type -> google.protobuf.Empty
82, // 141: grpc.Bridge.IsAllMailVisible:output_type -> google.protobuf.BoolValue
81, // 142: grpc.Bridge.SetIsTelemetryDisabled:output_type -> google.protobuf.Empty
82, // 143: grpc.Bridge.IsTelemetryDisabled:output_type -> google.protobuf.BoolValue
80, // 144: grpc.Bridge.GoOs:output_type -> google.protobuf.StringValue
81, // 145: grpc.Bridge.TriggerReset:output_type -> google.protobuf.Empty
80, // 146: grpc.Bridge.Version:output_type -> google.protobuf.StringValue
80, // 147: grpc.Bridge.LogsPath:output_type -> google.protobuf.StringValue
80, // 148: grpc.Bridge.LicensePath:output_type -> google.protobuf.StringValue
80, // 149: grpc.Bridge.ReleaseNotesPageLink:output_type -> google.protobuf.StringValue
80, // 150: grpc.Bridge.DependencyLicensesLink:output_type -> google.protobuf.StringValue
80, // 151: grpc.Bridge.LandingPageLink:output_type -> google.protobuf.StringValue
81, // 152: grpc.Bridge.SetColorSchemeName:output_type -> google.protobuf.Empty
80, // 153: grpc.Bridge.ColorSchemeName:output_type -> google.protobuf.StringValue
80, // 154: grpc.Bridge.CurrentEmailClient:output_type -> google.protobuf.StringValue
81, // 155: grpc.Bridge.ReportBug:output_type -> google.protobuf.Empty
81, // 156: grpc.Bridge.ForceLauncher:output_type -> google.protobuf.Empty
81, // 157: grpc.Bridge.SetMainExecutable:output_type -> google.protobuf.Empty
81, // 158: grpc.Bridge.RequestKnowledgeBaseSuggestions:output_type -> google.protobuf.Empty
81, // 159: grpc.Bridge.Login:output_type -> google.protobuf.Empty
81, // 160: grpc.Bridge.Login2FA:output_type -> google.protobuf.Empty
81, // 161: grpc.Bridge.Login2Passwords:output_type -> google.protobuf.Empty
81, // 162: grpc.Bridge.LoginAbort:output_type -> google.protobuf.Empty
81, // 163: grpc.Bridge.CheckUpdate:output_type -> google.protobuf.Empty
81, // 164: grpc.Bridge.InstallUpdate:output_type -> google.protobuf.Empty
81, // 165: grpc.Bridge.SetIsAutomaticUpdateOn:output_type -> google.protobuf.Empty
82, // 166: grpc.Bridge.IsAutomaticUpdateOn:output_type -> google.protobuf.BoolValue
80, // 167: grpc.Bridge.DiskCachePath:output_type -> google.protobuf.StringValue
81, // 168: grpc.Bridge.SetDiskCachePath:output_type -> google.protobuf.Empty
81, // 169: grpc.Bridge.SetIsDoHEnabled:output_type -> google.protobuf.Empty
82, // 170: grpc.Bridge.IsDoHEnabled:output_type -> google.protobuf.BoolValue
12, // 171: grpc.Bridge.MailServerSettings:output_type -> grpc.ImapSmtpSettings
81, // 172: grpc.Bridge.SetMailServerSettings:output_type -> google.protobuf.Empty
80, // 173: grpc.Bridge.Hostname:output_type -> google.protobuf.StringValue
82, // 174: grpc.Bridge.IsPortFree:output_type -> google.protobuf.BoolValue
13, // 175: grpc.Bridge.AvailableKeychains:output_type -> grpc.AvailableKeychainsResponse
81, // 176: grpc.Bridge.SetCurrentKeychain:output_type -> google.protobuf.Empty
80, // 177: grpc.Bridge.CurrentKeychain:output_type -> google.protobuf.StringValue
17, // 178: grpc.Bridge.GetUserList:output_type -> grpc.UserListResponse
14, // 179: grpc.Bridge.GetUser:output_type -> grpc.User
81, // 180: grpc.Bridge.SetUserSplitMode:output_type -> google.protobuf.Empty
81, // 181: grpc.Bridge.SendBadEventUserFeedback:output_type -> google.protobuf.Empty
81, // 182: grpc.Bridge.LogoutUser:output_type -> google.protobuf.Empty
81, // 183: grpc.Bridge.RemoveUser:output_type -> google.protobuf.Empty
81, // 184: grpc.Bridge.ConfigureUserAppleMail:output_type -> google.protobuf.Empty
82, // 185: grpc.Bridge.IsTLSCertificateInstalled:output_type -> google.protobuf.BoolValue
81, // 186: grpc.Bridge.InstallTLSCertificate:output_type -> google.protobuf.Empty
81, // 187: grpc.Bridge.ExportTLSCertificates:output_type -> google.protobuf.Empty
20, // 188: grpc.Bridge.RunEventStream:output_type -> grpc.StreamEvent
81, // 189: grpc.Bridge.StopEventStream:output_type -> google.protobuf.Empty
81, // 190: grpc.Bridge.TriggerRepair:output_type -> google.protobuf.Empty
130, // [130:191] is the sub-list for method output_type
69, // [69:130] is the sub-list for method input_type
69, // [69:69] is the sub-list for extension type_name
69, // [69:69] is the sub-list for extension extendee
0, // [0:69] is the sub-list for field type_name

View File

@ -98,11 +98,6 @@ service Bridge {
rpc RemoveUser(google.protobuf.StringValue) returns (google.protobuf.Empty);
rpc ConfigureUserAppleMail(ConfigureAppleMailRequest) returns (google.protobuf.Empty);
// Telemetry
rpc ReportBugClicked(google.protobuf.Empty) returns (google.protobuf.Empty);
rpc AutoconfigClicked(google.protobuf.StringValue) returns (google.protobuf.Empty);
rpc ExternalLinkClicked(google.protobuf.StringValue) returns (google.protobuf.Empty);
// TLS certificate related calls
rpc IsTLSCertificateInstalled(google.protobuf.Empty) returns (google.protobuf.BoolValue);
rpc InstallTLSCertificate(google.protobuf.Empty) returns (google.protobuf.Empty);

View File

@ -93,9 +93,6 @@ const (
Bridge_LogoutUser_FullMethodName = "/grpc.Bridge/LogoutUser"
Bridge_RemoveUser_FullMethodName = "/grpc.Bridge/RemoveUser"
Bridge_ConfigureUserAppleMail_FullMethodName = "/grpc.Bridge/ConfigureUserAppleMail"
Bridge_ReportBugClicked_FullMethodName = "/grpc.Bridge/ReportBugClicked"
Bridge_AutoconfigClicked_FullMethodName = "/grpc.Bridge/AutoconfigClicked"
Bridge_ExternalLinkClicked_FullMethodName = "/grpc.Bridge/ExternalLinkClicked"
Bridge_IsTLSCertificateInstalled_FullMethodName = "/grpc.Bridge/IsTLSCertificateInstalled"
Bridge_InstallTLSCertificate_FullMethodName = "/grpc.Bridge/InstallTLSCertificate"
Bridge_ExportTLSCertificates_FullMethodName = "/grpc.Bridge/ExportTLSCertificates"
@ -170,10 +167,6 @@ type BridgeClient interface {
LogoutUser(ctx context.Context, in *wrapperspb.StringValue, opts ...grpc.CallOption) (*emptypb.Empty, error)
RemoveUser(ctx context.Context, in *wrapperspb.StringValue, opts ...grpc.CallOption) (*emptypb.Empty, error)
ConfigureUserAppleMail(ctx context.Context, in *ConfigureAppleMailRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
// Telemetry
ReportBugClicked(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error)
AutoconfigClicked(ctx context.Context, in *wrapperspb.StringValue, opts ...grpc.CallOption) (*emptypb.Empty, error)
ExternalLinkClicked(ctx context.Context, in *wrapperspb.StringValue, opts ...grpc.CallOption) (*emptypb.Empty, error)
// TLS certificate related calls
IsTLSCertificateInstalled(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*wrapperspb.BoolValue, error)
InstallTLSCertificate(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error)
@ -688,33 +681,6 @@ func (c *bridgeClient) ConfigureUserAppleMail(ctx context.Context, in *Configure
return out, nil
}
func (c *bridgeClient) ReportBugClicked(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error) {
out := new(emptypb.Empty)
err := c.cc.Invoke(ctx, Bridge_ReportBugClicked_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *bridgeClient) AutoconfigClicked(ctx context.Context, in *wrapperspb.StringValue, opts ...grpc.CallOption) (*emptypb.Empty, error) {
out := new(emptypb.Empty)
err := c.cc.Invoke(ctx, Bridge_AutoconfigClicked_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *bridgeClient) ExternalLinkClicked(ctx context.Context, in *wrapperspb.StringValue, opts ...grpc.CallOption) (*emptypb.Empty, error) {
out := new(emptypb.Empty)
err := c.cc.Invoke(ctx, Bridge_ExternalLinkClicked_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *bridgeClient) IsTLSCertificateInstalled(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*wrapperspb.BoolValue, error) {
out := new(wrapperspb.BoolValue)
err := c.cc.Invoke(ctx, Bridge_IsTLSCertificateInstalled_FullMethodName, in, out, opts...)
@ -858,10 +824,6 @@ type BridgeServer interface {
LogoutUser(context.Context, *wrapperspb.StringValue) (*emptypb.Empty, error)
RemoveUser(context.Context, *wrapperspb.StringValue) (*emptypb.Empty, error)
ConfigureUserAppleMail(context.Context, *ConfigureAppleMailRequest) (*emptypb.Empty, error)
// Telemetry
ReportBugClicked(context.Context, *emptypb.Empty) (*emptypb.Empty, error)
AutoconfigClicked(context.Context, *wrapperspb.StringValue) (*emptypb.Empty, error)
ExternalLinkClicked(context.Context, *wrapperspb.StringValue) (*emptypb.Empty, error)
// TLS certificate related calls
IsTLSCertificateInstalled(context.Context, *emptypb.Empty) (*wrapperspb.BoolValue, error)
InstallTLSCertificate(context.Context, *emptypb.Empty) (*emptypb.Empty, error)
@ -1043,15 +1005,6 @@ func (UnimplementedBridgeServer) RemoveUser(context.Context, *wrapperspb.StringV
func (UnimplementedBridgeServer) ConfigureUserAppleMail(context.Context, *ConfigureAppleMailRequest) (*emptypb.Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method ConfigureUserAppleMail not implemented")
}
func (UnimplementedBridgeServer) ReportBugClicked(context.Context, *emptypb.Empty) (*emptypb.Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method ReportBugClicked not implemented")
}
func (UnimplementedBridgeServer) AutoconfigClicked(context.Context, *wrapperspb.StringValue) (*emptypb.Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method AutoconfigClicked not implemented")
}
func (UnimplementedBridgeServer) ExternalLinkClicked(context.Context, *wrapperspb.StringValue) (*emptypb.Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method ExternalLinkClicked not implemented")
}
func (UnimplementedBridgeServer) IsTLSCertificateInstalled(context.Context, *emptypb.Empty) (*wrapperspb.BoolValue, error) {
return nil, status.Errorf(codes.Unimplemented, "method IsTLSCertificateInstalled not implemented")
}
@ -2073,60 +2026,6 @@ func _Bridge_ConfigureUserAppleMail_Handler(srv interface{}, ctx context.Context
return interceptor(ctx, in, info, handler)
}
func _Bridge_ReportBugClicked_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(emptypb.Empty)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(BridgeServer).ReportBugClicked(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Bridge_ReportBugClicked_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(BridgeServer).ReportBugClicked(ctx, req.(*emptypb.Empty))
}
return interceptor(ctx, in, info, handler)
}
func _Bridge_AutoconfigClicked_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(wrapperspb.StringValue)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(BridgeServer).AutoconfigClicked(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Bridge_AutoconfigClicked_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(BridgeServer).AutoconfigClicked(ctx, req.(*wrapperspb.StringValue))
}
return interceptor(ctx, in, info, handler)
}
func _Bridge_ExternalLinkClicked_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(wrapperspb.StringValue)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(BridgeServer).ExternalLinkClicked(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Bridge_ExternalLinkClicked_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(BridgeServer).ExternalLinkClicked(ctx, req.(*wrapperspb.StringValue))
}
return interceptor(ctx, in, info, handler)
}
func _Bridge_IsTLSCertificateInstalled_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(emptypb.Empty)
if err := dec(in); err != nil {
@ -2465,18 +2364,6 @@ var Bridge_ServiceDesc = grpc.ServiceDesc{
MethodName: "ConfigureUserAppleMail",
Handler: _Bridge_ConfigureUserAppleMail_Handler,
},
{
MethodName: "ReportBugClicked",
Handler: _Bridge_ReportBugClicked_Handler,
},
{
MethodName: "AutoconfigClicked",
Handler: _Bridge_AutoconfigClicked_Handler,
},
{
MethodName: "ExternalLinkClicked",
Handler: _Bridge_ExternalLinkClicked_Handler,
},
{
MethodName: "IsTLSCertificateInstalled",
Handler: _Bridge_IsTLSCertificateInstalled_Handler,

View File

@ -465,7 +465,7 @@ func (s *Service) finishLogin() {
if apiErr := new(proton.APIError); errors.As(err, &apiErr) && apiErr.Code == proton.HumanValidationInvalidToken {
s.hvDetails = nil
_ = s.SendEvent(NewLoginError(LoginErrorType_HV_ERROR, err.Error()))
_ = s.SendEvent(NewLoginError(LoginErrorType_HV_ERROR, hv.VerificationFailedErrorMsg))
return
}
@ -643,7 +643,10 @@ func (s *Service) monitorParentPID() {
func (s *Service) handleHvRequest(err error) {
hvDet, hvErr := hv.VerifyAndExtractHvRequest(err)
if hvErr != nil {
_ = s.SendEvent(NewLoginError(LoginErrorType_HV_ERROR, hvErr.Error()))
_ = s.SendEvent(NewLoginError(LoginErrorType_HV_ERROR, hv.ExtractionErrorMsg))
s.bridge.ReportMessageWithContext("Unable to extract HV request details", map[string]any{
"error": err.Error(),
})
return
}

View File

@ -30,6 +30,7 @@ import (
"github.com/ProtonMail/proton-bridge/v3/internal/constants"
"github.com/ProtonMail/proton-bridge/v3/internal/events"
"github.com/ProtonMail/proton-bridge/v3/internal/frontend/theme"
"github.com/ProtonMail/proton-bridge/v3/internal/hv"
"github.com/ProtonMail/proton-bridge/v3/internal/kb"
"github.com/ProtonMail/proton-bridge/v3/internal/safe"
"github.com/ProtonMail/proton-bridge/v3/internal/service"
@ -468,7 +469,7 @@ func (s *Service) Login(_ context.Context, login *LoginRequest) (*emptypb.Empty,
case proton.HumanValidationInvalidToken:
s.hvDetails = nil
_ = s.SendEvent(NewLoginError(LoginErrorType_HV_ERROR, err.Error()))
_ = s.SendEvent(NewLoginError(LoginErrorType_HV_ERROR, hv.VerificationFailedErrorMsg))
default:
_ = s.SendEvent(NewLoginError(LoginErrorType_USERNAME_PASSWORD_ERROR, err.Error()))

View File

@ -1,44 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package grpc
import (
"context"
"github.com/ProtonMail/gluon/async"
"google.golang.org/protobuf/types/known/emptypb"
"google.golang.org/protobuf/types/known/wrapperspb"
)
func (s *Service) ReportBugClicked(context.Context, *emptypb.Empty) (*emptypb.Empty, error) {
defer async.HandlePanic(s.panicHandler)
s.bridge.ReportBugClicked()
return &emptypb.Empty{}, nil
}
func (s *Service) AutoconfigClicked(_ context.Context, client *wrapperspb.StringValue) (*emptypb.Empty, error) {
defer async.HandlePanic(s.panicHandler)
s.bridge.AutoconfigUsed(client.Value)
return &emptypb.Empty{}, nil
}
func (s *Service) ExternalLinkClicked(_ context.Context, article *wrapperspb.StringValue) (*emptypb.Empty, error) {
defer async.HandlePanic(s.panicHandler)
s.bridge.ExternalLinkClicked(article.Value)
return &emptypb.Empty{}, nil
}

View File

@ -21,6 +21,11 @@ import (
"github.com/ProtonMail/go-proton-api"
)
const (
ExtractionErrorMsg = "Human verification requested, but an issue occurred. Please try again."
VerificationFailedErrorMsg = "Human verification failed. Please try again."
)
// VerifyAndExtractHvRequest expects an error request as input
// determines whether the given error is a Proton human verification request; if it isn't then it returns -> nil, nil (no details, no error)
// if it is a HV req. then it tries to parse the json data and verify that the captcha method is included; if either fails -> nil, err
@ -34,7 +39,7 @@ func VerifyAndExtractHvRequest(err error) (*proton.APIHVDetails, error) {
if errors.As(err, &protonErr) && protonErr.IsHVError() {
hvDetails, hvErr := protonErr.GetHVDetails()
if hvErr != nil {
return nil, fmt.Errorf("received HV request, but can't decode HV details")
return nil, hvErr
}
return hvDetails, nil
}

View File

@ -188,16 +188,6 @@ func (l *Locations) ProvideUpdatesPath() (string, error) {
return l.getUpdatesPath(), nil
}
// ProvideStatsPath returns a location for statistics files (e.g. ~/.local/share/<company>/<app>/stats).
// It creates it if it doesn't already exist.
func (l *Locations) ProvideStatsPath() (string, error) {
if err := os.MkdirAll(l.getStatsPath(), 0o700); err != nil {
return "", err
}
return l.getStatsPath(), nil
}
func (l *Locations) ProvideIMAPSyncConfigPath() (string, error) {
if err := os.MkdirAll(l.getIMAPSyncConfigPath(), 0o700); err != nil {
return "", err
@ -252,10 +242,6 @@ func (l *Locations) getNotificationsCachePath() string {
return filepath.Join(l.userCache, "notifications")
}
func (l *Locations) getStatsPath() string {
return filepath.Join(l.userData, "stats")
}
func (l *Locations) getUnleashCachePath() string { return filepath.Join(l.userCache, "unleash_cache") }
// Clear removes everything except the lock and update files.

View File

@ -31,8 +31,8 @@ type CoolDownProvider interface {
Reset()
}
func jitter(max int) time.Duration { //nolint:predeclared
return time.Duration(rand.Intn(max)) * time.Second //nolint:gosec
func jitter(maxValue int) time.Duration {
return time.Duration(rand.Intn(maxValue)) * time.Second //nolint:gosec
}
type ExpCoolDown struct {

87
internal/plan/plan.go Normal file
View File

@ -0,0 +1,87 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package plan
import "strings"
const (
Unknown = "unknown"
Other = "other"
Business = "business"
Individual = "individual"
Group = "group"
)
var planHierarchy = map[string]int{ //nolint:gochecknoglobals
Business: 4,
Group: 3,
Individual: 2,
Other: 1,
Unknown: 0,
}
func IsHigherPriority(currentPlan, newPlan string) bool {
newRank, ok := planHierarchy[newPlan]
if !ok {
return false
}
currentRank, ok2 := planHierarchy[currentPlan]
if !ok2 {
return true // we don't have a valid plan, might as well replace it
}
return newRank > currentRank
}
func MapUserPlan(planName string) string {
if planName == "" {
return Unknown
}
switch strings.TrimSpace(strings.ToLower(planName)) {
case Individual:
return Individual
case Unknown:
return Unknown
case Business:
return Business
case Group:
return Group
case "mail2022":
return Individual
case "bundle2022":
return Individual
case "family2022":
return Group
case "visionary2022":
return Group
case "mailpro2022":
return Business
case "planbiz2024":
return Business
case "bundlepro2022":
return Business
case "bundlepro2024":
return Business
case "duo2024":
return Group
default:
return Other
}
}

View File

@ -56,7 +56,6 @@ type Connector struct {
identityState sharedIdentity
client APIClient
telemetry Telemetry
reporter reporter.Reporter
panicHandler async.PanicHandler
sendRecorder *sendrecorder.SendRecorder
@ -80,7 +79,6 @@ func NewConnector(
addressMode usertypes.AddressMode,
sendRecorder *sendrecorder.SendRecorder,
panicHandler async.PanicHandler,
telemetry Telemetry,
reporter reporter.Reporter,
showAllMail bool,
syncState *SyncState,
@ -96,7 +94,6 @@ func NewConnector(
attrs: defaultMailboxAttributes(),
client: apiClient,
telemetry: telemetry,
reporter: reporter,
panicHandler: panicHandler,
sendRecorder: sendRecorder,
@ -169,10 +166,9 @@ func (s *Connector) Init(ctx context.Context, cache connector.IMAPState) error {
})
}
func (s *Connector) Authorize(ctx context.Context, username string, password []byte) bool {
func (s *Connector) Authorize(_ context.Context, username string, password []byte) bool {
addrID, err := s.identityState.CheckAuth(username, password)
if err != nil {
s.telemetry.ReportConfigStatusFailure("IMAP " + err.Error())
return false
}
@ -180,8 +176,6 @@ func (s *Connector) Authorize(ctx context.Context, username string, password []b
return false
}
s.telemetry.SendConfigStatusSuccess(ctx)
return true
}

View File

@ -47,12 +47,6 @@ type EventProvider interface {
RewindEventID(ctx context.Context, eventID string) error
}
type Telemetry interface {
useridentity.Telemetry
SendConfigStatusSuccess(ctx context.Context)
ReportConfigStatusFailure(errDetails string)
}
type GluonIDProvider interface {
GetGluonID(addrID string) (string, bool)
GetGluonIDs() map[string]string
@ -77,7 +71,6 @@ type Service struct {
serverManager IMAPServerManager
eventPublisher events.EventPublisher
telemetry Telemetry
panicHandler async.PanicHandler
sendRecorder *sendrecorder.SendRecorder
reporter reporter.Reporter
@ -112,7 +105,6 @@ func NewService(
keyPassProvider useridentity.KeyPassProvider,
panicHandler async.PanicHandler,
sendRecorder *sendrecorder.SendRecorder,
telemetry Telemetry,
reporter reporter.Reporter,
addressMode usertypes.AddressMode,
subscription events.Subscription,
@ -150,7 +142,6 @@ func NewService(
panicHandler: panicHandler,
sendRecorder: sendRecorder,
telemetry: telemetry,
reporter: reporter,
connectors: make(map[string]*Connector),
@ -242,6 +233,12 @@ func (s *Service) OnLogout(ctx context.Context) error {
return err
}
func (s *Service) OnDelete(ctx context.Context) error {
_, err := s.cpc.Send(ctx, &onDeleteReq{})
return err
}
func (s *Service) ShowAllMail(ctx context.Context, v bool) error {
_, err := s.cpc.Send(ctx, &showAllMailReq{v: v})
@ -371,6 +368,11 @@ func (s *Service) run(ctx context.Context) { //nolint gocyclo
err := s.removeConnectorsFromServer(ctx, s.connectors, false)
req.Reply(ctx, nil, err)
case *onDeleteReq:
s.log.Debug("Delete Request")
err := s.removeConnectorsFromServer(ctx, s.connectors, true)
req.Reply(ctx, nil, err)
case *showAllMailReq:
s.log.Debug("Show all mail request")
req.Reply(ctx, nil, nil)
@ -513,7 +515,6 @@ func (s *Service) buildConnectors() (map[string]*Connector, error) {
s.addressMode,
s.sendRecorder,
s.panicHandler,
s.telemetry,
s.reporter,
s.showAllMail,
s.syncStateProvider,
@ -531,7 +532,6 @@ func (s *Service) buildConnectors() (map[string]*Connector, error) {
s.addressMode,
s.sendRecorder,
s.panicHandler,
s.telemetry,
s.reporter,
s.showAllMail,
s.syncStateProvider,
@ -655,6 +655,8 @@ type onLogoutReq struct{}
type showAllMailReq struct{ v bool }
type onDeleteReq struct{}
type setAddressModeReq struct {
mode usertypes.AddressMode
}

View File

@ -154,7 +154,6 @@ func addNewAddressSplitMode(ctx context.Context, s *Service, addrID string) erro
s.addressMode,
s.sendRecorder,
s.panicHandler,
s.telemetry,
s.reporter,
s.showAllMail,
s.syncStateProvider,

View File

@ -65,6 +65,22 @@ func (s syncMessageEventHandler) HandleMessageEvents(ctx context.Context, events
return err
}
case proton.EventUpdate:
if event.Message.IsDraft() || (event.Message.Flags&proton.MessageFlagSent != 0) {
updates, err := onMessageUpdateDraftOrSent(
logging.WithLogrusField(ctx, "action", "update draft or sent message (sync)"),
s.service,
event,
)
if err != nil {
return fmt.Errorf("failed to handle update draft event (sync): %w", err)
}
if err := waitOnIMAPUpdates(ctx, updates); err != nil {
return err
}
}
case proton.EventDelete:
updates := onMessageDeleted(
logging.WithLogrusField(ctx, "action", "delete message (sync)"),

View File

@ -49,6 +49,7 @@ type IMAPSettingsProvider interface {
Port() int
SetPort(int) error
UseSSL() bool
DisableIMAPAuthenticate() bool
CacheDirectory() string
DataDirectory() (string, error)
SetCacheDirectory(string) error
@ -74,6 +75,7 @@ func newIMAPServer(
tlsConfig *tls.Config,
reporter reporter.Reporter,
logClient, logServer bool,
disableIMAPAuthenticate bool,
eventPublisher IMAPEventPublisher,
tasks *async.Group,
uidValidityGenerator imap.UIDValidityGenerator,
@ -113,7 +115,7 @@ func newIMAPServer(
imapServerLog = io.Discard
}
imapServer, err := gluon.New(
options := []gluon.Option{
gluon.WithTLS(tlsConfig),
gluon.WithDataDir(gluonCacheDir),
gluon.WithDatabaseDir(gluonConfigDir),
@ -124,7 +126,13 @@ func newIMAPServer(
gluon.WithUIDValidityGenerator(uidValidityGenerator),
gluon.WithPanicHandler(panicHandler),
gluon.WithObservabilitySender(observability.NewAdapter(observabilitySender), int(observability.GluonImapError), int(observability.GluonMessageError), int(observability.GluonOtherError)),
)
}
if disableIMAPAuthenticate {
options = append(options, gluon.WithDisableIMAPAuthenticate())
}
imapServer, err := gluon.New(options...)
if err != nil {
return nil, err
}

View File

@ -451,6 +451,7 @@ func (sm *Service) createIMAPServer(ctx context.Context) (*gluon.Server, error)
sm.reporter,
sm.imapSettings.LogClient(),
sm.imapSettings.LogServer(),
sm.imapSettings.DisableIMAPAuthenticate(),
sm.imapSettings.EventPublisher(),
sm.tasks,
sm.uidValidityGenerator,

View File

@ -50,7 +50,6 @@ type Service struct {
}
const bitfieldRegexPattern = `^\\\d+`
const disableNotificationsKillSwitch = "InboxBridgeEventLoopNotificationDisabled"
func NewService(userID string, service userevents.Subscribable, eventPublisher events.EventPublisher, store *Store,
getFlagFn unleash.GetFlagValueFn, observabilitySender observability.Sender) *Service {
@ -103,7 +102,7 @@ func (s *Service) run(ctx context.Context) {
}
func (s *Service) HandleNotificationEvents(ctx context.Context, notificationEvents []proton.NotificationEvent) error {
if s.getFlagValueFn(disableNotificationsKillSwitch) {
if s.getFlagValueFn(unleash.EventLoopNotificationDisabled) {
s.log.Info("Received notification events. Skipping as kill switch is enabled.")
return nil
}

View File

@ -24,6 +24,7 @@ import (
"github.com/ProtonMail/gluon/async"
"github.com/ProtonMail/go-proton-api"
"github.com/ProtonMail/proton-bridge/v3/internal/plan"
"github.com/ProtonMail/proton-bridge/v3/internal/updater"
)
@ -62,7 +63,7 @@ func newDistinctionUtility(ctx context.Context, panicHandler async.PanicHandler,
observabilitySender: observabilitySender,
userPlanUnsafe: planUnknown,
userPlanUnsafe: plan.Unknown,
heartbeatData: heartbeatData{},
heartbeatTicker: time.NewTicker(updateInterval),

View File

@ -18,7 +18,7 @@
package observability
import (
"fmt"
"strconv"
"time"
"github.com/ProtonMail/gluon/async"
@ -87,10 +87,6 @@ func (d *distinctionUtility) sendHeartbeat() {
})
}
func formatBool(value bool) string {
return fmt.Sprintf("%t", value)
}
// generateHeartbeatUserMetric creates the heartbeat user metric and includes the relevant data.
func (d *distinctionUtility) generateHeartbeatUserMetric() proton.ObservabilityMetric {
return generateHeartbeatMetric(
@ -98,10 +94,10 @@ func (d *distinctionUtility) generateHeartbeatUserMetric() proton.ObservabilityM
d.getEmailClientUserAgent(),
getEnabled(d.settingsGetter.GetProxyAllowed()),
getEnabled(d.getBetaAccessEnabled()),
formatBool(d.heartbeatData.receivedOtherError),
formatBool(d.heartbeatData.receivedSyncError),
formatBool(d.heartbeatData.receivedEventLoopError),
formatBool(d.heartbeatData.receivedGluonError),
strconv.FormatBool(d.heartbeatData.receivedOtherError),
strconv.FormatBool(d.heartbeatData.receivedSyncError),
strconv.FormatBool(d.heartbeatData.receivedEventLoopError),
strconv.FormatBool(d.heartbeatData.receivedGluonError),
)
}

View File

@ -18,76 +18,9 @@
package observability
import (
"context"
"strings"
"github.com/ProtonMail/gluon/async"
"github.com/ProtonMail/go-proton-api"
"github.com/ProtonMail/proton-bridge/v3/internal/plan"
)
const (
planUnknown = "unknown"
planOther = "other"
planBusiness = "business"
planIndividual = "individual"
planGroup = "group"
)
var planHierarchy = map[string]int{ //nolint:gochecknoglobals
planBusiness: 4,
planGroup: 3,
planIndividual: 2,
planOther: 1,
planUnknown: 0,
}
type planGetter interface {
GetOrganizationData(ctx context.Context) (proton.OrganizationResponse, error)
}
func isHigherPriority(currentPlan, newPlan string) bool {
newRank, ok := planHierarchy[newPlan]
if !ok {
return false
}
currentRank, ok2 := planHierarchy[currentPlan]
if !ok2 {
return true // we don't have a valid plan, might as well replace it
}
return newRank > currentRank
}
func mapUserPlan(planName string) string {
if planName == "" {
return planUnknown
}
switch strings.TrimSpace(strings.ToLower(planName)) {
case "mail2022":
return planIndividual
case "bundle2022":
return planIndividual
case "family2022":
return planGroup
case "visionary2022":
return planGroup
case "mailpro2022":
return planBusiness
case "planbiz2024":
return planBusiness
case "bundlepro2022":
return planBusiness
case "bundlepro2024":
return planBusiness
case "duo2024":
return planGroup
default:
return planOther
}
}
func (d *distinctionUtility) setUserPlan(planName string) {
if planName == "" {
return
@ -96,24 +29,12 @@ func (d *distinctionUtility) setUserPlan(planName string) {
d.userPlanLock.Lock()
defer d.userPlanLock.Unlock()
userPlanMapped := mapUserPlan(planName)
if isHigherPriority(d.userPlanUnsafe, userPlanMapped) {
userPlanMapped := plan.MapUserPlan(planName)
if plan.IsHigherPriority(d.userPlanUnsafe, userPlanMapped) {
d.userPlanUnsafe = userPlanMapped
}
}
func (d *distinctionUtility) registerUserPlan(ctx context.Context, getter planGetter, panicHandler async.PanicHandler) {
go func() {
defer async.HandlePanic(panicHandler)
orgRes, err := getter.GetOrganizationData(ctx)
if err != nil {
return
}
d.setUserPlan(orgRes.Organization.PlanName)
}()
}
func (d *distinctionUtility) getUserPlanSafe() string {
d.userPlanLock.Lock()
defer d.userPlanLock.Unlock()

View File

@ -250,7 +250,7 @@ func (s *Service) addMetricsIfClients(metric ...proton.ObservabilityMetric) {
s.addMetrics(metric...)
}
func (s *Service) RegisterUserClient(userID string, protonClient *proton.Client, telemetryService *telemetry.Service) {
func (s *Service) RegisterUserClient(userID string, protonClient *proton.Client, telemetryService *telemetry.Service, userPlan string) {
s.log.Info("Registering user client, ID:", userID)
s.withUserClientStoreLock(func() {
@ -260,7 +260,7 @@ func (s *Service) RegisterUserClient(userID string, protonClient *proton.Client,
}
})
s.distinctionUtility.registerUserPlan(s.ctx, protonClient, s.panicHandler)
s.distinctionUtility.setUserPlan(userPlan)
// There may be a case where we already have metric updates stored, so try to flush;
s.sendSignal(s.signalDataArrived)

View File

@ -20,15 +20,16 @@ package observability
import (
gluonMetrics "github.com/ProtonMail/gluon/observability/metrics"
"github.com/ProtonMail/go-proton-api"
"github.com/ProtonMail/proton-bridge/v3/internal/plan"
)
func GenerateAllUsedDistinctionMetricPermutations() []proton.ObservabilityMetric {
planValues := []string{
planUnknown,
planOther,
planBusiness,
planIndividual,
planGroup}
plan.Unknown,
plan.Other,
plan.Business,
plan.Individual,
plan.Group}
mailClientValues := []string{
emailAgentAppleMail,
emailAgentOutlook,
@ -58,11 +59,11 @@ func GenerateAllUsedDistinctionMetricPermutations() []proton.ObservabilityMetric
func GenerateAllHeartbeatMetricPermutations() []proton.ObservabilityMetric {
planValues := []string{
planUnknown,
planOther,
planBusiness,
planIndividual,
planGroup}
plan.Unknown,
plan.Other,
plan.Business,
plan.Individual,
plan.Group}
mailClientValues := []string{
emailAgentAppleMail,
emailAgentOutlook,

View File

@ -104,8 +104,3 @@ func TestMatchUserAgent(t *testing.T) {
require.Equal(t, testCase.result, matchUserAgent(testCase.agent))
}
}
func TestFormatBool(t *testing.T) {
require.Equal(t, "false", formatBool(false))
require.Equal(t, "true", formatBool(true))
}

View File

@ -66,14 +66,9 @@ func (s *Accounts) CheckAuth(user string, password []byte) (string, string, erro
continue
}
account.service.telemetry.ReportSMTPAuthSuccess(context.Background())
return id, addrID, nil
}
for _, service := range s.accounts {
service.service.telemetry.ReportSMTPAuthFailed(user)
}
return "", "", ErrNoSuchUser
}

View File

@ -39,12 +39,6 @@ import (
"github.com/sirupsen/logrus"
)
type Telemetry interface {
useridentity.Telemetry
ReportSMTPAuthSuccess(context.Context)
ReportSMTPAuthFailed(username string)
}
type Service struct {
userID string
panicHandler async.PanicHandler
@ -57,7 +51,6 @@ type Service struct {
bridgePassProvider useridentity.BridgePassProvider
keyPassProvider useridentity.KeyPassProvider
identityState *useridentity.State
telemetry Telemetry
eventService userevents.Subscribable
subscription *userevents.EventChanneledSubscriber
@ -76,7 +69,6 @@ func NewService(
reporter reporter.Reporter,
bridgePassProvider useridentity.BridgePassProvider,
keyPassProvider useridentity.KeyPassProvider,
telemetry Telemetry,
eventService userevents.Subscribable,
mode usertypes.AddressMode,
identityState *useridentity.State,
@ -99,7 +91,6 @@ func NewService(
bridgePassProvider: bridgePassProvider,
keyPassProvider: keyPassProvider,
telemetry: telemetry,
identityState: identityState,
eventService: eventService,

View File

@ -231,7 +231,7 @@ func downloadAttachment(ctx context.Context, cache *DownloadCache, client APICli
}
type DownloadRateModifier interface {
Apply(wasSuccess bool, current int, max int) int //nolint:predeclared
Apply(wasSuccess bool, currentValue int, maxValue int) int
}
func autoDownloadRate[T any, R any](
@ -285,14 +285,14 @@ func autoDownloadRate[T any, R any](
type DefaultDownloadRateModifier struct{}
func (d DefaultDownloadRateModifier) Apply(wasSuccess bool, current int, max int) int { //nolint:predeclared
func (d DefaultDownloadRateModifier) Apply(wasSuccess bool, currentValue int, maxValue int) int {
if !wasSuccess {
return 2
}
parallelTasks := current * 2
if parallelTasks > max {
parallelTasks = max
parallelTasks := currentValue * 2
if parallelTasks > maxValue {
parallelTasks = maxValue
}
return parallelTasks

View File

@ -64,38 +64,3 @@ func (mr *MockIdentityProviderMockRecorder) GetUser(arg0 interface{}) *gomock.Ca
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUser", reflect.TypeOf((*MockIdentityProvider)(nil).GetUser), arg0)
}
// MockTelemetry is a mock of Telemetry interface.
type MockTelemetry struct {
ctrl *gomock.Controller
recorder *MockTelemetryMockRecorder
}
// MockTelemetryMockRecorder is the mock recorder for MockTelemetry.
type MockTelemetryMockRecorder struct {
mock *MockTelemetry
}
// NewMockTelemetry creates a new mock instance.
func NewMockTelemetry(ctrl *gomock.Controller) *MockTelemetry {
mock := &MockTelemetry{ctrl: ctrl}
mock.recorder = &MockTelemetryMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockTelemetry) EXPECT() *MockTelemetryMockRecorder {
return m.recorder
}
// ReportConfigStatusFailure mocks base method.
func (m *MockTelemetry) ReportConfigStatusFailure(arg0 string) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "ReportConfigStatusFailure", arg0)
}
// ReportConfigStatusFailure indicates an expected call of ReportConfigStatusFailure.
func (mr *MockTelemetryMockRecorder) ReportConfigStatusFailure(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReportConfigStatusFailure", reflect.TypeOf((*MockTelemetry)(nil).ReportConfigStatusFailure), arg0)
}

View File

@ -50,7 +50,6 @@ type Service struct {
subscription *userevents.EventChanneledSubscriber
bridgePassProvider BridgePassProvider
telemetry Telemetry
}
func NewService(
@ -58,7 +57,6 @@ func NewService(
eventPublisher events.EventPublisher,
state *State,
bridgePassProvider BridgePassProvider,
telemetry Telemetry,
) *Service {
subscriberName := fmt.Sprintf("identity-%v", state.User.ID)
@ -73,7 +71,6 @@ func NewService(
}),
subscription: userevents.NewEventSubscriber(subscriberName),
bridgePassProvider: bridgePassProvider,
telemetry: telemetry,
}
}

View File

@ -361,10 +361,9 @@ func newTestService(_ *testing.T, mockCtrl *gomock.Controller) (*Service, *mocks
eventPublisher := mocks2.NewMockEventPublisher(mockCtrl)
provider := mocks.NewMockIdentityProvider(mockCtrl)
user := newTestUser()
telemetry := mocks.NewMockTelemetry(mockCtrl)
bridgePassProvider := NewFixedBridgePassProvider([]byte("hello"))
service := NewService(subscribable, eventPublisher, NewState(*user, newTestAddresses(), provider), bridgePassProvider, telemetry)
service := NewService(subscribable, eventPublisher, NewState(*user, newTestAddresses(), provider), bridgePassProvider)
return service, eventPublisher, provider
}

View File

@ -1,22 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package useridentity
type Telemetry interface {
ReportConfigStatusFailure(errDetails string)
}

View File

@ -19,9 +19,12 @@ package telemetry
import (
"context"
"math"
"strconv"
"strings"
"time"
"github.com/ProtonMail/proton-bridge/v3/internal/plan"
"github.com/ProtonMail/proton-bridge/v3/internal/updater"
"github.com/sirupsen/logrus"
)
@ -31,71 +34,67 @@ func NewHeartbeat(manager HeartbeatManager, imapPort, smtpPort int, cacheDir, ke
log: logrus.WithField("pkg", "telemetry"),
manager: manager,
metrics: HeartbeatData{
MeasurementGroup: "bridge.any.usage",
Event: "bridge_heartbeat",
MeasurementGroup: "bridge.any.heartbeat",
Event: "bridge_heartbeat_new",
Dimensions: NewHeartbeatDimensions(),
},
defaultIMAPPort: imapPort,
defaultSMTPPort: smtpPort,
defaultCache: cacheDir,
defaultKeychain: keychain,
defaultUserPlan: plan.Unknown,
}
return heartbeat
}
func (heartbeat *Heartbeat) SetRollout(val float64) {
heartbeat.metrics.Dimensions.Rollout = strconv.Itoa(int(val * 100))
heartbeat.metrics.Values.Rollout = int(math.Floor(val * 10))
}
func (heartbeat *Heartbeat) SetNbAccount(val int) {
heartbeat.metrics.Values.NbAccount = val
func (heartbeat *Heartbeat) GetRollout() int {
return heartbeat.metrics.Values.Rollout
}
func (heartbeat *Heartbeat) SetNumberConnectedAccounts(val int) {
heartbeat.metrics.Values.NumberConnectedAccounts = val
}
func (heartbeat *Heartbeat) SetAutoUpdate(val bool) {
if val {
heartbeat.metrics.Dimensions.AutoUpdate = dimensionON
} else {
heartbeat.metrics.Dimensions.AutoUpdate = dimensionOFF
}
heartbeat.metrics.Dimensions.AutoUpdateEnabled = strconv.FormatBool(val)
}
func (heartbeat *Heartbeat) SetAutoStart(val bool) {
if val {
heartbeat.metrics.Dimensions.AutoStart = dimensionON
} else {
heartbeat.metrics.Dimensions.AutoStart = dimensionOFF
}
heartbeat.metrics.Dimensions.AutoStartEnabled = strconv.FormatBool(val)
}
func (heartbeat *Heartbeat) SetBeta(val updater.Channel) {
if val == updater.EarlyChannel {
heartbeat.metrics.Dimensions.Beta = dimensionON
} else {
heartbeat.metrics.Dimensions.Beta = dimensionOFF
}
heartbeat.metrics.Dimensions.BetaEnabled = strconv.FormatBool(val == updater.EarlyChannel)
}
func (heartbeat *Heartbeat) SetDoh(val bool) {
if val {
heartbeat.metrics.Dimensions.Doh = dimensionON
} else {
heartbeat.metrics.Dimensions.Doh = dimensionOFF
}
heartbeat.metrics.Dimensions.DohEnabled = strconv.FormatBool(val)
}
func (heartbeat *Heartbeat) SetSplitMode(val bool) {
if val {
heartbeat.metrics.Dimensions.SplitMode = dimensionON
} else {
heartbeat.metrics.Dimensions.SplitMode = dimensionOFF
heartbeat.metrics.Dimensions.UseSplitMode = strconv.FormatBool(val)
}
func (heartbeat *Heartbeat) SetUserPlan(val string) {
mappedUserPlan := plan.MapUserPlan(val)
if plan.IsHigherPriority(heartbeat.metrics.Dimensions.UserPlanGroup, mappedUserPlan) {
heartbeat.metrics.Dimensions.UserPlanGroup = val
}
}
func (heartbeat *Heartbeat) SetContactedByAppleNotes(uaName string) {
uaNameLowered := strings.ToLower(uaName)
if strings.Contains(uaNameLowered, "mac") && strings.Contains(uaNameLowered, "notes") {
heartbeat.metrics.Dimensions.ContactedByAppleNotes = strconv.FormatBool(true)
}
}
func (heartbeat *Heartbeat) SetShowAllMail(val bool) {
if val {
heartbeat.metrics.Dimensions.ShowAllMail = dimensionON
} else {
heartbeat.metrics.Dimensions.ShowAllMail = dimensionOFF
}
heartbeat.metrics.Dimensions.ShowAllMail = strconv.FormatBool(val)
}
func (heartbeat *Heartbeat) SetIMAPConnectionMode(val bool) {
@ -115,35 +114,19 @@ func (heartbeat *Heartbeat) SetSMTPConnectionMode(val bool) {
}
func (heartbeat *Heartbeat) SetIMAPPort(val int) {
if val == heartbeat.defaultIMAPPort {
heartbeat.metrics.Dimensions.IMAPPort = dimensionDefault
} else {
heartbeat.metrics.Dimensions.IMAPPort = dimensionCustom
}
heartbeat.metrics.Dimensions.UseDefaultIMAPPort = strconv.FormatBool(val == heartbeat.defaultIMAPPort)
}
func (heartbeat *Heartbeat) SetSMTPPort(val int) {
if val == heartbeat.defaultSMTPPort {
heartbeat.metrics.Dimensions.SMTPPort = dimensionDefault
} else {
heartbeat.metrics.Dimensions.SMTPPort = dimensionCustom
}
heartbeat.metrics.Dimensions.UseDefaultSMTPPort = strconv.FormatBool(val == heartbeat.defaultSMTPPort)
}
func (heartbeat *Heartbeat) SetCacheLocation(val string) {
if val == heartbeat.defaultCache {
heartbeat.metrics.Dimensions.CacheLocation = dimensionDefault
} else {
heartbeat.metrics.Dimensions.CacheLocation = dimensionCustom
}
heartbeat.metrics.Dimensions.UseDefaultCacheLocation = strconv.FormatBool(val == heartbeat.defaultCache)
}
func (heartbeat *Heartbeat) SetKeyChainPref(val string) {
if val == heartbeat.defaultKeychain {
heartbeat.metrics.Dimensions.KeychainPref = dimensionDefault
} else {
heartbeat.metrics.Dimensions.KeychainPref = dimensionCustom
}
heartbeat.metrics.Dimensions.UseDefaultKeychain = strconv.FormatBool(val == heartbeat.defaultKeychain)
}
func (heartbeat *Heartbeat) SetPrevVersion(val string) {

View File

@ -22,34 +22,38 @@ import (
"testing"
"time"
"github.com/ProtonMail/proton-bridge/v3/internal/plan"
"github.com/ProtonMail/proton-bridge/v3/internal/telemetry"
"github.com/ProtonMail/proton-bridge/v3/internal/telemetry/mocks"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
func TestHeartbeat_default_heartbeat(t *testing.T) {
withHeartbeat(t, 1143, 1025, "/tmp", "defaultKeychain", func(hb *telemetry.Heartbeat, mock *mocks.MockHeartbeatManager) {
data := telemetry.HeartbeatData{
MeasurementGroup: "bridge.any.usage",
Event: "bridge_heartbeat",
MeasurementGroup: "bridge.any.heartbeat",
Event: "bridge_heartbeat_new",
Values: telemetry.HeartbeatValues{
NbAccount: 1,
NumberConnectedAccounts: 1,
Rollout: 1,
},
Dimensions: telemetry.HeartbeatDimensions{
AutoUpdate: "on",
AutoStart: "on",
Beta: "off",
Doh: "off",
SplitMode: "off",
ShowAllMail: "off",
IMAPConnectionMode: "ssl",
SMTPConnectionMode: "ssl",
IMAPPort: "default",
SMTPPort: "default",
CacheLocation: "default",
KeychainPref: "default",
PrevVersion: "1.2.3",
Rollout: "10",
AutoUpdateEnabled: "true",
AutoStartEnabled: "true",
BetaEnabled: "false",
DohEnabled: "false",
UseSplitMode: "false",
ShowAllMail: "false",
UseDefaultIMAPPort: "true",
UseDefaultSMTPPort: "true",
UseDefaultCacheLocation: "true",
UseDefaultKeychain: "true",
ContactedByAppleNotes: "false",
PrevVersion: "1.2.3",
IMAPConnectionMode: "ssl",
SMTPConnectionMode: "ssl",
UserPlanGroup: plan.Unknown,
},
}
@ -81,7 +85,7 @@ func withHeartbeat(t *testing.T, imap, smtp int, cache, keychain string, tests f
heartbeat := telemetry.NewHeartbeat(manager, imap, smtp, cache, keychain)
heartbeat.SetRollout(0.1)
heartbeat.SetNbAccount(1)
heartbeat.SetNumberConnectedAccounts(1)
heartbeat.SetSplitMode(false)
heartbeat.SetAutoStart(true)
heartbeat.SetAutoUpdate(true)
@ -98,3 +102,29 @@ func withHeartbeat(t *testing.T, imap, smtp int, cache, keychain string, tests f
tests(&heartbeat, manager)
}
func Test_setRollout(t *testing.T) {
hb := telemetry.Heartbeat{}
type testStruct struct {
val float64
res int
}
tests := []testStruct{
{0.02, 0},
{0.04, 0},
{0.09999, 0},
{0.1, 1},
{0.132323, 1},
{0.2, 2},
{0.25, 2},
{0.7111, 7},
{0.93, 9},
{0.999, 9},
}
for _, test := range tests {
hb.SetRollout(test.val)
require.Equal(t, test.res, hb.GetRollout())
}
}

View File

@ -21,14 +21,11 @@ import (
"context"
"time"
"github.com/ProtonMail/proton-bridge/v3/internal/plan"
"github.com/sirupsen/logrus"
)
const (
dimensionON = "on"
dimensionOFF = "off"
dimensionDefault = "default"
dimensionCustom = "custom"
dimensionSSL = "ssl"
dimensionStartTLS = "starttls"
)
@ -46,24 +43,29 @@ type HeartbeatManager interface {
}
type HeartbeatValues struct {
NbAccount int `json:"nb_account"`
NumberConnectedAccounts int `json:"numberConnectedAccounts"`
Rollout int `json:"rolloutPercentage"`
}
type HeartbeatDimensions struct {
AutoUpdate string `json:"auto_update"`
AutoStart string `json:"auto_start"`
Beta string `json:"beta"`
Doh string `json:"doh"`
SplitMode string `json:"split_mode"`
ShowAllMail string `json:"show_all_mail"`
IMAPConnectionMode string `json:"imap_connection_mode"`
SMTPConnectionMode string `json:"smtp_connection_mode"`
IMAPPort string `json:"imap_port"`
SMTPPort string `json:"smtp_port"`
CacheLocation string `json:"cache_location"`
KeychainPref string `json:"keychain_pref"`
PrevVersion string `json:"prev_version"`
Rollout string `json:"rollout"`
// Fields below correspond to bool
AutoUpdateEnabled string `json:"isAutoUpdateEnabled"`
AutoStartEnabled string `json:"isAutoStartEnabled"`
BetaEnabled string `json:"isBetaEnabled"`
DohEnabled string `json:"isDohEnabled"`
UseSplitMode string `json:"usesSplitMode"`
ShowAllMail string `json:"useAllMail"`
UseDefaultIMAPPort string `json:"useDefaultImapPort"`
UseDefaultSMTPPort string `json:"useDefaultSmtpPort"`
UseDefaultCacheLocation string `json:"useDefaultCacheLocation"`
UseDefaultKeychain string `json:"useDefaultKeychain"`
ContactedByAppleNotes string `json:"isContactedByAppleNotes"`
// Fields below are enums.
PrevVersion string `json:"prevVersion"` // Free text (exception)
IMAPConnectionMode string `json:"imapConnectionMode"`
SMTPConnectionMode string `json:"smtpConnectionMode"`
UserPlanGroup string `json:"bridgePlanGroup"`
}
type HeartbeatData struct {
@ -82,4 +84,26 @@ type Heartbeat struct {
defaultSMTPPort int
defaultCache string
defaultKeychain string
defaultUserPlan string
}
func NewHeartbeatDimensions() HeartbeatDimensions {
return HeartbeatDimensions{
AutoUpdateEnabled: "false",
AutoStartEnabled: "false",
BetaEnabled: "false",
DohEnabled: "false",
UseSplitMode: "false",
ShowAllMail: "false",
UseDefaultIMAPPort: "false",
UseDefaultSMTPPort: "false",
UseDefaultCacheLocation: "false",
UseDefaultKeychain: "false",
ContactedByAppleNotes: "false",
PrevVersion: "unknown",
IMAPConnectionMode: dimensionSSL,
SMTPConnectionMode: dimensionSSL,
UserPlanGroup: plan.Unknown,
}
}

View File

@ -36,6 +36,12 @@ var pollJitter = 2 * time.Minute //nolint:gochecknoglobals
const filename = "unleash_flags"
const (
EventLoopNotificationDisabled = "InboxBridgeEventLoopNotificationDisabled"
IMAPAuthenticateCommandDisabled = "InboxBridgeImapAuthenticateCommandDisabled"
UserRemovalGluonDataCleanupDisabled = "InboxBridgeUserRemovalGluonDataCleanupDisabled"
)
type requestFeaturesFn func(ctx context.Context) (proton.FeatureFlagResult, error)
type GetFlagValueFn func(key string) bool

View File

@ -1,219 +0,0 @@
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package user
import (
"context"
"encoding/json"
"errors"
"github.com/ProtonMail/gluon/reporter"
"github.com/ProtonMail/proton-bridge/v3/internal/configstatus"
"github.com/ProtonMail/proton-bridge/v3/internal/kb"
)
func (user *User) SendConfigStatusSuccess(ctx context.Context) {
if user.configStatus.IsFromFailure() {
user.SendConfigStatusRecovery(ctx)
return
}
if !user.IsTelemetryEnabled(ctx) {
return
}
if !user.configStatus.IsPending() {
return
}
var builder configstatus.ConfigSuccessBuilder
success := builder.New(user.configStatus)
data, err := json.Marshal(success)
if err != nil {
if err := user.reporter.ReportMessageWithContext("Cannot parse config_success data.", reporter.Context{
"error": err,
}); err != nil {
user.log.WithError(err).Error("Failed to report config_success data parsing error.")
}
return
}
if err := user.SendTelemetry(ctx, data); err == nil {
user.log.Info("Configuration Status Success event sent.")
if err := user.configStatus.ApplySuccess(); err != nil {
user.log.WithError(err).Error("Failed to ApplySuccess on config_status.")
}
}
}
func (user *User) SendConfigStatusAbort(ctx context.Context, withTelemetry bool) {
if err := user.configStatus.Remove(); err != nil {
user.log.WithError(err).Error("Failed to remove config_status file.")
}
if !user.configStatus.IsPending() {
return
}
if !withTelemetry || !user.IsTelemetryEnabled(ctx) {
return
}
var builder configstatus.ConfigAbortBuilder
abort := builder.New(user.configStatus)
data, err := json.Marshal(abort)
if err != nil {
if err := user.reporter.ReportMessageWithContext("Cannot parse config_abort data.", reporter.Context{
"error": err,
}); err != nil {
user.log.WithError(err).Error("Failed to report config_abort data parsing error.")
}
return
}
if err := user.SendTelemetry(ctx, data); err == nil {
user.log.Info("Configuration Status Abort event sent.")
}
}
func (user *User) SendConfigStatusRecovery(ctx context.Context) {
if !user.configStatus.IsFromFailure() {
user.SendConfigStatusSuccess(ctx)
return
}
if !user.IsTelemetryEnabled(ctx) {
return
}
if !user.configStatus.IsPending() {
return
}
var builder configstatus.ConfigRecoveryBuilder
success := builder.New(user.configStatus)
data, err := json.Marshal(success)
if err != nil {
if err := user.reporter.ReportMessageWithContext("Cannot parse config_recovery data.", reporter.Context{
"error": err,
}); err != nil {
user.log.WithError(err).Error("Failed to report config_recovery data parsing error.")
}
return
}
if err := user.SendTelemetry(ctx, data); err == nil {
user.log.Info("Configuration Status Recovery event sent.")
if err := user.configStatus.ApplySuccess(); err != nil {
user.log.WithError(err).Error("Failed to ApplySuccess on config_status.")
}
}
}
func (user *User) SendConfigStatusProgress(ctx context.Context) {
if !user.IsTelemetryEnabled(ctx) {
return
}
if !user.configStatus.IsPending() {
return
}
var builder configstatus.ConfigProgressBuilder
progress := builder.New(user.configStatus)
if progress.Values.NbDay == 0 {
return
}
if progress.Values.NbDaySinceLast == 0 {
return
}
data, err := json.Marshal(progress)
if err != nil {
if err := user.reporter.ReportMessageWithContext("Cannot parse config_progress data.", reporter.Context{
"error": err,
}); err != nil {
user.log.WithError(err).Error("Failed to report config_progress data parsing error.")
}
return
}
if err := user.SendTelemetry(ctx, data); err == nil {
user.log.Info("Configuration Status Progress event sent.")
if err := user.configStatus.ApplyProgress(); err != nil {
user.log.WithError(err).Error("Failed to ApplyProgress on config_status.")
}
}
}
func (user *User) ReportConfigStatusFailure(errDetails string) {
if user.configStatus.IsPending() {
return
}
if err := user.configStatus.ApplyFailure(errDetails); err != nil {
user.log.WithError(err).Error("Failed to ApplyFailure on config_status.")
} else {
user.log.Info("Configuration Status is back to Pending due to Failure.")
}
}
func (user *User) ReportBugClicked() {
if !user.configStatus.IsPending() {
return
}
if err := user.configStatus.ReportClicked(); err != nil {
user.log.WithError(err).Error("Failed to log ReportClicked in config_status.")
}
}
func (user *User) ReportBugSent() {
if !user.configStatus.IsPending() {
return
}
if err := user.configStatus.ReportSent(); err != nil {
user.log.WithError(err).Error("Failed to log ReportSent in config_status.")
}
}
func (user *User) AutoconfigUsed(client string) {
if !user.configStatus.IsPending() {
return
}
if err := user.configStatus.AutoconfigUsed(client); err != nil {
user.log.WithError(err).Error("Failed to log Autoconf in config_status.")
}
}
func (user *User) ExternalLinkClicked(url string) {
if !user.configStatus.IsPending() {
return
}
const externalLinkWasClicked = "External link was clicked."
index, err := kb.GetArticleIndex(url)
if err != nil {
if errors.Is(err, kb.ErrArticleNotFound) {
user.log.WithField("report", false).WithField("url", url).Debug(externalLinkWasClicked)
} else {
user.log.WithError(err).Error("Failed to retrieve list of KB articles.")
}
return
}
if err := user.configStatus.RecordLinkClicked(index); err != nil {
user.log.WithError(err).Error("Failed to log LinkClicked in config_status.")
} else {
user.log.WithField("report", true).WithField("url", url).Debug(externalLinkWasClicked)
}
}

View File

@ -21,13 +21,11 @@ import (
"context"
"encoding/json"
"fmt"
"path/filepath"
"time"
"github.com/ProtonMail/gluon/async"
"github.com/ProtonMail/gluon/reporter"
"github.com/ProtonMail/go-proton-api"
"github.com/ProtonMail/proton-bridge/v3/internal/configstatus"
"github.com/ProtonMail/proton-bridge/v3/internal/events"
"github.com/ProtonMail/proton-bridge/v3/internal/safe"
"github.com/ProtonMail/proton-bridge/v3/internal/services/imapservice"
@ -65,6 +63,8 @@ type User struct {
id string
log *logrus.Entry
userPlan string
vault *vault.User
client *proton.Client
reporter reporter.Reporter
@ -78,10 +78,7 @@ type User struct {
maxSyncMemory uint64
panicHandler async.PanicHandler
configStatus *configstatus.ConfigurationStatus
telemetryManager telemetry.Availability
// goStatusProgress triggers a check/sending if progress is needed.
goStatusProgress func()
eventService *userevents.Service
identityService *useridentity.Service
@ -104,7 +101,6 @@ func New(
crashHandler async.PanicHandler,
showAllMail bool,
maxSyncMemory uint64,
statsDir string,
telemetryManager telemetry.Availability,
imapServerManager imapservice.IMAPServerManager,
smtpServerManager smtp.ServerManager,
@ -125,7 +121,6 @@ func New(
crashHandler,
showAllMail,
maxSyncMemory,
statsDir,
telemetryManager,
imapServerManager,
smtpServerManager,
@ -159,7 +154,6 @@ func newImpl(
crashHandler async.PanicHandler,
showAllMail bool,
maxSyncMemory uint64,
statsDir string,
telemetryManager telemetry.Availability,
imapServerManager imapservice.IMAPServerManager,
smtpServerManager smtp.ServerManager,
@ -184,6 +178,14 @@ func newImpl(
return nil, fmt.Errorf("failed to get addresses: %w", err)
}
// Get the user's plan name.
var userPlan string
if organizationData, err := client.GetOrganizationData(ctx); err != nil {
logrus.WithError(err).Info("Failed to obtain user organization data")
} else {
userPlan = organizationData.Organization.Name
}
// Get the user's API labels.
apiLabels, err := client.GetLabels(ctx, proton.LabelTypeSystem, proton.LabelTypeFolder, proton.LabelTypeLabel)
if err != nil {
@ -198,12 +200,6 @@ func newImpl(
"numLabels": len(apiLabels),
}).Info("Creating user object")
configStatusFile := filepath.Join(statsDir, apiUser.ID+".json")
configStatus, err := configstatus.LoadConfigurationStatus(configStatusFile)
if err != nil {
return nil, fmt.Errorf("failed to init configuration status file: %w", err)
}
sendRecorder := sendrecorder.NewSendRecorder(sendrecorder.SendEntryExpiry)
// Create the user object.
@ -211,6 +207,8 @@ func newImpl(
log: logrus.WithField("userID", apiUser.ID),
id: apiUser.ID,
userPlan: userPlan,
vault: encVault,
client: client,
reporter: reporter,
@ -225,7 +223,6 @@ func newImpl(
panicHandler: crashHandler,
configStatus: configStatus,
telemetryManager: telemetryManager,
serviceGroup: orderedtasks.NewOrderedCancelGroup(crashHandler),
@ -248,7 +245,7 @@ func newImpl(
addressMode := usertypes.VaultToAddressMode(encVault.AddressMode())
user.identityService = useridentity.NewService(user.eventService, user, identityState, encVault, user)
user.identityService = useridentity.NewService(user.eventService, user, identityState, encVault)
user.telemetryService = telemetryservice.NewService(apiUser.ID, client, user.eventService)
@ -260,7 +257,6 @@ func newImpl(
reporter,
encVault,
encVault,
user,
user.eventService,
addressMode,
identityState.Clone(),
@ -279,7 +275,6 @@ func newImpl(
encVault,
crashHandler,
sendRecorder,
user,
reporter,
addressMode,
eventSubscription,
@ -291,12 +286,6 @@ func newImpl(
user.notificationService = notifications.NewService(user.id, user.eventService, user, notificationStore, getFlagValueFn, observabilityService)
// Check for status_progress when triggered.
user.goStatusProgress = user.tasks.PeriodicOrTrigger(configstatus.ProgressCheckInterval, 0, func(ctx context.Context) {
user.SendConfigStatusProgress(ctx)
})
defer user.goStatusProgress()
// When we receive an auth object, we update it in the vault.
// This will be used to authorize the user on the next run.
user.client.AddAuthHandler(func(auth proton.Auth) {
@ -340,7 +329,7 @@ func newImpl(
user.identityService.Start(ctx, user.serviceGroup)
// Add user client to observability service
observabilityService.RegisterUserClient(user.id, client, user.telemetryService)
observabilityService.RegisterUserClient(user.id, client, user.telemetryService, userPlan)
// Start Notification service
user.notificationService.Start(ctx, user.serviceGroup)
@ -439,6 +428,11 @@ func (user *User) GetAddressMode() vault.AddressMode {
return user.vault.AddressMode()
}
// GetUserPlanName returns the user's subscription plan name.
func (user *User) GetUserPlanName() string {
return user.userPlan
}
// SetAddressMode sets the user's address mode.
func (user *User) SetAddressMode(ctx context.Context, mode vault.AddressMode) error {
user.log.WithField("mode", mode).Info("Setting address mode")
@ -598,8 +592,13 @@ func (user *User) CheckAuth(email string, password []byte) (string, error) {
}
// Logout logs the user out from the API.
func (user *User) Logout(ctx context.Context, withAPI bool) error {
user.log.WithField("withAPI", withAPI).Info("Logging out user")
func (user *User) Logout(ctx context.Context, withAPI, withData, withDataDisabledKillSwitch bool) error {
user.log.WithFields(
logrus.Fields{
"withAPI": withAPI,
"withData": withData,
"withDataDisabledKillSwitch": withDataDisabledKillSwitch,
}).Info("Logging out user")
user.log.Debug("Canceling ongoing tasks")
@ -607,8 +606,20 @@ func (user *User) Logout(ctx context.Context, withAPI bool) error {
return fmt.Errorf("failed to remove user from smtp server: %w", err)
}
if err := user.imapService.OnLogout(ctx); err != nil {
return fmt.Errorf("failed to remove user from imap server: %w", err)
if withData && !withDataDisabledKillSwitch {
if err := user.imapService.OnDelete(ctx); err != nil {
if rerr := user.reporter.ReportMessageWithContext("Failed to delete user IMAP data", map[string]any{
"error": err.Error(),
}); rerr != nil {
logrus.WithError(rerr).Info("Failed to report user IMAP deletion issue to Sentry")
}
return fmt.Errorf("failed to delete user from imap server: %w", err)
}
} else {
if err := user.imapService.OnLogout(ctx); err != nil {
return fmt.Errorf("failed to remove user from imap server: %w", err)
}
}
user.tasks.CancelAndWait()
@ -698,19 +709,6 @@ func (user *User) SendTelemetry(ctx context.Context, data []byte) error {
return nil
}
func (user *User) ReportSMTPAuthFailed(username string) {
emails := user.Emails()
for _, mail := range emails {
if mail == username {
user.ReportConfigStatusFailure("SMTP invalid username or password")
}
}
}
func (user *User) ReportSMTPAuthSuccess(ctx context.Context) {
user.SendConfigStatusSuccess(ctx)
}
func (user *User) GetSMTPService() *smtp.Service {
return user.smtpService
}

View File

@ -160,7 +160,6 @@ func withUser(tb testing.TB, ctx context.Context, _ *server.Server, m *proton.Ma
nil,
true,
vault.DefaultMaxSyncMemory,
tb.TempDir(),
manager,
nullIMAPServerManager,
nullSMTPServerManager,

View File

@ -21,6 +21,7 @@ import (
"fmt"
"regexp"
"runtime"
"strings"
"sync"
)
@ -42,9 +43,12 @@ func New() *UserAgent {
}
func (ua *UserAgent) SetClient(name, version string) {
if strings.EqualFold("Mac OS X Notes", name) {
return
}
ua.lock.Lock()
defer ua.lock.Unlock()
ua.client = fmt.Sprintf("%v/%v", name, regexp.MustCompile(`(.*) \((.*)\)`).ReplaceAllString(version, "$1-$2"))
}

View File

@ -64,6 +64,14 @@ func TestUserAgent(t *testing.T) {
platform: "Windows 10 (10.0)",
want: "Thunderbird/78.6.1 (Windows 10 (10.0))",
},
// We ignore Apple Notes.
{
name: "Mac OS X Notes",
version: "4.11",
platform: "Windows 10 (10.0)",
want: DefaultUserAgent + " (Windows 10 (10.0))",
},
}
for _, test := range tests {