Skip to content

Commit

Permalink
MG-2410 - Add wrapper for authN/authZ (#2411)
Browse files Browse the repository at this point in the history
Signed-off-by: 1998-felix <[email protected]>
  • Loading branch information
felixgateru authored and dborovcanin committed Sep 10, 2024
1 parent 762d622 commit b5c11c3
Show file tree
Hide file tree
Showing 21 changed files with 400 additions and 209 deletions.
170 changes: 1 addition & 169 deletions auth/api/grpc/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"time"

"github.com/absmach/magistrala"
"github.com/absmach/magistrala/auth"
"github.com/absmach/magistrala/pkg/errors"
svcerr "github.com/absmach/magistrala/pkg/errors/service"
"github.com/go-kit/kit/endpoint"
Expand All @@ -25,174 +24,7 @@ const (
policySvcName = "magistrala.PolicyService"
)

var (
_ AuthServiceClient = (*authGrpcClient)(nil)
_ magistrala.PolicyServiceClient = (*policyGrpcClient)(nil)
)

//go:generate mockery --name AuthServiceClient --output=../../mocks --filename auth_client.go --quiet --note "Copyright (c) Abstract Machines"
type AuthServiceClient interface {
magistrala.AuthzServiceClient
magistrala.AuthnServiceClient
}

type authGrpcClient struct {
issue endpoint.Endpoint
refresh endpoint.Endpoint
identify endpoint.Endpoint
authorize endpoint.Endpoint
timeout time.Duration
}

// NewAuthClient returns new auth gRPC client instance.
func NewAuthClient(conn *grpc.ClientConn, timeout time.Duration) AuthServiceClient {
return &authGrpcClient{
issue: kitgrpc.NewClient(
conn,
authnSvcName,
"Issue",
encodeIssueRequest,
decodeIssueResponse,
magistrala.Token{},
).Endpoint(),
refresh: kitgrpc.NewClient(
conn,
authnSvcName,
"Refresh",
encodeRefreshRequest,
decodeRefreshResponse,
magistrala.Token{},
).Endpoint(),
identify: kitgrpc.NewClient(
conn,
authnSvcName,
"Identify",
encodeIdentifyRequest,
decodeIdentifyResponse,
magistrala.IdentityRes{},
).Endpoint(),
authorize: kitgrpc.NewClient(
conn,
authzSvcName,
"Authorize",
encodeAuthorizeRequest,
decodeAuthorizeResponse,
magistrala.AuthorizeRes{},
).Endpoint(),
timeout: timeout,
}
}

func (client authGrpcClient) Issue(ctx context.Context, req *magistrala.IssueReq, _ ...grpc.CallOption) (*magistrala.Token, error) {
ctx, cancel := context.WithTimeout(ctx, client.timeout)
defer cancel()

res, err := client.issue(ctx, issueReq{
userID: req.GetUserId(),
domainID: req.GetDomainId(),
keyType: auth.KeyType(req.GetType()),
})
if err != nil {
return &magistrala.Token{}, decodeError(err)
}
return res.(*magistrala.Token), nil
}

func encodeIssueRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(issueReq)
return &magistrala.IssueReq{
UserId: req.userID,
DomainId: &req.domainID,
Type: uint32(req.keyType),
}, nil
}

func decodeIssueResponse(_ context.Context, grpcRes interface{}) (interface{}, error) {
return grpcRes, nil
}

func (client authGrpcClient) Refresh(ctx context.Context, req *magistrala.RefreshReq, _ ...grpc.CallOption) (*magistrala.Token, error) {
ctx, cancel := context.WithTimeout(ctx, client.timeout)
defer cancel()

res, err := client.refresh(ctx, refreshReq{refreshToken: req.GetRefreshToken(), domainID: req.GetDomainId()})
if err != nil {
return &magistrala.Token{}, decodeError(err)
}
return res.(*magistrala.Token), nil
}

func encodeRefreshRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(refreshReq)
return &magistrala.RefreshReq{RefreshToken: req.refreshToken, DomainId: &req.domainID}, nil
}

func decodeRefreshResponse(_ context.Context, grpcRes interface{}) (interface{}, error) {
return grpcRes, nil
}

func (client authGrpcClient) Identify(ctx context.Context, token *magistrala.IdentityReq, _ ...grpc.CallOption) (*magistrala.IdentityRes, error) {
ctx, cancel := context.WithTimeout(ctx, client.timeout)
defer cancel()

res, err := client.identify(ctx, identityReq{token: token.GetToken()})
if err != nil {
return &magistrala.IdentityRes{}, decodeError(err)
}
ir := res.(identityRes)
return &magistrala.IdentityRes{Id: ir.id, UserId: ir.userID, DomainId: ir.domainID}, nil
}

func encodeIdentifyRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(identityReq)
return &magistrala.IdentityReq{Token: req.token}, nil
}

func decodeIdentifyResponse(_ context.Context, grpcRes interface{}) (interface{}, error) {
res := grpcRes.(*magistrala.IdentityRes)
return identityRes{id: res.GetId(), userID: res.GetUserId(), domainID: res.GetDomainId()}, nil
}

func (client authGrpcClient) Authorize(ctx context.Context, req *magistrala.AuthorizeReq, _ ...grpc.CallOption) (r *magistrala.AuthorizeRes, err error) {
ctx, cancel := context.WithTimeout(ctx, client.timeout)
defer cancel()

res, err := client.authorize(ctx, authReq{
Domain: req.GetDomain(),
SubjectType: req.GetSubjectType(),
Subject: req.GetSubject(),
SubjectKind: req.GetSubjectKind(),
Relation: req.GetRelation(),
Permission: req.GetPermission(),
ObjectType: req.GetObjectType(),
Object: req.GetObject(),
})
if err != nil {
return &magistrala.AuthorizeRes{}, decodeError(err)
}

ar := res.(authorizeRes)
return &magistrala.AuthorizeRes{Authorized: ar.authorized, Id: ar.id}, nil
}

func decodeAuthorizeResponse(_ context.Context, grpcRes interface{}) (interface{}, error) {
res := grpcRes.(*magistrala.AuthorizeRes)
return authorizeRes{authorized: res.Authorized, id: res.Id}, nil
}

func encodeAuthorizeRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
req := grpcReq.(authReq)
return &magistrala.AuthorizeReq{
Domain: req.Domain,
SubjectType: req.SubjectType,
Subject: req.Subject,
SubjectKind: req.SubjectKind,
Relation: req.Relation,
Permission: req.Permission,
ObjectType: req.ObjectType,
Object: req.Object,
}, nil
}
var _ magistrala.PolicyServiceClient = (*policyGrpcClient)(nil)

