Skip to content

Commit

Permalink
Merge branch 'master' into auth_mock
Browse files Browse the repository at this point in the history
  • Loading branch information
zzokki81 committed Aug 3, 2023
2 parents 2083144 + d36fbeb commit a9164c2
Show file tree
Hide file tree
Showing 45 changed files with 1,095 additions and 473 deletions.
309 changes: 206 additions & 103 deletions auth.pb.go

Large diffs are not rendered by default.

8 changes: 5 additions & 3 deletions auth.proto
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ service AuthService {
rpc Issue(IssueReq) returns (Token) {}
rpc Identify(Token) returns (UserIdentity) {}
rpc Authorize(AuthorizeReq) returns (google.protobuf.Empty) {}
rpc CanAccessGroup(AccessGroupReq) returns (google.protobuf.Empty) {}
rpc AddPolicy(PolicyReq) returns (google.protobuf.Empty) {}
rpc Assign(Assignment) returns (google.protobuf.Empty) {}
rpc Members(MembersReq) returns (MembersRes) {}
rpc AssignRole(AssignRoleReq) returns (google.protobuf.Empty) {}
Expand Down Expand Up @@ -82,9 +82,11 @@ message AuthorizeRes {
bool authorized = 1;
}

message AccessGroupReq {
message PolicyReq {
string token = 1;
string groupID = 2;
string policy = 2;
string subject = 3;
string object = 4;
}

message Assignment {
Expand Down
37 changes: 19 additions & 18 deletions auth/api/grpc/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ const (
var _ mainflux.AuthServiceClient = (*grpcClient)(nil)

type grpcClient struct {
issue endpoint.Endpoint
identify endpoint.Endpoint
authorize endpoint.Endpoint
canAccessGroup endpoint.Endpoint
assign endpoint.Endpoint
members endpoint.Endpoint
assignRole endpoint.Endpoint
timeout time.Duration
issue endpoint.Endpoint
identify endpoint.Endpoint
authorize endpoint.Endpoint
addPolicy endpoint.Endpoint
assign endpoint.Endpoint
members endpoint.Endpoint
assignRole endpoint.Endpoint
timeout time.Duration
}

// NewClient returns new gRPC client instance.
Expand Down Expand Up @@ -60,11 +60,11 @@ func NewClient(tracer opentracing.Tracer, conn *grpc.ClientConn, timeout time.Du
decodeEmptyResponse,
empty.Empty{},
).Endpoint()),
canAccessGroup: kitot.TraceClient(tracer, "can_access_group")(kitgrpc.NewClient(
addPolicy: kitot.TraceClient(tracer, "add_policy")(kitgrpc.NewClient(
conn,
svcName,
"CanAccessGroup",
encodeAccessGroupRequest,
"AddPolicy",
encodeAddPolicyRequest,
decodeEmptyResponse,
empty.Empty{},
).Endpoint()),
Expand Down Expand Up @@ -166,11 +166,11 @@ func encodeAuthorizeRequest(_ context.Context, grpcReq interface{}) (interface{}
}, nil
}

func (client grpcClient) CanAccessGroup(ctx context.Context, req *mainflux.AccessGroupReq, opts ...grpc.CallOption) (r *empty.Empty, err error) {
func (client grpcClient) AddPolicy(ctx context.Context, req *mainflux.PolicyReq, opts ...grpc.CallOption) (r *empty.Empty, err error) {
ctx, close := context.WithTimeout(ctx, client.timeout)
defer close()

res, err := client.canAccessGroup(ctx, accessGroupReq{Token: req.GetToken(), GroupID: req.GetGroupID()})
res, err := client.addPolicy(ctx, policyReq{Token: req.GetToken(), Object: req.GetObject(), Policy: req.GetPolicy()})
if err != nil {
return nil, err
}
Expand All @@ -179,11 +179,12 @@ func (client grpcClient) CanAccessGroup(ctx context.Context, req *mainflux.Acces
return &empty.Empty{}, er.err
}

func encodeAccessGroupRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(accessGroupReq)
return &mainflux.AccessGroupReq{
Token: req.Token,
GroupID: req.GroupID,
func encodeAddPolicyRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(policyReq)
return &mainflux.PolicyReq{
Token: req.Token,
Object: req.Object,
Policy: req.Policy,
}, nil
}

Expand Down
8 changes: 4 additions & 4 deletions auth/api/grpc/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func identifyEndpoint(svc auth.Service) endpoint.Endpoint {
id: id.ID,
email: id.Email,
}

return ret, nil
}
}
Expand Down Expand Up @@ -94,14 +94,14 @@ func assignRoleEndpoint(svc auth.Service) endpoint.Endpoint {
}
}

func accessGroupEndpoint(svc auth.Service) endpoint.Endpoint {
func addPolicyEndpoint(svc auth.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(accessGroupReq)
req := request.(policyReq)
if err := req.validate(); err != nil {
return emptyRes{}, err
}

if err := svc.CanAccessGroup(ctx, req.Token, req.GroupID); err != nil {
if err := svc.AddPolicy(ctx, req.Token, req.Object, req.Policy); err != nil {
return emptyRes{}, err
}

Expand Down
24 changes: 17 additions & 7 deletions auth/api/grpc/requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,25 +94,35 @@ func (req authReq) validate() error {
return apiutil.ErrBearerToken
}

if req.Subject == "" {
return apiutil.ErrMissingSubject
if req.Subject != auth.RootSubject && req.Subject != auth.GroupSubject {
return apiutil.ErrInvalidSubject
}

return nil
}

type accessGroupReq struct {
type policyReq struct {
Token string
GroupID string
Policy string
Subject string
Object string
}

func (req accessGroupReq) validate() error {
func (req policyReq) validate() error {
if req.Token == "" {
return apiutil.ErrBearerToken
}

if req.GroupID == "" {
return apiutil.ErrMissingID
if req.Object == "" {
return apiutil.ErrMissingObject
}

if req.Subject != auth.RootSubject && req.Subject != auth.GroupSubject {
return apiutil.ErrInvalidSubject
}

if req.Policy != auth.RPolicy && req.Policy != auth.RwPolicy && req.Policy != "" {
return apiutil.ErrInvalidPolicy
}

return nil
Expand Down
30 changes: 15 additions & 15 deletions auth/api/grpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ import (
var _ mainflux.AuthServiceServer = (*grpcServer)(nil)

type grpcServer struct {
issue kitgrpc.Handler
identify kitgrpc.Handler
authorize kitgrpc.Handler
canAccessGroup kitgrpc.Handler
assign kitgrpc.Handler
members kitgrpc.Handler
assignRole kitgrpc.Handler
issue kitgrpc.Handler
identify kitgrpc.Handler
authorize kitgrpc.Handler
addPolicy kitgrpc.Handler
assign kitgrpc.Handler
members kitgrpc.Handler
assignRole kitgrpc.Handler
}

// NewServer returns new AuthServiceServer instance.
Expand All @@ -48,9 +48,9 @@ func NewServer(tracer opentracing.Tracer, svc auth.Service) mainflux.AuthService
decodeAuthorizeRequest,
encodeEmptyResponse,
),
canAccessGroup: kitgrpc.NewServer(
kitot.TraceServer(tracer, "can_access_group")(accessGroupEndpoint(svc)),
decodeAccessGroupRequest,
addPolicy: kitgrpc.NewServer(
kitot.TraceServer(tracer, "add_policy")(addPolicyEndpoint(svc)),
decodeAddPolicyRequest,
encodeEmptyResponse,
),
assign: kitgrpc.NewServer(
Expand Down Expand Up @@ -95,8 +95,8 @@ func (s *grpcServer) Authorize(ctx context.Context, req *mainflux.AuthorizeReq)
return res.(*empty.Empty), nil
}

func (s *grpcServer) CanAccessGroup(ctx context.Context, req *mainflux.AccessGroupReq) (*empty.Empty, error) {
_, res, err := s.canAccessGroup.ServeGRPC(ctx, req)
func (s *grpcServer) AddPolicy(ctx context.Context, req *mainflux.PolicyReq) (*empty.Empty, error) {
_, res, err := s.addPolicy.ServeGRPC(ctx, req)
if err != nil {
return nil, encodeError(err)
}
Expand Down Expand Up @@ -162,9 +162,9 @@ func decodeAssignRequest(_ context.Context, grpcReq interface{}) (interface{}, e
return assignReq{token: req.GetValue()}, nil
}

func decodeAccessGroupRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(*mainflux.AccessGroupReq)
return accessGroupReq{Token: req.GetToken(), GroupID: req.GetGroupID()}, nil
func decodeAddPolicyRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(*mainflux.PolicyReq)
return policyReq{Token: req.GetToken(), Object: req.GetObject(), Policy: req.GetPolicy()}, nil
}

func decodeMembersRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
Expand Down
6 changes: 3 additions & 3 deletions auth/api/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,17 +289,17 @@ func (lm *loggingMiddleware) ListOrgGroups(ctx context.Context, token, orgID str
return lm.svc.ListOrgGroups(ctx, token, orgID, pm)
}

func (lm *loggingMiddleware) CanAccessGroup(ctx context.Context, token, orgID string) (err error) {
func (lm *loggingMiddleware) AddPolicy(ctx context.Context, token, groupID, policy string) (err error) {
defer func(begin time.Time) {
message := fmt.Sprintf("Method can_access_group for token %s and org id %s took %s to complete", token, orgID, time.Since(begin))
message := fmt.Sprintf("Method add_policy for token %s and took %s to complete", token, time.Since(begin))
if err != nil {
lm.logger.Warn(fmt.Sprintf("%s with error: %s.", message, err))
return
}
lm.logger.Info(fmt.Sprintf("%s without errors.", message))
}(time.Now())

return lm.svc.CanAccessGroup(ctx, token, orgID)
return lm.svc.AddPolicy(ctx, token, groupID, policy)
}

func (lm *loggingMiddleware) Backup(ctx context.Context, token string) (backup auth.Backup, err error) {
Expand Down
8 changes: 4 additions & 4 deletions auth/api/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,13 +206,13 @@ func (ms *metricsMiddleware) ListOrgGroups(ctx context.Context, token, groupID s
return ms.svc.ListOrgGroups(ctx, token, groupID, pm)
}

func (ms *metricsMiddleware) CanAccessGroup(ctx context.Context, token, groupID string) error {
func (ms *metricsMiddleware) AddPolicy(ctx context.Context, token, groupID, policy string) error {
defer func(begin time.Time) {
ms.counter.With("method", "can_access_group").Add(1)
ms.latency.With("method", "can_access_group").Observe(time.Since(begin).Seconds())
ms.counter.With("method", "add_policy").Add(1)
ms.latency.With("method", "add_policy").Observe(time.Since(begin).Seconds())
}(time.Now())

return ms.svc.CanAccessGroup(ctx, token, groupID)
return ms.svc.AddPolicy(ctx, token, groupID, policy)
}

func (ms *metricsMiddleware) Backup(ctx context.Context, token string) (auth.Backup, error) {
Expand Down
16 changes: 16 additions & 0 deletions auth/mocks/orgs.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,22 @@ func (orm *orgRepositoryMock) RetrieveAllGroupRelations(ctx context.Context) ([]
return grs, nil
}

func (orm *orgRepositoryMock) SavePolicy(ctx context.Context, memberID string, policy string, groupIDs ...string) error {
panic("not implemented")
}

func (orm *orgRepositoryMock) RetrievePolicy(ctx context.Context, gp auth.GroupsPolicy) (string, error) {
panic("not implemented")
}

func (orm *orgRepositoryMock) UpdatePolicy(ctx context.Context, gp auth.GroupsPolicy) error {
panic("not implemented")
}

func (orm *orgRepositoryMock) RemovePolicy(ctx context.Context, gp auth.GroupsPolicy) error {
panic("not implemented")
}

func sortOrgsByID(orgs map[string]auth.Org) []string {
var keys []string
for k := range orgs {
Expand Down
18 changes: 18 additions & 0 deletions auth/orgs.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,12 @@ type GroupRelationsPage struct {
GroupRelations []GroupRelation
}

type GroupsPolicy struct {
GroupID string
MemberID string
Policy string
}

type Member struct {
ID string `json:"id"`
Role string `json:"role"`
Expand Down Expand Up @@ -235,4 +241,16 @@ type OrgRepository interface {

// RetrieveAllGroupRelations retrieves all group relations.
RetrieveAllGroupRelations(ctx context.Context) ([]GroupRelation, error)

// SavePolicy saves group policy for a user.
SavePolicy(ctx context.Context, memberID, policy string, groupID ...string) error

// RetrievePolicy retrieves group policy for a user.
RetrievePolicy(ctc context.Context, gp GroupsPolicy) (string, error)

// RemovePolicy removes group policy for a user.
RemovePolicy(ctx context.Context, gp GroupsPolicy) error

// UpdatePolicy updates group policy for a user.
UpdatePolicy(ctx context.Context, gp GroupsPolicy) error
}
21 changes: 17 additions & 4 deletions auth/postgres/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,15 +108,28 @@ func migrateDB(db *sqlx.DB) error {
Id: "auth_4",
Up: []string{
`CREATE TABLE IF NOT EXISTS users_roles (
role VARCHAR(12) CHECK (role IN ('root', 'admin')),
user_id UUID NOT NULL,
PRIMARY KEY (user_id)
)`,
role VARCHAR(12) CHECK (role IN ('root', 'admin')),
user_id UUID NOT NULL,
PRIMARY KEY (user_id)
)`,
},
Down: []string{
"DROP TABLE users_roles",
},
},
{
Id: "auth_5",
Up: []string{
`CREATE TABLE IF NOT EXISTS group_policies (
group_id UUID UNIQUE NOT NULL,
member_id UUID NOT NULL,
policy VARCHAR(15)
)`,
},
Down: []string{
`DROP TABLE IF EXISTS group_policies`,
},
},
},
}

Expand Down
Loading

0 comments on commit a9164c2

Please sign in to comment.