diff --git a/deployments/docker-compose.dev.yaml b/deployments/docker-compose.dev.yaml index bd72e2e50..1873cc2f7 100644 --- a/deployments/docker-compose.dev.yaml +++ b/deployments/docker-compose.dev.yaml @@ -3,11 +3,13 @@ services: rabbit: container_name: rabbit image: rabbitmq:3-management + network_mode: "host" ports: - "5672:5672" - "15672:15672" postgresql: container_name: postgresql + network_mode: "host" image: postgres:12 ports: - "5432:5432" @@ -30,10 +32,11 @@ services: - "rabbit" restart: always container_name: horusec-messages + network_mode: "host" ports: - "8004:8004" environment: - HORUSEC_BROKER_HOST: rabbit + HORUSEC_BROKER_HOST: "127.0.0.1" HORUSEC_BROKER_PORT: "5672" HORUSEC_BROKER_USERNAME: "guest" HORUSEC_BROKER_PASSWORD: "guest" @@ -52,18 +55,19 @@ services: - postgresql restart: always container_name: horusec-account + network_mode: "host" ports: - "8003:8003" environment: HORUSEC_ACCOUNT_DISABLE_EMAIL_SERVICE: "true" - HORUSEC_BROKER_HOST: rabbit + HORUSEC_BROKER_HOST: "127.0.0.1" HORUSEC_BROKER_PORT: "5672" HORUSEC_BROKER_USERNAME: "guest" HORUSEC_BROKER_PASSWORD: "guest" - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" HORUSEC_JWT_SECRET_KEY: "horusec-secret" - HORUSEC_AUTH_URL: "http://horusec-auth:8006" + HORUSEC_AUTH_URL: "127.0.0.1:8007" horusec-auth: build: context: ../ @@ -72,10 +76,12 @@ services: - postgresql restart: always container_name: horusec-auth + network_mode: "host" ports: - "8006:8006" + - "8007:8007" environment: - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" HORUSEC_JWT_SECRET_KEY: "horusec-secret" HORUSEC_KEYCLOAK_BASE_PATH: ${HORUSEC_KEYCLOAK_BASE_PATH} @@ -93,12 +99,13 @@ services: - postgresql restart: always container_name: horusec-analytic + network_mode: "host" ports: - "8005:8005" environment: - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" - HORUSEC_AUTH_URL: "http://horusec-auth:8006" + HORUSEC_AUTH_URL: "127.0.0.1:8007" horusec-api: build: context: ../ @@ -108,13 +115,14 @@ services: - postgresql restart: always container_name: horusec-api + network_mode: "host" ports: - "8000:8000" environment: - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" HORUSEC_JWT_SECRET_KEY: "horusec-secret" - HORUSEC_AUTH_URL: "http://horusec-auth:8006" + HORUSEC_AUTH_URL: "127.0.0.1:8007" horusec-manager: build: context: ../ diff --git a/deployments/docker-compose.test.yaml b/deployments/docker-compose.test.yaml index 1f4697e80..a1327b6cd 100644 --- a/deployments/docker-compose.test.yaml +++ b/deployments/docker-compose.test.yaml @@ -3,11 +3,13 @@ services: rabbit: container_name: rabbit image: rabbitmq:3-management + network_mode: "host" ports: - "5672:5672" - "15672:15672" postgresql: container_name: postgresql + network_mode: "host" image: postgres:12 ports: - "5432:5432" @@ -30,10 +32,11 @@ services: - "rabbit" restart: always container_name: horusec-messages + network_mode: "host" ports: - "8004:8004" environment: - HORUSEC_BROKER_HOST: rabbit + HORUSEC_BROKER_HOST: "127.0.0.1" HORUSEC_BROKER_PORT: "5672" HORUSEC_BROKER_USERNAME: "guest" HORUSEC_BROKER_PASSWORD: "guest" @@ -52,18 +55,19 @@ services: - postgresql restart: always container_name: horusec-account + network_mode: "host" ports: - "8003:8003" environment: HORUSEC_ACCOUNT_DISABLE_EMAIL_SERVICE: "true" - HORUSEC_BROKER_HOST: rabbit + HORUSEC_BROKER_HOST: "127.0.0.1" HORUSEC_BROKER_PORT: "5672" HORUSEC_BROKER_USERNAME: "guest" HORUSEC_BROKER_PASSWORD: "guest" - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" HORUSEC_JWT_SECRET_KEY: "horusec-secret" - HORUSEC_AUTH_URL: "http://horusec-auth:8006" + HORUSEC_AUTH_URL: "127.0.0.1:8007" horusec-auth: build: context: ../ @@ -72,10 +76,12 @@ services: - postgresql restart: always container_name: horusec-auth + network_mode: "host" ports: - "8006:8006" + - "8007:8007" environment: - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" HORUSEC_JWT_SECRET_KEY: "horusec-secret" HORUSEC_KEYCLOAK_BASE_PATH: ${HORUSEC_KEYCLOAK_BASE_PATH} @@ -93,12 +99,13 @@ services: - postgresql restart: always container_name: horusec-analytic + network_mode: "host" ports: - "8005:8005" environment: - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" - HORUSEC_AUTH_URL: "http://horusec-auth:8006" + HORUSEC_AUTH_URL: "127.0.0.1:8007" horusec-api: build: context: ../ @@ -108,13 +115,14 @@ services: - postgresql restart: always container_name: horusec-api + network_mode: "host" ports: - "8000:8000" environment: - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" HORUSEC_JWT_SECRET_KEY: "horusec-secret" - HORUSEC_AUTH_URL: "http://horusec-auth:8006" + HORUSEC_AUTH_URL: "127.0.0.1:8007" horusec-manager: build: context: ../ diff --git a/deployments/docker-compose.yaml b/deployments/docker-compose.yaml index afe8c9936..c7001811e 100644 --- a/deployments/docker-compose.yaml +++ b/deployments/docker-compose.yaml @@ -3,12 +3,14 @@ services: rabbit: container_name: rabbit image: rabbitmq:3-management + network_mode: "host" ports: - "5672:5672" - "15672:15672" postgresql: container_name: postgresql image: postgres:12 + network_mode: "host" ports: - "5432:5432" environment: @@ -26,10 +28,11 @@ services: image: horuszup/horusec-messages:latest restart: always container_name: horusec-messages + network_mode: "host" ports: - "8004:8004" environment: - HORUSEC_BROKER_HOST: rabbit + HORUSEC_BROKER_HOST: "127.0.0.1" HORUSEC_BROKER_PORT: "5672" HORUSEC_BROKER_USERNAME: "guest" HORUSEC_BROKER_PASSWORD: "guest" @@ -45,10 +48,12 @@ services: # - postgresql # restart: always # container_name: horusec-auth +# network_mode: "host" # ports: # - "8006:8006" +# - "8007:8007" # environment: -# HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" +# HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" # HORUSEC_DATABASE_SQL_DIALECT: "postgres" # HORUSEC_JWT_SECRET_KEY: "horusec-secret" # HORUSEC_KEYCLOAK_BASE_PATH: ${HORUSEC_KEYCLOAK_BASE_PATH} @@ -65,30 +70,32 @@ services: - postgresql restart: always container_name: horusec-account + network_mode: "host" ports: - "8003:8003" environment: HORUSEC_ACCOUNT_DISABLE_EMAIL_SERVICE: "true" - HORUSEC_BROKER_HOST: rabbit + HORUSEC_BROKER_HOST: "127.0.0.1" HORUSEC_BROKER_PORT: "5672" HORUSEC_BROKER_USERNAME: "guest" HORUSEC_BROKER_PASSWORD: "guest" - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" HORUSEC_JWT_SECRET_KEY: "horusec-secret" - HORUSEC_AUTH_URL: "http://horusec-auth:8006" + HORUSEC_AUTH_URL: "127.0.0.1:8007" horusec-analytic: image: horuszup/horusec-analytic:latest depends_on: - postgresql restart: always container_name: horusec-analytic + network_mode: "host" ports: - "8005:8005" environment: - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" - HORUSEC_AUTH_URL: "http://horusec-auth:8006" + HORUSEC_AUTH_URL: "127.0.0.1:8007" horusec-api: image: horuszup/horusec-api:latest depends_on: @@ -96,13 +103,14 @@ services: - postgresql restart: always container_name: horusec-api + network_mode: "host" ports: - "8000:8000" environment: - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" HORUSEC_JWT_SECRET_KEY: "horusec-secret" - HORUSEC_AUTH_URL: "http://horusec-auth:8006" + HORUSEC_AUTH_URL: "127.0.0.1:8007" horusec-manager: image: horuszup/horusec-manager:latest restart: always diff --git a/development-kit/pkg/enums/errors/auth.go b/development-kit/pkg/enums/errors/auth.go index ff51eccbc..e132482c9 100644 --- a/development-kit/pkg/enums/errors/auth.go +++ b/development-kit/pkg/enums/errors/auth.go @@ -5,4 +5,8 @@ import "errors" var ErrorInvalidAuthType = errors.New("{AUTH} invalid auth type, should be ldap, keycloak or horus") var ErrorTokenCanNotBeEmpty = errors.New("{AUTH} token can not be empty in authorization header") -const ErrorAuthTypeNotActive = "{AUTH} this auth type it is no active, should be %s" +const ( + ErrorAuthTypeNotActive = "{AUTH} this auth type it is no active, should be %s" + ErrorFailedToVerifyIsAuthorized = "{AUTH} failed to verify is authorized request" + ErrorFailedToGetAccountID = "{AUTH} failed to get account id from token" +) diff --git a/development-kit/pkg/services/grpc/auth/auth.pb.go b/development-kit/pkg/services/grpc/auth/auth.pb.go new file mode 100644 index 000000000..d860bfa68 --- /dev/null +++ b/development-kit/pkg/services/grpc/auth/auth.pb.go @@ -0,0 +1,673 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.25.0 +// protoc v3.13.0 +// source: development-kit/pkg/services/grpc/auth/auth.proto + +package auth + +import ( + context "context" + proto "github.com/golang/protobuf/proto" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + +type IsAuthorizedData struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` + Role string `protobuf:"bytes,2,opt,name=role,proto3" json:"role,omitempty"` + CompanyID string `protobuf:"bytes,3,opt,name=companyID,proto3" json:"companyID,omitempty"` + RepositoryID string `protobuf:"bytes,4,opt,name=repositoryID,proto3" json:"repositoryID,omitempty"` +} + +func (x *IsAuthorizedData) Reset() { + *x = IsAuthorizedData{} + if protoimpl.UnsafeEnabled { + mi := &file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *IsAuthorizedData) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*IsAuthorizedData) ProtoMessage() {} + +func (x *IsAuthorizedData) ProtoReflect() protoreflect.Message { + mi := &file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use IsAuthorizedData.ProtoReflect.Descriptor instead. +func (*IsAuthorizedData) Descriptor() ([]byte, []int) { + return file_development_kit_pkg_services_grpc_auth_auth_proto_rawDescGZIP(), []int{0} +} + +func (x *IsAuthorizedData) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +func (x *IsAuthorizedData) GetRole() string { + if x != nil { + return x.Role + } + return "" +} + +func (x *IsAuthorizedData) GetCompanyID() string { + if x != nil { + return x.CompanyID + } + return "" +} + +func (x *IsAuthorizedData) GetRepositoryID() string { + if x != nil { + return x.RepositoryID + } + return "" +} + +type IsAuthorizedResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + IsAuthorized bool `protobuf:"varint,1,opt,name=isAuthorized,proto3" json:"isAuthorized,omitempty"` +} + +func (x *IsAuthorizedResponse) Reset() { + *x = IsAuthorizedResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *IsAuthorizedResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*IsAuthorizedResponse) ProtoMessage() {} + +func (x *IsAuthorizedResponse) ProtoReflect() protoreflect.Message { + mi := &file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use IsAuthorizedResponse.ProtoReflect.Descriptor instead. +func (*IsAuthorizedResponse) Descriptor() ([]byte, []int) { + return file_development_kit_pkg_services_grpc_auth_auth_proto_rawDescGZIP(), []int{1} +} + +func (x *IsAuthorizedResponse) GetIsAuthorized() bool { + if x != nil { + return x.IsAuthorized + } + return false +} + +type GetAccountIDData struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` +} + +func (x *GetAccountIDData) Reset() { + *x = GetAccountIDData{} + if protoimpl.UnsafeEnabled { + mi := &file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetAccountIDData) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetAccountIDData) ProtoMessage() {} + +func (x *GetAccountIDData) ProtoReflect() protoreflect.Message { + mi := &file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetAccountIDData.ProtoReflect.Descriptor instead. +func (*GetAccountIDData) Descriptor() ([]byte, []int) { + return file_development_kit_pkg_services_grpc_auth_auth_proto_rawDescGZIP(), []int{2} +} + +func (x *GetAccountIDData) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +type GetAccountIDResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + AccountID string `protobuf:"bytes,1,opt,name=accountID,proto3" json:"accountID,omitempty"` +} + +func (x *GetAccountIDResponse) Reset() { + *x = GetAccountIDResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetAccountIDResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetAccountIDResponse) ProtoMessage() {} + +func (x *GetAccountIDResponse) ProtoReflect() protoreflect.Message { + mi := &file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetAccountIDResponse.ProtoReflect.Descriptor instead. +func (*GetAccountIDResponse) Descriptor() ([]byte, []int) { + return file_development_kit_pkg_services_grpc_auth_auth_proto_rawDescGZIP(), []int{3} +} + +func (x *GetAccountIDResponse) GetAccountID() string { + if x != nil { + return x.AccountID + } + return "" +} + +type GetAuthConfigData struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *GetAuthConfigData) Reset() { + *x = GetAuthConfigData{} + if protoimpl.UnsafeEnabled { + mi := &file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetAuthConfigData) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetAuthConfigData) ProtoMessage() {} + +func (x *GetAuthConfigData) ProtoReflect() protoreflect.Message { + mi := &file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetAuthConfigData.ProtoReflect.Descriptor instead. +func (*GetAuthConfigData) Descriptor() ([]byte, []int) { + return file_development_kit_pkg_services_grpc_auth_auth_proto_rawDescGZIP(), []int{4} +} + +type GetAuthConfigResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ApplicationAdminEnable bool `protobuf:"varint,1,opt,name=ApplicationAdminEnable,proto3" json:"ApplicationAdminEnable,omitempty"` + AuthType string `protobuf:"bytes,2,opt,name=AuthType,proto3" json:"AuthType,omitempty"` +} + +func (x *GetAuthConfigResponse) Reset() { + *x = GetAuthConfigResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetAuthConfigResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetAuthConfigResponse) ProtoMessage() {} + +func (x *GetAuthConfigResponse) ProtoReflect() protoreflect.Message { + mi := &file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetAuthConfigResponse.ProtoReflect.Descriptor instead. +func (*GetAuthConfigResponse) Descriptor() ([]byte, []int) { + return file_development_kit_pkg_services_grpc_auth_auth_proto_rawDescGZIP(), []int{5} +} + +func (x *GetAuthConfigResponse) GetApplicationAdminEnable() bool { + if x != nil { + return x.ApplicationAdminEnable + } + return false +} + +func (x *GetAuthConfigResponse) GetAuthType() string { + if x != nil { + return x.AuthType + } + return "" +} + +var File_development_kit_pkg_services_grpc_auth_auth_proto protoreflect.FileDescriptor + +var file_development_kit_pkg_services_grpc_auth_auth_proto_rawDesc = []byte{ + 0x0a, 0x31, 0x64, 0x65, 0x76, 0x65, 0x6c, 0x6f, 0x70, 0x6d, 0x65, 0x6e, 0x74, 0x2d, 0x6b, 0x69, + 0x74, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2f, 0x67, + 0x72, 0x70, 0x63, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x12, 0x04, 0x67, 0x72, 0x70, 0x63, 0x22, 0x7e, 0x0a, 0x10, 0x49, 0x73, 0x41, + 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x44, 0x61, 0x74, 0x61, 0x12, 0x14, 0x0a, + 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, + 0x6b, 0x65, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x72, 0x6f, 0x6c, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x04, 0x72, 0x6f, 0x6c, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x63, 0x6f, 0x6d, 0x70, 0x61, + 0x6e, 0x79, 0x49, 0x44, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x63, 0x6f, 0x6d, 0x70, + 0x61, 0x6e, 0x79, 0x49, 0x44, 0x12, 0x22, 0x0a, 0x0c, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, + 0x6f, 0x72, 0x79, 0x49, 0x44, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x72, 0x65, 0x70, + 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x49, 0x44, 0x22, 0x3a, 0x0a, 0x14, 0x49, 0x73, 0x41, + 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x22, 0x0a, 0x0c, 0x69, 0x73, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, + 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, 0x69, 0x73, 0x41, 0x75, 0x74, 0x68, 0x6f, + 0x72, 0x69, 0x7a, 0x65, 0x64, 0x22, 0x28, 0x0a, 0x10, 0x47, 0x65, 0x74, 0x41, 0x63, 0x63, 0x6f, + 0x75, 0x6e, 0x74, 0x49, 0x44, 0x44, 0x61, 0x74, 0x61, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, + 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x22, + 0x34, 0x0a, 0x14, 0x47, 0x65, 0x74, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x49, 0x44, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x63, 0x63, 0x6f, 0x75, + 0x6e, 0x74, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x61, 0x63, 0x63, 0x6f, + 0x75, 0x6e, 0x74, 0x49, 0x44, 0x22, 0x13, 0x0a, 0x11, 0x47, 0x65, 0x74, 0x41, 0x75, 0x74, 0x68, + 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x44, 0x61, 0x74, 0x61, 0x22, 0x6b, 0x0a, 0x15, 0x47, 0x65, + 0x74, 0x41, 0x75, 0x74, 0x68, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x36, 0x0a, 0x16, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x41, 0x64, 0x6d, 0x69, 0x6e, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x08, 0x52, 0x16, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x41, 0x64, 0x6d, 0x69, 0x6e, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x41, + 0x75, 0x74, 0x68, 0x54, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x41, + 0x75, 0x74, 0x68, 0x54, 0x79, 0x70, 0x65, 0x32, 0xe2, 0x01, 0x0a, 0x0b, 0x41, 0x75, 0x74, 0x68, + 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x44, 0x0a, 0x0c, 0x49, 0x73, 0x41, 0x75, 0x74, + 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x12, 0x16, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x49, + 0x73, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x44, 0x61, 0x74, 0x61, 0x1a, + 0x1a, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x49, 0x73, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, + 0x7a, 0x65, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x44, 0x0a, + 0x0c, 0x47, 0x65, 0x74, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x49, 0x44, 0x12, 0x16, 0x2e, + 0x67, 0x72, 0x70, 0x63, 0x2e, 0x47, 0x65, 0x74, 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x49, + 0x44, 0x44, 0x61, 0x74, 0x61, 0x1a, 0x1a, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x47, 0x65, 0x74, + 0x41, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x49, 0x44, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x22, 0x00, 0x12, 0x47, 0x0a, 0x0d, 0x47, 0x65, 0x74, 0x41, 0x75, 0x74, 0x68, 0x43, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x12, 0x17, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x47, 0x65, 0x74, 0x41, + 0x75, 0x74, 0x68, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x44, 0x61, 0x74, 0x61, 0x1a, 0x1b, 0x2e, + 0x67, 0x72, 0x70, 0x63, 0x2e, 0x47, 0x65, 0x74, 0x41, 0x75, 0x74, 0x68, 0x43, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x28, 0x5a, 0x26, + 0x64, 0x65, 0x76, 0x65, 0x6c, 0x6f, 0x70, 0x6d, 0x65, 0x6e, 0x74, 0x2d, 0x6b, 0x69, 0x74, 0x2f, + 0x70, 0x6b, 0x67, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2f, 0x67, 0x72, 0x70, + 0x63, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_development_kit_pkg_services_grpc_auth_auth_proto_rawDescOnce sync.Once + file_development_kit_pkg_services_grpc_auth_auth_proto_rawDescData = file_development_kit_pkg_services_grpc_auth_auth_proto_rawDesc +) + +func file_development_kit_pkg_services_grpc_auth_auth_proto_rawDescGZIP() []byte { + file_development_kit_pkg_services_grpc_auth_auth_proto_rawDescOnce.Do(func() { + file_development_kit_pkg_services_grpc_auth_auth_proto_rawDescData = protoimpl.X.CompressGZIP(file_development_kit_pkg_services_grpc_auth_auth_proto_rawDescData) + }) + return file_development_kit_pkg_services_grpc_auth_auth_proto_rawDescData +} + +var file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes = make([]protoimpl.MessageInfo, 6) +var file_development_kit_pkg_services_grpc_auth_auth_proto_goTypes = []interface{}{ + (*IsAuthorizedData)(nil), // 0: grpc.IsAuthorizedData + (*IsAuthorizedResponse)(nil), // 1: grpc.IsAuthorizedResponse + (*GetAccountIDData)(nil), // 2: grpc.GetAccountIDData + (*GetAccountIDResponse)(nil), // 3: grpc.GetAccountIDResponse + (*GetAuthConfigData)(nil), // 4: grpc.GetAuthConfigData + (*GetAuthConfigResponse)(nil), // 5: grpc.GetAuthConfigResponse +} +var file_development_kit_pkg_services_grpc_auth_auth_proto_depIdxs = []int32{ + 0, // 0: grpc.AuthService.IsAuthorized:input_type -> grpc.IsAuthorizedData + 2, // 1: grpc.AuthService.GetAccountID:input_type -> grpc.GetAccountIDData + 4, // 2: grpc.AuthService.GetAuthConfig:input_type -> grpc.GetAuthConfigData + 1, // 3: grpc.AuthService.IsAuthorized:output_type -> grpc.IsAuthorizedResponse + 3, // 4: grpc.AuthService.GetAccountID:output_type -> grpc.GetAccountIDResponse + 5, // 5: grpc.AuthService.GetAuthConfig:output_type -> grpc.GetAuthConfigResponse + 3, // [3:6] is the sub-list for method output_type + 0, // [0:3] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_development_kit_pkg_services_grpc_auth_auth_proto_init() } +func file_development_kit_pkg_services_grpc_auth_auth_proto_init() { + if File_development_kit_pkg_services_grpc_auth_auth_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*IsAuthorizedData); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*IsAuthorizedResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetAccountIDData); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetAccountIDResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetAuthConfigData); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetAuthConfigResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_development_kit_pkg_services_grpc_auth_auth_proto_rawDesc, + NumEnums: 0, + NumMessages: 6, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_development_kit_pkg_services_grpc_auth_auth_proto_goTypes, + DependencyIndexes: file_development_kit_pkg_services_grpc_auth_auth_proto_depIdxs, + MessageInfos: file_development_kit_pkg_services_grpc_auth_auth_proto_msgTypes, + }.Build() + File_development_kit_pkg_services_grpc_auth_auth_proto = out.File + file_development_kit_pkg_services_grpc_auth_auth_proto_rawDesc = nil + file_development_kit_pkg_services_grpc_auth_auth_proto_goTypes = nil + file_development_kit_pkg_services_grpc_auth_auth_proto_depIdxs = nil +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConnInterface + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion6 + +// AuthServiceClient is the client API for AuthService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type AuthServiceClient interface { + IsAuthorized(ctx context.Context, in *IsAuthorizedData, opts ...grpc.CallOption) (*IsAuthorizedResponse, error) + GetAccountID(ctx context.Context, in *GetAccountIDData, opts ...grpc.CallOption) (*GetAccountIDResponse, error) + GetAuthConfig(ctx context.Context, in *GetAuthConfigData, opts ...grpc.CallOption) (*GetAuthConfigResponse, error) +} + +type authServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewAuthServiceClient(cc grpc.ClientConnInterface) AuthServiceClient { + return &authServiceClient{cc} +} + +func (c *authServiceClient) IsAuthorized(ctx context.Context, in *IsAuthorizedData, opts ...grpc.CallOption) (*IsAuthorizedResponse, error) { + out := new(IsAuthorizedResponse) + err := c.cc.Invoke(ctx, "/grpc.AuthService/IsAuthorized", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *authServiceClient) GetAccountID(ctx context.Context, in *GetAccountIDData, opts ...grpc.CallOption) (*GetAccountIDResponse, error) { + out := new(GetAccountIDResponse) + err := c.cc.Invoke(ctx, "/grpc.AuthService/GetAccountID", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *authServiceClient) GetAuthConfig(ctx context.Context, in *GetAuthConfigData, opts ...grpc.CallOption) (*GetAuthConfigResponse, error) { + out := new(GetAuthConfigResponse) + err := c.cc.Invoke(ctx, "/grpc.AuthService/GetAuthConfig", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// AuthServiceServer is the server API for AuthService service. +type AuthServiceServer interface { + IsAuthorized(context.Context, *IsAuthorizedData) (*IsAuthorizedResponse, error) + GetAccountID(context.Context, *GetAccountIDData) (*GetAccountIDResponse, error) + GetAuthConfig(context.Context, *GetAuthConfigData) (*GetAuthConfigResponse, error) +} + +// UnimplementedAuthServiceServer can be embedded to have forward compatible implementations. +type UnimplementedAuthServiceServer struct { +} + +func (*UnimplementedAuthServiceServer) IsAuthorized(context.Context, *IsAuthorizedData) (*IsAuthorizedResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method IsAuthorized not implemented") +} +func (*UnimplementedAuthServiceServer) GetAccountID(context.Context, *GetAccountIDData) (*GetAccountIDResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetAccountID not implemented") +} +func (*UnimplementedAuthServiceServer) GetAuthConfig(context.Context, *GetAuthConfigData) (*GetAuthConfigResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetAuthConfig not implemented") +} + +func RegisterAuthServiceServer(s *grpc.Server, srv AuthServiceServer) { + s.RegisterService(&_AuthService_serviceDesc, srv) +} + +func _AuthService_IsAuthorized_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(IsAuthorizedData) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(AuthServiceServer).IsAuthorized(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc.AuthService/IsAuthorized", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(AuthServiceServer).IsAuthorized(ctx, req.(*IsAuthorizedData)) + } + return interceptor(ctx, in, info, handler) +} + +func _AuthService_GetAccountID_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetAccountIDData) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(AuthServiceServer).GetAccountID(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc.AuthService/GetAccountID", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(AuthServiceServer).GetAccountID(ctx, req.(*GetAccountIDData)) + } + return interceptor(ctx, in, info, handler) +} + +func _AuthService_GetAuthConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetAuthConfigData) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(AuthServiceServer).GetAuthConfig(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc.AuthService/GetAuthConfig", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(AuthServiceServer).GetAuthConfig(ctx, req.(*GetAuthConfigData)) + } + return interceptor(ctx, in, info, handler) +} + +var _AuthService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.AuthService", + HandlerType: (*AuthServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "IsAuthorized", + Handler: _AuthService_IsAuthorized_Handler, + }, + { + MethodName: "GetAccountID", + Handler: _AuthService_GetAccountID_Handler, + }, + { + MethodName: "GetAuthConfig", + Handler: _AuthService_GetAuthConfig_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "development-kit/pkg/services/grpc/auth/auth.proto", +} diff --git a/development-kit/pkg/services/grpc/auth/auth.proto b/development-kit/pkg/services/grpc/auth/auth.proto new file mode 100644 index 000000000..112173ab7 --- /dev/null +++ b/development-kit/pkg/services/grpc/auth/auth.proto @@ -0,0 +1,37 @@ +syntax = "proto3"; + +package grpc; + +option go_package = "development-kit/pkg/services/grpc/auth"; + +service AuthService { + rpc IsAuthorized (IsAuthorizedData) returns (IsAuthorizedResponse) {} + rpc GetAccountID (GetAccountIDData) returns (GetAccountIDResponse) {} + rpc GetAuthConfig (GetAuthConfigData) returns (GetAuthConfigResponse) {} +} + +message IsAuthorizedData { + string token = 1; + string role = 2; + string companyID = 3; + string repositoryID = 4; +} + +message IsAuthorizedResponse { + bool isAuthorized = 1; +} + +message GetAccountIDData { + string token = 1; +} + +message GetAccountIDResponse { + string accountID = 1; +} + +message GetAuthConfigData {} + +message GetAuthConfigResponse { + bool ApplicationAdminEnable = 1; + string AuthType = 2; +} diff --git a/development-kit/pkg/services/grpc/auth/mock.go b/development-kit/pkg/services/grpc/auth/mock.go new file mode 100644 index 000000000..21a3abf63 --- /dev/null +++ b/development-kit/pkg/services/grpc/auth/mock.go @@ -0,0 +1,30 @@ +package auth + +import ( + "context" + mockUtils "github.com/ZupIT/horusec/development-kit/pkg/utils/mock" + "github.com/stretchr/testify/mock" + "google.golang.org/grpc" +) + +type Mock struct { + mock.Mock +} + +func (m *Mock) IsAuthorized( + _ context.Context, _ *IsAuthorizedData, _ ...grpc.CallOption) (*IsAuthorizedResponse, error) { + args := m.MethodCalled("IsAuthorized") + return args.Get(0).(*IsAuthorizedResponse), mockUtils.ReturnNilOrError(args, 1) +} + +func (m *Mock) GetAccountID( + ctx context.Context, in *GetAccountIDData, opts ...grpc.CallOption) (*GetAccountIDResponse, error) { + args := m.MethodCalled("GetAccountID") + return args.Get(0).(*GetAccountIDResponse), mockUtils.ReturnNilOrError(args, 1) +} + +func (m *Mock) GetAuthConfig( + ctx context.Context, in *GetAuthConfigData, opts ...grpc.CallOption) (*GetAuthConfigResponse, error) { + args := m.MethodCalled("GetAuthConfig") + return args.Get(0).(*GetAuthConfigResponse), mockUtils.ReturnNilOrError(args, 1) +} diff --git a/development-kit/pkg/services/middlewares/horusec_authz.go b/development-kit/pkg/services/middlewares/horusec_authz.go index 58b586142..aeff3677a 100644 --- a/development-kit/pkg/services/middlewares/horusec_authz.go +++ b/development-kit/pkg/services/middlewares/horusec_authz.go @@ -15,22 +15,17 @@ package middlewares import ( - "bytes" "context" - "encoding/json" - "fmt" authEntities "github.com/ZupIT/horusec/development-kit/pkg/entities/auth" - httpEntities "github.com/ZupIT/horusec/development-kit/pkg/entities/http" authEnums "github.com/ZupIT/horusec/development-kit/pkg/enums/auth" - "github.com/ZupIT/horusec/development-kit/pkg/utils/env" + authGrpc "github.com/ZupIT/horusec/development-kit/pkg/services/grpc/auth" httpClient "github.com/ZupIT/horusec/development-kit/pkg/utils/http-request/client" - httpResponse "github.com/ZupIT/horusec/development-kit/pkg/utils/http-request/response" + "google.golang.org/grpc" "net/http" "github.com/ZupIT/horusec/development-kit/pkg/enums/errors" httpUtil "github.com/ZupIT/horusec/development-kit/pkg/utils/http" "github.com/go-chi/chi" - "github.com/google/uuid" ) type IHorusAuthzMiddleware interface { @@ -44,12 +39,16 @@ type IHorusAuthzMiddleware interface { } type HorusAuthzMiddleware struct { - httpUtil httpClient.Interface + httpUtil httpClient.Interface + grpcClient authGrpc.AuthServiceClient + ctx context.Context } -func NewHorusAuthzMiddleware() IHorusAuthzMiddleware { +func NewHorusAuthzMiddleware(grpcCon grpc.ClientConnInterface) IHorusAuthzMiddleware { return &HorusAuthzMiddleware{ - httpUtil: httpClient.NewHTTPClient(10), + httpUtil: httpClient.NewHTTPClient(10), + grpcClient: authGrpc.NewAuthServiceClient(grpcCon), + ctx: context.Background(), } } @@ -67,8 +66,8 @@ func (h *HorusAuthzMiddleware) IsApplicationAdmin(next http.Handler) http.Handle return } if configAuth.ApplicationAdminEnable { - isValid, err := h.validateRequest(r, authEnums.ApplicationAdmin) - if err != nil || !isValid { + response, err := h.grpcClient.IsAuthorized(h.ctx, h.setAuthorizedData(r, authEnums.ApplicationAdmin)) + if err != nil || !response.GetIsAuthorized() { httpUtil.StatusUnauthorized(w, errors.ErrorUnauthorized) return } @@ -88,8 +87,8 @@ func (h *HorusAuthzMiddleware) getConfigAuthAndSetInContext(r *http.Request) ( func (h *HorusAuthzMiddleware) IsCompanyMember(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - isValid, err := h.validateRequest(r, authEnums.CompanyMember) - if err != nil || !isValid { + response, err := h.grpcClient.IsAuthorized(h.ctx, h.setAuthorizedData(r, authEnums.CompanyMember)) + if err != nil || !response.GetIsAuthorized() { httpUtil.StatusUnauthorized(w, errors.ErrorUnauthorized) return } @@ -100,8 +99,8 @@ func (h *HorusAuthzMiddleware) IsCompanyMember(next http.Handler) http.Handler { func (h *HorusAuthzMiddleware) IsCompanyAdmin(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - isValid, err := h.validateRequest(r, authEnums.CompanyAdmin) - if err != nil || !isValid { + response, err := h.grpcClient.IsAuthorized(h.ctx, h.setAuthorizedData(r, authEnums.CompanyAdmin)) + if err != nil || !response.GetIsAuthorized() { httpUtil.StatusUnauthorized(w, errors.ErrorUnauthorized) return } @@ -112,8 +111,8 @@ func (h *HorusAuthzMiddleware) IsCompanyAdmin(next http.Handler) http.Handler { func (h *HorusAuthzMiddleware) IsRepositoryMember(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - isValid, err := h.validateRequest(r, authEnums.RepositoryMember) - if err != nil || !isValid { + response, err := h.grpcClient.IsAuthorized(h.ctx, h.setAuthorizedData(r, authEnums.RepositoryMember)) + if err != nil || !response.GetIsAuthorized() { httpUtil.StatusUnauthorized(w, errors.ErrorUnauthorized) return } @@ -124,8 +123,8 @@ func (h *HorusAuthzMiddleware) IsRepositoryMember(next http.Handler) http.Handle func (h *HorusAuthzMiddleware) IsRepositorySupervisor(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - isValid, err := h.validateRequest(r, authEnums.RepositorySupervisor) - if err != nil || !isValid { + response, err := h.grpcClient.IsAuthorized(h.ctx, h.setAuthorizedData(r, authEnums.RepositorySupervisor)) + if err != nil || !response.GetIsAuthorized() { httpUtil.StatusUnauthorized(w, errors.ErrorUnauthorized) return } @@ -136,8 +135,8 @@ func (h *HorusAuthzMiddleware) IsRepositorySupervisor(next http.Handler) http.Ha func (h *HorusAuthzMiddleware) IsRepositoryAdmin(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - isValid, err := h.validateRequest(r, authEnums.RepositoryAdmin) - if err != nil || !isValid { + response, err := h.grpcClient.IsAuthorized(h.ctx, h.setAuthorizedData(r, authEnums.RepositoryAdmin)) + if err != nil || !response.GetIsAuthorized() { httpUtil.StatusUnauthorized(w, errors.ErrorUnauthorized) return } @@ -156,92 +155,41 @@ func (h *HorusAuthzMiddleware) setContextAndReturn(next http.Handler, w http.Res next.ServeHTTP(w, r.WithContext(ctx)) } -func (h *HorusAuthzMiddleware) validateRequest(r *http.Request, role authEnums.HorusecRoles) (bool, error) { - companyID, _ := uuid.Parse(chi.URLParam(r, "companyID")) - repositoryID, _ := uuid.Parse(chi.URLParam(r, "repositoryID")) - - return h.sendRequestAuthentication(r.Header.Get("Authorization"), role, companyID, repositoryID) -} - -func (h *HorusAuthzMiddleware) sendRequestAuthentication(token string, role authEnums.HorusecRoles, companyID, - repositoryID uuid.UUID) (bool, error) { - req, _ := http.NewRequest(http.MethodPost, h.getHorusecAuthURL("/authorize"), - bytes.NewReader(h.newAuthorizationData(token, role, companyID, repositoryID))) - - return h.parseResponseBool(h.httpUtil.DoRequest(req, nil)) -} - -func (h *HorusAuthzMiddleware) getHorusecAuthURL(subPath string) string { - return fmt.Sprintf("%s/api/auth%s", - env.GetEnvOrDefault("HORUSEC_AUTH_URL", "http://0.0.0.0:8006"), subPath) -} - -func (h *HorusAuthzMiddleware) newAuthorizationData(token string, role authEnums.HorusecRoles, companyID, - repositoryID uuid.UUID) []byte { - authorizationData := &authEntities.AuthorizationData{ - Token: token, - Role: role, - CompanyID: companyID, - RepositoryID: repositoryID, - } - - return authorizationData.ToBytes() -} - -func (h *HorusAuthzMiddleware) parseResponseBool( - response httpResponse.Interface, err error) (isValid bool, errParse error) { - if err != nil { - return false, err - } - - responseContent := httpEntities.Response{} - body, _ := response.GetBody() - if errParse := json.Unmarshal(body, &responseContent); errParse != nil { - return false, errParse +func (h *HorusAuthzMiddleware) setAuthorizedData(r *http.Request, + role authEnums.HorusecRoles) *authGrpc.IsAuthorizedData { + return &authGrpc.IsAuthorizedData{ + Token: r.Header.Get("Authorization"), + Role: role.ToString(), + CompanyID: chi.URLParam(r, "companyID"), + RepositoryID: chi.URLParam(r, "repositoryID"), } - - return isValid, json.Unmarshal(responseContent.ContentToBytes(), &isValid) } -func (h *HorusAuthzMiddleware) parseResponseAccountID( - response httpResponse.Interface, err error) (accountID uuid.UUID, errParse error) { - if err != nil { - return uuid.Nil, err +func (h *HorusAuthzMiddleware) setGetAccountIDData(token string) *authGrpc.GetAccountIDData { + return &authGrpc.GetAccountIDData{ + Token: token, } - - responseContent := httpEntities.Response{} - body, _ := response.GetBody() - if errParse := json.Unmarshal(body, &responseContent); errParse != nil { - return uuid.Nil, errParse - } - - return accountID, json.Unmarshal(responseContent.ContentToBytes(), &accountID) -} - -func (h *HorusAuthzMiddleware) sendRequestGetAccountID(token string) (uuid.UUID, error) { - req, _ := http.NewRequest(http.MethodGet, h.getHorusecAuthURL("/account-id"), nil) - req.Header.Add("Authorization", token) - - return h.parseResponseAccountID(h.httpUtil.DoRequest(req, nil)) } func (h *HorusAuthzMiddleware) setAccountIDInContext(r *http.Request, token string) (context.Context, error) { - accountID, err := h.sendRequestGetAccountID(token) + response, err := h.grpcClient.GetAccountID(h.ctx, h.setGetAccountIDData(token)) if err != nil { return nil, err } - return context.WithValue(r.Context(), authEnums.AccountID, accountID.String()), nil + return context.WithValue(r.Context(), authEnums.AccountID, response.AccountID), nil } func (h *HorusAuthzMiddleware) getConfigAuth() (authEntities.ConfigAuth, error) { - req, _ := http.NewRequest(http.MethodGet, h.getHorusecAuthURL("/config"), nil) - - res, err := h.httpUtil.DoRequest(req, nil) + response, err := h.grpcClient.GetAuthConfig(h.ctx, &authGrpc.GetAuthConfigData{}) if err != nil { return authEntities.ConfigAuth{}, err } - return h.parseResponseConfigAuth(res) + + return authEntities.ConfigAuth{ + ApplicationAdminEnable: response.GetApplicationAdminEnable(), + AuthType: authEnums.AuthorizationType(response.GetAuthType()), + }, nil } func (h *HorusAuthzMiddleware) setConfigAuthInContextAndReturnRequest( @@ -249,13 +197,3 @@ func (h *HorusAuthzMiddleware) setConfigAuthInContextAndReturnRequest( ctx := context.WithValue(r.Context(), authEnums.ConfigAuth, configAuth) return r.WithContext(ctx) } - -func (h *HorusAuthzMiddleware) parseResponseConfigAuth( - response httpResponse.Interface) (entity authEntities.ConfigAuth, err error) { - responseContent := httpEntities.Response{} - body, _ := response.GetBody() - if errParse := json.Unmarshal(body, &responseContent); errParse != nil { - return authEntities.ConfigAuth{}, errParse - } - return authEntities.ParseInterfaceToConfigAuth(responseContent.Content) -} diff --git a/development-kit/pkg/services/middlewares/horusec_authz_test.go b/development-kit/pkg/services/middlewares/horusec_authz_test.go index 5844f6633..0a1624206 100644 --- a/development-kit/pkg/services/middlewares/horusec_authz_test.go +++ b/development-kit/pkg/services/middlewares/horusec_authz_test.go @@ -15,24 +15,21 @@ package middlewares import ( - "encoding/json" "errors" - httpEntities "github.com/ZupIT/horusec/development-kit/pkg/entities/http" + authEnums "github.com/ZupIT/horusec/development-kit/pkg/enums/auth" + authGrpc "github.com/ZupIT/horusec/development-kit/pkg/services/grpc/auth" httpClient "github.com/ZupIT/horusec/development-kit/pkg/utils/http-request/client" - httpResponse "github.com/ZupIT/horusec/development-kit/pkg/utils/http-request/response" "github.com/ZupIT/horusec/development-kit/pkg/utils/test" "github.com/google/uuid" "github.com/stretchr/testify/assert" - "io/ioutil" "net/http" "net/http/httptest" - "strings" "testing" ) func TestNewHorusAuthzMiddleware(t *testing.T) { t.Run("should create a new middleware service", func(t *testing.T) { - middleware := NewHorusAuthzMiddleware() + middleware := NewHorusAuthzMiddleware(nil) assert.NotNil(t, middleware) }) } @@ -40,17 +37,14 @@ func TestNewHorusAuthzMiddleware(t *testing.T) { func TestIsMember(t *testing.T) { t.Run("should return 200 when valid request", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - respBytes, _ := json.Marshal(httpEntities.Response{Content: true}) - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Once().Return(httpResponse.NewHTTPResponse(resp), nil) - - respBytes, _ = json.Marshal(httpEntities.Response{Content: uuid.New()}) - resp = &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Once().Return(httpResponse.NewHTTPResponse(resp), nil) + grpcMock.On("IsAuthorized").Return(&authGrpc.IsAuthorizedResponse{IsAuthorized: true}, nil) + grpcMock.On("GetAccountID").Return(&authGrpc.GetAccountIDResponse{AccountID: uuid.New().String()}, nil) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } handler := middleware.IsCompanyMember(http.HandlerFunc(test.Handler)) @@ -66,13 +60,13 @@ func TestIsMember(t *testing.T) { t.Run("should return 401 when invalid request", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - respBytes, _ := json.Marshal(httpEntities.Response{Content: false}) - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Return(httpResponse.NewHTTPResponse(resp), errors.New("test")) + grpcMock.On("IsAuthorized").Return(&authGrpc.IsAuthorizedResponse{IsAuthorized: true}, errors.New("test")) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } handler := middleware.IsCompanyMember(http.HandlerFunc(test.Handler)) @@ -90,17 +84,14 @@ func TestIsMember(t *testing.T) { func TestIsCompanyAdmin(t *testing.T) { t.Run("should return 200 when valid request", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - respBytes, _ := json.Marshal(httpEntities.Response{Content: true}) - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Once().Return(httpResponse.NewHTTPResponse(resp), nil) - - respBytes, _ = json.Marshal(httpEntities.Response{Content: uuid.New()}) - resp = &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Once().Return(httpResponse.NewHTTPResponse(resp), nil) + grpcMock.On("IsAuthorized").Return(&authGrpc.IsAuthorizedResponse{IsAuthorized: true}, nil) + grpcMock.On("GetAccountID").Return(&authGrpc.GetAccountIDResponse{AccountID: uuid.New().String()}, nil) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } handler := middleware.IsCompanyAdmin(http.HandlerFunc(test.Handler)) @@ -116,13 +107,13 @@ func TestIsCompanyAdmin(t *testing.T) { t.Run("should return 401 when invalid request", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - respBytes, _ := json.Marshal(httpEntities.Response{Content: false}) - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Return(httpResponse.NewHTTPResponse(resp), errors.New("test")) + grpcMock.On("IsAuthorized").Return(&authGrpc.IsAuthorizedResponse{IsAuthorized: true}, errors.New("test")) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } handler := middleware.IsCompanyAdmin(http.HandlerFunc(test.Handler)) @@ -140,17 +131,14 @@ func TestIsCompanyAdmin(t *testing.T) { func TestIsRepositoryMember(t *testing.T) { t.Run("should return 200 when valid request", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - respBytes, _ := json.Marshal(httpEntities.Response{Content: true}) - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Once().Return(httpResponse.NewHTTPResponse(resp), nil) - - respBytes, _ = json.Marshal(httpEntities.Response{Content: uuid.New()}) - resp = &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Once().Return(httpResponse.NewHTTPResponse(resp), nil) + grpcMock.On("IsAuthorized").Return(&authGrpc.IsAuthorizedResponse{IsAuthorized: true}, nil) + grpcMock.On("GetAccountID").Return(&authGrpc.GetAccountIDResponse{AccountID: uuid.New().String()}, nil) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } handler := middleware.IsRepositoryMember(http.HandlerFunc(test.Handler)) @@ -166,13 +154,13 @@ func TestIsRepositoryMember(t *testing.T) { t.Run("should return 401 when invalid request", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - respBytes, _ := json.Marshal(httpEntities.Response{Content: false}) - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Return(httpResponse.NewHTTPResponse(resp), errors.New("test")) + grpcMock.On("IsAuthorized").Return(&authGrpc.IsAuthorizedResponse{IsAuthorized: true}, errors.New("test")) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } handler := middleware.IsRepositoryMember(http.HandlerFunc(test.Handler)) @@ -190,17 +178,14 @@ func TestIsRepositoryMember(t *testing.T) { func TestIsRepositorySupervisor(t *testing.T) { t.Run("should return 200 when valid request", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - respBytes, _ := json.Marshal(httpEntities.Response{Content: true}) - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Once().Return(httpResponse.NewHTTPResponse(resp), nil) - - respBytes, _ = json.Marshal(httpEntities.Response{Content: uuid.New()}) - resp = &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Once().Return(httpResponse.NewHTTPResponse(resp), nil) + grpcMock.On("IsAuthorized").Return(&authGrpc.IsAuthorizedResponse{IsAuthorized: true}, nil) + grpcMock.On("GetAccountID").Return(&authGrpc.GetAccountIDResponse{AccountID: uuid.New().String()}, nil) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } handler := middleware.IsRepositorySupervisor(http.HandlerFunc(test.Handler)) @@ -216,13 +201,13 @@ func TestIsRepositorySupervisor(t *testing.T) { t.Run("should return 401 when invalid request", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - respBytes, _ := json.Marshal(httpEntities.Response{Content: false}) - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Return(httpResponse.NewHTTPResponse(resp), errors.New("test")) + grpcMock.On("IsAuthorized").Return(&authGrpc.IsAuthorizedResponse{IsAuthorized: true}, errors.New("test")) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } handler := middleware.IsRepositorySupervisor(http.HandlerFunc(test.Handler)) @@ -235,18 +220,43 @@ func TestIsRepositorySupervisor(t *testing.T) { assert.Equal(t, http.StatusUnauthorized, w.Code) }) +} - t.Run("should return 401 when failed to unmarshall", func(t *testing.T) { +func TestIsRepositoryAdmin(t *testing.T) { + t.Run("should return 200 when valid request", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(""))} - httpMock.On("DoRequest").Once().Return(httpResponse.NewHTTPResponse(resp), nil) + grpcMock.On("IsAuthorized").Return(&authGrpc.IsAuthorizedResponse{IsAuthorized: true}, nil) + grpcMock.On("GetAccountID").Return(&authGrpc.GetAccountIDResponse{AccountID: uuid.New().String()}, nil) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } + handler := middleware.IsRepositoryAdmin(http.HandlerFunc(test.Handler)) - handler := middleware.IsRepositorySupervisor(http.HandlerFunc(test.Handler)) + req, _ := http.NewRequest("GET", "http://test", nil) + req.Header.Add("Authorization", "123") + + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + + assert.Equal(t, http.StatusOK, w.Code) + }) + + t.Run("should return 401 when invalid request", func(t *testing.T) { + httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} + + grpcMock.On("IsAuthorized").Return(&authGrpc.IsAuthorizedResponse{IsAuthorized: true}, errors.New("test")) + + middleware := HorusAuthzMiddleware{ + httpUtil: httpMock, + grpcClient: grpcMock, + } + + handler := middleware.IsRepositoryAdmin(http.HandlerFunc(test.Handler)) req, _ := http.NewRequest("GET", "http://test", nil) req.Header.Add("Authorization", "123") @@ -258,23 +268,19 @@ func TestIsRepositorySupervisor(t *testing.T) { }) } -func TestIsRepositoryAdmin(t *testing.T) { - t.Run("should return 200 when valid request", func(t *testing.T) { +func TestSetContextAccountID(t *testing.T) { + t.Run("should return 200 when success set context", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - respBytes, _ := json.Marshal(httpEntities.Response{Content: true}) - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Once().Return(httpResponse.NewHTTPResponse(resp), nil) - - respBytes, _ = json.Marshal(httpEntities.Response{Content: uuid.New()}) - resp = &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Once().Return(httpResponse.NewHTTPResponse(resp), nil) + grpcMock.On("GetAccountID").Return(&authGrpc.GetAccountIDResponse{AccountID: uuid.New().String()}, nil) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } - handler := middleware.IsRepositoryAdmin(http.HandlerFunc(test.Handler)) + handler := middleware.SetContextAccountID(http.HandlerFunc(test.Handler)) req, _ := http.NewRequest("GET", "http://test", nil) req.Header.Add("Authorization", "123") @@ -285,18 +291,18 @@ func TestIsRepositoryAdmin(t *testing.T) { assert.Equal(t, http.StatusOK, w.Code) }) - t.Run("should return 401 when invalid request", func(t *testing.T) { + t.Run("should return 401 when failed to set context", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - respBytes, _ := json.Marshal(httpEntities.Response{Content: false}) - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Return(httpResponse.NewHTTPResponse(resp), errors.New("test")) + grpcMock.On("GetAccountID").Return(&authGrpc.GetAccountIDResponse{AccountID: uuid.New().String()}, errors.New("test")) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } - handler := middleware.IsRepositoryAdmin(http.HandlerFunc(test.Handler)) + handler := middleware.SetContextAccountID(http.HandlerFunc(test.Handler)) req, _ := http.NewRequest("GET", "http://test", nil) req.Header.Add("Authorization", "123") @@ -308,19 +314,21 @@ func TestIsRepositoryAdmin(t *testing.T) { }) } -func TestSetContextAccountID(t *testing.T) { - t.Run("should return 200 when success set context", func(t *testing.T) { +func TestIsApplicationAdmin(t *testing.T) { + t.Run("should return 200 when valid request", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - respBytes, _ := json.Marshal(httpEntities.Response{Content: uuid.New()}) - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Return(httpResponse.NewHTTPResponse(resp), nil) + grpcMock.On("IsAuthorized").Return(&authGrpc.IsAuthorizedResponse{IsAuthorized: true}, nil) + grpcMock.On("GetAccountID").Return(&authGrpc.GetAccountIDResponse{AccountID: uuid.New().String()}, nil) + grpcMock.On("GetAuthConfig").Return(&authGrpc.GetAuthConfigResponse{AuthType: authEnums.Horusec.ToString(), ApplicationAdminEnable: true}, nil) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } - handler := middleware.SetContextAccountID(http.HandlerFunc(test.Handler)) + handler := middleware.IsApplicationAdmin(http.HandlerFunc(test.Handler)) req, _ := http.NewRequest("GET", "http://test", nil) req.Header.Add("Authorization", "123") @@ -331,18 +339,20 @@ func TestSetContextAccountID(t *testing.T) { assert.Equal(t, http.StatusOK, w.Code) }) - t.Run("should return 401 when failed to set context", func(t *testing.T) { + t.Run("should return 401 when invalid request", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - respBytes, _ := json.Marshal(httpEntities.Response{Content: uuid.New()}) - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(string(respBytes)))} - httpMock.On("DoRequest").Return(httpResponse.NewHTTPResponse(resp), errors.New("test")) + grpcMock.On("IsAuthorized").Return(&authGrpc.IsAuthorizedResponse{IsAuthorized: true}, errors.New("test")) + grpcMock.On("GetAccountID").Return(&authGrpc.GetAccountIDResponse{AccountID: uuid.New().String()}, nil) + grpcMock.On("GetAuthConfig").Return(&authGrpc.GetAuthConfigResponse{AuthType: authEnums.Horusec.ToString(), ApplicationAdminEnable: true}, nil) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } - handler := middleware.SetContextAccountID(http.HandlerFunc(test.Handler)) + handler := middleware.IsApplicationAdmin(http.HandlerFunc(test.Handler)) req, _ := http.NewRequest("GET", "http://test", nil) req.Header.Add("Authorization", "123") @@ -353,17 +363,20 @@ func TestSetContextAccountID(t *testing.T) { assert.Equal(t, http.StatusUnauthorized, w.Code) }) - t.Run("should return 401 when failed to parse body", func(t *testing.T) { + t.Run("should return 401 when failed to get auth type", func(t *testing.T) { httpMock := &httpClient.Mock{} + grpcMock := &authGrpc.Mock{} - resp := &http.Response{Body: ioutil.NopCloser(strings.NewReader(""))} - httpMock.On("DoRequest").Return(httpResponse.NewHTTPResponse(resp), nil) + grpcMock.On("IsAuthorized").Return(&authGrpc.IsAuthorizedResponse{IsAuthorized: true}, errors.New("test")) + grpcMock.On("GetAccountID").Return(&authGrpc.GetAccountIDResponse{AccountID: uuid.New().String()}, nil) + grpcMock.On("GetAuthConfig").Return(&authGrpc.GetAuthConfigResponse{}, errors.New("test")) middleware := HorusAuthzMiddleware{ - httpUtil: httpMock, + httpUtil: httpMock, + grpcClient: grpcMock, } - handler := middleware.SetContextAccountID(http.HandlerFunc(test.Handler)) + handler := middleware.IsApplicationAdmin(http.HandlerFunc(test.Handler)) req, _ := http.NewRequest("GET", "http://test", nil) req.Header.Add("Authorization", "123") diff --git a/e2e/deployments/docker-compose.yaml b/e2e/deployments/docker-compose.yaml index 2cada0643..5804012d6 100644 --- a/e2e/deployments/docker-compose.yaml +++ b/e2e/deployments/docker-compose.yaml @@ -3,12 +3,14 @@ services: # rabbit: # container_name: rabbit # image: rabbitmq:3-management +# network_mode: "host" # ports: # - "5672:5672" # - "15672:15672" postgresql: container_name: postgresql image: postgres:12 + network_mode: "host" ports: - "5432:5432" environment: @@ -30,10 +32,11 @@ services: # - "rabbit" # restart: always # container_name: horusec-messages +# network_mode: "host" # ports: # - "8004:8004" # environment: -# HORUSEC_BROKER_HOST: rabbit +# HORUSEC_BROKER_HOST: "127.0.0.1" # HORUSEC_BROKER_PORT: "5672" # HORUSEC_BROKER_USERNAME: "guest" # HORUSEC_BROKER_PASSWORD: "guest" @@ -52,18 +55,19 @@ services: - postgresql restart: always container_name: horusec-account + network_mode: "host" ports: - "8003:8003" environment: HORUSEC_ACCOUNT_DISABLE_EMAIL_SERVICE: "true" -# HORUSEC_BROKER_HOST: rabbit +# HORUSEC_BROKER_HOST: "127.0.0.1" # HORUSEC_BROKER_PORT: "5672" # HORUSEC_BROKER_USERNAME: "guest" # HORUSEC_BROKER_PASSWORD: "guest" - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" HORUSEC_JWT_SECRET_KEY: "horusec-secret" - HORUSEC_AUTH_URL: "http://horusec-auth:8006" + HORUSEC_AUTH_URL: "127.0.0.1:8007" horusec-auth: build: context: ../../ @@ -72,10 +76,12 @@ services: - postgresql restart: always container_name: horusec-auth + network_mode: "host" ports: - "8006:8006" + - "8007:8007" environment: - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" HORUSEC_JWT_SECRET_KEY: "horusec-secret" HORUSEC_KEYCLOAK_BASE_PATH: ${HORUSEC_KEYCLOAK_BASE_PATH} @@ -93,12 +99,13 @@ services: - postgresql restart: always container_name: horusec-analytic + network_mode: "host" ports: - "8005:8005" environment: - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" - HORUSEC_AUTH_URL: "http://horusec-auth:8006" + HORUSEC_AUTH_URL: "127.0.0.1:8007" horusec-api: build: context: ../../ @@ -107,10 +114,11 @@ services: - postgresql restart: always container_name: horusec-api + network_mode: "host" ports: - "8000:8000" environment: - HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@postgresql:5432/horusec_db?sslmode=disable" + HORUSEC_DATABASE_SQL_URI: "postgresql://root:root@127.0.0.1:5432/horusec_db?sslmode=disable" HORUSEC_DATABASE_SQL_DIALECT: "postgres" HORUSEC_JWT_SECRET_KEY: "horusec-secret" - HORUSEC_AUTH_URL: "http://horusec-auth:8006" \ No newline at end of file + HORUSEC_AUTH_URL: "127.0.0.1:8007" \ No newline at end of file diff --git a/e2e/server/http_test.go b/e2e/server/http_test.go index 06da23499..90d12675b 100644 --- a/e2e/server/http_test.go +++ b/e2e/server/http_test.go @@ -46,9 +46,9 @@ func TestServer(t *testing.T) { } t.Run("Should tests default auth-type (horusec) http requests", func(t *testing.T) { CreateAccount(t, &accountentities.Account{ - Email: "e2e@example.com", - Password: "Ch@ng3m3", - Username: "e2e_user", + Email: "e2e@example.com", + Password: "Ch@ng3m3", + Username: "e2e_user", }) bearerToken, _ := Login(t, &accountentities.LoginData{ Email: "e2e@example.com", @@ -137,18 +137,18 @@ func RunDashboardByRepository(t *testing.T, bearerToken, companyID, repositoryID func RunCompanyCRUD(t *testing.T, bearerToken string) string { companyID := CreateCompany(t, bearerToken, &accountentities.Company{ - Name: "zup", + Name: "zup", }) _ = ReadAllCompanies(t, bearerToken) UpdateCompany(t, bearerToken, companyID, &accountentities.Company{ - Name: "zup-1", + Name: "zup-1", }) allCompaniesUpdated := ReadAllCompanies(t, bearerToken) allCompaniesBytes, _ := json.Marshal(allCompaniesUpdated) assert.Contains(t, string(allCompaniesBytes), "zup-1") DeleteCompany(t, bearerToken, companyID) return CreateCompany(t, bearerToken, &accountentities.Company{ - Name: "zup", + Name: "zup", }) } @@ -161,4 +161,4 @@ func RunRepositoryCRUD(t *testing.T, bearerToken, companyID string) string { func RunRepositoryTokenCRUD(t *testing.T, bearerToken, companyID, repositoryID string) string { return GenerateRepositoryToken(t, bearerToken, companyID, repositoryID, api.Token{Description: "access_token"}) -} \ No newline at end of file +} diff --git a/e2e/server/requests.go b/e2e/server/requests.go index bd9cf7435..20981c90e 100644 --- a/e2e/server/requests.go +++ b/e2e/server/requests.go @@ -185,7 +185,7 @@ func InsertAnalysisWithRepositoryToken(t *testing.T, analysisData *api.AnalysisD } func GetChartContent(t *testing.T, route, bearerToken, companyID, repositoryID string) []byte { - fmt.Println("Running test for GetChartContent in route: "+ route) + fmt.Println("Running test for GetChartContent in route: " + route) fmt.Println("Running test for GetChartRESTContentAndReturnBody") now := time.Now() initialDateStr := now.Format("2006-01-02") + "T00:00:00Z" @@ -198,7 +198,7 @@ func GetChartContent(t *testing.T, route, bearerToken, companyID, repositoryID s assert.NoError(t, err) res, err := client.NewHTTPClient(15).DoRequest(req, &tls.Config{}) assert.NoError(t, err) - assert.Equal(t, res.GetStatusCode(), http.StatusOK) + assert.Equal(t, http.StatusOK, res.GetStatusCode()) body, err := res.GetBody() assert.NoError(t, err) return body @@ -249,8 +249,8 @@ func GetChartDetailsUsingGraphQLAndReturnBody(t *testing.T, bearerToken, company assert.NoError(t, err) res, err := client.NewHTTPClient(15).DoRequest(req, &tls.Config{}) assert.NoError(t, err) - assert.Equal(t, res.GetStatusCode(), http.StatusOK) + assert.Equal(t, http.StatusOK, res.GetStatusCode()) body, err := res.GetBody() assert.NoError(t, err) return body -} \ No newline at end of file +} diff --git a/go.mod b/go.mod index 8dd6e49a5..1e7fa25c3 100644 --- a/go.mod +++ b/go.mod @@ -25,6 +25,7 @@ require ( github.com/go-openapi/swag v0.19.11 // indirect github.com/go-ozzo/ozzo-validation/v4 v4.3.0 github.com/golang-migrate/migrate/v4 v4.13.0 + github.com/golang/protobuf v1.4.3 github.com/google/uuid v1.1.2 github.com/graphql-go/graphql v0.7.9 github.com/hashicorp/errwrap v1.1.0 // indirect @@ -67,6 +68,8 @@ require ( golang.org/x/sys v0.0.0-20201029080932-201ba4db2418 // indirect golang.org/x/text v0.3.4 // indirect golang.org/x/tools v0.0.0-20201029182919-e7a17c4c1366 // indirect + google.golang.org/grpc v1.31.0 + google.golang.org/protobuf v1.25.0 gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df gopkg.in/ini.v1 v1.62.0 // indirect diff --git a/go.sum b/go.sum index 2b0c628d9..b8472932f 100644 --- a/go.sum +++ b/go.sum @@ -1104,6 +1104,7 @@ google.golang.org/genproto v0.0.0-20200726014623-da3ae01ef02d/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200806141610-86f49bd18e98/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200815001618-f69a88009b70 h1:wboULUXGF3c5qdUnKp+6gLAccE6PRpa/czkYvQ4UXv8= google.golang.org/genproto v0.0.0-20200815001618-f69a88009b70/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= @@ -1121,6 +1122,7 @@ google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8 google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.0 h1:T7P4R73V3SSDPhH7WW7ATbfViLtmamH0DKrP3f9AuDI= google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= diff --git a/horusec-account/README.md b/horusec-account/README.md index 29789bc64..00e1648f9 100644 --- a/horusec-account/README.md +++ b/horusec-account/README.md @@ -48,7 +48,9 @@ To change variables environment to run your analysis also you set new values. | HORUSEC_PORT | 8003 | This environment get the port that the service will start | | HORUSEC_JWT_SECRET_KEY | horusec-secret | This environment get JWT secret key | | HORUSEC_ACCOUNT_DISABLE_EMAIL_SERVICE | false | Disable email confirmation on user register | -| HORUSEC_AUTH_URL | http://localhost:8006 | This environment get horusec url to mount horusec auth url | +| HORUSEC_GRPC_AUTH_URL | localhost:8007 | This environment get horusec url to mount horusec auth url | +| HORUSEC_GRPC_USE_CERTS | false | This environment get if use of certificates is active or not | +| HORUSEC_GRPC_CERT_PATH | | This environment get grpc certificate path | ## Swagger To update swagger.json, you need run command into **root horusec-account folder** diff --git a/horusec-account/cmd/app/main.go b/horusec-account/cmd/app/main.go index bc32558b4..6f8702098 100644 --- a/horusec-account/cmd/app/main.go +++ b/horusec-account/cmd/app/main.go @@ -18,6 +18,7 @@ package main import ( "github.com/ZupIT/horusec/development-kit/pkg/databases/relational/repository/cache" brokerLib "github.com/ZupIT/horusec/development-kit/pkg/services/broker" + grpcConfig "github.com/ZupIT/horusec/horusec-account/config/grpc" "log" "net/http" @@ -54,7 +55,8 @@ func main() { cacheRepository := cache.NewCacheRepository(databaseRead, databaseWrite) server := serverUtil.NewServerConfig("8003", cors.NewCorsConfig()).Timeout(10) - chiRouter := router.NewRouter(server).GetRouter(broker, databaseRead, databaseWrite, cacheRepository, appConfig) + chiRouter := router.NewRouter(server).GetRouter(broker, databaseRead, databaseWrite, + cacheRepository, appConfig, grpcConfig.SetupGrpcConnection()) log.Println("service running on port", server.GetPort()) swagger.SetupSwagger(chiRouter, "8003") diff --git a/horusec-account/config/grpc/grpc.go b/horusec-account/config/grpc/grpc.go new file mode 100644 index 000000000..8a94508d2 --- /dev/null +++ b/horusec-account/config/grpc/grpc.go @@ -0,0 +1,40 @@ +package grpc + +import ( + "github.com/ZupIT/horusec/development-kit/pkg/utils/env" + "github.com/ZupIT/horusec/development-kit/pkg/utils/logger" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" +) + +func SetupGrpcConnection() *grpc.ClientConn { + if env.GetEnvOrDefaultBool("HORUSEC_GRPC_USE_CERTS", false) { + return setupWithCerts() + } + + return setupWithoutCerts() +} + +func setupWithoutCerts() *grpc.ClientConn { + conn, err := grpc.Dial(env.GetEnvOrDefault("HORUSEC_GRPC_AUTH_URL", "localhost:8007"), grpc.WithInsecure()) + if err != nil { + logger.LogPanic("failed to connect to auth grpc", err) + } + + return conn +} + +func setupWithCerts() *grpc.ClientConn { + cred, err := credentials.NewClientTLSFromFile(env.GetEnvOrDefault("HORUSEC_GRPC_CERT_PATH", ""), "") + if err != nil { + logger.LogPanic("failed to get grpc credentials", err) + } + + conn, err := grpc.Dial(env.GetEnvOrDefault("HORUSEC_GRPC_AUTH_URL", "localhost:8007"), + grpc.WithTransportCredentials(cred)) + if err != nil { + logger.LogPanic("failed to connect to auth grpc", err) + } + + return conn +} diff --git a/horusec-account/internal/router/route_test.go b/horusec-account/internal/router/route_test.go index 06cc9b472..34b57c184 100644 --- a/horusec-account/internal/router/route_test.go +++ b/horusec-account/internal/router/route_test.go @@ -34,7 +34,7 @@ func TestGetRouter(t *testing.T) { router := NewRouter(server.NewServerConfig("8000", &cors.Options{})) assert.NotNil(t, router) - mux := router.GetRouter(nil, nil, nil, nil, nil) + mux := router.GetRouter(nil, nil, nil, nil, nil, nil) assert.NotNil(t, mux) }) } diff --git a/horusec-account/internal/router/router.go b/horusec-account/internal/router/router.go index 2e8e72ae1..6e3b98eb5 100644 --- a/horusec-account/internal/router/router.go +++ b/horusec-account/internal/router/router.go @@ -30,6 +30,7 @@ import ( "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/prometheus/client_golang/prometheus/promhttp" + "google.golang.org/grpc" ) type Router struct { @@ -44,10 +45,10 @@ func NewRouter(config *serverConfig.Server) *Router { } } -func (r *Router) GetRouter(broker brokerLib.IBroker, databaseRead SQL.InterfaceRead, - databaseWrite SQL.InterfaceWrite, cacheRepository cache.Interface, appConfig app.IAppConfig) *chi.Mux { +func (r *Router) GetRouter(broker brokerLib.IBroker, databaseRead SQL.InterfaceRead, databaseWrite SQL.InterfaceWrite, + cacheRepository cache.Interface, appConfig app.IAppConfig, grpcCon *grpc.ClientConn) *chi.Mux { r.setMiddleware() - r.setAPIRoutes(broker, databaseRead, databaseWrite, cacheRepository, appConfig) + r.setAPIRoutes(broker, databaseRead, databaseWrite, cacheRepository, appConfig, grpcCon) return r.router } @@ -62,11 +63,11 @@ func (r *Router) setMiddleware() { r.RouterMetrics() } -func (r *Router) setAPIRoutes(broker brokerLib.IBroker, databaseRead SQL.InterfaceRead, - databaseWrite SQL.InterfaceWrite, cacheRepository cache.Interface, appConfig app.IAppConfig) { +func (r *Router) setAPIRoutes(broker brokerLib.IBroker, databaseRead SQL.InterfaceRead, databaseWrite SQL.InterfaceWrite, + cacheRepository cache.Interface, appConfig app.IAppConfig, grpcCon *grpc.ClientConn) { r.RouterHealth(broker, databaseRead, databaseWrite, appConfig) - r.RouterAccount(broker, databaseRead, databaseWrite, cacheRepository, appConfig) - r.RouterCompany(broker, databaseRead, databaseWrite, cacheRepository, appConfig) + r.RouterAccount(broker, databaseRead, databaseWrite, cacheRepository, appConfig, grpcCon) + r.RouterCompany(broker, databaseRead, databaseWrite, cacheRepository, appConfig, grpcCon) } func (r *Router) EnableRealIP() *Router { @@ -110,9 +111,10 @@ func (r *Router) RouterMetrics() *Router { } func (r *Router) RouterAccount(broker brokerLib.IBroker, databaseRead SQL.InterfaceRead, - databaseWrite SQL.InterfaceWrite, cacheRepository cache.Interface, appConfig app.IAppConfig) *Router { + databaseWrite SQL.InterfaceWrite, cacheRepository cache.Interface, appConfig app.IAppConfig, + grpcCon *grpc.ClientConn) *Router { handler := account.NewHandler(broker, databaseRead, databaseWrite, cacheRepository, appConfig) - authzMiddleware := middlewares.NewHorusAuthzMiddleware() + authzMiddleware := middlewares.NewHorusAuthzMiddleware(grpcCon) r.router.Route(routes.AccountHandler, func(router chi.Router) { router.Post("/login", handler.Login) router.Post("/create-account", handler.CreateAccount) @@ -131,9 +133,10 @@ func (r *Router) RouterAccount(broker brokerLib.IBroker, databaseRead SQL.Interf } func (r *Router) RouterCompany(broker brokerLib.IBroker, databaseRead SQL.InterfaceRead, - databaseWrite SQL.InterfaceWrite, cacheRepository cache.Interface, appConfig app.IAppConfig) *Router { + databaseWrite SQL.InterfaceWrite, cacheRepository cache.Interface, + appConfig app.IAppConfig, grpcCon *grpc.ClientConn) *Router { handler := company.NewHandler(databaseWrite, databaseRead, cacheRepository, broker, appConfig) - authzMiddleware := middlewares.NewHorusAuthzMiddleware() + authzMiddleware := middlewares.NewHorusAuthzMiddleware(grpcCon) r.router.Route(routes.CompanyHandler, func(router chi.Router) { router.With(authzMiddleware.IsApplicationAdmin).Post("/", handler.Create) router.With(authzMiddleware.SetContextAccountID).Get("/", handler.List) @@ -145,16 +148,16 @@ func (r *Router) RouterCompany(broker brokerLib.IBroker, databaseRead SQL.Interf router.With(authzMiddleware.IsCompanyAdmin).Delete("/{companyID}", handler.Delete) router.With(authzMiddleware.IsCompanyAdmin).Delete("/{companyID}/roles/{accountID}", handler.RemoveUser) router.Route("/{companyID}/repositories", - r.routerCompanyRepositories(databaseRead, databaseWrite, broker, appConfig)) + r.routerCompanyRepositories(databaseRead, databaseWrite, broker, appConfig, grpcCon)) }) return r } func (r *Router) routerCompanyRepositories(databaseRead SQL.InterfaceRead, databaseWrite SQL.InterfaceWrite, broker brokerLib.IBroker, - appConfig app.IAppConfig) func(router chi.Router) { + appConfig app.IAppConfig, grpcCon *grpc.ClientConn) func(router chi.Router) { handler := repositories.NewRepositoryHandler(databaseWrite, databaseRead, broker, appConfig) - authzMiddleware := middlewares.NewHorusAuthzMiddleware() + authzMiddleware := middlewares.NewHorusAuthzMiddleware(grpcCon) return func(router chi.Router) { router.Use(authzMiddleware.IsCompanyMember) router.With(authzMiddleware.SetContextAccountID).Get("/", handler.List) diff --git a/horusec-analytic/README.md b/horusec-analytic/README.md index f898cd862..8b0ac9fba 100644 --- a/horusec-analytic/README.md +++ b/horusec-analytic/README.md @@ -33,7 +33,9 @@ To change variables environment to run your analysis also you set new values. | HORUSEC_DATABASE_SQL_DIALECT | postgres | This environment get dialect to connect on database POSTGRES | | HORUSEC_DATABASE_SQL_LOG_MODE | false | This environment get bool to enable logs on POSTGRES | | HORUSEC_PORT | 8005 | This environment get the port that the service will start | -| HORUSEC_AUTH_URL | http://localhost:8006 | This environment get horusec url to mount horusec auth url | +| HORUSEC_GRPC_AUTH_URL | localhost:8007 | This environment get horusec url to mount horusec auth url | +| HORUSEC_GRPC_USE_CERTS | false | This environment get if use of certificates is active or not | +| HORUSEC_GRPC_CERT_PATH | | This environment get grpc certificate path | ## Swagger To update swagger.json, you need run command into **root horusec-analytic folder** diff --git a/horusec-analytic/cmd/app/main.go b/horusec-analytic/cmd/app/main.go index c120daca3..43afc98d3 100644 --- a/horusec-analytic/cmd/app/main.go +++ b/horusec-analytic/cmd/app/main.go @@ -15,6 +15,7 @@ package main import ( + "github.com/ZupIT/horusec/horusec-analytic/config/grpc" "log" "net/http" @@ -40,7 +41,7 @@ func main() { postgresRead := adapter.NewRepositoryRead() server := serverUtil.NewServerConfig("8005", cors.NewCorsConfig()).Timeout(10) - chiRouter := router.NewRouter(server).GetRouter(postgresRead) + chiRouter := router.NewRouter(server).GetRouter(postgresRead, grpc.SetupGrpcConnection()) log.Println("service running on port", server.GetPort()) swagger.SetupSwagger(chiRouter, "8005") diff --git a/horusec-analytic/config/grpc/grpc.go b/horusec-analytic/config/grpc/grpc.go new file mode 100644 index 000000000..8a94508d2 --- /dev/null +++ b/horusec-analytic/config/grpc/grpc.go @@ -0,0 +1,40 @@ +package grpc + +import ( + "github.com/ZupIT/horusec/development-kit/pkg/utils/env" + "github.com/ZupIT/horusec/development-kit/pkg/utils/logger" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" +) + +func SetupGrpcConnection() *grpc.ClientConn { + if env.GetEnvOrDefaultBool("HORUSEC_GRPC_USE_CERTS", false) { + return setupWithCerts() + } + + return setupWithoutCerts() +} + +func setupWithoutCerts() *grpc.ClientConn { + conn, err := grpc.Dial(env.GetEnvOrDefault("HORUSEC_GRPC_AUTH_URL", "localhost:8007"), grpc.WithInsecure()) + if err != nil { + logger.LogPanic("failed to connect to auth grpc", err) + } + + return conn +} + +func setupWithCerts() *grpc.ClientConn { + cred, err := credentials.NewClientTLSFromFile(env.GetEnvOrDefault("HORUSEC_GRPC_CERT_PATH", ""), "") + if err != nil { + logger.LogPanic("failed to get grpc credentials", err) + } + + conn, err := grpc.Dial(env.GetEnvOrDefault("HORUSEC_GRPC_AUTH_URL", "localhost:8007"), + grpc.WithTransportCredentials(cred)) + if err != nil { + logger.LogPanic("failed to connect to auth grpc", err) + } + + return conn +} diff --git a/horusec-analytic/internal/router/route_test.go b/horusec-analytic/internal/router/route_test.go index ad77d030a..c46e426a6 100644 --- a/horusec-analytic/internal/router/route_test.go +++ b/horusec-analytic/internal/router/route_test.go @@ -34,7 +34,7 @@ func TestGetRouter(t *testing.T) { router := NewRouter(server.NewServerConfig("8005", &cors.Options{})) assert.NotNil(t, router) - mux := router.GetRouter(nil) + mux := router.GetRouter(nil, nil) assert.NotNil(t, mux) }) } diff --git a/horusec-analytic/internal/router/router.go b/horusec-analytic/internal/router/router.go index 4ca02f68a..d05780afb 100644 --- a/horusec-analytic/internal/router/router.go +++ b/horusec-analytic/internal/router/router.go @@ -25,6 +25,7 @@ import ( "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/prometheus/client_golang/prometheus/promhttp" + "google.golang.org/grpc" ) type Router struct { @@ -50,10 +51,10 @@ func (r *Router) setMiddleware() { r.RouterMetrics() } -func (r *Router) GetRouter(postgresRead relational.InterfaceRead) *chi.Mux { +func (r *Router) GetRouter(postgresRead relational.InterfaceRead, grpcCon *grpc.ClientConn) *chi.Mux { r.setMiddleware() - r.RouterCompanyAnalytic(postgresRead) - r.RouterRepositoryAnalytic(postgresRead) + r.RouterCompanyAnalytic(postgresRead, grpcCon) + r.RouterRepositoryAnalytic(postgresRead, grpcCon) r.RouterHealth(postgresRead) return r.router } @@ -108,9 +109,9 @@ func (r *Router) RouterHealth(postgresRead relational.InterfaceRead) *Router { return r } -func (r *Router) RouterCompanyAnalytic(postgresRead relational.InterfaceRead) *Router { +func (r *Router) RouterCompanyAnalytic(postgresRead relational.InterfaceRead, grpcCon *grpc.ClientConn) *Router { handler := dashboard.NewDashboardHandler(postgresRead) - authz := middlewares.NewHorusAuthzMiddleware() + authz := middlewares.NewHorusAuthzMiddleware(grpcCon) r.router.Route(routes.CompanyHandler, func(router chi.Router) { router.With(authz.IsCompanyAdmin).Get("/{companyID}/details", handler.GetVulnDetails) router.With(authz.IsCompanyAdmin).Get("/{companyID}/total-developers", handler.GetCompanyTotalDevelopers) @@ -127,9 +128,9 @@ func (r *Router) RouterCompanyAnalytic(postgresRead relational.InterfaceRead) *R return r } -func (r *Router) RouterRepositoryAnalytic(postgresRead relational.InterfaceRead) *Router { +func (r *Router) RouterRepositoryAnalytic(postgresRead relational.InterfaceRead, grpcCon *grpc.ClientConn) *Router { handler := dashboard.NewDashboardHandler(postgresRead) - authz := middlewares.NewHorusAuthzMiddleware() + authz := middlewares.NewHorusAuthzMiddleware(grpcCon) r.router.Route(routes.RepositoryHandler, func(router chi.Router) { router.With(authz.IsRepositoryMember).Get("/{repositoryID}/details", handler.GetVulnDetails) router.With(authz.IsRepositoryMember).Get("/{repositoryID}/total-developers", handler.GetRepositoryTotalDevelopers) diff --git a/horusec-api/README.md b/horusec-api/README.md index 71b453b5e..a675e4248 100644 --- a/horusec-api/README.md +++ b/horusec-api/README.md @@ -42,7 +42,9 @@ To change variables environment to run your analysis also you set new values. | HORUSEC_PORT | 8000 | This environment get the port that the service will start | | HORUSEC_SWAGGER_HOST | localhost | This environment get the host for swagger start | | HORUSEC_JWT_SECRET_KEY | horusec-secret | This environment get JWT secret key | -| HORUSEC_AUTH_URL | http://localhost:8006 | This environment get horusec url to mount horusec auth url | +| HORUSEC_GRPC_AUTH_URL | localhost:8007 | This environment get horusec url to mount horusec auth url | +| HORUSEC_GRPC_USE_CERTS | false | This environment get if use of certificates is active or not | +| HORUSEC_GRPC_CERT_PATH | | This environment get grpc certificate path | ## Swagger To update swagger.json, you need run command into **root horusec-api folder** diff --git a/horusec-api/cmd/app/main.go b/horusec-api/cmd/app/main.go index 893cdef6a..204134e62 100644 --- a/horusec-api/cmd/app/main.go +++ b/horusec-api/cmd/app/main.go @@ -15,6 +15,7 @@ package main import ( + "github.com/ZupIT/horusec/horusec-api/config/grpc" "log" "net/http" @@ -42,7 +43,7 @@ func main() { postgresWrite := adapter.NewRepositoryWrite() server := serverUtil.NewServerConfig("8000", cors.NewCorsConfig()).Timeout(10) - chiRouter := router.NewRouter(server).GetRouter(postgresRead, postgresWrite) + chiRouter := router.NewRouter(server).GetRouter(postgresRead, postgresWrite, grpc.SetupGrpcConnection()) log.Println("service running on port", server.GetPort()) swagger.SetupSwagger(chiRouter, "8000") diff --git a/horusec-api/config/grpc/grpc.go b/horusec-api/config/grpc/grpc.go new file mode 100644 index 000000000..8a94508d2 --- /dev/null +++ b/horusec-api/config/grpc/grpc.go @@ -0,0 +1,40 @@ +package grpc + +import ( + "github.com/ZupIT/horusec/development-kit/pkg/utils/env" + "github.com/ZupIT/horusec/development-kit/pkg/utils/logger" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" +) + +func SetupGrpcConnection() *grpc.ClientConn { + if env.GetEnvOrDefaultBool("HORUSEC_GRPC_USE_CERTS", false) { + return setupWithCerts() + } + + return setupWithoutCerts() +} + +func setupWithoutCerts() *grpc.ClientConn { + conn, err := grpc.Dial(env.GetEnvOrDefault("HORUSEC_GRPC_AUTH_URL", "localhost:8007"), grpc.WithInsecure()) + if err != nil { + logger.LogPanic("failed to connect to auth grpc", err) + } + + return conn +} + +func setupWithCerts() *grpc.ClientConn { + cred, err := credentials.NewClientTLSFromFile(env.GetEnvOrDefault("HORUSEC_GRPC_CERT_PATH", ""), "") + if err != nil { + logger.LogPanic("failed to get grpc credentials", err) + } + + conn, err := grpc.Dial(env.GetEnvOrDefault("HORUSEC_GRPC_AUTH_URL", "localhost:8007"), + grpc.WithTransportCredentials(cred)) + if err != nil { + logger.LogPanic("failed to connect to auth grpc", err) + } + + return conn +} diff --git a/horusec-api/internal/router/route_test.go b/horusec-api/internal/router/route_test.go index 8918b174a..27c8e9b85 100644 --- a/horusec-api/internal/router/route_test.go +++ b/horusec-api/internal/router/route_test.go @@ -34,7 +34,7 @@ func TestGetRouter(t *testing.T) { router := NewRouter(server.NewServerConfig("8000", &cors.Options{})) assert.NotNil(t, router) - mux := router.GetRouter(nil, nil) + mux := router.GetRouter(nil, nil, nil) assert.NotNil(t, mux) }) } diff --git a/horusec-api/internal/router/router.go b/horusec-api/internal/router/router.go index e09fd22ba..85cd59a16 100644 --- a/horusec-api/internal/router/router.go +++ b/horusec-api/internal/router/router.go @@ -28,6 +28,7 @@ import ( "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/prometheus/client_golang/prometheus/promhttp" + "google.golang.org/grpc" ) type Router struct { @@ -53,13 +54,14 @@ func (r *Router) setMiddleware() { r.RouterMetrics() } -func (r *Router) GetRouter(postgresRead relational.InterfaceRead, postgresWrite relational.InterfaceWrite) *chi.Mux { +func (r *Router) GetRouter(postgresRead relational.InterfaceRead, postgresWrite relational.InterfaceWrite, + grpcCon *grpc.ClientConn) *chi.Mux { r.setMiddleware() r.RouterHealth(postgresRead, postgresWrite) r.RouterAnalysis(postgresRead, postgresWrite) - r.RouterTokensRepository(postgresRead, postgresWrite) - r.RouterTokensCompany(postgresRead, postgresWrite) - r.RouterManagement(postgresRead, postgresWrite) + r.RouterTokensRepository(postgresRead, postgresWrite, grpcCon) + r.RouterTokensCompany(postgresRead, postgresWrite, grpcCon) + r.RouterManagement(postgresRead, postgresWrite, grpcCon) return r.router } @@ -128,9 +130,9 @@ func (r *Router) RouterAnalysis(postgresRead relational.InterfaceRead, } func (r *Router) RouterTokensRepository( - postgresRead relational.InterfaceRead, postgresWrite relational.InterfaceWrite) *Router { + postgresRead relational.InterfaceRead, postgresWrite relational.InterfaceWrite, grpcCon *grpc.ClientConn) *Router { handler := tokensRepository.NewHandler(postgresRead, postgresWrite) - authMiddleware := middlewares.NewHorusAuthzMiddleware() + authMiddleware := middlewares.NewHorusAuthzMiddleware(grpcCon) r.router.Route(routes.TokensRepositoryHandler, func(router chi.Router) { router.With(authMiddleware.IsRepositoryAdmin).Post("/", handler.Post) router.With(authMiddleware.IsRepositoryAdmin).Get("/", handler.Get) @@ -142,9 +144,9 @@ func (r *Router) RouterTokensRepository( } func (r *Router) RouterTokensCompany( - postgresRead relational.InterfaceRead, postgresWrite relational.InterfaceWrite) *Router { + postgresRead relational.InterfaceRead, postgresWrite relational.InterfaceWrite, grpcCon *grpc.ClientConn) *Router { handler := tokensCompany.NewHandler(postgresRead, postgresWrite) - companyMiddleware := middlewares.NewHorusAuthzMiddleware() + companyMiddleware := middlewares.NewHorusAuthzMiddleware(grpcCon) r.router.Route(routes.TokensCompanyHandler, func(router chi.Router) { router.With(companyMiddleware.IsCompanyAdmin).Post("/", handler.Post) router.With(companyMiddleware.IsCompanyAdmin).Get("/", handler.Get) @@ -156,8 +158,8 @@ func (r *Router) RouterTokensCompany( } func (r *Router) RouterManagement( - postgresRead relational.InterfaceRead, postgresWrite relational.InterfaceWrite) *Router { - repositoryMiddleware := middlewares.NewHorusAuthzMiddleware() + postgresRead relational.InterfaceRead, postgresWrite relational.InterfaceWrite, grpcCon *grpc.ClientConn) *Router { + repositoryMiddleware := middlewares.NewHorusAuthzMiddleware(grpcCon) handler := management.NewHandler(postgresRead, postgresWrite) r.router.Route(routes.ManagementHandler, func(router chi.Router) { router.With(repositoryMiddleware.IsRepositoryMember).Get("/", handler.Get) diff --git a/horusec-auth/README.md b/horusec-auth/README.md index 4784d5680..47c0d5c62 100644 --- a/horusec-auth/README.md +++ b/horusec-auth/README.md @@ -43,6 +43,10 @@ To change variables environment to run your analysis also you set new values. | HORUSEC_KEYCLOAK_CLIENT_SECRET | | This environment get keycloak client secret | | HORUSEC_KEYCLOAK_REALM | | This environment get keycloak realm | | HORUSEC_KEYCLOAK_OTP | false | This environment get keycloak opt | +| HORUSEC_GRPC_PORT | 8007 | This environment get grpc port | +| HORUSEC_GRPC_USE_CERTS | false | This environment get if use of certificates is active or not | +| HORUSEC_GRPC_CERT_PATH | | This environment get grpc certificate path | +| HORUSEC_GRPC_KEY_PATH | | This environment get grpc certificate key path | | HORUSEC_ENABLE_APPLICATION_ADMIN | false | This environment set if you need active application admin in system. When this environment is setup to `true` only application admin users can create company in horusec. | | HORUSEC_APPLICATION_ADMIN_DATA | {\"username\": \"horusec-admin\", \"email\":\"horusec-admin@example.com\", \"password\":\"Devpass0*\"} | When application admin is enable and auth-type is `horusec` we need create default user application admin with this content in horusec. Don't forget to **escape the json** at the value of the environment variable. | diff --git a/horusec-auth/cmd/app/main.go b/horusec-auth/cmd/app/main.go index edf0b3e73..713870244 100644 --- a/horusec-auth/cmd/app/main.go +++ b/horusec-auth/cmd/app/main.go @@ -15,14 +15,12 @@ package main import ( - "github.com/ZupIT/horusec/development-kit/pkg/databases/relational" "github.com/ZupIT/horusec/development-kit/pkg/databases/relational/adapter" - "github.com/ZupIT/horusec/development-kit/pkg/databases/relational/repository/account" - accountEntities "github.com/ZupIT/horusec/development-kit/pkg/entities/account" serverUtil "github.com/ZupIT/horusec/development-kit/pkg/utils/http/server" - "github.com/ZupIT/horusec/development-kit/pkg/utils/logger" + adminConfig "github.com/ZupIT/horusec/horusec-auth/config/admin" "github.com/ZupIT/horusec/horusec-auth/config/app" "github.com/ZupIT/horusec/horusec-auth/config/cors" + grpcConfig "github.com/ZupIT/horusec/horusec-auth/config/grpc" "github.com/ZupIT/horusec/horusec-auth/config/swagger" "github.com/ZupIT/horusec/horusec-auth/internal/router" "log" @@ -46,7 +44,7 @@ func main() { postgresRead := adapter.NewRepositoryRead() postgresWrite := adapter.NewRepositoryWrite() - createApplicationAdmin(appConfig, postgresRead, postgresWrite) + adminConfig.CreateApplicationAdmin(appConfig, postgresRead, postgresWrite) server := serverUtil.NewServerConfig("8006", cors.NewCorsConfig()).Timeout(10) chiRouter := router.NewRouter(server).GetRouter(postgresRead, postgresWrite, appConfig) @@ -54,35 +52,6 @@ func main() { log.Println("service running on port", server.GetPort()) swagger.SetupSwagger(chiRouter, "8006") + go grpcConfig.SetUpGRPCServer(postgresRead, appConfig) log.Fatal(http.ListenAndServe(server.GetPort(), chiRouter)) } - -func createApplicationAdmin(config *app.Config, read relational.InterfaceRead, write relational.InterfaceWrite) { - if config.GetEnableApplicationAdmin() { - err := account.NewAccountRepository(read, write).Create(getDefaultAccountApplicationAdmin(config).SetAccountData()) - if err != nil { - if err.Error() != "pq: duplicate key value violates unique constraint \"accounts_email_key\"" { - logger.LogPanic("Some error occurs when create application admin", err) - } else { - logger.LogInfo("Application admin already exists") - } - } else { - logger.LogInfo("Application admin created with success") - } - } -} - -func getDefaultAccountApplicationAdmin(config *app.Config) *accountEntities.Account { - entity, err := config.GetApplicationAdminData() - if err != nil { - logger.LogPanic("Some error occurs when parse Application Admin Data to Account", err) - } - pass := entity.Password - return &accountEntities.Account{ - Email: entity.Email, - Password: pass, - Username: entity.Username, - IsConfirmed: true, - IsApplicationAdmin: true, - } -} diff --git a/horusec-auth/config/admin/admin.go b/horusec-auth/config/admin/admin.go new file mode 100644 index 000000000..7ad5334b9 --- /dev/null +++ b/horusec-auth/config/admin/admin.go @@ -0,0 +1,39 @@ +package admin + +import ( + "github.com/ZupIT/horusec/development-kit/pkg/databases/relational" + "github.com/ZupIT/horusec/development-kit/pkg/databases/relational/repository/account" + accountEntities "github.com/ZupIT/horusec/development-kit/pkg/entities/account" + "github.com/ZupIT/horusec/development-kit/pkg/utils/logger" + "github.com/ZupIT/horusec/horusec-auth/config/app" +) + +func CreateApplicationAdmin(config *app.Config, read relational.InterfaceRead, write relational.InterfaceWrite) { + if config.GetEnableApplicationAdmin() { + err := account.NewAccountRepository(read, write).Create(getDefaultAccountApplicationAdmin(config).SetAccountData()) + if err != nil { + if err.Error() != "pq: duplicate key value violates unique constraint \"accounts_email_key\"" { + logger.LogPanic("Some error occurs when create application admin", err) + } else { + logger.LogInfo("Application admin already exists") + } + } else { + logger.LogInfo("Application admin created with success") + } + } +} + +func getDefaultAccountApplicationAdmin(config *app.Config) *accountEntities.Account { + entity, err := config.GetApplicationAdminData() + if err != nil { + logger.LogPanic("Some error occurs when parse Application Admin Data to Account", err) + } + pass := entity.Password + return &accountEntities.Account{ + Email: entity.Email, + Password: pass, + Username: entity.Username, + IsConfirmed: true, + IsApplicationAdmin: true, + } +} diff --git a/horusec-auth/config/grpc/grpc.go b/horusec-auth/config/grpc/grpc.go new file mode 100644 index 000000000..c17bc6bd8 --- /dev/null +++ b/horusec-auth/config/grpc/grpc.go @@ -0,0 +1,54 @@ +package grpc + +import ( + "fmt" + "github.com/ZupIT/horusec/development-kit/pkg/databases/relational" + authGrpc "github.com/ZupIT/horusec/development-kit/pkg/services/grpc/auth" + "github.com/ZupIT/horusec/development-kit/pkg/utils/env" + "github.com/ZupIT/horusec/development-kit/pkg/utils/logger" + "github.com/ZupIT/horusec/horusec-auth/config/app" + authController "github.com/ZupIT/horusec/horusec-auth/internal/controller/auth" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + "net" +) + +func SetUpGRPCServer(postgresRead relational.InterfaceRead, appConfig *app.Config) { + if env.GetEnvOrDefaultBool("HORUSEC_GRPC_USE_CERTS", false) { + setupWithCerts(postgresRead, appConfig) + } + + setupWithoutCerts(postgresRead, appConfig) +} + +func setupWithoutCerts(postgresRead relational.InterfaceRead, appConfig *app.Config) { + server := grpc.NewServer() + authGrpc.RegisterAuthServiceServer(server, authController.NewAuthController(postgresRead, appConfig)) + if err := server.Serve(getNetListener()); err != nil { + logger.LogPanic("failed to setup grpc server", err) + } +} + +func setupWithCerts(postgresRead relational.InterfaceRead, appConfig *app.Config) { + grpCredentials, err := credentials.NewServerTLSFromFile(env.GetEnvOrDefault("HORUSEC_GRPC_CERT_PATH", ""), + env.GetEnvOrDefault("HORUSEC_GRPC_KEY_PATH", "")) + if err != nil { + logger.LogPanic("failed to get grpc credentials", err) + } + + server := grpc.NewServer(grpc.Creds(grpCredentials)) + authGrpc.RegisterAuthServiceServer(server, authController.NewAuthController(postgresRead, appConfig)) + if err := server.Serve(getNetListener()); err != nil { + logger.LogPanic("failed to setup grpc server", err) + } +} + +func getNetListener() net.Listener { + port := env.GetEnvOrDefaultInt("HORUSEC_GRPC_PORT", 8007) + listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) + if err != nil { + logger.LogPanic("failed to get net listener", err) + } + + return listener +} diff --git a/horusec-auth/internal/controller/auth/auth.go b/horusec-auth/internal/controller/auth/auth.go index 60ed13224..34f049b84 100644 --- a/horusec-auth/internal/controller/auth/auth.go +++ b/horusec-auth/internal/controller/auth/auth.go @@ -15,12 +15,15 @@ package auth import ( + "context" "github.com/ZupIT/horusec/development-kit/pkg/databases/relational" authEntities "github.com/ZupIT/horusec/development-kit/pkg/entities/auth" authEnums "github.com/ZupIT/horusec/development-kit/pkg/enums/auth" "github.com/ZupIT/horusec/development-kit/pkg/enums/errors" + authGrpc "github.com/ZupIT/horusec/development-kit/pkg/services/grpc/auth" "github.com/ZupIT/horusec/development-kit/pkg/services/jwt" "github.com/ZupIT/horusec/development-kit/pkg/services/keycloak" + "github.com/ZupIT/horusec/development-kit/pkg/utils/logger" "github.com/ZupIT/horusec/horusec-auth/config/app" "github.com/ZupIT/horusec/horusec-auth/internal/services" horusecService "github.com/ZupIT/horusec/horusec-auth/internal/services/horusec" @@ -30,9 +33,9 @@ import ( type IController interface { AuthByType(credentials *authEntities.Credentials) (interface{}, error) - AuthorizeByType(authorizationData *authEntities.AuthorizationData) (bool, error) - GetAuthType() (authEnums.AuthorizationType, error) - GetAccountIDByAuthType(token string) (uuid.UUID, error) + IsAuthorized(_ context.Context, data *authGrpc.IsAuthorizedData) (*authGrpc.IsAuthorizedResponse, error) + GetAuthConfig(_ context.Context, data *authGrpc.GetAuthConfigData) (*authGrpc.GetAuthConfigResponse, error) + GetAccountID(_ context.Context, data *authGrpc.GetAccountIDData) (*authGrpc.GetAccountIDResponse, error) } type Controller struct { @@ -64,41 +67,82 @@ func (c *Controller) AuthByType(credentials *authEntities.Credentials) (interfac return nil, errors.ErrorUnauthorized } -func (c *Controller) AuthorizeByType(authorizationData *authEntities.AuthorizationData) (bool, error) { +func (c *Controller) IsAuthorized(_ context.Context, + data *authGrpc.IsAuthorizedData) (*authGrpc.IsAuthorizedResponse, error) { switch c.getAuthorizationType() { case authEnums.Horusec: - return c.horusAuthService.IsAuthorized(authorizationData) + return c.setIsAuthorizedResponse(c.horusAuthService.IsAuthorized(c.parseToAuthorizationData(data))) case authEnums.Keycloak: - return c.keycloakAuthService.IsAuthorized(authorizationData) + return c.setIsAuthorizedResponse(c.keycloakAuthService.IsAuthorized(c.parseToAuthorizationData(data))) case authEnums.Ldap: - return false, errors.ErrorUnauthorized + return c.setIsAuthorizedResponse(false, errors.ErrorUnauthorized) } - return false, errors.ErrorUnauthorized + return c.setIsAuthorizedResponse(false, errors.ErrorUnauthorized) } -func (c *Controller) GetAuthType() (authorizationType authEnums.AuthorizationType, err error) { +func (c *Controller) parseToAuthorizationData(data *authGrpc.IsAuthorizedData) *authEntities.AuthorizationData { + companyID, _ := uuid.Parse(data.CompanyID) + repositoryID, _ := uuid.Parse(data.RepositoryID) + + return &authEntities.AuthorizationData{ + Token: data.Token, + Role: authEnums.HorusecRoles(data.Role), + CompanyID: companyID, + RepositoryID: repositoryID, + } +} + +func (c *Controller) setIsAuthorizedResponse(isAuthorized bool, err error) (*authGrpc.IsAuthorizedResponse, error) { + if err != nil { + logger.LogError(errors.ErrorFailedToVerifyIsAuthorized, err) + return nil, err + } + + return &authGrpc.IsAuthorizedResponse{ + IsAuthorized: isAuthorized, + }, nil +} + +func (c *Controller) GetAuthConfig(_ context.Context, + _ *authGrpc.GetAuthConfigData) (*authGrpc.GetAuthConfigResponse, error) { authType := c.getAuthorizationType() - if authType != authEnums.Unknown { - return authType, nil + if authType == authEnums.Unknown { + logger.LogError("", errors.ErrorInvalidAuthType) + return &authGrpc.GetAuthConfigResponse{AuthType: authEnums.Unknown.ToString()}, errors.ErrorInvalidAuthType } - return "", errors.ErrorInvalidAuthType + return &authGrpc.GetAuthConfigResponse{ + ApplicationAdminEnable: c.appConfig.EnableApplicationAdmin, + AuthType: authType.ToString(), + }, nil } func (c *Controller) getAuthorizationType() authEnums.AuthorizationType { return authEnums.GetAuthTypeByString(c.appConfig.GetAuthType()) } -func (c *Controller) GetAccountIDByAuthType(token string) (uuid.UUID, error) { +func (c *Controller) GetAccountID(_ context.Context, + data *authGrpc.GetAccountIDData) (*authGrpc.GetAccountIDResponse, error) { switch c.getAuthorizationType() { case authEnums.Horusec: - return jwt.GetAccountIDByJWTToken(token) + return c.setGetAccountIDResponse(jwt.GetAccountIDByJWTToken(data.Token)) case authEnums.Keycloak: - return c.keycloak.GetAccountIDByJWTToken(token) + return c.setGetAccountIDResponse(c.keycloak.GetAccountIDByJWTToken(data.Token)) case authEnums.Ldap: - return jwt.GetAccountIDByJWTToken(token) + return c.setGetAccountIDResponse(jwt.GetAccountIDByJWTToken(data.Token)) + } + + return c.setGetAccountIDResponse(uuid.Nil, errors.ErrorUnauthorized) +} + +func (c *Controller) setGetAccountIDResponse(accountID uuid.UUID, err error) (*authGrpc.GetAccountIDResponse, error) { + if err != nil { + logger.LogError(errors.ErrorFailedToGetAccountID, err) + return &authGrpc.GetAccountIDResponse{}, err } - return uuid.Nil, errors.ErrorUnauthorized + return &authGrpc.GetAccountIDResponse{ + AccountID: accountID.String(), + }, nil } diff --git a/horusec-auth/internal/controller/auth/auth_mock.go b/horusec-auth/internal/controller/auth/auth_mock.go index 1229d2f4e..f237b8b80 100644 --- a/horusec-auth/internal/controller/auth/auth_mock.go +++ b/horusec-auth/internal/controller/auth/auth_mock.go @@ -15,10 +15,10 @@ package auth import ( + "context" authEntities "github.com/ZupIT/horusec/development-kit/pkg/entities/auth" - authEnums "github.com/ZupIT/horusec/development-kit/pkg/enums/auth" + authGrpc "github.com/ZupIT/horusec/development-kit/pkg/services/grpc/auth" mockUtils "github.com/ZupIT/horusec/development-kit/pkg/utils/mock" - "github.com/google/uuid" "github.com/stretchr/testify/mock" ) @@ -26,22 +26,22 @@ type MockAuthController struct { mock.Mock } -func (m *MockAuthController) AuthByType(credentials *authEntities.Credentials) (interface{}, error) { +func (m *MockAuthController) AuthByType(_ *authEntities.Credentials) (interface{}, error) { args := m.MethodCalled("AuthByType") return args.Get(0), mockUtils.ReturnNilOrError(args, 1) } -func (m *MockAuthController) AuthorizeByType(authorizationData *authEntities.AuthorizationData) (bool, error) { - args := m.MethodCalled("AuthorizeByType") - return args.Get(0).(bool), mockUtils.ReturnNilOrError(args, 1) +func (m *MockAuthController) IsAuthorized(_ context.Context, _ *authGrpc.IsAuthorizedData) (*authGrpc.IsAuthorizedResponse, error) { + args := m.MethodCalled("IsAuthorized") + return args.Get(0).(*authGrpc.IsAuthorizedResponse), mockUtils.ReturnNilOrError(args, 1) } -func (m *MockAuthController) GetAuthType() (authEnums.AuthorizationType, error) { +func (m *MockAuthController) GetAuthConfig(_ context.Context, _ *authGrpc.GetAuthConfigData) (*authGrpc.GetAuthConfigResponse, error) { args := m.MethodCalled("GetAuthType") - return args.Get(0).(authEnums.AuthorizationType), mockUtils.ReturnNilOrError(args, 1) + return args.Get(0).(*authGrpc.GetAuthConfigResponse), mockUtils.ReturnNilOrError(args, 1) } -func (m *MockAuthController) GetAccountIDByAuthType(token string) (uuid.UUID, error) { - args := m.MethodCalled("GetAccountIDByAuthType") - return args.Get(0).(uuid.UUID), mockUtils.ReturnNilOrError(args, 1) +func (m *MockAuthController) GetAccountID(_ context.Context, _ *authGrpc.GetAccountIDData) (*authGrpc.GetAccountIDResponse, error) { + args := m.MethodCalled("GetAccountID") + return args.Get(0).(*authGrpc.GetAccountIDResponse), mockUtils.ReturnNilOrError(args, 1) } diff --git a/horusec-auth/internal/controller/auth/auth_test.go b/horusec-auth/internal/controller/auth/auth_test.go index 1aa6c8028..cb3d39de7 100644 --- a/horusec-auth/internal/controller/auth/auth_test.go +++ b/horusec-auth/internal/controller/auth/auth_test.go @@ -21,6 +21,7 @@ import ( authEntities "github.com/ZupIT/horusec/development-kit/pkg/entities/auth" authEnums "github.com/ZupIT/horusec/development-kit/pkg/enums/auth" errorsEnum "github.com/ZupIT/horusec/development-kit/pkg/enums/errors" + authGrpc "github.com/ZupIT/horusec/development-kit/pkg/services/grpc/auth" "github.com/ZupIT/horusec/development-kit/pkg/services/jwt" keycloakService "github.com/ZupIT/horusec/development-kit/pkg/services/keycloak" "github.com/ZupIT/horusec/horusec-auth/config/app" @@ -126,10 +127,15 @@ func TestAuthorizeByType(t *testing.T) { keycloakAuthService: mockService, } - result, err := controller.AuthorizeByType(&authEntities.AuthorizationData{}) + result, err := controller.IsAuthorized(nil, &authGrpc.IsAuthorizedData{ + Token: "test", + Role: "test", + CompanyID: "test", + RepositoryID: "test", + }) - assert.True(t, result) assert.NoError(t, err) + assert.True(t, result.GetIsAuthorized()) }) t.Run("should authenticate with keycloak and return no errors", func(t *testing.T) { @@ -143,10 +149,15 @@ func TestAuthorizeByType(t *testing.T) { keycloakAuthService: mockService, } - result, err := controller.AuthorizeByType(&authEntities.AuthorizationData{}) + result, err := controller.IsAuthorized(nil, &authGrpc.IsAuthorizedData{ + Token: "test", + Role: "test", + CompanyID: "test", + RepositoryID: "test", + }) - assert.True(t, result) assert.NoError(t, err) + assert.True(t, result.GetIsAuthorized()) }) //TODO implements @@ -161,10 +172,15 @@ func TestAuthorizeByType(t *testing.T) { keycloakAuthService: mockService, } - result, err := controller.AuthorizeByType(&authEntities.AuthorizationData{}) + result, err := controller.IsAuthorized(nil, &authGrpc.IsAuthorizedData{ + Token: "test", + Role: "test", + CompanyID: "test", + RepositoryID: "test", + }) - assert.False(t, result) assert.Error(t, err) + assert.False(t, result.GetIsAuthorized()) }) t.Run("should return unauthorized error when invalid auth type", func(t *testing.T) { @@ -180,11 +196,16 @@ func TestAuthorizeByType(t *testing.T) { keycloakAuthService: mockService, } - result, err := controller.AuthorizeByType(&authEntities.AuthorizationData{}) + result, err := controller.IsAuthorized(nil, &authGrpc.IsAuthorizedData{ + Token: "test", + Role: "test", + CompanyID: "test", + RepositoryID: "test", + }) assert.Error(t, err) assert.Equal(t, errorsEnum.ErrorUnauthorized, err) - assert.False(t, result) + assert.False(t, result.GetIsAuthorized()) }) } @@ -196,9 +217,21 @@ func TestController_GetAuthTypes(t *testing.T) { horusAuthService: mockService, keycloakAuthService: mockService, } - authType, err := controller.GetAuthType() + authType, err := controller.GetAuthConfig(nil, nil) assert.NoError(t, err) - assert.Equal(t, authEnums.Horusec, authType) + assert.Equal(t, authEnums.Horusec.ToString(), authType.GetAuthType()) + }) + + t.Run("Should return error when invalid type", func(t *testing.T) { + mockService := &services.MockAuthService{} + controller := Controller{ + appConfig: &app.Config{AuthType: "test"}, + horusAuthService: mockService, + keycloakAuthService: mockService, + } + authType, err := controller.GetAuthConfig(nil, nil) + assert.Error(t, err) + assert.Equal(t, authEnums.Unknown.ToString(), authType.GetAuthType()) }) } @@ -220,10 +253,10 @@ func TestGetAccountIDByAuthType(t *testing.T) { keycloakAuthService: mockService, } - accountID, err := controller.GetAccountIDByAuthType(token) + response, err := controller.GetAccountID(nil, &authGrpc.GetAccountIDData{Token: token}) assert.NoError(t, err) - assert.NotEqual(t, uuid.Nil, accountID) + assert.NotEmpty(t, response.GetAccountID()) }) t.Run("should return account id when keycloak", func(t *testing.T) { @@ -247,10 +280,10 @@ func TestGetAccountIDByAuthType(t *testing.T) { keycloak: keycloakMock, } - accountID, err := controller.GetAccountIDByAuthType(token) + response, err := controller.GetAccountID(nil, &authGrpc.GetAccountIDData{Token: token}) assert.NoError(t, err) - assert.NotEqual(t, uuid.Nil, accountID) + assert.NotEmpty(t, response.GetAccountID()) }) t.Run("should return account id when horusec", func(t *testing.T) { @@ -270,13 +303,13 @@ func TestGetAccountIDByAuthType(t *testing.T) { keycloakAuthService: mockService, } - accountID, err := controller.GetAccountIDByAuthType(token) + response, err := controller.GetAccountID(nil, &authGrpc.GetAccountIDData{Token: token}) assert.NoError(t, err) - assert.NotEqual(t, uuid.Nil, accountID) + assert.NotEmpty(t, response.GetAccountID()) }) - t.Run("should return account id when horusec", func(t *testing.T) { + t.Run("should return error when invalid auth type", func(t *testing.T) { mockService := &services.MockAuthService{} controller := Controller{ @@ -285,9 +318,9 @@ func TestGetAccountIDByAuthType(t *testing.T) { keycloakAuthService: mockService, } - accountID, err := controller.GetAccountIDByAuthType("test") + response, err := controller.GetAccountID(nil, &authGrpc.GetAccountIDData{Token: "test"}) assert.Error(t, err) - assert.Equal(t, uuid.Nil, accountID) + assert.Empty(t, response.GetAccountID()) }) } diff --git a/horusec-auth/internal/handler/auth/auth.go b/horusec-auth/internal/handler/auth/auth.go index e90367a68..4c3de868a 100644 --- a/horusec-auth/internal/handler/auth/auth.go +++ b/horusec-auth/internal/handler/auth/auth.go @@ -18,7 +18,7 @@ import ( "github.com/ZupIT/horusec/development-kit/pkg/databases/relational" "github.com/ZupIT/horusec/development-kit/pkg/entities/auth" // [swagger-import] _ "github.com/ZupIT/horusec/development-kit/pkg/entities/http" // [swagger-import] - "github.com/ZupIT/horusec/development-kit/pkg/enums/errors" + authEnums "github.com/ZupIT/horusec/development-kit/pkg/enums/auth" authUseCases "github.com/ZupIT/horusec/development-kit/pkg/usecases/auth" httpUtil "github.com/ZupIT/horusec/development-kit/pkg/utils/http" "github.com/ZupIT/horusec/horusec-auth/config/app" @@ -50,18 +50,11 @@ func (h *Handler) Options(w netHTTP.ResponseWriter, _ *netHTTP.Request) { // @Accept json // @Produce json // @Success 200 {object} http.Response{content=auth.ConfigAuth{}} "STATUS OK" -// @Failure 400 {object} http.Response{content=string} "BAD REQUEST" // @Router /api/auth/config [get] func (h *Handler) Config(w netHTTP.ResponseWriter, _ *netHTTP.Request) { - authType, err := h.authController.GetAuthType() - if err != nil { - httpUtil.StatusBadRequest(w, err) - return - } - httpUtil.StatusOK(w, auth.ConfigAuth{ ApplicationAdminEnable: h.appConfig.GetEnableApplicationAdmin(), - AuthType: authType, + AuthType: authEnums.AuthorizationType(h.appConfig.GetAuthType()), }) } @@ -99,63 +92,3 @@ func (h *Handler) getCredentials(r *netHTTP.Request) (*auth.Credentials, error) return credentials, nil } - -// @Tags Auth -// @Description verify if request is valid! -// @ID authenticate request -// @Accept json -// @Produce json -// @Param AuthorizationData body auth.AuthorizationData true "authorization data" -// @Success 200 {object} http.Response{content=string} "STATUS OK" -// @Failure 400 {object} http.Response{content=string} "BAD REQUEST" -// @Failure 500 {object} http.Response{content=string} "INTERNAL SERVER ERROR" -// @Router /api/auth/authorize [post] -func (h *Handler) Authorize(w netHTTP.ResponseWriter, r *netHTTP.Request) { - authorizationData, err := h.getAuthorizationData(r) - if err != nil { - httpUtil.StatusBadRequest(w, err) - return - } - - response, err := h.authController.AuthorizeByType(authorizationData) - if err != nil { - httpUtil.StatusInternalServerError(w, err) - return - } - - httpUtil.StatusOK(w, response) -} - -func (h *Handler) getAuthorizationData(r *netHTTP.Request) (*auth.AuthorizationData, error) { - authorizationData, err := h.authUseCases.NewAuthorizationDataFromReadCloser(r.Body) - if err != nil { - return nil, err - } - - return authorizationData, nil -} - -// @Tags Auth -// @Description get account by token and auth type! -// @ID get account id -// @Accept json -// @Produce json -// @Success 200 {object} http.Response{content=string} "STATUS OK" -// @Failure 400 {object} http.Response{content=string} "BAD REQUEST" -// @Failure 400 {object} http.Response{content=string} "INTERNAL SERVER ERROR" -// @Router /api/auth/account-id [get] -func (h *Handler) GetAccountIDByAuthType(w netHTTP.ResponseWriter, r *netHTTP.Request) { - token := r.Header.Get("Authorization") - if token == "" { - httpUtil.StatusBadRequest(w, errors.ErrorTokenCanNotBeEmpty) - return - } - - accountID, err := h.authController.GetAccountIDByAuthType(token) - if err != nil { - httpUtil.StatusInternalServerError(w, err) - return - } - - httpUtil.StatusOK(w, accountID) -} diff --git a/horusec-auth/internal/handler/auth/auth_test.go b/horusec-auth/internal/handler/auth/auth_test.go index e0aed0d48..20a6970e9 100644 --- a/horusec-auth/internal/handler/auth/auth_test.go +++ b/horusec-auth/internal/handler/auth/auth_test.go @@ -9,7 +9,6 @@ import ( authUseCases "github.com/ZupIT/horusec/development-kit/pkg/usecases/auth" "github.com/ZupIT/horusec/horusec-auth/config/app" authController "github.com/ZupIT/horusec/horusec-auth/internal/controller/auth" - "github.com/google/uuid" "github.com/stretchr/testify/assert" "net/http" "net/http/httptest" @@ -106,75 +105,6 @@ func TestAuthByType(t *testing.T) { }) } -func TestAuthorize(t *testing.T) { - t.Run("should return 200 when successful authorize", func(t *testing.T) { - controllerMock := &authController.MockAuthController{} - - controllerMock.On("AuthorizeByType").Return(true, nil) - - handler := Handler{ - appConfig: &app.Config{}, - authUseCases: authUseCases.NewAuthUseCases(), - authController: controllerMock, - } - - dataBytes, _ := json.Marshal(authEntities.AuthorizationData{Token: "test", Role: authEnums.RepositoryMember}) - - r, _ := http.NewRequest(http.MethodPost, "test", bytes.NewReader(dataBytes)) - w := httptest.NewRecorder() - - r.Header.Add("X_AUTH_TYPE", "horusec") - - handler.Authorize(w, r) - - assert.Equal(t, http.StatusOK, w.Code) - }) - - t.Run("should return 500 when something went wrong", func(t *testing.T) { - controllerMock := &authController.MockAuthController{} - - controllerMock.On("AuthorizeByType").Return(false, errors.New("test")) - - handler := Handler{ - appConfig: &app.Config{}, - authUseCases: authUseCases.NewAuthUseCases(), - authController: controllerMock, - } - - dataBytes, _ := json.Marshal(authEntities.AuthorizationData{Token: "test", Role: authEnums.RepositoryMember}) - - r, _ := http.NewRequest(http.MethodPost, "test", bytes.NewReader(dataBytes)) - w := httptest.NewRecorder() - - r.Header.Add("X_AUTH_TYPE", "horusec") - - handler.Authorize(w, r) - - assert.Equal(t, http.StatusInternalServerError, w.Code) - }) - - t.Run("should return 400 when invalid authorization data", func(t *testing.T) { - controllerMock := &authController.MockAuthController{} - - handler := Handler{ - appConfig: &app.Config{}, - authUseCases: authUseCases.NewAuthUseCases(), - authController: controllerMock, - } - - dataBytes, _ := json.Marshal(authEntities.AuthorizationData{}) - - r, _ := http.NewRequest(http.MethodPost, "test", bytes.NewReader(dataBytes)) - w := httptest.NewRecorder() - - r.Header.Add("X_AUTH_TYPE", "horusec") - - handler.Authorize(w, r) - - assert.Equal(t, http.StatusBadRequest, w.Code) - }) -} - func TestHandler_AuthTypes(t *testing.T) { t.Run("should return 200 when get auth types", func(t *testing.T) { handler := NewAuthHandler(nil, &app.Config{ @@ -188,18 +118,6 @@ func TestHandler_AuthTypes(t *testing.T) { assert.Equal(t, http.StatusOK, w.Code) }) - t.Run("should return 400 when get auth types", func(t *testing.T) { - handler := NewAuthHandler(nil, &app.Config{ - AuthType: "test", - }) - - r, _ := http.NewRequest(http.MethodGet, "test", nil) - w := httptest.NewRecorder() - - handler.Config(w, r) - - assert.Equal(t, http.StatusBadRequest, w.Code) - }) t.Run("should return 200 when get auth types mocked", func(t *testing.T) { controllerMock := &authController.MockAuthController{} controllerMock.On("GetAuthType").Return(authEnums.Horusec, nil) @@ -219,61 +137,3 @@ func TestHandler_AuthTypes(t *testing.T) { assert.Equal(t, http.StatusOK, w.Code) }) } - -func TestGetAccountIDByAuthType(t *testing.T) { - t.Run("should return 200 when get auth types", func(t *testing.T) { - controllerMock := &authController.MockAuthController{} - controllerMock.On("GetAccountIDByAuthType").Return(uuid.New(), nil) - - handler := Handler{ - appConfig: &app.Config{ - AuthType: authEnums.Horusec.ToString(), - }, - authUseCases: authUseCases.NewAuthUseCases(), - authController: controllerMock, - } - - r, _ := http.NewRequest(http.MethodGet, "test", nil) - w := httptest.NewRecorder() - r.Header.Add("Authorization", "test") - - handler.GetAccountIDByAuthType(w, r) - - assert.Equal(t, http.StatusOK, w.Code) - }) - - t.Run("should return 500 when something went wrong getting id", func(t *testing.T) { - controllerMock := &authController.MockAuthController{} - controllerMock.On("GetAccountIDByAuthType").Return(uuid.Nil, errors.New("test")) - - handler := Handler{ - appConfig: &app.Config{ - AuthType: authEnums.Horusec.ToString(), - }, - authUseCases: authUseCases.NewAuthUseCases(), - authController: controllerMock, - } - - r, _ := http.NewRequest(http.MethodGet, "test", nil) - w := httptest.NewRecorder() - r.Header.Add("Authorization", "test") - - handler.GetAccountIDByAuthType(w, r) - - assert.Equal(t, http.StatusInternalServerError, w.Code) - }) - - t.Run("should return 500 when something went wrong getting id", func(t *testing.T) { - handler := Handler{ - appConfig: &app.Config{ - AuthType: authEnums.Horusec.ToString(), - }, - } - r, _ := http.NewRequest(http.MethodGet, "test", nil) - w := httptest.NewRecorder() - - handler.GetAccountIDByAuthType(w, r) - - assert.Equal(t, http.StatusBadRequest, w.Code) - }) -} diff --git a/horusec-auth/internal/router/router.go b/horusec-auth/internal/router/router.go index 5a08d86c8..8899dc660 100644 --- a/horusec-auth/internal/router/router.go +++ b/horusec-auth/internal/router/router.go @@ -113,9 +113,7 @@ func (r *Router) RouterAuth(postgresRead relational.InterfaceRead, appConfig *ap handler := auth.NewAuthHandler(postgresRead, appConfig) r.router.Route(routes.AuthHandler, func(router chi.Router) { router.Get("/config", handler.Config) - router.Get("/account-id", handler.GetAccountIDByAuthType) router.Post("/authenticate", handler.AuthByType) - router.Post("/authorize", handler.Authorize) router.Options("/", handler.Options) })