type policyGrpcClient struct {
deleteUserPolicies endpoint.Endpoint
Expand Down
9 changes: 5 additions & 4 deletions auth/api/grpc/endpoint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/absmach/magistrala"
"github.com/absmach/magistrala/auth"
grpcapi "github.com/absmach/magistrala/auth/api/grpc"
client "github.com/absmach/magistrala/internal/auth"
"github.com/absmach/magistrala/internal/testsutil"
"github.com/absmach/magistrala/pkg/apiutil"
"github.com/absmach/magistrala/pkg/errors"
Expand Down Expand Up @@ -65,7 +66,7 @@ func startGRPCServer(svc auth.Service, port int) {
func TestIssue(t *testing.T) {
conn, err := grpc.NewClient(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
assert.Nil(t, err, fmt.Sprintf("Unexpected error creating client connection %s", err))
client := grpcapi.NewAuthClient(conn, time.Second)
client := client.NewAuthClient(conn, time.Second)

cases := []struct {
desc string
Expand Down Expand Up @@ -134,7 +135,7 @@ func TestIssue(t *testing.T) {
func TestRefresh(t *testing.T) {
conn, err := grpc.NewClient(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
assert.Nil(t, err, fmt.Sprintf("Unexpected error creating client connection %s", err))
client := grpcapi.NewAuthClient(conn, time.Second)
client := client.NewAuthClient(conn, time.Second)

cases := []struct {
desc string
Expand Down Expand Up @@ -180,7 +181,7 @@ func TestRefresh(t *testing.T) {
func TestIdentify(t *testing.T) {
conn, err := grpc.NewClient(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
assert.Nil(t, err, fmt.Sprintf("Unexpected error creating client connection %s", err))
client := grpcapi.NewAuthClient(conn, time.Second)
client := client.NewAuthClient(conn, time.Second)

cases := []struct {
desc string
Expand Down Expand Up @@ -224,7 +225,7 @@ func TestIdentify(t *testing.T) {
func TestAuthorize(t *testing.T) {
conn, err := grpc.NewClient(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
assert.Nil(t, err, fmt.Sprintf("Unexpected error creating client connection %s", err))
client := grpcapi.NewAuthClient(conn, time.Second)
client := client.NewAuthClient(conn, time.Second)

cases := []struct {
desc string
Expand Down
6 changes: 3 additions & 3 deletions bootstrap/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (

"github.com/absmach/magistrala"
"github.com/absmach/magistrala/auth"
grpcclient "github.com/absmach/magistrala/auth/api/grpc"
authclient "github.com/absmach/magistrala/pkg/auth"
"github.com/absmach/magistrala/pkg/errors"
repoerr "github.com/absmach/magistrala/pkg/errors/repository"
svcerr "github.com/absmach/magistrala/pkg/errors/service"
Expand Down Expand Up @@ -121,7 +121,7 @@ type ConfigReader interface {
}

type bootstrapService struct {
auth grpcclient.AuthServiceClient
auth authclient.AuthClient
policy policy.PolicyClient
configs ConfigRepository
sdk mgsdk.SDK
Expand All @@ -130,7 +130,7 @@ type bootstrapService struct {
}

// New returns new Bootstrap service.
func New(authClient grpcclient.AuthServiceClient, policyClient policy.PolicyClient, configs ConfigRepository, sdk mgsdk.SDK, encKey []byte, idp magistrala.IDProvider) Service {
func New(authClient authclient.AuthClient, policyClient policy.PolicyClient, configs ConfigRepository, sdk mgsdk.SDK, encKey []byte, idp magistrala.IDProvider) Service {
return &bootstrapService{
configs: configs,
sdk: sdk,
Expand Down
4 changes: 2 additions & 2 deletions cmd/bootstrap/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

chclient "github.com/absmach/callhome/pkg/client"
"github.com/absmach/magistrala"
authclient "github.com/absmach/magistrala/auth/api/grpc"
authclient "github.com/absmach/magistrala/pkg/auth"
"github.com/absmach/magistrala/bootstrap"
"github.com/absmach/magistrala/bootstrap/api"
"github.com/absmach/magistrala/bootstrap/events/consumer"
Expand Down Expand Up @@ -190,7 +190,7 @@ func main() {
}
}

func newService(ctx context.Context, authClient authclient.AuthServiceClient, policyClient policy.PolicyClient, db *sqlx.DB, tracer trace.Tracer, logger *slog.Logger, cfg config, dbConfig pgclient.Config) (bootstrap.Service, error) {
func newService(ctx context.Context, authClient authclient.AuthClient, policyClient policy.PolicyClient, db *sqlx.DB, tracer trace.Tracer, logger *slog.Logger, cfg config, dbConfig pgclient.Config) (bootstrap.Service, error) {
database := postgres.NewDatabase(db, dbConfig, tracer)

repoConfig := bootstrappg.NewConfigRepository(database, logger)
Expand Down
4 changes: 2 additions & 2 deletions cmd/invitations/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ import (

chclient "github.com/absmach/callhome/pkg/client"
"github.com/absmach/magistrala"
authclient "github.com/absmach/magistrala/auth/api/grpc"
"github.com/absmach/magistrala/invitations"
"github.com/absmach/magistrala/invitations/api"
"github.com/absmach/magistrala/invitations/middleware"
invitationspg "github.com/absmach/magistrala/invitations/postgres"
mglog "github.com/absmach/magistrala/logger"
authclient "github.com/absmach/magistrala/pkg/auth"
"github.com/absmach/magistrala/pkg/grpcclient"
"github.com/absmach/magistrala/pkg/jaeger"
"github.com/absmach/magistrala/pkg/postgres"
Expand Down Expand Up @@ -155,7 +155,7 @@ func main() {
}
}

func newService(db *sqlx.DB, dbConfig clientspg.Config, authClient authclient.AuthServiceClient, tracer trace.Tracer, conf config, logger *slog.Logger) (invitations.Service, error) {
func newService(db *sqlx.DB, dbConfig clientspg.Config, authClient authclient.AuthClient, tracer trace.Tracer, conf config, logger *slog.Logger) (invitations.Service, error) {
database := postgres.NewDatabase(db, dbConfig, tracer)
repo := invitationspg.NewRepository(database)

Expand Down
4 changes: 2 additions & 2 deletions cmd/journal/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ import (

chclient "github.com/absmach/callhome/pkg/client"
"github.com/absmach/magistrala"
authclient "github.com/absmach/magistrala/auth/api/grpc"
"github.com/absmach/magistrala/journal"
"github.com/absmach/magistrala/journal/api"
"github.com/absmach/magistrala/journal/events"
"github.com/absmach/magistrala/journal/middleware"
journalpg "github.com/absmach/magistrala/journal/postgres"
mglog "github.com/absmach/magistrala/logger"
authclient "github.com/absmach/magistrala/pkg/auth"
"github.com/absmach/magistrala/pkg/events/store"
"github.com/absmach/magistrala/pkg/grpcclient"
jaegerclient "github.com/absmach/magistrala/pkg/jaeger"
Expand Down Expand Up @@ -167,7 +167,7 @@ func main() {
}
}

func newService(db *sqlx.DB, dbConfig pgclient.Config, authClient authclient.AuthServiceClient, logger *slog.Logger, tracer trace.Tracer) journal.Service {
func newService(db *sqlx.DB, dbConfig pgclient.Config, authClient authclient.AuthClient, logger *slog.Logger, tracer trace.Tracer) journal.Service {
database := postgres.NewDatabase(db, dbConfig, tracer)
repo := journalpg.NewRepository(database)
idp := uuid.New()
Expand Down
6 changes: 3 additions & 3 deletions cmd/things/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (

chclient "github.com/absmach/callhome/pkg/client"
"github.com/absmach/magistrala"
authclient "github.com/absmach/magistrala/auth/api/grpc"
redisclient "github.com/absmach/magistrala/internal/clients/redis"
mggroups "github.com/absmach/magistrala/internal/groups"
gapi "github.com/absmach/magistrala/internal/groups/api"
Expand All @@ -24,6 +23,7 @@ import (
gtracing "github.com/absmach/magistrala/internal/groups/tracing"
mgpolicy "github.com/absmach/magistrala/internal/policy"
mglog "github.com/absmach/magistrala/logger"
authclient "github.com/absmach/magistrala/pkg/auth"
"github.com/absmach/magistrala/pkg/groups"
"github.com/absmach/magistrala/pkg/grpcclient"
jaegerclient "github.com/absmach/magistrala/pkg/jaeger"
Expand Down Expand Up @@ -155,7 +155,7 @@ func main() {
defer cacheclient.Close()

var (
authClient authclient.AuthServiceClient
authClient authclient.AuthClient
policyClient policy.PolicyClient
)
switch cfg.StandaloneID != "" && cfg.StandaloneToken != "" {
Expand Down Expand Up @@ -241,7 +241,7 @@ func main() {
}
}

func newService(ctx context.Context, db *sqlx.DB, dbConfig pgclient.Config, authClient authclient.AuthServiceClient, policyClient policy.PolicyClient, cacheClient *redis.Client, keyDuration time.Duration, esURL string, tracer trace.Tracer, logger *slog.Logger) (things.Service, groups.Service, error) {
func newService(ctx context.Context, db *sqlx.DB, dbConfig pgclient.Config, authClient authclient.AuthClient, policyClient policy.PolicyClient, cacheClient *redis.Client, keyDuration time.Duration, esURL string, tracer trace.Tracer, logger *slog.Logger) (things.Service, groups.Service, error) {
database := postgres.NewDatabase(db, dbConfig, tracer)
cRepo := thingspg.NewRepository(database)
gRepo := gpostgres.New(database)
Expand Down
6 changes: 3 additions & 3 deletions cmd/users/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
chclient "github.com/absmach/callhome/pkg/client"
"github.com/absmach/magistrala"
authSvc "github.com/absmach/magistrala/auth"
authclient "github.com/absmach/magistrala/auth/api/grpc"
"github.com/absmach/magistrala/internal/email"
mggroups "github.com/absmach/magistrala/internal/groups"
gapi "github.com/absmach/magistrala/internal/groups/api"
Expand All @@ -26,6 +25,7 @@ import (
gtracing "github.com/absmach/magistrala/internal/groups/tracing"
mgpolicy "github.com/absmach/magistrala/internal/policy"
mglog "github.com/absmach/magistrala/logger"
authclient "github.com/absmach/magistrala/pkg/auth"
mgclients "github.com/absmach/magistrala/pkg/clients"
"github.com/absmach/magistrala/pkg/groups"
"github.com/absmach/magistrala/pkg/grpcclient"
Expand Down Expand Up @@ -235,7 +235,7 @@ func main() {
}
}

func newService(ctx context.Context, authClient authclient.AuthServiceClient, authPolicyClient magistrala.PolicyServiceClient, policyClient policy.PolicyClient, db *sqlx.DB, dbConfig pgclient.Config, tracer trace.Tracer, c config, ec email.Config, logger *slog.Logger) (users.Service, groups.Service, error) {
func newService(ctx context.Context, authClient authclient.AuthClient, authPolicyClient magistrala.PolicyServiceClient, policyClient policy.PolicyClient, db *sqlx.DB, dbConfig pgclient.Config, tracer trace.Tracer, c config, ec email.Config, logger *slog.Logger) (users.Service, groups.Service, error) {
database := postgres.NewDatabase(db, dbConfig, tracer)
cRepo := clientspg.NewRepository(database)
gRepo := gpostgres.New(database)
Expand Down Expand Up @@ -323,7 +323,7 @@ func createAdmin(ctx context.Context, c config, crepo clientspg.Repository, hsr
return client.ID, nil
}

func createAdminPolicy(ctx context.Context, clientID string, authClient authclient.AuthServiceClient, policyService policy.PolicyClient) error {
func createAdminPolicy(ctx context.Context, clientID string, authClient authclient.AuthClient, policyService policy.PolicyClient) error {
res, err := authClient.Authorize(ctx, &magistrala.AuthorizeReq{
SubjectType: authSvc.UserType,
Subject: clientID,
Expand Down
Loading

0 comments on commit b5c11c3

Please sign in to comment.