forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
227 lines (189 loc) · 5.25 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
"os/exec"
"regexp"
"strings"
)
var errInvalidMethod = errors.New("invalid method")
var errInvalidInput = errors.New("invalid input")
var errMissingField = errors.New("missing field")
var errUserNotFound = errors.New("user not found")
var errParsing = errors.New("failed to parse keybase output")
var errKeybaseNotRunning = errors.New("keybase is not running")
var errKeybaseNotLoggedIn = errors.New("keybase is not logged in")
type errUnexpected struct {
value string
}
func (err *errUnexpected) Error() string {
return fmt.Sprintf("unexpected error: %s", err.value)
}
func execRunner(cmd *exec.Cmd) error {
return cmd.Run()
}
// reUsernameQuery matches valid username queries
var reUsernameQuery = regexp.MustCompile(`^[a-zA-Z0-9_\-.:@]{1,256}$`)
// checkUsernameQuery returns the query if it's valid to use
// We return the valid string so that it can be used as a separate
// pre-validated variable which makes it less likely that the validation will
// be accidentally removed in the future, as opposed to if we just continued
// using the input variable after validating it.
func checkUsernameQuery(s string) (string, error) {
if s == "" {
return "", errMissingField
}
if !reUsernameQuery.MatchString(s) {
return "", errInvalidInput
}
return s, nil
}
// newHandler returns a request handler.
func newHandler() *handler {
return &handler{
Run: execRunner,
FindKeybaseBinary: func() (string, error) {
return findKeybaseBinary(keybaseBinary)
},
}
}
type handler struct {
// Run wraps the equivalent of cmd.Run(), allowing for mocking
Run func(cmd *exec.Cmd) error
// FindCmd returns the path of the keybase binary if it can find it
FindKeybaseBinary func() (string, error)
}
// Handle accepts a request, handles it, and returns an optional result if there was no error
func (h *handler) Handle(req *Request) (interface{}, error) {
switch req.Method {
case "chat":
return nil, h.handleChat(req)
case "query":
return h.handleQuery(req)
}
return nil, errInvalidMethod
}
// handleChat sends a chat message to a user.
func (h *handler) handleChat(req *Request) error {
if req.Body == "" {
return errMissingField
}
idQuery, err := checkUsernameQuery(req.To)
if err != nil {
return err
}
binPath, err := h.FindKeybaseBinary()
if err != nil {
return err
}
var out bytes.Buffer
cmd := exec.Command(binPath, "chat", "send", "--private", idQuery)
cmd.Env = append(os.Environ(), "KEYBASE_LOG_FORMAT=plain")
cmd.Stdin = strings.NewReader(req.Body)
cmd.Stdout = &out
cmd.Stderr = &out
if err := h.Run(cmd); err != nil {
return parseError(&out, err)
}
return nil
}
type resultQuery struct {
Username string `json:"username"`
}
// parseQuery reads the stderr from a keybase query command and returns a result
func parseQuery(r io.Reader) (*resultQuery, error) {
scanner := bufio.NewScanner(r)
var lastErrLine string
for scanner.Scan() {
// Find a line that looks like... "[INFO] 001 Identifying someuser"
line := strings.TrimSpace(scanner.Text())
parts := strings.Split(line, " ")
if len(parts) < 4 {
continue
}
// Short circuit errors
if parts[0] == "[ERRO]" {
lastErrLine = strings.Join(parts[2:], " ")
if lastErrLine == "Not found" {
return nil, errUserNotFound
}
continue
}
if parts[2] != "Identifying" {
continue
}
resp := &resultQuery{
Username: parts[3],
}
return resp, nil
}
if err := scanner.Err(); err != nil {
return nil, scanner.Err()
}
// This could happen if the keybase service is broken
return nil, &errUnexpected{lastErrLine}
}
// parseError reads stderr output and returns an error made from it. If it
// fails to parse an error, it returns the fallback error.
func parseError(r io.Reader, fallback error) error {
scanner := bufio.NewScanner(r)
// Find the final error
var lastErr error
for scanner.Scan() {
// Should be of the form "[ERRO] 001 Not found" or "...: No resolution found"
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
// Check some error states we know about:
if strings.Contains(line, "Keybase isn't running.") {
return errKeybaseNotRunning
}
if strings.Contains(line, "You are not logged into Keybase.") {
return errKeybaseNotLoggedIn
}
parts := strings.SplitN(line, " ", 3)
if len(parts) < 3 {
continue
}
if parts[0] != "[ERRO]" {
continue
}
if strings.HasSuffix(parts[2], "No resolution found") {
return errUserNotFound
}
if strings.HasPrefix(parts[2], "Not found") {
return errUserNotFound
}
lastErr = fmt.Errorf(parts[2])
}
if lastErr != nil {
return lastErr
}
return fallback
}
// handleQuery searches whether a user is present in Keybase.
func (h *handler) handleQuery(req *Request) (*resultQuery, error) {
idQuery, err := checkUsernameQuery(req.To)
if err != nil {
return nil, err
}
binPath, err := h.FindKeybaseBinary()
if err != nil {
return nil, err
}
// Unfortunately `keybase id ...` does not support JSON output, so we parse the output
var out bytes.Buffer
cmd := exec.Command(binPath, "id", idQuery)
cmd.Env = append(os.Environ(), "KEYBASE_LOG_FORMAT=plain")
cmd.Stdout = &out
cmd.Stderr = &out
if err := h.Run(cmd); err != nil {
return nil, parseError(&out, err)
}
return parseQuery(&out)
}