Debian Codegraph @

browserpass-native/request/process.go

raw
1 package request
2
3 import (
4 "encoding/binary"
5 "encoding/json"
6 "io"
7 "os"
8
9 "github.com/browserpass/browserpass-native/errors"
10 "github.com/browserpass/browserpass-native/response"
11 log "github.com/sirupsen/logrus"
12 )
13
14 type StoreSettings struct {
15 GpgPath string `json:"gpgPath"`
16 }
17
18 type store struct {
19 ID string `json:"id"`
20 Name string `json:"name"`
21 Path string `json:"path"`
22 Settings StoreSettings `json:"settings"`
23 }
24
25 type settings struct {
26 GpgPath string `json:"gpgPath"`
27 Stores map[string]store `json:"stores"`
28 }
29
30 type request struct {
31 Action string `json:"action"`
32 Settings settings `json:"settings"`
33 File string `json:"file"`
34 StoreID string `json:"storeId"`
35 EchoResponse interface{} `json:"echoResponse"`
36 }
37
38 // Process handles browser request
39 func Process() {
40 requestLength, err := parseRequestLength(os.Stdin)
41 if err != nil {
42 log.Error("Unable to parse the length of the browser request: ", err)
43 response.SendErrorAndExit(
44 errors.CodeParseRequestLength,
45 &map[errors.Field]string{
46 errors.FieldMessage: "Unable to parse the length of the browser request",
47 errors.FieldError: err.Error(),
48 },
49 )
50 }
51
52 request, err := parseRequest(requestLength, os.Stdin)
53 if err != nil {
54 log.Error("Unable to parse the browser request: ", err)
55 response.SendErrorAndExit(
56 errors.CodeParseRequest,
57 &map[errors.Field]string{
58 errors.FieldMessage: "Unable to parse the browser request",
59 errors.FieldError: err.Error(),
60 },
61 )
62 }
63
64 switch request.Action {
65 case "configure":
66 configure(request)
67 case "list":
68 listFiles(request)
69 case "fetch":
70 fetchDecryptedContents(request)
71 case "echo":
72 response.SendRaw(request.EchoResponse)
73 default:
74 log.Errorf("Received a browser request with an unknown action: %+v", request)
75 response.SendErrorAndExit(
76 errors.CodeInvalidRequestAction,
77 &map[errors.Field]string{
78 errors.FieldMessage: "Invalid request action",
79 errors.FieldAction: request.Action,
80 },
81 )
82 }
83 }
84
85 // Request length is the first 4 bytes in LittleEndian encoding
86 func parseRequestLength(input io.Reader) (uint32, error) {
87 var length uint32
88 if err := binary.Read(input, binary.LittleEndian, &length); err != nil {
89 return 0, err
90 }
91 return length, nil
92 }
93
94 // Request is a json with a predefined structure
95 func parseRequest(messageLength uint32, input io.Reader) (*request, error) {
96 var parsed request
97 reader := &io.LimitedReader{R: input, N: int64(messageLength)}
98 if err := json.NewDecoder(reader).Decode(&parsed); err != nil {
99 return nil, err
100 }
101 return &parsed, nil
102 }