-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc.go
289 lines (246 loc) · 8.33 KB
/
grpc.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
package server
import (
"context"
"fmt"
"net"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
authz "github.com/chef/automate/api/interservice/authz/common"
"github.com/chef/automate/api/interservice/local_user"
teams "github.com/chef/automate/api/interservice/teams/v1"
"github.com/chef/automate/components/local-user-service/constants"
"github.com/chef/automate/components/local-user-service/users"
"github.com/chef/automate/lib/grpc/health"
"github.com/chef/automate/lib/tracing"
uuid "github.com/chef/automate/lib/uuid4"
)
// NewGRPCServer returns a server that provides our services: clients, users,
// and authentication requests.
func (s *Server) NewGRPCServer() *grpc.Server {
g := s.connFactory.NewServer(
grpc.UnaryInterceptor(
grpc_middleware.ChainUnaryServer(
tracing.ServerInterceptor(tracing.GlobalTracer()),
inputValidationInterceptor(),
),
),
)
local_user.RegisterUsersMgmtServer(g, s)
health.RegisterHealthServer(g, s.health)
reflection.Register(g)
return g
}
func inputValidationInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context,
req interface{},
_ *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {
if req, ok := req.(interface {
Validate() error
}); ok {
if err := req.Validate(); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
}
return handler(ctx, req)
}
}
// GRPC serves the GRPC API for all services. On success, it never returns.
func (s *Server) GRPC(addr string) error {
list, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return s.NewGRPCServer().Serve(list)
}
// GetUsers fetches hash of users, implemented without wrapping usersAPI struct
func (s *Server) GetUsers(ctx context.Context, _ *local_user.GetUsersReq) (*local_user.Users, error) {
us, err := s.users.GetUsers(ctx)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
users := map[string]*local_user.User{}
for _, user := range us {
users[user.Email] = toUserResp(&user)
}
resp := local_user.Users{
Users: users,
}
return &resp, nil
}
// GetUser fetches user by email, which dex uses as unique identifier
func (s *Server) GetUser(ctx context.Context, req *local_user.Email) (*local_user.User, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
us, err := s.users.GetUser(ctx, req.Email)
if err != nil {
if _, ok := errors.Cause(err).(*users.NotFoundError); ok {
return nil, status.Error(codes.NotFound, err.Error())
}
return nil, status.Error(codes.Internal, err.Error())
}
return toUserResp(us), nil
}
// CreateUser adds a user with a generated UUID to dex
func (s *Server) CreateUser(ctx context.Context, req *local_user.CreateUserReq) (*local_user.User, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if err := s.validator.Validate(req.Password); err != nil {
return nil, status.Errorf(codes.InvalidArgument, constants.PasswordValidationErrorFormat, err)
}
id, err := uuid.NewV4()
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
newUser := users.User{
ID: id.String(),
Name: req.Name,
Email: req.Email,
Password: req.Password,
}
us, err := s.users.CreateUser(ctx, newUser)
if err != nil {
if _, ok := errors.Cause(err).(*users.AlreadyExistsError); ok {
return nil, status.Error(codes.AlreadyExists, err.Error())
}
return nil, status.Error(codes.Internal, err.Error())
}
return toUserResp(us), nil
}
// DeleteUser deletes user from dex
func (s *Server) DeleteUser(ctx context.Context, req *local_user.Email) (*local_user.DeleteUserResp, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
us, err := s.users.GetUser(ctx, req.Email)
if err != nil {
if _, ok := errors.Cause(err).(*users.NotFoundError); ok {
return nil, status.Error(codes.NotFound, err.Error())
}
return nil, status.Error(codes.Internal, err.Error())
}
_, err = s.users.DeleteUser(ctx, req.Email)
if err != nil {
if _, ok := errors.Cause(err).(*users.NotFoundError); ok {
return nil, status.Error(codes.NotFound, err.Error())
}
return nil, status.Error(codes.Internal, err.Error())
}
purgeReq := &teams.PurgeUserMembershipReq{
UserId: us.ID,
}
_, err = s.teamsClient.PurgeUserMembership(ctx, purgeReq)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
authzPurgeReq := &authz.PurgeSubjectFromPoliciesReq{
Subject: "user:local:" + us.Name,
}
_, err = s.authzClient.PurgeSubjectFromPolicies(ctx, authzPurgeReq)
if err != nil {
s.logger.Warn(fmt.Sprintf("failed to purge subjects on user delete: %s", err.Error()))
return nil, status.Error(codes.Internal,
fmt.Sprintf("the user named %s with id %s was successfully deleted but its "+
"subject could not be purged from the policies: %s", us.Name, us.ID, err.Error()))
}
return &local_user.DeleteUserResp{}, nil
}
// UpdateSelf updates the user's name and, optionally, password.
// If password is updated, the user must provide the previous_password.
func (s *Server) UpdateSelf(ctx context.Context, req *local_user.UpdateSelfReq) (*local_user.User, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
updateUser := users.UserWithHashedPass{ShowUser: users.ShowUser{
Name: req.Name,
Email: req.Email,
ID: req.Id,
},
}
if req.Password != "" {
if req.PreviousPassword == "" {
return nil, status.Error(codes.InvalidArgument,
"to update existing password, provide previous password")
}
// check if previous password is OK
s.logger.Info(fmt.Sprintf("attempting to validate user %s by logging in so we can update their password", req.Email))
ok, err := s.users.ValidatePassword(ctx, req.Email, req.PreviousPassword)
if err != nil {
return nil, status.Error(codes.Internal, "could not validate previous password")
}
if !ok {
// Note: this could be used for guessing passwords; however, to guess a
// password using this API, the sender needs some kind of authentication
// already. You can also guess passwords completely unauthenticated by
// just querying dex.
return nil, status.Error(codes.InvalidArgument, "previous password does not match")
}
// If successful, we are set to update using the new hashed password.
updatedHash, err := s.validateAndHashPassword(ctx, req.Password)
if err != nil {
return nil, err
}
updateUser.HashedPass = updatedHash
}
us, err := s.updateUserOrParseError(ctx, updateUser)
if err != nil {
return nil, err
}
return toUserResp(us), nil
}
// UpdateUser updates the user's name and, optionally, password.
func (s *Server) UpdateUser(ctx context.Context, req *local_user.UpdateUserReq) (*local_user.User, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
updateUser := users.UserWithHashedPass{ShowUser: users.ShowUser{
Name: req.Name,
Email: req.Email,
ID: req.Id,
},
}
// Update hash if we want a new password, otherwise pass empty hash to dex.
if req.Password != "" {
updatedHash, err := s.validateAndHashPassword(ctx, req.Password)
s.logger.Warn(fmt.Sprintf("updated: %v", updatedHash))
if err != nil {
return nil, err
}
updateUser.HashedPass = updatedHash
}
us, err := s.updateUserOrParseError(ctx, updateUser)
if err != nil {
return nil, err
}
return toUserResp(us), nil
}
func (s *Server) validateAndHashPassword(_ context.Context, password string) ([]byte, error) {
if err := s.validator.Validate(password); err != nil {
return nil, status.Errorf(codes.InvalidArgument, constants.PasswordValidationErrorFormat, err)
}
hashedPass, err := s.users.HashPassword(password)
if err != nil {
return nil, status.Error(codes.Internal,
errors.Wrap(err, "generate hashed password").Error())
}
return hashedPass, nil
}
func (s *Server) updateUserOrParseError(ctx context.Context,
updateUser users.UserWithHashedPass) (*users.ShowUser, error) {
us, err := s.users.UpdateUser(ctx, updateUser)
if err != nil {
if _, ok := errors.Cause(err).(*users.NotFoundError); ok {
return nil, status.Error(codes.NotFound, err.Error())
}
return nil, status.Error(codes.Internal, err.Error())
}
return us, nil
}
func toUserResp(u *users.ShowUser) *local_user.User {
return &local_user.User{
Id: u.ID,
Name: u.Name,
Email: u.Email,
}
}