-
Notifications
You must be signed in to change notification settings - Fork 43
/
importuser.go
176 lines (165 loc) · 4.96 KB
/
importuser.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
/*
* Copyright 2018-2023 The NATS Authors
* 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 cmd
import (
"os"
"strings"
"github.com/nats-io/jwt/v2"
"github.com/nats-io/nkeys"
"github.com/spf13/cobra"
"github.com/nats-io/nsc/v2/cmd/store"
)
func createImportUserCmd() *cobra.Command {
var params ImportUser
cmd := &cobra.Command{
Use: "user --file <user-jwt/user-creds>",
Short: "Imports an user from a jwt or user and nkey from a creds file",
Example: `nsc import user --file <account-jwt>`,
Args: MaxArgs(0),
SilenceUsage: false,
RunE: func(cmd *cobra.Command, args []string) error {
if err := RunMaybeStorelessAction(cmd, args, ¶ms); err != nil {
return err
}
return nil
},
}
cmd.Flags().BoolVarP(¶ms.skip, "skip", "", false, "skip validation issues")
cmd.Flags().BoolVarP(¶ms.overwrite, "overwrite", "", false, "overwrite existing user")
cmd.Flags().StringVarP(¶ms.file, "file", "f", "", "user jwt or creds to import")
return cmd
}
func init() {
importCmd.AddCommand(createImportUserCmd())
}
type ImportUser struct {
fileImport
}
func (p *ImportUser) SetDefaults(_ctx ActionCtx) error {
return nil
}
func (p *ImportUser) Validate(ctx ActionCtx) error {
return p.fileImport.Validate(ctx, ".jwt", ".creds")
}
// returns true when blocking and not skipped
func validateAndReport(claim jwt.Claims, force bool, r *store.Report) bool {
vr := jwt.ValidationResults{}
claim.Validate(&vr)
for _, i := range vr.Issues {
if i.Blocking {
r.AddError("validation resulted in: %s", i.Description)
} else {
r.AddWarning("validation resulted in: %s", i.Description)
}
}
if vr.IsBlocking(true) && !force {
r.AddError("validation is blocking, skip with --skip")
return true
}
return false
}
func (p *ImportUser) Run(ctx ActionCtx) (store.Status, error) {
r := store.NewDetailedReport(true)
content, err := os.ReadFile(p.file)
if err != nil {
r.AddError("failed to import %#q: %v", p.file, err)
return r, err
}
theJWT := strings.TrimSpace(string(content))
var kp nkeys.KeyPair
if !strings.HasPrefix(theJWT, "ey") {
theJWT, err = jwt.ParseDecoratedJWT(content)
if err != nil {
r.AddError("failed to parse decorated JWT in %q: %v", p.file, err)
return r, err
}
if kp, err = jwt.ParseDecoratedUserNKey(content); err != nil {
r.AddWarning("failed to parse decorated key in %#q: %v", p.file, err)
}
}
claim, err := jwt.DecodeUserClaims(theJWT)
if err != nil {
r.AddError("failed to decode %#q: %v", p.file, err)
return r, err
}
if validateAndReport(claim, p.skip, r) {
return r, err
}
acc := claim.IssuerAccount
if acc == "" {
acc = claim.Issuer
}
var accClaim *jwt.AccountClaims
accs, _ := ctx.StoreCtx().Store.ListSubContainers(store.Accounts)
for _, accName := range accs {
accClaim, _ = ctx.StoreCtx().Store.ReadAccountClaim(accName)
if accClaim.Subject != acc {
accClaim = nil
} else {
break
}
}
if accClaim == nil {
r.AddError("referenced Account %s not found, import first", acc)
return r, nil
}
if ctx.StoreCtx().Store.Has(store.Accounts, accClaim.Name, store.Users, store.JwtName(claim.Name)) {
if !p.overwrite {
r.AddError("user already exists, overwrite with --overwrite")
return r, nil
}
if old, err := ctx.StoreCtx().Store.ReadUserClaim(accClaim.Name, claim.Name); err != nil {
r.AddError("existing User not found: %v", err)
return r, nil
} else if old.Subject != claim.Subject {
r.AddError("existing User has a name collision only and does not reference the same entity "+
"(Subject is %s and differs from %s). This problem needs to be resolved manually.",
old.Subject, claim.Subject)
return r, nil
}
}
sameAccount := false
keys := []string{accClaim.Subject}
keys = append(keys, accClaim.SigningKeys.Keys()...)
for _, key := range keys {
if key == claim.Issuer {
sameAccount = true
break
}
}
if !sameAccount {
r.AddError("can only import user signed by exiting account. Possibly update your account")
return r, nil
}
if kp != nil {
keyPath, err := ctx.StoreCtx().KeyStore.Store(kp)
if err != nil {
r.AddError("key could not be stored: %v", err)
return r, nil
}
r.AddOK("key stored %s", keyPath)
}
sub, err := ctx.StoreCtx().Store.StoreClaim([]byte(theJWT))
if err != nil {
r.AddError("Error when storing user: %v", err)
}
r.Add(sub)
if r.HasNoErrors() {
r.AddOK("user %s was successfully imported", claim.Name)
} else {
r.AddOK("user %s was not imported: %v", claim.Name, err)
}
return r, nil
}