-
Notifications
You must be signed in to change notification settings - Fork 36
/
main.go
302 lines (255 loc) · 7.41 KB
/
main.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/signal"
"path/filepath"
"strings"
"github.com/nats-io/jwt/v2"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/micro"
"github.com/nats-io/nkeys"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
var (
natsUrl string
natsUser string
natsPass string
natsCreds string
issuerSeed string
xkeySeed string
signingKeyFiles string
usersFile string
)
flag.StringVar(&natsUrl, "nats.url", nats.DefaultURL, "NATS server URL")
flag.StringVar(&natsUser, "nats.user", "", "NATS user")
flag.StringVar(&natsPass, "nats.pass", "", "NATS password")
flag.StringVar(&natsCreds, "nats.creds", "", "NATS creds file")
flag.StringVar(&issuerSeed, "issuer.seed", "", "Issuer seed")
flag.StringVar(&xkeySeed, "xkey.seed", "", "Xkey seed")
flag.StringVar(&signingKeyFiles, "signing.keys", "", "Signing keys")
flag.StringVar(&usersFile, "users", "", "Users file")
flag.Parse()
// Parse the issuer account signing key.
issuerKeyPair, err := fromSeedOrFile(issuerSeed)
if err != nil {
return fmt.Errorf("error parsing issuer seed: %s", err)
}
// Parse the xkey seed if present.
var curveKeyPair nkeys.KeyPair
if len(xkeySeed) > 0 {
curveKeyPair, err = fromSeedOrFile(xkeySeed)
if err != nil {
return fmt.Errorf("error parsing xkey seed: %s", err)
}
}
// Parse each of the account signing key files can create a map
// of the local name to the key pair.
var signingKeys map[string]*signingKey
if len(signingKeyFiles) > 0 {
signingKeys, err = loadSigningKeys(strings.Split(signingKeyFiles, ","))
if err != nil {
return fmt.Errorf("error loading signing keys: %s", err)
}
}
// Load users from the users file, emulating an IAM backend.
users, err := loadUsers(usersFile)
if err != nil {
return fmt.Errorf("error loading users: %s", err)
}
var opts []nats.Option
if natsCreds != "" {
opts = append(opts, nats.UserCredentials(natsCreds))
} else {
opts = append(opts, nats.UserInfo(natsUser, natsPass))
}
// Open the NATS connection passing the auth account creds file.
nc, err := nats.Connect(natsUrl, opts...)
if err != nil {
return err
}
defer nc.Drain()
// Helper function to construct an authorization response.
respondMsg := func(req micro.Request, userNkey, serverId, userJwt, errMsg string) {
rc := jwt.NewAuthorizationResponseClaims(userNkey)
rc.Audience = serverId
rc.Error = errMsg
rc.Jwt = userJwt
// Sign the response with the issuer account.
token, err := rc.Encode(issuerKeyPair)
if err != nil {
log.Printf("error encoding response JWT: %s", err)
req.Respond(nil)
return
}
data := []byte(token)
// Check if encryption is required.
xkey := req.Headers().Get("Nats-Server-Xkey")
if len(xkey) > 0 {
data, err = curveKeyPair.Seal(data, xkey)
if err != nil {
log.Printf("error encrypting response JWT: %s", err)
req.Respond(nil)
return
}
}
log.Print("responding to authorization request")
req.Respond(data)
}
// Define the message handler for the authorization request.
msgHandler := func(req micro.Request) {
var token []byte
// Check for Xkey header and decrypt
xkey := req.Headers().Get("Nats-Server-Xkey")
if len(xkey) > 0 {
if curveKeyPair == nil {
respondMsg(req, "", "", "", "xkey not supported")
return
}
// Decrypt the message.
token, err = curveKeyPair.Open(req.Data(), xkey)
if err != nil {
respondMsg(req, "", "", "", fmt.Sprintf("error decrypting message: %s", err))
return
}
} else {
token = req.Data()
}
// Decode the authorization request claims.
rc, err := jwt.DecodeAuthorizationRequestClaims(string(token))
if err != nil {
respondMsg(req, "", "", "", err.Error())
return
}
// Used for creating the auth response.
userNkey := rc.UserNkey
serverId := rc.Server.ID
// Check if the user exists.
userProfile, ok := users[rc.ConnectOptions.Username]
if !ok {
respondMsg(req, userNkey, serverId, "", "user not found")
return
}
// Check if the credential is valid.
if userProfile.Pass != rc.ConnectOptions.Password {
respondMsg(req, userNkey, serverId, "", "invalid credentials")
return
}
// Prepare a user JWT.
uc := jwt.NewUserClaims(rc.UserNkey)
uc.Name = rc.ConnectOptions.Username
// Check if signing key is associated, otherwise assume non-operator mode
// and set the audience to the account.
var sk nkeys.KeyPair
signingKey, ok := signingKeys[userProfile.Account]
if !ok {
uc.Audience = userProfile.Account
} else {
sk = signingKey.KeyPair
uc.IssuerAccount = signingKey.PublicKey
}
// Set the associated permissions if present.
uc.Permissions = userProfile.Permissions
// Validate the claims.
vr := jwt.CreateValidationResults()
uc.Validate(vr)
if len(vr.Errors()) > 0 {
respondMsg(req, userNkey, serverId, "", fmt.Sprintf("error validating claims: %s", vr.Errors()))
return
}
// Sign it with the issuer key.
ejwt, err := uc.Encode(sk)
if err != nil {
respondMsg(req, userNkey, serverId, "", fmt.Sprintf("error signing user JWT: %s", err))
return
}
respondMsg(req, userNkey, serverId, ejwt, "")
}
// Create a service for auth callout with an endpoint binding to
// the required subject. This allows for running multiple instances
// to distribute the load, observe stats, and provide high availability.
srv, err := micro.AddService(nc, micro.Config{
Name: "auth-callout",
Version: "0.0.1",
Description: "Auth callout service.",
})
if err != nil {
return err
}
g := srv.
AddGroup("$SYS").
AddGroup("REQ").
AddGroup("USER")
err = g.AddEndpoint("AUTH", micro.HandlerFunc(msgHandler))
if err != nil {
return err
}
// Block and wait for interrupt.
sigch := make(chan os.Signal, 1)
signal.Notify(sigch, os.Interrupt)
<-sigch
return nil
}
type signingKey struct {
PublicKey string
KeyPair nkeys.KeyPair
}
func loadSigningKeys(keyFiles []string) (map[string]*signingKey, error) {
keys := make(map[string]*signingKey)
for _, item := range keyFiles {
toks := strings.Split(item, ":")
if len(toks) != 2 {
return nil, fmt.Errorf("invalid signing key format: %s", item)
}
pk, fname := toks[0], toks[1]
kp, err := fromSeedOrFile(fname)
if err != nil {
return nil, fmt.Errorf("error loading signing key: %s", err)
}
name := strings.SplitN(filepath.Base(fname), ".", 2)[0]
keys[name] = &signingKey{PublicKey: pk, KeyPair: kp}
}
return keys, nil
}
// fromSeedOrFile will attempt to load a keypair from a seed file or
// or a literal seed string.
func fromSeedOrFile(seedOrFile string) (nkeys.KeyPair, error) {
contents, err := ioutil.ReadFile(seedOrFile)
if err != nil {
if os.IsNotExist(err) {
contents = []byte(seedOrFile)
} else {
return nil, fmt.Errorf("failed to read file: %s", err)
}
}
return nkeys.FromSeed(contents)
}
// Model the user encoded in the users file.
type User struct {
Pass string
Account string
Permissions jwt.Permissions
}
// Load and decode the users file.
func loadUsers(usersFile string) (map[string]*User, error) {
users := make(map[string]*User)
data, err := os.ReadFile(usersFile)
if err != nil {
return nil, fmt.Errorf("error reading user directory: %s", err)
}
err = json.Unmarshal(data, &users)
if err != nil {
return nil, fmt.Errorf("error parsing user directory: %s", err)
}
return users, nil
}