/
command-line.go
175 lines (159 loc) · 5.03 KB
/
command-line.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
/*
* Copyright 2020, Cossack Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package keys
import (
"errors"
"flag"
"fmt"
"os"
"strings"
log "github.com/sirupsen/logrus"
"github.com/cossacklabs/acra/cmd"
keystoreV1 "github.com/cossacklabs/acra/keystore"
"github.com/cossacklabs/acra/logging"
"github.com/cossacklabs/acra/utils"
)
// ServiceName constant for logging and configuration parsing.
const ServiceName = "acra-keys"
// DefaultKeyDirectory is the default path to key directory.
const DefaultKeyDirectory = keystoreV1.DefaultKeyDirShort
// DefaultConfigPath is the default path to service configuration file.
var DefaultConfigPath = utils.GetConfigPathByName("acra-keys")
// Sub-command names:
const (
CmdGenerate = "generate"
CmdListKeys = "list"
CmdExportKeys = "export"
CmdImportKeys = "import"
CmdMigrateKeys = "migrate"
CmdReadKey = "read"
CmdDestroyKey = "destroy"
CmdExtractClientID = "extract-client-id"
)
// Command-line parsing errors:
var (
ErrUnknownSubCommand = errors.New("unknown command")
ErrMissingKeyKind = errors.New("missing key kind")
ErrMissingKeyID = errors.New("missing key IDs")
ErrMultipleKeyKinds = errors.New("multiple key kinds")
ErrMissingOutputFile = errors.New("output file not specified")
ErrOutputSame = errors.New("output files are the same")
)
// Subcommand is "acra-keys" subcommand, like "acra-keys export".
type Subcommand interface {
Name() string
RegisterFlags()
GetFlagSet() *flag.FlagSet
Parse(arguments []string) error
Execute()
}
// ParseParameters parses command-line parameters and returns the selected subcommand.
// There may be no subcommand selected, in which case nil is returned.
// It terminates the process on error.
func ParseParameters(subcommands []Subcommand) Subcommand {
flag.CommandLine.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage:\n\t%s [options...] <command> [arguments...]\n", os.Args[0])
fmt.Fprintf(os.Stderr, "\nGlobal options:\n")
cmd.PrintFlags(flag.CommandLine)
names := make([]string, len(subcommands))
for i, c := range subcommands {
names[i] = c.Name()
}
fmt.Fprintf(os.Stderr, "\nSupported commands:\n %s\n", strings.Join(names, ", "))
}
for _, c := range subcommands {
c.RegisterFlags()
}
subcommand, err := parseParameters(subcommands)
if err == flag.ErrHelp {
os.Exit(0)
}
if err != nil {
log.WithError(err).
WithField(logging.FieldKeyEventCode, logging.EventCodeErrorCantReadServiceConfig).
Fatal("Cannot parse arguments")
}
return subcommand
}
func parseParameters(subcommands []Subcommand) (Subcommand, error) {
err := cmd.ParseFlags(flag.CommandLine, os.Args[1:])
// If there is "--dump_config" on the command line,
// dump configuration for all subcommand and immediately exit.
if err == cmd.ErrDumpRequested {
flagSets := make([]*flag.FlagSet, len(subcommands)+1)
flagSets[0] = flag.CommandLine
for i, command := range subcommands {
flagSets[i+1] = command.GetFlagSet()
}
cmd.DumpConfigFromFlagSets(flagSets, DefaultConfigPath, ServiceName, true)
os.Exit(0)
}
if err != nil {
return nil, err
}
_, err = cmd.ParseConfig(DefaultConfigPath, ServiceName)
if err != nil {
return nil, err
}
names := make([]string, len(subcommands))
for i, command := range subcommands {
names[i] = command.Name()
}
args := flag.CommandLine.Args()
if len(args) == 0 {
log.WithField("supported", names).Info("No command specified")
return nil, nil
}
subcommandName := args[0]
for _, c := range subcommands {
if c.Name() == subcommandName {
err = c.Parse(args[1:])
if err != nil {
return c, err
}
return c, nil
}
}
log.WithField("expected", names).Errorf("Unknown command: %s", subcommandName)
return nil, ErrUnknownSubCommand
}
// ParseKeyKind parses key ID of form "client/Alice/storage" and returns key kind and possible ID.
func ParseKeyKind(keyID string) (string, []byte, error) {
parts := strings.Split(keyID, "/")
if len(parts) == 1 {
switch parts[0] {
case "poison-record":
return keystoreV1.KeyPoisonKeypair, nil, nil
case "poison-record-symmetric":
return keystoreV1.KeyPoisonSymmetric, nil, nil
}
}
if len(parts) == 3 {
id := []byte(parts[1])
if parts[0] == "client" {
switch parts[2] {
case "symmetric":
return keystoreV1.KeySymmetric, id, nil
case "storage":
return keystoreV1.KeyStorageKeypair, id, nil
case "searchable":
return keystoreV1.KeySearch, id, nil
}
}
log.Warningln("Zone keys are deprecated since 0.94.0 and will be removed soon.")
}
return "", nil, ErrUnknownKeyKind
}