interserviceclient

package module
v0.0.20 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 11, 2023 License: MIT Imports: 29 Imported by: 26

README

Maintained Linting and Tests Coverage Status

Interservice Library

interserviceclient play a major role in implementing Microservices Inter-service communication using either HTTP protocol or asynchronous message patterns.

Installing it

interserviceclient is compatible with modern Go releases in module mode, with Go installed:

go get -u github.com/savannahghi/interserviceclient

will resolve and add the package to the current development module, along with its dependencies.

Alternatively the same can be achieved if you use import in a package:

import "github.com/savannahghi/interserviceclient"

and run go get without parameters.

The package name is interserviceclient

Developing

The default branch library is main

We try to follow semantic versioning ( https://semver.org/ ). For that reason, every major, minor and point release should be tagged.

git tag -m "v0.0.1" "v0.0.1"
git push --tags

Continuous integration tests must pass on Travis CI. Our coverage threshold is 90% i.e you must keep coverage above 90%.

Environment variables

In order to run tests, you need to have an env.sh file similar to this one:

# Application settings
export DEBUG=true
export IS_RUNNING_TESTS=true
export SENTRY_DSN=<a Sentry Data Source Name>

# Google Cloud credentials
export GOOGLE_APPLICATION_CREDENTIALS="<path to a service account JSON file"
export GOOGLE_CLOUD_PROJECT="Google Cloud project id"
export FIREBASE_WEB_API_KEY="<a web API key that corresponds to the project named above>"
export FIREBASE_DYNAMIC_LINKS_DOMAIN=https://bwlci.page.link
# Firestore documents root collection suffix
export ROOT_COLLECTION_SUFFIX="testing"
export JWT_KEY="jwt-key"

This file must not be committed to version control.

It is important to export the environment variables. If they are not exported, they will not be visible to child processes e.g go test ./....

These environment variables should also be set up on Travis CI environment variable section.

Contributing

I would like to cover the entire GitHub API and contributions are of course always welcome. The calling pattern is pretty well established, so adding new methods is relatively straightforward. See CONTRIBUTING.md for details.

Versioning

In general, interserviceclient follows semver as closely as we can for tagging releases of the package. For self-contained libraries, the application of semantic versioning is relatively straightforward and generally understood. We've adopted the following versioning policy:

  • We increment the major version with any incompatible change to non-preview functionality, including changes to the exported Go API surface or behavior of the API.
  • We increment the minor version with any backwards-compatible changes to functionality, as well as any changes to preview functionality in the GitHub API. GitHub makes no guarantee about the stability of preview functionality, so neither do we consider it a stable part of the go-github API.
  • We increment the patch version with any backwards-compatible bug fixes.

License

This library is distributed under the MIT license found in the LICENSE file.

Documentation

Index

Constants

View Source
const (
	// Secret Key for signing json web tokens
	JWTSecretKey = "JWT_KEY"

	// TestUserPin used for testing purposes
	TestUserPin = "1234"

	// AuthTokenContextKey is used to add/retrieve the Firebase UID on the context
	AuthTokenContextKey = ContextKey("UID")

	// The file that contains dependency definition. Each service which depends on other service
	// via REST, need to have this file in their root
	DepsFileName = "deps.yaml"

	// running the service under e2e
	E2eEnv = "e2e"

	// TestUserPhoneNumber is used by integration tests
	TestUserPhoneNumber = "+254711223344"

	// TestUserPhoneNumberWithPin is used by integration tests
	TestUserPhoneNumberWithPin = "+254778990088"

	// The role used to run tests
	TestRoleName = "Test Role"
)

#nosec

View Source
const (
	// VerifyOTPEndPoint ISC endpoint to verify OTP
	VerifyOTPEndPoint = "internal/verify_otp/"
	// SendOTPEndPoint ISC endpoint to sent OTP
	SendOTPEndPoint = "internal/send_otp/"
)
View Source
const (
	ISCExpireEnvVarName = "INTER_SERVICE_TOKEN_EXPIRE_MINUTES"
)

Inter service token expire minutes. Specify after how long a token will expire

Variables

This section is empty.

Functions

func CreateOrLoginTestPhoneNumberAuthorizedUser added in v0.0.16

func CreateOrLoginTestPhoneNumberAuthorizedUser(t *testing.T, onboardingClient *InterServiceClient) (*profileutils.UserResponse, error)

CreateOrLoginTestPhoneNumberAuthorizedUser creates an phone number test user if they do not exist or `Logs them in` if the test user exists to retrieve authenticated user response For documentation and test purposes only

func CreateOrLoginTestPhoneNumberUser added in v0.0.5

func CreateOrLoginTestPhoneNumberUser(t *testing.T, onboardingClient *InterServiceClient) (*profileutils.UserResponse, error)

CreateOrLoginTestPhoneNumberUser creates an phone number test user if they do not exist or `Logs them in` if the test user exists to retrieve authenticated user response For documentation and test purposes only

func CreateTestPhoneNumberUser added in v0.0.16

func CreateTestPhoneNumberUser(t *testing.T, onboardingClient *InterServiceClient, otp string) (*profileutils.UserResponse, error)

CreateTestPhoneNumberUser creates the user for test phone number

func ExtractToken

func ExtractToken(r *http.Request, header string, prefix string) (string, error)

ExtractToken extracts a token with the specified prefix from the specified header

func GetDefaultHeaders added in v0.0.5

func GetDefaultHeaders(t *testing.T, rootDomain string, serviceName string) map[string]string

GetDefaultHeaders returns headers used in inter service communication acceptance tests

func GetInterserviceBearerTokenHeader

func GetInterserviceBearerTokenHeader(t *testing.T, rootDomain string, serviceName string) string

GetInterserviceBearerTokenHeader returns a valid isc bearer token header

func GetJWTKey

func GetJWTKey() []byte

GetJWTKey returns a byte slice of the JWT secret key

func GetPhoneNumberAuthenticatedContextAndToken added in v0.0.5

func GetPhoneNumberAuthenticatedContextAndToken(
	t *testing.T,
	onboardingClient *InterServiceClient,
) (context.Context, *auth.Token, error)

GetPhoneNumberAuthenticatedContextAndToken returns a phone number logged in context and an auth Token that contains the the test user UID useful for test purposes

func GetTestAuthorizedContextAndToken added in v0.0.16

func GetTestAuthorizedContextAndToken(
	t *testing.T,
	onboardingClient *InterServiceClient,
) (context.Context, *auth.Token, error)

GetTestAuthorizedContextAndToken returns an authorized phone number with permissions logged in context and an auth Token that contains the the test user UID useful for test purposes

func GetTestBearerTokenHeader added in v0.0.8

func GetTestBearerTokenHeader(
	t *testing.T,
	onboardingClient *InterServiceClient,
) (string, error)

GetTestBearerTokenHeader gets bearer Token Header for running GraphQL acceptance tests

func GetTestGraphQLHeaders added in v0.0.8

func GetTestGraphQLHeaders(
	t *testing.T,
	onboardingClient *InterServiceClient,
) (map[string]string, error)

GetTestGraphQLHeaders gets relevant GraphQLHeaders for running GraphQL acceptance tests

func HasValidJWTBearerToken

func HasValidJWTBearerToken(r *http.Request) (bool, map[string]string, *jwt.Token)

HasValidJWTBearerToken returns true with no errors if the request has a valid bearer token in the authorization header. Otherwise, it returns false and the error in a map with the key "error"

func InterServiceAuthenticationMiddleware

func InterServiceAuthenticationMiddleware() func(http.Handler) http.Handler

InterServiceAuthenticationMiddleware handles jwt authentication

func IsKenyanNumber

func IsKenyanNumber(phoneNumber string) bool

IsKenyanNumber checks if phone number belongs to KENYA TELECOM

func IsMSISDNValid

func IsMSISDNValid(msisdn string) bool

IsMSISDNValid uses regular expression to validate the a phone number TODO: Retire this once once to use the once in (converters and formatters) package

func LoginTestPhoneUser added in v0.0.5

func LoginTestPhoneUser(
	t *testing.T,
	phone string,
	PIN string,
	flavour feedlib.Flavour,
	onboardingClient *InterServiceClient,
) (*profileutils.UserResponse, error)

LoginTestPhoneUser returns user response data for a created test user allowing them to run and access test resources

func PathToDepsFile

func PathToDepsFile() string

PathToDepsFile return the path to deps.yaml file

func RemoveTestPhoneNumberAuthorizedUser added in v0.0.16

func RemoveTestPhoneNumberAuthorizedUser(
	t *testing.T,
	onboardingClient *InterServiceClient,
) error

RemoveTestPhoneNumberAuthorizedUser removes the records created by the test phonenumber user

func RemoveTestPhoneNumberUser added in v0.0.6

func RemoveTestPhoneNumberUser(
	t *testing.T,
	onboardingClient *InterServiceClient,
) error

RemoveTestPhoneNumberUser removes the records created by the test phonenumber user

func SendOTPHelper

func SendOTPHelper(ctx context.Context, msisdn string, otpClient *InterServiceClient) (string, error)

SendOTPHelper is a helper used in tests to send OTP to a test number

func SendSMS

func SendSMS(ctx context.Context, phoneNumbers []string, message string, smsClient, twilioClient SmsISC) error

SendSMS is send a text message to specified phone No.s both local and foreign

func UpdateBioData added in v0.0.5

func UpdateBioData(
	t *testing.T,
	onboardingClient *InterServiceClient,
	UID string,
) error

UpdateBioData adds Bio Data to our test user

func VerifyOTP

func VerifyOTP(ctx context.Context, msisdn string, otp string, otpClient *InterServiceClient) (bool, error)

VerifyOTP confirms a phone number is valid by verifying the code that was sent to the number

func VerifyTestPhoneNumber added in v0.0.5

func VerifyTestPhoneNumber(
	t *testing.T,
	phone string,
	onboardingClient *InterServiceClient,
) (string, error)

VerifyTestPhoneNumber checks if the test `Phone Number` exists as a primary phone number in any user profile record

Types

type Claims

type Claims struct {
	jwt.StandardClaims
}

Claims a struct that will be encoded to a JWT. We add jwt.StandardClaims as an embedded type, to provide public claims Provides way for adding private claims

type ContextKey added in v0.0.5

type ContextKey string

ContextKey is used as a type for the UID key for the Firebase *auth.Token on context.Context. It is a custom type in order to minimize context key collissions on the context (.and to shut up golint).

type Dep

type Dep struct {
	DepName       string `yaml:"depName"`
	DepRootDomain string `yaml:"depRootDomain"`
}

Dep is the dependency definition

func GetDepFromConfig

func GetDepFromConfig(name string, config []Dep) *Dep

GetDepFromConfig retrives a specific config from config slice

type DepsConfig

type DepsConfig struct {
	Staging    []Dep `yaml:"staging"`
	Testing    []Dep `yaml:"testing"`
	Demo       []Dep `yaml:"demo"`
	Production []Dep `yaml:"production"`
	E2E        []Dep `yaml:"e2e"`
}

DepsConfig is the config for dependencies of a particular service

func LoadDepsFromYAML

func LoadDepsFromYAML() (*DepsConfig, error)

LoadDepsFromYAML loads the interservice dependency config from a deps.yaml file that is at the default location

type ISCService

type ISCService struct {
	// The name of the service that is been depended upon e.g mailgun, mpesa
	Name string

	// The endpoint where the service serves requests. The dependant should know forehand where to
	// this services lives
	RootDomain string
}

ISCService defines the blueprint of a dependency service. This struct is here to maintain uniform structure definitions

type InterServiceClient

type InterServiceClient struct {
	Name              string
	RequestRootDomain string
	// contains filtered or unexported fields
}

InterServiceClient defines a client for use in interservice communication

func GetInterserviceClient

func GetInterserviceClient(t *testing.T, rootDomain string, serviceName string) *InterServiceClient

GetInterserviceClient returns an isc client used in acceptance testing

func NewInterserviceClient

func NewInterserviceClient(s ISCService) (*InterServiceClient, error)

NewInterserviceClient initializes a new interservice client

func SetupISCclient

func SetupISCclient(config DepsConfig, serviceName string) (*InterServiceClient, error)

SetupISCclient returns an InterServiceClient

func (InterServiceClient) CreateAuthToken

func (c InterServiceClient) CreateAuthToken(ctx context.Context) (string, error)

CreateAuthToken returns a signed JWT for use in authentication.

func (InterServiceClient) MakeRequest

func (c InterServiceClient) MakeRequest(ctx context.Context, method string, path string, body interface{}) (*http.Response, error)

MakeRequest performs an inter service http request and returns a response

type OnboardingService added in v0.0.18

type OnboardingService interface {
	RegisterUser(ctx context.Context, payload interface{}) (*profileutils.UserProfile, error)
}

OnboardingService is a representation of an ISC client

type OnboardingServiceImpl added in v0.0.18

type OnboardingServiceImpl struct {
	// contains filtered or unexported fields
}

OnboardingServiceImpl represents the implemented methods in this ISC

func NewOnboardingService added in v0.0.18

func NewOnboardingService(isc *InterServiceClient) *OnboardingServiceImpl

NewOnboardingService initializes a new instance of OnboardingServiceImpl

func (*OnboardingServiceImpl) RegisterUser added in v0.0.18

func (o *OnboardingServiceImpl) RegisterUser(ctx context.Context, payload interface{}) (*profileutils.UserProfile, error)

RegisterUser makes the request to register a user

type SmsISC

type SmsISC struct {
	Isc      *InterServiceClient
	EndPoint string
}

SmsISC is a representation of an ISC client

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL