From 25775a4c107788bf476b7d6443ac844c9fbe4c18 Mon Sep 17 00:00:00 2001 From: Bernhard B Date: Fri, 6 May 2022 19:28:23 +0200 Subject: [PATCH 1/2] implemented trust mode * implemented possibility to set the trust mode globally see #240 --- src/api/api.go | 56 ++++++++++++ src/client/cli.go | 125 +++++++++++++++++++++++++ src/client/client.go | 161 +++++++++++---------------------- src/client/jsonrpc2.go | 13 ++- src/main.go | 5 +- src/scripts/jsonrpc2-helper.go | 2 +- src/utils/api_config.go | 96 ++++++++++++++++++++ src/utils/config.go | 12 +-- 8 files changed, 348 insertions(+), 122 deletions(-) create mode 100644 src/client/cli.go create mode 100644 src/utils/api_config.go diff --git a/src/api/api.go b/src/api/api.go index 3f02927..7fc7295 100644 --- a/src/api/api.go +++ b/src/api/api.go @@ -124,6 +124,14 @@ type SendMessageResponse struct { Timestamp string `json:"timestamp"` } +type TrustModeRequest struct { + TrustMode string `json:"trust_mode"` +} + +type TrustModeResponse struct { + TrustMode string `json:"trust_mode"` +} + var connectionUpgrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true @@ -1430,3 +1438,51 @@ func (a *Api) AddDevice(c *gin.Context) { } c.Status(http.StatusNoContent) } + +func (a *Api) SetTrustMode(c *gin.Context) { + number := c.Param("number") + if number == "" { + c.JSON(400, Error{Msg: "Couldn't process request - number missing"}) + return + } + + var req TrustModeRequest + err := c.BindJSON(&req) + if err != nil { + c.JSON(400, Error{Msg: "Couldn't process request - invalid request"}) + return + } + + trustMode, err := utils.StringToTrustMode(req.TrustMode) + if err != nil { + c.JSON(400, Error{Msg: "Invalid trust mode"}) + return + } + + err = a.signalClient.SetTrustMode(number, trustMode) + if err != nil { + c.JSON(400, Error{Msg: "Couldn't set trust mode"}) + log.Error("Couldn't set trust mode: ", err.Error()) + return + } + c.Status(http.StatusNoContent) +} + +func (a *Api) GetTrustMode(c *gin.Context) { + number := c.Param("number") + if number == "" { + c.JSON(400, Error{Msg: "Couldn't process request - number missing"}) + return + } + + var err error + trustMode := TrustModeResponse{} + trustMode.TrustMode, err = utils.TrustModeToString(a.signalClient.GetTrustMode(number)) + if err != nil { + c.JSON(400, Error{Msg: "Invalid trust mode"}) + log.Error("Invalid trust mode: ", err.Error()) + return + } + + c.JSON(200, trustMode) +} diff --git a/src/client/cli.go b/src/client/cli.go new file mode 100644 index 0000000..991963f --- /dev/null +++ b/src/client/cli.go @@ -0,0 +1,125 @@ +package client + +import ( + "strings" + "errors" + "os/exec" + "bytes" + "time" + "bufio" + log "github.com/sirupsen/logrus" + utils "github.com/bbernhard/signal-cli-rest-api/utils" +) + +type CliClient struct { + signalCliMode SignalCliMode + signalCliApiConfig *utils.SignalCliApiConfig +} + +func NewCliClient(signalCliMode SignalCliMode, signalCliApiConfig *utils.SignalCliApiConfig) *CliClient { + return &CliClient { + signalCliMode: signalCliMode, + signalCliApiConfig: signalCliApiConfig, + } +} + +func (s *CliClient) Execute(wait bool, args []string, stdin string) (string, error) { + containerId, err := getContainerId() + + log.Debug("If you want to run this command manually, run the following steps on your host system:") + if err == nil { + log.Debug("*) docker exec -it ", containerId, " /bin/bash") + } else { + log.Debug("*) docker exec -it /bin/bash") + } + + signalCliBinary := "" + if s.signalCliMode == Normal { + signalCliBinary = "signal-cli" + } else if s.signalCliMode == Native { + signalCliBinary = "signal-cli-native" + } else { + return "", errors.New("Invalid signal-cli mode") + } + + //check if args contain number + trustModeStr := "" + for i, arg := range args { + if (arg == "-a" || arg == "--account") && (((i+1) < len(args)) && (utils.IsPhoneNumber(args[i+1]))) { + number := args[i+1] + trustMode, err := s.signalCliApiConfig.GetTrustModeForNumber(number) + if err == nil { + trustModeStr, err = utils.TrustModeToString(trustMode) + if err != nil { + trustModeStr = "" + log.Error("Invalid trust mode: ", trustModeStr) + } + } + break + } + } + + if trustModeStr != "" { + args = append([]string{"--trust-new-identities", trustModeStr}, args...) + } + + fullCmd := "" + if stdin != "" { + fullCmd += "echo '" + stdin + "' | " + } + fullCmd += signalCliBinary + " " + strings.Join(args, " ") + + log.Debug("*) su signal-api") + log.Debug("*) ", fullCmd) + + cmdTimeout, err := utils.GetIntEnv("SIGNAL_CLI_CMD_TIMEOUT", 120) + if err != nil { + log.Error("Env variable 'SIGNAL_CLI_CMD_TIMEOUT' contains an invalid timeout...falling back to default timeout (120 seconds)") + cmdTimeout = 120 + } + + cmd := exec.Command(signalCliBinary, args...) + if stdin != "" { + cmd.Stdin = strings.NewReader(stdin) + } + if wait { + var errBuffer bytes.Buffer + var outBuffer bytes.Buffer + cmd.Stderr = &errBuffer + cmd.Stdout = &outBuffer + + err := cmd.Start() + if err != nil { + return "", err + } + + done := make(chan error, 1) + go func() { + done <- cmd.Wait() + }() + select { + case <-time.After(time.Duration(cmdTimeout) * time.Second): + err := cmd.Process.Kill() + if err != nil { + return "", err + } + return "", errors.New("process killed as timeout reached") + case err := <-done: + if err != nil { + return "", errors.New(errBuffer.String()) + } + } + + return outBuffer.String(), nil + } else { + stdout, err := cmd.StdoutPipe() + if err != nil { + return "", err + } + cmd.Start() + buf := bufio.NewReader(stdout) // Notice that this is not in a loop + line, _, _ := buf.ReadLine() + return string(line), nil + } +} + diff --git a/src/client/client.go b/src/client/client.go index ea193c0..2f42919 100644 --- a/src/client/client.go +++ b/src/client/client.go @@ -1,26 +1,19 @@ package client import ( - "bufio" - "bytes" "encoding/base64" "encoding/json" "errors" "io/ioutil" "os" - "os/exec" "path/filepath" "strconv" "strings" - "time" securejoin "github.com/cyphar/filepath-securejoin" "github.com/gabriel-vasile/mimetype" "github.com/h2non/filetype" - //"github.com/sourcegraph/jsonrpc2"//"net/rpc/jsonrpc" - log "github.com/sirupsen/logrus" - uuid "github.com/gofrs/uuid" qrcode "github.com/skip2/go-qrcode" @@ -200,84 +193,6 @@ func getContainerId() (string, error) { return containerId, nil } -func runSignalCli(wait bool, args []string, stdin string, signalCliMode SignalCliMode) (string, error) { - containerId, err := getContainerId() - - log.Debug("If you want to run this command manually, run the following steps on your host system:") - if err == nil { - log.Debug("*) docker exec -it ", containerId, " /bin/bash") - } else { - log.Debug("*) docker exec -it /bin/bash") - } - - signalCliBinary := "" - if signalCliMode == Normal { - signalCliBinary = "signal-cli" - } else if signalCliMode == Native { - signalCliBinary = "signal-cli-native" - } else { - return "", errors.New("Invalid signal-cli mode") - } - - fullCmd := "" - if stdin != "" { - fullCmd += "echo '" + stdin + "' | " - } - fullCmd += signalCliBinary + " " + strings.Join(args, " ") - - log.Debug("*) su signal-api") - log.Debug("*) ", fullCmd) - - cmdTimeout, err := utils.GetIntEnv("SIGNAL_CLI_CMD_TIMEOUT", 120) - if err != nil { - log.Error("Env variable 'SIGNAL_CLI_CMD_TIMEOUT' contains an invalid timeout...falling back to default timeout (120 seconds)") - cmdTimeout = 120 - } - - cmd := exec.Command(signalCliBinary, args...) - if stdin != "" { - cmd.Stdin = strings.NewReader(stdin) - } - if wait { - var errBuffer bytes.Buffer - var outBuffer bytes.Buffer - cmd.Stderr = &errBuffer - cmd.Stdout = &outBuffer - - err := cmd.Start() - if err != nil { - return "", err - } - - done := make(chan error, 1) - go func() { - done <- cmd.Wait() - }() - select { - case <-time.After(time.Duration(cmdTimeout) * time.Second): - err := cmd.Process.Kill() - if err != nil { - return "", err - } - return "", errors.New("process killed as timeout reached") - case err := <-done: - if err != nil { - return "", errors.New(errBuffer.String()) - } - } - - return outBuffer.String(), nil - } else { - stdout, err := cmd.StdoutPipe() - if err != nil { - return "", err - } - cmd.Start() - buf := bufio.NewReader(stdout) // Notice that this is not in a loop - line, _, _ := buf.ReadLine() - return string(line), nil - } -} func ConvertGroupIdToInternalGroupId(id string) (string, error) { @@ -309,10 +224,13 @@ type SignalClient struct { jsonRpc2ClientConfig *utils.JsonRpc2ClientConfig jsonRpc2ClientConfigPath string jsonRpc2Clients map[string]*JsonRpc2Client + signalCliApiConfigPath string + signalCliApiConfig *utils.SignalCliApiConfig + cliClient *CliClient } func NewSignalClient(signalCliConfig string, attachmentTmpDir string, avatarTmpDir string, signalCliMode SignalCliMode, - jsonRpc2ClientConfigPath string) *SignalClient { + jsonRpc2ClientConfigPath string, signalCliApiConfigPath string) *SignalClient { return &SignalClient{ signalCliConfig: signalCliConfig, attachmentTmpDir: attachmentTmpDir, @@ -320,6 +238,7 @@ func NewSignalClient(signalCliConfig string, attachmentTmpDir string, avatarTmpD signalCliMode: signalCliMode, jsonRpc2ClientConfigPath: jsonRpc2ClientConfigPath, jsonRpc2Clients: make(map[string]*JsonRpc2Client), + signalCliApiConfigPath: signalCliApiConfigPath, } } @@ -328,6 +247,12 @@ func (s *SignalClient) GetSignalCliMode() SignalCliMode { } func (s *SignalClient) Init() error { + s.signalCliApiConfig = utils.NewSignalCliApiConfig() + err := s.signalCliApiConfig.Load(s.signalCliApiConfigPath) + if err != nil { + return err + } + if s.signalCliMode == JsonRpc { s.jsonRpc2ClientConfig = utils.NewJsonRpc2ClientConfig() err := s.jsonRpc2ClientConfig.Load(s.jsonRpc2ClientConfigPath) @@ -337,7 +262,7 @@ func (s *SignalClient) Init() error { tcpPortsNumberMapping := s.jsonRpc2ClientConfig.GetTcpPortsForNumbers() for number, tcpPort := range tcpPortsNumberMapping { - s.jsonRpc2Clients[number] = NewJsonRpc2Client() + s.jsonRpc2Clients[number] = NewJsonRpc2Client(s.signalCliApiConfig) err := s.jsonRpc2Clients[number].Dial("127.0.0.1:" + strconv.FormatInt(tcpPort, 10)) if err != nil { return err @@ -345,7 +270,10 @@ func (s *SignalClient) Init() error { go s.jsonRpc2Clients[number].ReceiveData(number) //receive messages in goroutine } + } else { + s.cliClient = NewCliClient(s.signalCliMode, s.signalCliApiConfig) } + return nil } @@ -455,7 +383,7 @@ func (s *SignalClient) send(number string, message string, cmd = append(cmd, attachmentTmpPaths...) } - rawData, err := runSignalCli(true, cmd, message, s.signalCliMode) + rawData, err := s.cliClient.Execute(true, cmd, message) if err != nil { cleanupTmpFiles(attachmentTmpPaths) if strings.Contains(err.Error(), signalCliV2GroupError) { @@ -495,7 +423,7 @@ func (s *SignalClient) RegisterNumber(number string, useVoice bool, captcha stri command = append(command, []string{"--captcha", captcha}...) } - _, err := runSignalCli(true, command, "", s.signalCliMode) + _, err := s.cliClient.Execute(true, command, "") return err } @@ -509,7 +437,7 @@ func (s *SignalClient) UnregisterNumber(number string, deleteAccount bool) error command = append(command, "--delete-account") } - _, err := runSignalCli(true, command, "", s.signalCliMode) + _, err := s.cliClient.Execute(true, command, "") return err } @@ -524,7 +452,7 @@ func (s *SignalClient) VerifyRegisteredNumber(number string, token string, pin s cmd = append(cmd, pin) } - _, err := runSignalCli(true, cmd, "", s.signalCliMode) + _, err := s.cliClient.Execute(true, cmd, "") return err } @@ -602,7 +530,7 @@ func (s *SignalClient) Receive(number string, timeout int64) (string, error) { } else { command := []string{"--config", s.signalCliConfig, "--output", "json", "-a", number, "receive", "-t", strconv.FormatInt(timeout, 10)} - out, err := runSignalCli(true, command, "", s.signalCliMode) + out, err := s.cliClient.Execute(true, command, "") if err != nil { return "", err } @@ -679,7 +607,7 @@ func (s *SignalClient) CreateGroup(number string, name string, members []string, cmd = append(cmd, []string{"--description", description}...) } - rawData, err := runSignalCli(true, cmd, "", s.signalCliMode) + rawData, err := s.cliClient.Execute(true, cmd, "") if err != nil { if strings.Contains(err.Error(), signalCliV2GroupError) { return "", errors.New("Cannot create group - please first update your profile.") @@ -743,7 +671,7 @@ func (s *SignalClient) updateGroupMembers(number string, groupId string, members } cmd = append(cmd, members...) - _, err = runSignalCli(true, cmd, "", s.signalCliMode) + _, err = s.cliClient.Execute(true, cmd, "") } return err } @@ -806,7 +734,7 @@ func (s *SignalClient) updateGroupAdmins(number string, groupId string, admins [ } cmd = append(cmd, admins...) - _, err = runSignalCli(true, cmd, "", s.signalCliMode) + _, err = s.cliClient.Execute(true, cmd, "") } return err } @@ -836,7 +764,7 @@ func (s *SignalClient) GetGroups(number string) ([]GroupEntry, error) { return groupEntries, err } } else { - rawData, err = runSignalCli(true, []string{"--config", s.signalCliConfig, "--output", "json", "-a", number, "listGroups", "-d"}, "", s.signalCliMode) + rawData, err = s.cliClient.Execute(true, []string{"--config", s.signalCliConfig, "--output", "json", "-a", number, "listGroups", "-d"}, "") if err != nil { return groupEntries, err } @@ -904,7 +832,7 @@ func (s *SignalClient) GetGroup(number string, groupId string) (*GroupEntry, err } func (s *SignalClient) DeleteGroup(number string, groupId string) error { - _, err := runSignalCli(true, []string{"--config", s.signalCliConfig, "-a", number, "quitGroup", "-g", string(groupId)}, "", s.signalCliMode) + _, err := s.cliClient.Execute(true, []string{"--config", s.signalCliConfig, "-a", number, "quitGroup", "-g", string(groupId)}, "") return err } @@ -914,7 +842,7 @@ func (s *SignalClient) GetQrCodeLink(deviceName string) ([]byte, error) { } command := []string{"--config", s.signalCliConfig, "link", "-n", deviceName} - tsdeviceLink, err := runSignalCli(false, command, "", s.signalCliMode) + tsdeviceLink, err := s.cliClient.Execute(false, command, "") if err != nil { return []byte{}, errors.New("Couldn't create QR code: " + err.Error()) } @@ -1046,7 +974,7 @@ func (s *SignalClient) UpdateProfile(number string, profileName string, base64Av cmd = append(cmd, []string{"--avatar", avatarTmpPath}...) } - _, err = runSignalCli(true, cmd, "", s.signalCliMode) + _, err = s.cliClient.Execute(true, cmd, "") } cleanupTmpFiles([]string{avatarTmpPath}) @@ -1077,7 +1005,7 @@ func (s *SignalClient) ListIdentities(number string) (*[]IdentityEntry, error) { identityEntries = append(identityEntries, identityEntry) } } else { - rawData, err := runSignalCli(true, []string{"--config", s.signalCliConfig, "-a", number, "listIdentities"}, "", s.signalCliMode) + rawData, err := s.cliClient.Execute(true, []string{"--config", s.signalCliConfig, "-a", number, "listIdentities"}, "") if err != nil { return nil, err } @@ -1134,7 +1062,7 @@ func (s *SignalClient) TrustIdentity(number string, numberToTrust string, verifi cmd = append(cmd, "--trust-all-known-keys") } - _, err = runSignalCli(true, cmd, "", s.signalCliMode) + _, err = s.cliClient.Execute(true, cmd, "") } return err } @@ -1152,7 +1080,7 @@ func (s *SignalClient) BlockGroup(number string, groupId string) error { } _, err = jsonRpc2Client.getRaw("block", request) } else { - _, err = runSignalCli(true, []string{"--config", s.signalCliConfig, "-a", number, "block", "-g", groupId}, "", s.signalCliMode) + _, err = s.cliClient.Execute(true, []string{"--config", s.signalCliConfig, "-a", number, "block", "-g", groupId}, "") } return err } @@ -1170,7 +1098,7 @@ func (s *SignalClient) JoinGroup(number string, groupId string) error { } _, err = jsonRpc2Client.getRaw("updateGroup", request) } else { - _, err = runSignalCli(true, []string{"--config", s.signalCliConfig, "-a", number, "updateGroup", "-g", groupId}, "", s.signalCliMode) + _, err = s.cliClient.Execute(true, []string{"--config", s.signalCliConfig, "-a", number, "updateGroup", "-g", groupId}, "") } return err } @@ -1188,7 +1116,7 @@ func (s *SignalClient) QuitGroup(number string, groupId string) error { } _, err = jsonRpc2Client.getRaw("quitGroup", request) } else { - _, err = runSignalCli(true, []string{"--config", s.signalCliConfig, "-a", number, "quitGroup", "-g", groupId}, "", s.signalCliMode) + _, err = s.cliClient.Execute(true, []string{"--config", s.signalCliConfig, "-a", number, "quitGroup", "-g", groupId}, "") } return err } @@ -1252,7 +1180,7 @@ func (s *SignalClient) SendReaction(number string, recipient string, emoji strin if remove { cmd = append(cmd, "-r") } - _, err = runSignalCli(true, cmd, "", s.signalCliMode) + _, err = s.cliClient.Execute(true, cmd, "") return err } @@ -1292,7 +1220,7 @@ func (s *SignalClient) SendStartTyping(number string, recipient string) error { } else { cmd = append(cmd, []string{"-g", recp}...) } - _, err = runSignalCli(true, cmd, "", s.signalCliMode) + _, err = s.cliClient.Execute(true, cmd, "") } return err @@ -1335,7 +1263,7 @@ func (s *SignalClient) SendStopTyping(number string, recipient string) error { } else { cmd = append(cmd, []string{"-g", recp}...) } - _, err = runSignalCli(true, cmd, "", s.signalCliMode) + _, err = s.cliClient.Execute(true, cmd, "") } return err @@ -1369,7 +1297,7 @@ func (s *SignalClient) SearchForNumbers(numbers []string) ([]SearchResultEntry, } else { cmd := []string{"--config", s.signalCliConfig, "--output", "json", "getUserStatus"} cmd = append(cmd, numbers...) - rawData, err = runSignalCli(true, cmd, "", s.signalCliMode) + rawData, err = s.cliClient.Execute(true, cmd, "") } if err != nil { @@ -1423,7 +1351,7 @@ func (s *SignalClient) UpdateContact(number string, recipient string, name *stri if expirationInSeconds != nil { cmd = append(cmd, []string{"-e", strconv.Itoa(*expirationInSeconds)}...) } - _, err = runSignalCli(true, cmd, "", s.signalCliMode) + _, err = s.cliClient.Execute(true, cmd, "") } return err } @@ -1442,7 +1370,20 @@ func (s *SignalClient) AddDevice(number string, uri string) error { _, err = jsonRpc2Client.getRaw("addDevice", request) } else { cmd := []string{"--config", s.signalCliConfig, "-a", number, "addDevice", "--uri", uri} - _, err = runSignalCli(true, cmd, "", s.signalCliMode) + _, err = s.cliClient.Execute(true, cmd, "") } return err } + +func (s *SignalClient) SetTrustMode(number string, trustMode utils.SignalCliTrustMode) error { + s.signalCliApiConfig.SetTrustModeForNumber(number, trustMode) + return s.signalCliApiConfig.Persist() +} + +func (s *SignalClient) GetTrustMode(number string) utils.SignalCliTrustMode { + trustMode, err := s.signalCliApiConfig.GetTrustModeForNumber(number) + if err != nil { //no trust mode explicitly set, use signal-cli default + return utils.OnFirstUseTrust + } + return trustMode +} diff --git a/src/client/jsonrpc2.go b/src/client/jsonrpc2.go index 9c86200..94e1ff5 100644 --- a/src/client/jsonrpc2.go +++ b/src/client/jsonrpc2.go @@ -4,10 +4,12 @@ import ( "bufio" "encoding/json" "errors" - uuid "github.com/gofrs/uuid" - log "github.com/sirupsen/logrus" "net" "time" + + "github.com/bbernhard/signal-cli-rest-api/utils" + uuid "github.com/gofrs/uuid" + log "github.com/sirupsen/logrus" ) type Error struct { @@ -32,10 +34,13 @@ type JsonRpc2Client struct { receivedMessageResponses chan JsonRpc2MessageResponse receivedMessages chan JsonRpc2ReceivedMessage lastTimeErrorMessageSent time.Time + signalCliApiConfig *utils.SignalCliApiConfig } -func NewJsonRpc2Client() *JsonRpc2Client { - return &JsonRpc2Client{} +func NewJsonRpc2Client(signalCliApiConfig *utils.SignalCliApiConfig) *JsonRpc2Client { + return &JsonRpc2Client{ + signalCliApiConfig: signalCliApiConfig, + } } func (r *JsonRpc2Client) Dial(address string) error { diff --git a/src/main.go b/src/main.go index c53aa24..f718854 100644 --- a/src/main.go +++ b/src/main.go @@ -131,7 +131,8 @@ func main() { } jsonRpc2ClientConfigPathPath := *signalCliConfig + "/jsonrpc2.yml" - signalClient := client.NewSignalClient(*signalCliConfig, *attachmentTmpDir, *avatarTmpDir, signalCliMode, jsonRpc2ClientConfigPathPath) + signalCliApiConfigPath := *signalCliConfig + "/api-config.yml" + signalClient := client.NewSignalClient(*signalCliConfig, *attachmentTmpDir, *avatarTmpDir, signalCliMode, jsonRpc2ClientConfigPathPath, signalCliApiConfigPath) err = signalClient.Init() if err != nil { log.Fatal("Couldn't init Signal Client: ", err.Error()) @@ -149,6 +150,8 @@ func main() { { configuration.GET("", api.GetConfiguration) configuration.POST("", api.SetConfiguration) + configuration.POST(":number/trustmode", api.SetTrustMode) + configuration.GET(":number/trustmode", api.GetTrustMode) } health := v1.Group("/health") diff --git a/src/scripts/jsonrpc2-helper.go b/src/scripts/jsonrpc2-helper.go index 5ac288c..c9c1008 100644 --- a/src/scripts/jsonrpc2-helper.go +++ b/src/scripts/jsonrpc2-helper.go @@ -113,7 +113,7 @@ func main() { fifoPathname := fifoBasePathName + strconv.FormatInt(ctr, 10) tcpPort := tcpBasePort + ctr - jsonRpc2ClientConfig.AddEntry(number, utils.ConfigEntry{TcpPort: tcpPort, FifoPathname: fifoPathname}) + jsonRpc2ClientConfig.AddEntry(number, utils.JsonRpc2ClientConfigEntry{TcpPort: tcpPort, FifoPathname: fifoPathname}) ctr += 1 os.Remove(fifoPathname) //remove any existing named pipe diff --git a/src/utils/api_config.go b/src/utils/api_config.go new file mode 100644 index 0000000..dd9f022 --- /dev/null +++ b/src/utils/api_config.go @@ -0,0 +1,96 @@ +package utils + +import ( + "io/ioutil" + "gopkg.in/yaml.v2" + "errors" + "os" +) + +type SignalCliTrustMode int + +const ( + OnFirstUseTrust SignalCliTrustMode = iota + AlwaysTrust + NeverTrust +) + +func TrustModeToString(trustMode SignalCliTrustMode) (string, error) { + if trustMode == OnFirstUseTrust { + return "on-first-use", nil + } else if trustMode == AlwaysTrust { + return "always", nil + } else if trustMode == NeverTrust { + return "never", nil + } + return "", errors.New("Invalid Trust Mode") +} + +func StringToTrustMode(trustMode string) (SignalCliTrustMode, error) { + if trustMode == "on-first-use" { + return OnFirstUseTrust, nil + } else if trustMode == "always" { + return AlwaysTrust, nil + } else if trustMode == "never" { + return NeverTrust, nil + } + return OnFirstUseTrust, errors.New("Invalid Trust Mode") +} + +type SignalCliApiConfigEntry struct { + TrustMode SignalCliTrustMode `yaml:"trust_mode"` +} + +type SignalCliApiConfigEntries struct { + Entries map[string]SignalCliApiConfigEntry `yaml:"config,omitempty"` +} + +type SignalCliApiConfig struct { + config SignalCliApiConfigEntries + path string +} + +func NewSignalCliApiConfig() *SignalCliApiConfig { + return &SignalCliApiConfig{} +} + +func (c *SignalCliApiConfig) Load(path string) error { + c.path = path + if _, err := os.Stat(path); err == nil { + data, err := ioutil.ReadFile(path) + if err != nil { + return err + } + + err = yaml.Unmarshal(data, &c.config) + if err != nil { + return err + } + } + + return nil +} + +func (c *SignalCliApiConfig) GetTrustModeForNumber(number string) (SignalCliTrustMode, error) { + if val, ok := c.config.Entries[number]; ok { + return val.TrustMode, nil + } + + return NeverTrust, errors.New("Number " + number + " not found in local map") +} + +func (c *SignalCliApiConfig) SetTrustModeForNumber(number string, trustMode SignalCliTrustMode) { + if c.config.Entries == nil { + c.config.Entries = make(map[string]SignalCliApiConfigEntry) + } + c.config.Entries[number] = SignalCliApiConfigEntry{TrustMode: trustMode} +} + +func (c *SignalCliApiConfig) Persist() error { + out, err := yaml.Marshal(&c.config) + if err != nil { + return err + } + + return ioutil.WriteFile(c.path, out, 0644) +} diff --git a/src/utils/config.go b/src/utils/config.go index dff209e..c6f7667 100644 --- a/src/utils/config.go +++ b/src/utils/config.go @@ -6,17 +6,17 @@ import ( "io/ioutil" ) -type ConfigEntry struct { +type JsonRpc2ClientConfigEntry struct { TcpPort int64 `yaml:"tcp_port"` FifoPathname string `yaml:"fifo_pathname"` } -type Config struct { - Entries map[string]ConfigEntry `yaml:"config,omitempty"` +type JsonRpc2ClientConfigEntries struct { + Entries map[string]JsonRpc2ClientConfigEntry `yaml:"config,omitempty"` } type JsonRpc2ClientConfig struct { - config Config + config JsonRpc2ClientConfigEntries } func NewJsonRpc2ClientConfig() *JsonRpc2ClientConfig { @@ -62,9 +62,9 @@ func (c *JsonRpc2ClientConfig) GetTcpPortsForNumbers() map[string]int64 { return mapping } -func (c *JsonRpc2ClientConfig) AddEntry(number string, configEntry ConfigEntry) { +func (c *JsonRpc2ClientConfig) AddEntry(number string, configEntry JsonRpc2ClientConfigEntry) { if c.config.Entries == nil { - c.config.Entries = make(map[string]ConfigEntry) + c.config.Entries = make(map[string]JsonRpc2ClientConfigEntry) } c.config.Entries[number] = configEntry } From 798f897ad12ceb00278a2763bc4ca9fbf6566ca1 Mon Sep 17 00:00:00 2001 From: Bernhard B Date: Sun, 8 May 2022 20:23:54 +0200 Subject: [PATCH 2/2] added trust mode parameter to json-rpc mode see #240 --- src/api/api.go | 20 +++++++++ src/client/client.go | 2 +- src/client/jsonrpc2.go | 22 +++++++++- src/docs/docs.go | 98 ++++++++++++++++++++++++++++++++++++++++++ src/docs/swagger.json | 98 ++++++++++++++++++++++++++++++++++++++++++ src/docs/swagger.yaml | 65 ++++++++++++++++++++++++++++ src/go.mod | 1 + src/go.sum | 8 ++++ src/main.go | 4 +- 9 files changed, 314 insertions(+), 4 deletions(-) diff --git a/src/api/api.go b/src/api/api.go index 7fc7295..811e584 100644 --- a/src/api/api.go +++ b/src/api/api.go @@ -1439,6 +1439,16 @@ func (a *Api) AddDevice(c *gin.Context) { c.Status(http.StatusNoContent) } +// @Summary Set account specific settings. +// @Tags General +// @Description Set account specific settings. +// @Accept json +// @Produce json +// @Param number path string true "Registered Phone Number" +// @Success 204 +// @Param data body TrustModeRequest true "Request" +// @Failure 400 {object} Error +// @Router /v1/configuration/{number}/settings [post] func (a *Api) SetTrustMode(c *gin.Context) { number := c.Param("number") if number == "" { @@ -1468,6 +1478,16 @@ func (a *Api) SetTrustMode(c *gin.Context) { c.Status(http.StatusNoContent) } +// @Summary List account specific settings. +// @Tags General +// @Description List account specific settings. +// @Accept json +// @Produce json +// @Param number path string true "Registered Phone Number" +// @Success 200 +// @Param data body TrustModeResponse true "Request" +// @Failure 400 {object} Error +// @Router /v1/configuration/{number}/settings [get] func (a *Api) GetTrustMode(c *gin.Context) { number := c.Param("number") if number == "" { diff --git a/src/client/client.go b/src/client/client.go index 2f42919..ba2969f 100644 --- a/src/client/client.go +++ b/src/client/client.go @@ -262,7 +262,7 @@ func (s *SignalClient) Init() error { tcpPortsNumberMapping := s.jsonRpc2ClientConfig.GetTcpPortsForNumbers() for number, tcpPort := range tcpPortsNumberMapping { - s.jsonRpc2Clients[number] = NewJsonRpc2Client(s.signalCliApiConfig) + s.jsonRpc2Clients[number] = NewJsonRpc2Client(s.signalCliApiConfig, number) err := s.jsonRpc2Clients[number].Dial("127.0.0.1:" + strconv.FormatInt(tcpPort, 10)) if err != nil { return err diff --git a/src/client/jsonrpc2.go b/src/client/jsonrpc2.go index 94e1ff5..64ccca3 100644 --- a/src/client/jsonrpc2.go +++ b/src/client/jsonrpc2.go @@ -10,6 +10,7 @@ import ( "github.com/bbernhard/signal-cli-rest-api/utils" uuid "github.com/gofrs/uuid" log "github.com/sirupsen/logrus" + "github.com/tidwall/sjson" ) type Error struct { @@ -35,11 +36,13 @@ type JsonRpc2Client struct { receivedMessages chan JsonRpc2ReceivedMessage lastTimeErrorMessageSent time.Time signalCliApiConfig *utils.SignalCliApiConfig + number string } -func NewJsonRpc2Client(signalCliApiConfig *utils.SignalCliApiConfig) *JsonRpc2Client { +func NewJsonRpc2Client(signalCliApiConfig *utils.SignalCliApiConfig, number string) *JsonRpc2Client { return &JsonRpc2Client{ signalCliApiConfig: signalCliApiConfig, + number: number, } } @@ -64,6 +67,16 @@ func (r *JsonRpc2Client) getRaw(command string, args interface{}) (string, error Params interface{} `json:"params,omitempty"` } + trustModeStr := "" + trustMode, err := r.signalCliApiConfig.GetTrustModeForNumber(r.number) + if err == nil { + trustModeStr, err = utils.TrustModeToString(trustMode) + if err != nil { + trustModeStr = "" + log.Error("Invalid trust mode: ", trustModeStr) + } + } + u, err := uuid.NewV4() if err != nil { return "", err @@ -79,6 +92,13 @@ func (r *JsonRpc2Client) getRaw(command string, args interface{}) (string, error return "", err } + if trustModeStr != "" { + fullCommandBytes, err = sjson.SetBytes(fullCommandBytes, "params.trustNewIdentities", trustModeStr) + if err != nil { + return "", err + } + } + log.Debug("full command: ", string(fullCommandBytes)) _, err = r.conn.Write([]byte(string(fullCommandBytes) + "\n")) diff --git a/src/docs/docs.go b/src/docs/docs.go index 7dad03e..91fcacc 100644 --- a/src/docs/docs.go +++ b/src/docs/docs.go @@ -209,6 +209,88 @@ var doc = `{ } } }, + "/v1/configuration/{number}/settings": { + "get": { + "description": "List account specific settings.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "General" + ], + "summary": "List account specific settings.", + "parameters": [ + { + "type": "string", + "description": "Registered Phone Number", + "name": "number", + "in": "path", + "required": true + }, + { + "description": "Request", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/api.TrustModeResponse" + } + } + ], + "responses": { + "200": {}, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/api.Error" + } + } + } + }, + "post": { + "description": "Set account specific settings.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "General" + ], + "summary": "Set account specific settings.", + "parameters": [ + { + "type": "string", + "description": "Registered Phone Number", + "name": "number", + "in": "path", + "required": true + }, + { + "description": "Request", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/api.TrustModeRequest" + } + } + ], + "responses": { + "204": {}, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/api.Error" + } + } + } + } + }, "/v1/contacts{number}": { "put": { "description": "Updates the info associated to a number on the contact list.", @@ -1658,6 +1740,22 @@ var doc = `{ } } }, + "api.TrustModeRequest": { + "type": "object", + "properties": { + "trust_mode": { + "type": "string" + } + } + }, + "api.TrustModeResponse": { + "type": "object", + "properties": { + "trust_mode": { + "type": "string" + } + } + }, "api.TypingIndicatorRequest": { "type": "object", "properties": { diff --git a/src/docs/swagger.json b/src/docs/swagger.json index 00bd4a3..84355ab 100644 --- a/src/docs/swagger.json +++ b/src/docs/swagger.json @@ -193,6 +193,88 @@ } } }, + "/v1/configuration/{number}/settings": { + "get": { + "description": "List account specific settings.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "General" + ], + "summary": "List account specific settings.", + "parameters": [ + { + "type": "string", + "description": "Registered Phone Number", + "name": "number", + "in": "path", + "required": true + }, + { + "description": "Request", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/api.TrustModeResponse" + } + } + ], + "responses": { + "200": {}, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/api.Error" + } + } + } + }, + "post": { + "description": "Set account specific settings.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "General" + ], + "summary": "Set account specific settings.", + "parameters": [ + { + "type": "string", + "description": "Registered Phone Number", + "name": "number", + "in": "path", + "required": true + }, + { + "description": "Request", + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/api.TrustModeRequest" + } + } + ], + "responses": { + "204": {}, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/api.Error" + } + } + } + } + }, "/v1/contacts{number}": { "put": { "description": "Updates the info associated to a number on the contact list.", @@ -1642,6 +1724,22 @@ } } }, + "api.TrustModeRequest": { + "type": "object", + "properties": { + "trust_mode": { + "type": "string" + } + } + }, + "api.TrustModeResponse": { + "type": "object", + "properties": { + "trust_mode": { + "type": "string" + } + } + }, "api.TypingIndicatorRequest": { "type": "object", "properties": { diff --git a/src/docs/swagger.yaml b/src/docs/swagger.yaml index 5b5752f..b1c54ce 100644 --- a/src/docs/swagger.yaml +++ b/src/docs/swagger.yaml @@ -141,6 +141,16 @@ definitions: verified_safety_number: type: string type: object + api.TrustModeRequest: + properties: + trust_mode: + type: string + type: object + api.TrustModeResponse: + properties: + trust_mode: + type: string + type: object api.TypingIndicatorRequest: properties: recipient: @@ -356,6 +366,61 @@ paths: summary: Set the REST API configuration. tags: - General + /v1/configuration/{number}/settings: + get: + consumes: + - application/json + description: List account specific settings. + parameters: + - description: Registered Phone Number + in: path + name: number + required: true + type: string + - description: Request + in: body + name: data + required: true + schema: + $ref: '#/definitions/api.TrustModeResponse' + produces: + - application/json + responses: + "200": {} + "400": + description: Bad Request + schema: + $ref: '#/definitions/api.Error' + summary: List account specific settings. + tags: + - General + post: + consumes: + - application/json + description: Set account specific settings. + parameters: + - description: Registered Phone Number + in: path + name: number + required: true + type: string + - description: Request + in: body + name: data + required: true + schema: + $ref: '#/definitions/api.TrustModeRequest' + produces: + - application/json + responses: + "204": {} + "400": + description: Bad Request + schema: + $ref: '#/definitions/api.Error' + summary: Set account specific settings. + tags: + - General /v1/contacts{number}: put: consumes: diff --git a/src/go.mod b/src/go.mod index 56b5303..dab8360 100644 --- a/src/go.mod +++ b/src/go.mod @@ -20,6 +20,7 @@ require ( github.com/swaggo/files v0.0.0-20190704085106-630677cd5c14 github.com/swaggo/gin-swagger v1.2.0 github.com/swaggo/swag v1.6.7 + github.com/tidwall/sjson v1.2.4 // indirect github.com/urfave/cli/v2 v2.2.0 // indirect golang.org/x/net v0.0.0-20200625001655-4c5254603344 // indirect golang.org/x/text v0.3.3 // indirect diff --git a/src/go.sum b/src/go.sum index 236835e..7bf88df 100644 --- a/src/go.sum +++ b/src/go.sum @@ -128,6 +128,14 @@ github.com/swaggo/gin-swagger v1.2.0/go.mod h1:qlH2+W7zXGZkczuL+r2nEBR2JTT+/lX05 github.com/swaggo/swag v1.5.1/go.mod h1:1Bl9F/ZBpVWh22nY0zmYyASPO1lI/zIwRDrpZU+tv8Y= github.com/swaggo/swag v1.6.7 h1:e8GC2xDllJZr3omJkm9YfmK0Y56+rMO3cg0JBKNz09s= github.com/swaggo/swag v1.6.7/go.mod h1:xDhTyuFIujYiN3DKWC/H/83xcfHp+UE/IzWWampG7Zc= +github.com/tidwall/gjson v1.12.1 h1:ikuZsLdhr8Ws0IdROXUS1Gi4v9Z4pGqpX/CvJkxvfpo= +github.com/tidwall/gjson v1.12.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/sjson v1.2.4 h1:cuiLzLnaMeBhRmEv00Lpk3tkYrcxpmbU81tAY4Dw0tc= +github.com/tidwall/sjson v1.2.4/go.mod h1:098SZ494YoMWPmMO6ct4dcFnqxwj9r/gF0Etp19pSNM= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go v1.1.5-pre/go.mod h1:FwP/aQVg39TXzItUBMwnWp9T9gPQnXw4Poh4/oBQZ/0= github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= diff --git a/src/main.go b/src/main.go index f718854..48fe752 100644 --- a/src/main.go +++ b/src/main.go @@ -150,8 +150,8 @@ func main() { { configuration.GET("", api.GetConfiguration) configuration.POST("", api.SetConfiguration) - configuration.POST(":number/trustmode", api.SetTrustMode) - configuration.GET(":number/trustmode", api.GetTrustMode) + configuration.POST(":number/settings", api.SetTrustMode) + configuration.GET(":number/settings", api.GetTrustMode) } health := v1.Group("/health")