Merge branch 'v3' into 'master'

V3

See merge request integration-system/isp-gate-service!9
This commit is contained in:
komissarovyv committed 2022-08-05 09:42:23 +00:00
commit 1cb43ec54d
102 files changed
+2598 -4319

No files matched your search

+3 -1
View File
@@ -71,4 +71,6 @@ fabric.properties
/vendor/
google/
package.json
yarn.lock
yarn.lock
conf/config_dev.yml
+1 -1
View File
@@ -1 +1 @@
2.8.3
3.0.0
+2
View File
@@ -1,3 +1,5 @@
### v3.0.0
* реализация новой схемы аутентификации/авторизации
### v2.8.3
* use isp-kit logger instead local logger
* use log string instead log any (common log type)
-41
View File
@@ -1,41 +0,0 @@
package accounting
import (
"isp-gate-service/accounting/state"
"isp-gate-service/service/matcher"
"sync"
)
type accountant struct {
mx sync.Mutex
matcher matcher.Matcher
limitStates map[string]state.LimitState
version int64
}
func (app *accountant) Accept(method string) bool {
patternArray := app.matcher.Match(method)
stateStorage := make([]state.LimitState, len(patternArray))
for i, pattern := range patternArray {
stateStorage[i] = app.limitStates[pattern]
}
app.mx.Lock()
resp := state.Update(stateStorage)
if resp {
app.version++
}
app.mx.Unlock()
return resp
}
func (app *accountant) Snapshot() (map[string]state.Snapshot, int64) {
app.mx.Lock()
version := app.version
snapshotLimitState := make(map[string]state.Snapshot, len(app.limitStates))
for method, limitState := range app.limitStates {
snapshotLimitState[method] = limitState.Export()
}
app.mx.Unlock()
return snapshotLimitState, version
}
-147
View File
@@ -1,147 +0,0 @@
package accounting
import (
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/structure"
log "github.com/integration-system/isp-log"
"isp-gate-service/accounting/state"
"isp-gate-service/conf"
"isp-gate-service/entity"
"isp-gate-service/log_code"
"isp-gate-service/repository"
"isp-gate-service/service/matcher"
"sync"
"time"
)
var worker = &accountingWorker{
accountingStorage: make(map[int32]Accounting),
requestsStoring: make(map[int32]bool),
}
type (
Accounting interface {
Accept(string) bool
Snapshot() (map[string]state.Snapshot, int64)
}
accountingWorker struct {
accountingStorage map[int32]Accounting
requestsStoring map[int32]bool
}
)
func NewConnectionConsumer(list []structure.AddressConfiguration) bool {
accountingSetting := config.GetRemote().(*conf.RemoteConfig).AccountingSetting
worker.init(accountingSetting)
return true
}
func ReceiveConfiguration(accountingSetting conf.Accounting) {
worker.init(accountingSetting)
}
func AcceptRequest(appId int32, path string) bool {
if accouter, ok := worker.accountingStorage[appId]; ok {
ok := accouter.Accept(path)
if ok && worker.requestsStoring[appId] {
storage.TakeRequest(appId, path, time.Now())
}
return ok
} else {
if worker.requestsStoring[appId] {
storage.TakeRequest(appId, path, time.Now())
}
return true
}
}
func Close() {
if snapshot != nil {
snapshot.Stop()
}
if storage != nil {
storage.Stop()
}
}
func (w *accountingWorker) init(accountingSetting conf.Accounting) {
Close()
newAccountingStorage := make(map[int32]Accounting)
newRequestsStoringStorage := make(map[int32]bool)
if accountingSetting.Enable {
for _, s := range accountingSetting.Setting {
limitStates, patternArray := state.InitLimitState(s.Limits)
accounting := w.recoveryAccounting(s.ApplicationId, limitStates, patternArray)
newAccountingStorage[s.ApplicationId] = accounting
newRequestsStoringStorage[s.ApplicationId] = s.EnableStoring
}
w.requestsStoring = newRequestsStoringStorage
w.accountingStorage = newAccountingStorage
InitStoringTask(accountingSetting.Storing)
InitSnapshotTask(accountingSetting.SnapshotTimeout)
} else {
w.requestsStoring = newRequestsStoringStorage
w.accountingStorage = newAccountingStorage
}
}
func (w *accountingWorker) takeSnapshot() []entity.Snapshot {
lastStorage := w.accountingStorage
response := make([]entity.Snapshot, 0, len(lastStorage))
for appId, account := range lastStorage {
limitState, version := account.Snapshot()
response = append(response, entity.Snapshot{
AppId: appId,
LimitState: limitState,
Version: version,
})
}
return response
}
func (w *accountingWorker) recoveryAccounting(appId int32, limitStates map[string]state.LimitState, patternArray []string) *accountant {
var (
version = int64(0)
importNotComplete = true
)
dbSnapshot, err := repository.SnapshotRep.GetByApplication(appId)
if err != nil {
log.Warn(log_code.ErrorSnapshotAccounting, err)
}
if cache, ok := w.accountingStorage[appId]; ok {
cashLimitState, cashVersion := cache.Snapshot()
if dbSnapshot == nil || dbSnapshot.Version < cashVersion {
version = cashVersion
w.importLimitState(limitStates, cashLimitState)
importNotComplete = false
}
}
if dbSnapshot != nil && importNotComplete {
version = dbSnapshot.Version
w.importLimitState(limitStates, dbSnapshot.LimitState)
}
return &accountant{
mx: sync.Mutex{},
matcher: matcher.NewCacheableMatcher(patternArray),
limitStates: limitStates,
version: version,
}
}
func (w *accountingWorker) importLimitState(limitStates map[string]state.LimitState, snapshot map[string]state.Snapshot) {
for method, limitState := range limitStates {
if oldState, ok := snapshot[method]; ok {
limitState.Import(oldState)
}
}
}
-205
View File
@@ -1,205 +0,0 @@
//nolint
package accounting
import (
"github.com/stretchr/testify/assert"
"isp-gate-service/conf"
"isp-gate-service/entity"
"isp-gate-service/repository"
"sync"
"testing"
"time"
)
var (
accountingSetting = conf.Accounting{
Enable: true,
SnapshotTimeout: "290ms",
Setting: []conf.AccountingSetting{
{ApplicationId: 1, Limits: []conf.LimitSetting{
{Pattern: "mdm-master/group/method", MaxCount: 1, Timeout: "90ms"},
{Pattern: "mdm-master/group3/method", MaxCount: 10, Timeout: "10s"},
{Pattern: "mdm-master/group3/*", MaxCount: 5, Timeout: "10s"},
{Pattern: "mdm-master/group4/method", MaxCount: 2, Timeout: "0s"},
{Pattern: "mdm-master/group5/method", MaxCount: 3, Timeout: "10s"},
{Pattern: "mdm-master/group6/method", MaxCount: 5, Timeout: "10s"},
}},
{ApplicationId: 2, Limits: []conf.LimitSetting{
{Pattern: "mdm-master/group/method", MaxCount: 0, Timeout: "10s"},
}},
},
Storing: conf.StoringSetting{
Size: 100,
Timeout: "1h",
},
}
reqExample = []struct {
appId int32
path []string
}{
0: {appId: 1, path: []string{
"mdm-master/group/method", "mdm-master/group/method", "mdm-master/group/method",
"mdm-master/group/method", "mdm-master/group/method", "mdm-master/group/method",
}},
1: {appId: 2, path: []string{
"mdm-master/group3/method", "mdm-master/group/method", "mdm-master/group3/method",
"mdm-master/group/method", "mdm-master/group3/method", "mdm-master/group/method",
}},
2: {appId: 1, path: []string{
"mdm-master/group3/method", "mdm-master/group3/method", "mdm-master/group3/method",
"mdm-master/group3/method", "mdm-master/group3/method", "mdm-master/group3/method",
}},
3: {appId: 1, path: []string{
"mdm-master/group4/method", "mdm-master/group4/method", "mdm-master/group4/method",
"mdm-master/group4/method", "mdm-master/group4/method", "mdm-master/group4/method",
}},
4: {appId: 1, path: []string{
"mdm-master/group5/method", "mdm-master/group5/method", "mdm-master/group5/method",
}},
}
)
func TestAccounting(t *testing.T) {
a := assert.New(t)
snapshotRep := newSnapshotRepository(false)
repository.SnapshotRep = snapshotRep
worker = &accountingWorker{
accountingStorage: make(map[int32]Accounting),
requestsStoring: make(map[int32]bool),
}
worker.init(accountingSetting)
req := reqExample[4]
for _, path := range req.path {
a.True(AcceptRequest(req.appId, path))
}
expected := true
req = reqExample[0]
for _, path := range req.path {
a.Equal(expected, AcceptRequest(req.appId, path))
expected = !expected
time.Sleep(50 * time.Millisecond)
}
//expected == true
req = reqExample[1]
for _, path := range req.path {
a.Equal(expected, AcceptRequest(req.appId, path))
expected = !expected
}
req = reqExample[2]
expectedArray := []bool{true, true, true, true, true, false}
for key, path := range req.path {
a.Equal(expectedArray[key], AcceptRequest(req.appId, path))
}
//expected == true
req = reqExample[3]
for _, path := range req.path {
a.Equal(expected, AcceptRequest(req.appId, path))
}
worker.init(accountingSetting)
req = reqExample[4]
for _, path := range req.path {
a.False(AcceptRequest(req.appId, path))
}
}
func TestWorker_recoveryAccounting(t *testing.T) {
a := assert.New(t)
snapshotRep := newSnapshotRepository(true)
repository.SnapshotRep = snapshotRep
worker = &accountingWorker{
accountingStorage: make(map[int32]Accounting),
requestsStoring: make(map[int32]bool),
}
secondWorker := &accountingWorker{
accountingStorage: make(map[int32]Accounting),
requestsStoring: make(map[int32]bool),
}
worker.init(accountingSetting)
secondWorker.init(accountingSetting)
appId := int32(1)
request := "1_3_5"
for range request {
a.True(AcceptRequest(appId, "mdm-master/group6/method"))
}
a.False(AcceptRequest(appId, "mdm-master/group6/method"))
time.Sleep(time.Millisecond * 300)
a.True(snapshotRep.Wait())
snapshot, err := repository.SnapshotRep.GetByApplication(appId)
a.NoError(err)
a.NotNil(snapshot)
a.Equal(len(request), int(snapshot.Version))
Close()
worker = secondWorker
worker.init(accountingSetting)
a.False(AcceptRequest(appId, "mdm-master/group6/method"))
}
type snapshotRepository struct {
enableWaitGroup bool
wg sync.WaitGroup
mx sync.Mutex
cache map[int32]entity.Snapshot
}
func newSnapshotRepository(enableWaitGroup bool) *snapshotRepository {
return &snapshotRepository{
enableWaitGroup: enableWaitGroup,
wg: sync.WaitGroup{},
cache: make(map[int32]entity.Snapshot),
}
}
func (r *snapshotRepository) Wait() bool {
done := make(chan struct{})
go func() {
r.wg.Wait()
close(done)
}()
select {
case <-done:
return true
case <-time.After(time.Second):
return false
}
}
func (r *snapshotRepository) GetByApplication(appId int32) (*entity.Snapshot, error) {
r.mx.Lock()
defer r.mx.Unlock()
if snapshot, ok := r.cache[appId]; ok {
return &snapshot, nil
} else {
return nil, nil
}
}
func (r *snapshotRepository) Update(list []entity.Snapshot) error {
r.mx.Lock()
defer r.mx.Unlock()
if r.enableWaitGroup {
r.wg.Add(1)
defer r.wg.Done()
}
for _, s := range list {
r.cache[s.AppId] = s
}
return nil
}
-84
View File
@@ -1,84 +0,0 @@
package accounting
import (
log "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
"isp-gate-service/entity"
"isp-gate-service/log_code"
"isp-gate-service/repository"
"sync"
"time"
)
var snapshot *snapshotTask
type snapshotTask struct {
mx sync.Mutex
wg sync.WaitGroup
process bool
timeout <-chan time.Time
close chan bool
}
func InitSnapshotTask(snapshotTimeout string) {
timeout, err := time.ParseDuration(snapshotTimeout)
if err != nil {
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
}
snapshot = newSnapshotTask(timeout)
}
func (t *snapshotTask) Stop() {
t.mx.Lock()
if t.process {
snapshotList := worker.takeSnapshot()
if len(snapshotList) != 0 {
defer func() {
t.wg.Add(1)
t.unload(snapshotList)
t.wg.Wait()
}()
}
t.process = false
t.close <- true
}
t.mx.Unlock()
}
func (t *snapshotTask) run(timeout time.Duration) {
defer t.wg.Done()
t.timeout = time.After(timeout)
for {
select {
case <-t.close:
return
case <-t.timeout:
list := worker.takeSnapshot()
if len(list) > 0 {
t.wg.Add(1)
go t.unload(list)
}
t.timeout = time.After(timeout)
}
}
}
func (t *snapshotTask) unload(list []entity.Snapshot) {
if err := repository.SnapshotRep.Update(list); err != nil {
log.Error(log_code.ErrorSnapshotAccounting, err)
}
t.wg.Done()
}
func newSnapshotTask(timeout time.Duration) *snapshotTask {
task := &snapshotTask{
process: true,
timeout: make(chan time.Time),
close: make(chan bool),
}
task.wg.Add(1)
go task.run(timeout)
return task
}
-69
View File
@@ -1,69 +0,0 @@
package state
import (
log "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
"isp-gate-service/conf"
"time"
)
type (
LimitState interface {
Import(Snapshot)
Export() Snapshot
check() (bool, int, time.Time)
update(int, time.Time)
}
Snapshot struct {
Timeout time.Duration
Datetime []time.Time
Pattern string
Pointer int
}
updateRequest struct {
pointer int
requestTime time.Time
}
)
func InitLimitState(limits []conf.LimitSetting) (map[string]LimitState, []string) {
limitStates := make(map[string]LimitState)
patternArray := make([]string, len(limits))
for i, limit := range limits {
timeout, err := time.ParseDuration(limit.Timeout)
if err != nil {
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
}
if timeout == 0 && limit.MaxCount != 0 {
limit.MaxCount = 1
}
patternArray[i] = limit.Pattern
limitStates[limit.Pattern] = &limiter{
timeout: timeout,
datetime: make([]time.Time, limit.MaxCount),
pattern: limit.Pattern,
pointer: -1,
}
}
return limitStates, patternArray
}
func Update(states []LimitState) bool {
update := make([]updateRequest, len(states))
for i, st := range states {
if ok, point, requestTime := st.check(); ok {
update[i] = updateRequest{pointer: point, requestTime: requestTime}
} else {
return false
}
}
for i, st := range states {
u := update[i]
st.update(u.pointer, u.requestTime)
}
return true
}
-89
View File
@@ -1,89 +0,0 @@
package state
import (
"time"
)
type limiter struct {
timeout time.Duration
datetime []time.Time
pattern string
pointer int
}
func (lim *limiter) Export() Snapshot {
ls := *lim
return Snapshot{
Timeout: ls.timeout,
Datetime: ls.datetime,
Pattern: ls.pattern,
Pointer: ls.pointer,
}
}
func (lim *limiter) Import(oldState Snapshot) {
oldLim := limiter{
timeout: oldState.Timeout,
datetime: oldState.Datetime,
pattern: oldState.Pattern,
pointer: oldState.Pointer,
}
lenOldDatetime := len(oldLim.datetime)
lenNewDatetime := len(lim.datetime)
switch {
case lenOldDatetime == lenNewDatetime:
lim.datetime = oldLim.datetime
lim.pointer = oldLim.pointer
case lenOldDatetime < lenNewDatetime:
oldPointer := oldLim.pointer
for i := range lim.datetime {
oldLim.pointer++
if oldLim.pointer >= len(oldLim.datetime) {
oldLim.pointer = 0
}
lim.datetime[i] = oldLim.datetime[oldLim.pointer]
if oldPointer == oldLim.pointer {
lim.pointer = i
break
}
}
case lenOldDatetime > lenNewDatetime:
for i := range lim.datetime {
oldLim.pointer++
if oldLim.pointer >= len(oldLim.datetime) {
oldLim.pointer = 0
}
lim.datetime[i] = oldLim.datetime[oldLim.pointer]
}
}
}
func (lim *limiter) check() (bool, int, time.Time) {
if len(lim.datetime) == 0 {
return false, 0, time.Time{}
}
if lim.timeout == 0 {
return true, 0, time.Now()
}
pointer := lim.pointer + 1
if pointer >= len(lim.datetime) {
pointer = 0
}
date := lim.datetime[pointer]
requestTime := time.Now()
account := requestTime.Sub(date) > lim.timeout
return account, pointer, requestTime
}
func (lim *limiter) update(point int, requestTime time.Time) {
lim.pointer = point
lim.datetime[point] = requestTime
}
-51
View File
@@ -1,51 +0,0 @@
package state
import (
"github.com/stretchr/testify/assert"
"testing"
"time"
)
func TestLimiter(t *testing.T) {
a := assert.New(t)
newLimiter := func(count int) *limiter {
return &limiter{timeout: 5 * time.Second, pattern: "example", pointer: -1, datetime: make([]time.Time, count)}
}
store12 := newLimiter(12)
store10 := newLimiter(10)
store7 := newLimiter(7)
store5 := newLimiter(5)
for i := 0; i < 7; i++ {
expectedTrue, pointer, reqTime := store10.check()
a.True(expectedTrue)
store10.update(pointer, reqTime)
expectedTrue, pointer, reqTime = store7.check()
a.True(expectedTrue)
store7.update(pointer, reqTime)
}
expectedFalse, _, _ := store7.check()
a.False(expectedFalse)
store12.Import(store7.Export())
store5.Import(store10.Export())
a.Equal(store5.datetime[0], store10.datetime[store10.pointer+1])
a.Equal(store12.datetime[0], store7.datetime[0])
a.Equal(store12.datetime[store7.pointer], store7.datetime[store7.pointer])
a.Equal(store12.datetime[store7.pointer+1], time.Time{})
expectedTrue, _, _ := store12.check()
a.True(expectedTrue)
for i := 0; i < 3; i++ {
expectedTrue, pointer, reqTime := store5.check()
a.True(expectedTrue)
store5.update(pointer, reqTime)
}
expectedFalse, _, _ = store5.check()
a.False(expectedFalse)
}
-131
View File
@@ -1,131 +0,0 @@
package accounting
import (
log "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
"isp-gate-service/conf"
"isp-gate-service/entity"
"isp-gate-service/log_code"
"isp-gate-service/repository"
"sync"
"time"
)
var storage *storingTask
type storingTask struct {
buffer []entity.Request
counter int
chanTimeout <-chan time.Time
chanCounter chan []entity.Request
chanClose chan bool
mx sync.Mutex
wg sync.WaitGroup
process bool
}
func InitStoringTask(setting conf.StoringSetting) {
timeout, err := time.ParseDuration(setting.Timeout)
if err != nil {
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
}
storage = newStoringTask(timeout, setting.Size)
}
func (t *storingTask) TakeRequest(appId int32, method string, date time.Time) {
t.mx.Lock()
if !t.process {
t.mx.Unlock()
return
}
t.buffer[t.counter] = entity.Request{
AppId: appId,
Method: method,
CreatedAt: date,
}
t.counter++
if t.counter == len(t.buffer) {
t.chanCounter <- t.buffer
t.clearBuffer()
}
t.mx.Unlock()
}
func (t *storingTask) Stop() {
t.mx.Lock()
if t.process {
if t.counter != 0 {
buffer := t.clearBuffer()
defer func() {
t.wg.Add(1)
t.unload(buffer)
t.wg.Wait()
}()
}
t.chanClose <- true
t.process = false
}
t.mx.Unlock()
}
func (t *storingTask) run(timeout time.Duration) {
defer t.wg.Done()
t.chanTimeout = time.After(timeout)
for {
select {
case <-t.chanClose:
return
case cache := <-t.chanCounter:
t.wg.Add(1)
go t.unload(cache)
t.chanTimeout = time.After(timeout)
case <-t.chanTimeout:
t.mx.Lock()
if t.counter != 0 {
buffer := t.clearBuffer()
t.wg.Add(1)
go t.unload(buffer)
}
t.mx.Unlock()
t.chanTimeout = time.After(timeout)
}
}
}
func (t *storingTask) unload(cache []entity.Request) {
if err := repository.RequestsRep.Insert(cache); err != nil {
log.Error(log_code.ErrorUnloadAccounting, err)
}
t.wg.Done()
}
func (t *storingTask) clearBuffer() []entity.Request {
oldBuffer := t.buffer[:t.counter]
oldLen := len(t.buffer)
t.counter = 0
t.buffer = make([]entity.Request, oldLen)
return oldBuffer
}
func newStoringTask(timeout time.Duration, bufSize int) *storingTask {
task := &storingTask{
mx: sync.Mutex{},
counter: 0,
buffer: make([]entity.Request, bufSize),
process: true,
chanTimeout: make(chan time.Time),
chanCounter: make(chan []entity.Request),
chanClose: make(chan bool),
}
task.wg.Add(1)
go task.run(timeout)
return task
}
-112
View File
@@ -1,112 +0,0 @@
package accounting
import (
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"isp-gate-service/conf"
"isp-gate-service/entity"
"isp-gate-service/repository"
)
var (
timeoutSetting = conf.StoringSetting{
Size: 3,
Timeout: "30ms",
}
bufferSetting = conf.StoringSetting{
Size: 3,
Timeout: "2s",
}
unloadSetting = conf.StoringSetting{
Size: 3,
Timeout: "100ms",
}
)
func initStoring(setting conf.StoringSetting) *requestsRepository {
rep := &requestsRepository{cache: make([]entity.Request, 0), wg: &sync.WaitGroup{}}
repository.RequestsRep = rep
InitStoringTask(setting)
return rep
}
func wait(wg *sync.WaitGroup) bool {
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
return true
case <-time.After(time.Second):
return false
}
}
func TestStoringTask_Stop(t *testing.T) {
a := assert.New(t)
rep := initStoring(bufferSetting)
rep.wg.Add(2)
for i, j := range []string{"Stop_1", "Stop_2", "Stop_3", "Stop_4", "Stop_5"} {
storage.TakeRequest(int32(i), j, time.Now())
}
storage.Stop()
a.Len(rep.cache, 5)
}
func TestStoringTask_Buffer(t *testing.T) {
a := assert.New(t)
rep := initStoring(bufferSetting)
rep.wg.Add(1)
for i, j := range []string{"Buffer_1", "Buffer_2", "Buffer_3", "Buffer_4", "Buffer_5"} {
storage.TakeRequest(int32(i), j, time.Now())
}
a.True(wait(rep.wg))
a.Len(rep.cache, 3)
}
func TestStoringTask_Timeout(t *testing.T) {
a := assert.New(t)
rep := initStoring(timeoutSetting)
rep.wg.Add(1)
for i, j := range []string{"Timeout_1", "Timeout_2"} {
storage.TakeRequest(int32(i), j, time.Now())
}
a.True(wait(rep.wg))
a.Len(rep.cache, 2)
}
func TestStoringTask_Unload(t *testing.T) {
a := assert.New(t)
rep := initStoring(unloadSetting)
rep.wg.Add(2)
for i, j := range []string{"Unload_1", "Unload_2", "Unload_3", "Unload_4", "Unload_5"} {
storage.TakeRequest(int32(i), j, time.Now())
}
a.True(wait(rep.wg))
a.Len(rep.cache, 5)
}
type requestsRepository struct {
cache []entity.Request
mx sync.Mutex
wg *sync.WaitGroup
}
func (r *requestsRepository) Insert(model []entity.Request) error {
r.mx.Lock()
r.cache = append(r.cache, model...)
r.mx.Unlock()
r.wg.Done()
return nil
}
+174
View File
@@ -0,0 +1,174 @@
package assembly
import (
"context"
"github.com/go-redis/redis/v8"
"github.com/integration-system/isp-kit/app"
"github.com/integration-system/isp-kit/bootstrap"
"github.com/integration-system/isp-kit/cluster"
"github.com/integration-system/isp-kit/grpc/client"
"github.com/integration-system/isp-kit/http"
"github.com/integration-system/isp-kit/lb"
"github.com/integration-system/isp-kit/log"
"github.com/pkg/errors"
"isp-gate-service/conf"
"isp-gate-service/routes"
)
type Assembly struct {
boot *bootstrap.Bootstrap
server *http.Server
logger *log.Adapter
routes *routes.Routes
redisCli redis.UniversalClient
systemCli *client.Client
locations []conf.Location
grpcClientByModuleName map[string]*client.Client
httpHostManagerByModuleName map[string]*lb.RoundRobin
}
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
server := http.NewServer()
localConfig := conf.Local{}
err := boot.App.Config().Read(&localConfig)
if err != nil {
return nil, errors.WithMessage(err, "read local config")
}
grpcClientByModuleName := make(map[string]*client.Client)
httpHostManagerByModuleName := make(map[string]*lb.RoundRobin)
for _, location := range localConfig.Locations {
switch location.Protocol {
case conf.GrpcProtocol:
cli, err := client.Default()
if err != nil {
return nil, errors.WithMessage(err, "new grpc client")
}
grpcClientByModuleName[location.TargetModule] = cli
case conf.HttpProtocol:
rb := lb.NewRoundRobin(nil)
httpHostManagerByModuleName[location.TargetModule] = rb
default:
return nil, errors.Errorf("unexpected location protocol: %s", location.Protocol)
}
}
systemCli, err := client.Default()
if err != nil {
return nil, errors.WithMessage(err, "create system cli")
}
return &Assembly{
boot: boot,
server: server,
logger: boot.App.Logger(),
routes: routes.NewRoutes(),
locations: localConfig.Locations,
grpcClientByModuleName: grpcClientByModuleName,
httpHostManagerByModuleName: httpHostManagerByModuleName,
systemCli: systemCli,
}, nil
}
func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error {
var (
newCfg conf.Remote
prevCfg conf.Remote
)
err := a.boot.RemoteConfig.Upgrade(remoteConfig, &newCfg, &prevCfg)
if err != nil {
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade remote config"))
}
err = newCfg.Validate()
if err != nil {
a.logger.Fatal(ctx, errors.WithMessage(err, "invalid remote config"))
}
a.logger.SetLevel(newCfg.Logging.LogLevel)
var newRedisCli redis.UniversalClient
if newCfg.Redis != nil {
newRedisCli = a.redisClient(*newCfg.Redis)
}
locator := NewLocator(a.logger, a.grpcClientByModuleName, a.httpHostManagerByModuleName, a.routes, a.systemCli)
handler, err := locator.Handler(newCfg, a.locations, newRedisCli)
if err != nil {
return errors.WithMessage(err, "locator handler")
}
a.server.Upgrade(handler)
if a.redisCli != nil {
_ = a.redisCli.Close()
a.redisCli = newRedisCli
}
return nil
}
func (a *Assembly) Runners() []app.Runner {
eventHandler := cluster.NewEventHandler().
RoutesReceiver(a.routes).
RemoteConfigReceiver(a)
for moduleName, upgrader := range a.grpcClientByModuleName {
eventHandler.RequireModule(moduleName, upgrader)
}
for moduleName, upgrader := range a.httpHostManagerByModuleName {
eventHandler.RequireModule(moduleName, upgrader)
}
eventHandler.RequireModule("isp-system-service", a.systemCli)
return []app.Runner{
app.RunnerFunc(func(ctx context.Context) error {
return a.server.ListenAndServe(a.boot.BindingAddress)
}),
app.RunnerFunc(func(ctx context.Context) error {
return a.boot.ClusterCli.Run(ctx, eventHandler)
}),
}
}
func (a *Assembly) Closers() []app.Closer {
closers := []app.Closer{
a.boot.ClusterCli,
app.CloserFunc(func() error {
return a.server.Shutdown(context.Background())
}),
}
for _, cliCloser := range a.grpcClientByModuleName {
closers = append(closers, cliCloser)
}
closers = append(closers, a.systemCli, app.CloserFunc(func() error {
if a.redisCli != nil {
return a.redisCli.Close()
}
return nil
}))
return closers
}
func (a *Assembly) redisClient(config conf.Redis) redis.UniversalClient {
if config.Sentinel != nil {
return redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: config.Sentinel.MasterName,
SentinelAddrs: config.Sentinel.Addresses,
SentinelUsername: config.Sentinel.Username,
SentinelPassword: config.Sentinel.Password,
Username: config.Username,
Password: config.Password,
})
}
return redis.NewClient(&redis.Options{
Addr: config.Address,
Username: config.Username,
Password: config.Password,
})
}
+107
View File
@@ -0,0 +1,107 @@
package assembly
import (
"fmt"
"net/http"
"time"
"github.com/go-redis/redis/v8"
"github.com/integration-system/isp-kit/grpc/client"
"github.com/integration-system/isp-kit/lb"
"github.com/integration-system/isp-kit/log"
"github.com/pkg/errors"
"isp-gate-service/conf"
"isp-gate-service/middleware"
"isp-gate-service/proxy"
"isp-gate-service/repository"
"isp-gate-service/routes"
"isp-gate-service/service"
)
type Locator struct {
logger log.Logger
grpcClientByModuleName map[string]*client.Client
httpHostManagerByModuleName map[string]*lb.RoundRobin
routes *routes.Routes
systemCli *client.Client
}
func NewLocator(
logger log.Logger,
grpcClientByModuleName map[string]*client.Client,
httpHostManagerByModuleName map[string]*lb.RoundRobin,
routes *routes.Routes,
systemCli *client.Client,
) Locator {
return Locator{
logger: logger,
grpcClientByModuleName: grpcClientByModuleName,
httpHostManagerByModuleName: httpHostManagerByModuleName,
routes: routes,
systemCli: systemCli,
}
}
func (l Locator) Handler(config conf.Remote, locations []conf.Location, redisCli redis.UniversalClient) (http.Handler, error) {
systemRepo := repository.NewSystem(l.systemCli)
authenticationCache := repository.NewAuthenticationCache(time.Duration(config.Caching.AuthenticationDataInSec) * time.Second)
authentication := service.NewAuthentication(authenticationCache, systemRepo)
adminService := service.NewAdmin(config.Secrets.AdminTokenSecret)
authorizationCache := repository.NewAuthorizationCache(time.Duration(config.Caching.AuthorizationDataInSec) * time.Second)
authorization := service.NewAuthorization(authorizationCache, systemRepo)
dailyLimitRepo := repository.NewDailyLimit(redisCli)
dailyLimitService := service.NewDailyLimit(dailyLimitRepo, config.DailyLimits)
throttlingRepo := repository.NewThrottling(redisCli)
throttlingService := service.NewThrottling(throttlingRepo, config.Throttling)
mux := http.NewServeMux()
for _, location := range locations {
var proxyFunc middleware.Handler
switch location.Protocol {
case conf.GrpcProtocol:
cli := l.grpcClientByModuleName[location.TargetModule]
proxyFunc = proxy.NewGrpc(cli, location.SkipAuth, time.Duration(config.Http.ProxyTimeoutInSec)*time.Second)
case conf.HttpProtocol:
hostManager := l.httpHostManagerByModuleName[location.TargetModule]
proxyFunc = proxy.NewHttp(hostManager, location.SkipAuth, time.Duration(config.Http.ProxyTimeoutInSec)*time.Second)
default:
return nil, errors.Errorf("not supported protocol %s", location.Protocol)
}
handler := middleware.Chain(
proxyFunc,
middleware.RequestId(),
middleware.Logger(l.logger, config.Logging.RequestLogEnable, config.Logging.BodyLogEnable),
middleware.ErrorHandler(l.logger),
middleware.Authenticate(authentication),
middleware.AdminAuthenticate(adminService),
middleware.Authorize(authorization, l.logger),
middleware.AdminAuthorize(l.routes),
middleware.Throttling(throttlingService),
middleware.DailyLimit(dailyLimitService),
)
if location.SkipAuth {
handler = middleware.Chain(
proxyFunc,
middleware.RequestId(),
middleware.Logger(l.logger, config.Logging.RequestLogEnable, config.Logging.BodyLogEnable),
middleware.ErrorHandler(l.logger),
)
}
entrypoint := middleware.Entrypoint(
config.Http.MaxRequestBodySizeInMb*1024*1024, //nolint:gomnd
handler,
location.PathPrefix,
l.logger,
)
mux.Handle(fmt.Sprintf("%s/", location.PathPrefix), entrypoint)
}
return mux, nil
}
-208
View File
@@ -1,208 +0,0 @@
package authenticate
import (
"strconv"
"time"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/conf"
"isp-gate-service/log_code"
"isp-gate-service/routing"
"isp-gate-service/service/veritification"
)
const (
// TODO move to isp-lib
AdminTokenHeader = "x-auth-admin"
awaitLengthVerifiableHeaders = 4
)
var notExpectedHeaders = []string{
utils.SystemIdHeader,
utils.DomainIdHeader,
utils.ServiceIdHeader,
utils.ApplicationIdHeader,
utils.UserIdHeader,
utils.DeviceIdHeader,
}
var auth = authenticate{}
type (
authenticate struct {
verify veritification.Verify
}
verifiable struct {
appId int32
adminId int64
ctx *fasthttp.RequestCtx
path string
headers map[string]string
}
)
func ReceiveConfiguration(conf conf.Cache) {
if conf.EnableCache {
if timeout, err := time.ParseDuration(conf.EvictTimeout); err != nil {
log.Fatalf(stdcodes.ModuleInvalidRemoteConfig, "invalid timeout '%s'", timeout)
} else {
auth.verify = veritification.NewCacheablesVerify(timeout)
}
} else {
auth.verify = veritification.NewRuntimeVerify()
}
}
func Do(ctx *fasthttp.RequestCtx, path string) (int32, int64, error) {
for _, notExpectedHeader := range notExpectedHeaders {
ctx.Request.Header.Del(notExpectedHeader)
}
verifiable := newVerifiable(ctx, path)
err := verifiable.verifyAppToken()
if err != nil {
return 0, 0, err
}
err = verifiable.verifyUserToken()
if err != nil {
return 0, 0, err
}
verifiable.setHeaders()
err = verifiable.checkInnerMethods()
if err != nil {
return 0, 0, err
}
err = verifiable.checkUserMethods()
if err != nil {
return 0, 0, err
}
return verifiable.appId, verifiable.adminId, nil
}
func newVerifiable(ctx *fasthttp.RequestCtx, path string) *verifiable {
return &verifiable{
ctx: ctx,
path: path,
appId: -1,
adminId: -1,
headers: make(map[string]string),
}
}
func (v *verifiable) verifyAppToken() error {
appToken := v.getParam(utils.ApplicationTokenHeader)
var err error
if len(appToken) == 0 {
return createError("unauthorized", codes.Unauthenticated, "application token required")
} else if config.GetRemote().(*conf.RemoteConfig).TokensSetting.ApplicationVerify {
if v.appId, err = verifyToken.Application(string(appToken)); err != nil || v.appId == 0 {
return createError("unauthorized", codes.Unauthenticated, "received invalid application token")
}
}
verifiableHeaders, err := auth.verify.ApplicationToken(string(appToken))
if err != nil {
log.Error(log_code.ErrorAuthenticate, err)
return createError("internal Server error", codes.Internal)
}
if len(verifiableHeaders) != awaitLengthVerifiableHeaders {
return createError("unauthorized", codes.Unauthenticated, "received unexpected identities")
}
applicationId, err := strconv.ParseInt(verifiableHeaders[utils.ApplicationIdHeader], 10, 32) //nolint
if err != nil {
log.Error(log_code.ErrorAuthenticate, errors.WithMessagef(err, "parse appId from redis"))
return createError("internal Server error", codes.Internal)
}
//nolint
if v.appId != -1 && int32(applicationId) != v.appId {
return createError("unauthorized", codes.Unauthenticated, "received unexpected application identity")
}
v.appId = int32(applicationId)
v.headers = verifiableHeaders
return nil
}
func (v *verifiable) verifyUserToken() error {
userToken := string(v.getParam(utils.UserTokenHeader))
if userToken != "" {
userId, err := verifyToken.User(userToken)
if err != nil {
return createError("unauthorized", codes.Unauthenticated, "received invalid user token")
}
v.headers[utils.UserIdHeader] = userId
}
v.headers[utils.UserTokenHeader] = userToken
v.headers[utils.DeviceTokenHeader] = string(v.getParam(utils.DeviceTokenHeader))
var err error
v.headers, err = auth.verify.Identity(v.headers, v.path)
if err != nil {
switch err {
case veritification.ErrorInvalidUserId:
return createError("unauthorized", codes.Unauthenticated, err.Error())
case veritification.ErrorPermittedToCallUser, veritification.ErrorPermittedToCallApplication:
return createError("forbidden", codes.PermissionDenied, err.Error())
default:
return createError("internal server error", codes.Internal)
}
}
return nil
}
func (v *verifiable) setHeaders() {
for key, value := range v.headers {
if value != "" {
v.ctx.Request.Header.Set(key, value)
}
}
}
func (v *verifiable) checkInnerMethods() error {
_, ok := routing.InnerMethods[v.path]
if ok {
adminToken := string(v.getParam(AdminTokenHeader))
if adminToken == "" {
return createError("unauthorized", codes.Unauthenticated, "admin token required")
}
adminId, err := verifyToken.Admin(adminToken)
if err != nil {
return createError("unauthorized", codes.Unauthenticated, "received invalid admin token")
}
v.adminId = adminId
}
return nil
}
func (v *verifiable) checkUserMethods() error {
if v.headers[utils.UserIdHeader] == "" {
if _, ok := routing.AuthUserMethods[v.path]; ok {
return createError("unauthorized", codes.Unauthenticated, "user token required")
}
}
return nil
}
func (v *verifiable) getParam(key string) []byte {
val := v.ctx.Request.Header.Peek(key)
if len(val) != 0 {
return val
}
return v.ctx.Request.URI().QueryArgs().Peek(key)
}
-32
View File
@@ -1,32 +0,0 @@
package authenticate
import (
"fmt"
"google.golang.org/grpc/codes"
)
func createError(msg string, status codes.Code, details ...interface{}) error {
return ErrorDescription{message: msg, grpcStatus: status, details: details}
}
type ErrorDescription struct {
message string
grpcStatus codes.Code
details []interface{}
}
func (e ErrorDescription) Error() string {
return fmt.Sprintf("code: %v, message: %s, details: %v", e.grpcStatus, e.message, e.details)
}
func (e ErrorDescription) Message() string {
return e.message
}
func (e ErrorDescription) ConvertToGrpcStatus() codes.Code {
return e.grpcStatus
}
func (e ErrorDescription) Details() []interface{} {
return e.details
}
-90
View File
@@ -1,90 +0,0 @@
package authenticate
import (
"github.com/dgrijalva/jwt-go"
"github.com/integration-system/isp-lib/v2/config"
"github.com/pkg/errors"
"github.com/spf13/cast"
"isp-gate-service/conf"
)
var (
errInvalidToken = errors.New("invalid token")
verifyToken token
)
type appClaims struct {
*jwt.StandardClaims
AppId int32
}
type userClaims struct {
*jwt.StandardClaims
UserId int64
}
type adminClaims struct {
*jwt.StandardClaims
Id int64
}
type token struct{}
func (t token) Admin(token string) (int64, error) {
secret := config.GetRemote().(*conf.RemoteConfig).TokensSetting.AdminSecret
parsed, err := t.parse(token, secret, &adminClaims{StandardClaims: &jwt.StandardClaims{}})
if err != nil {
return 0, err
}
claims, ok := parsed.Claims.(*adminClaims)
if !ok {
return 0, errInvalidToken
}
return claims.Id, nil
}
func (t token) Application(token string) (int32, error) {
secret := config.GetRemote().(*conf.RemoteConfig).TokensSetting.ApplicationSecret
parsed, err := t.parse(token, secret, &appClaims{StandardClaims: &jwt.StandardClaims{}})
if err != nil {
return 0, err
}
claims, ok := parsed.Claims.(*appClaims)
if !ok {
return 0, errInvalidToken
}
return claims.AppId, nil
}
func (t token) User(token string) (string, error) {
secret := config.GetRemote().(*conf.RemoteConfig).TokensSetting.UserSecret
parsed, err := t.parse(token, secret, &userClaims{StandardClaims: &jwt.StandardClaims{}})
if err != nil {
return "", err
}
claims, ok := parsed.Claims.(*userClaims)
if !ok {
return "", errInvalidToken
}
return cast.ToString(claims.UserId), nil
}
func (token) parse(token, secret string, claims jwt.Claims) (*jwt.Token, error) {
parsed, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
_, ok := token.Method.(*jwt.SigningMethodHMAC)
if !ok {
return nil, errors.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret), nil
})
if err != nil {
return nil, err
}
if !parsed.Valid {
return nil, errInvalidToken
}
return parsed, nil
}
+53
View File
@@ -0,0 +1,53 @@
package cache
import (
"sync"
"time"
)
type Item struct {
data []byte
expiredAt time.Time
}
type Cache struct {
store map[string]Item
lock *sync.RWMutex
}
func New() *Cache {
return &Cache{
store: map[string]Item{},
lock: &sync.RWMutex{},
}
}
func (c *Cache) Get(key string) ([]byte, bool) {
c.lock.RLock()
defer c.lock.RUnlock()
item, ok := c.store[key]
if !ok {
return nil, false
}
if c.now().After(item.expiredAt) {
return nil, false
}
return item.data, true
}
func (c *Cache) Set(key string, data []byte, lifeTime time.Duration) {
c.lock.Lock()
defer c.lock.Unlock()
c.store[key] = Item{
data: data,
expiredAt: c.now().Add(lifeTime),
}
}
func (c *Cache) now() time.Time {
return time.Now()
}
+47
View File
@@ -0,0 +1,47 @@
package cache_test
import (
"testing"
"time"
"github.com/stretchr/testify/require"
"isp-gate-service/cache"
)
func TestGetBasic(t *testing.T) {
require := require.New(t)
cache := cache.New()
cache.Set("key", []byte("data"), 24*time.Hour)
data, ok := cache.Get("key")
require.True(ok)
require.EqualValues("data", data)
_, ok = cache.Get("key2")
require.False(ok)
}
func TestGetExpired(t *testing.T) {
require := require.New(t)
cache := cache.New()
cache.Set("key", []byte("data"), 500*time.Millisecond)
time.Sleep(1 * time.Second)
data, ok := cache.Get("key")
require.False(ok)
require.Nil(data)
}
func TestNilValue(t *testing.T) {
require := require.New(t)
cache := cache.New()
cache.Set("key", nil, 24*time.Hour)
data, ok := cache.Get("key")
require.True(ok)
require.Nil(data)
}
+6 -8
View File
@@ -1,14 +1,16 @@
configServiceAddress:
ip: 127.0.0.1
port: 9001
httpOuterAddress:
grpcOuterAddress:
#ip: 127.0.0.1
port: 9003
httpInnerAddress:
grpcInnerAddress:
ip: 0.0.0.0
port: 9003
moduleName: isp-gate
instanceUuid: 9d89354b-c728-4b48-b002-a7d3b229f151
moduleName: isp-gate-service
infraServerPort: 9553
locations:
- pathPrefix: /api
protocol: grpc
@@ -16,7 +18,3 @@ locations:
- pathPrefix: /mdm
protocol: http
targetModule: mdm-api
- pathPrefix: /ws
protocol: websocket
skipAuth: true
targetModule: admin
+12 -56
View File
@@ -1,62 +1,18 @@
{
"database": {
"address": "{{ msp_pgsql_address }}",
"port": "{{ msp_pgsql_port }}",
"schema": "gate_service",
"database": "{{ msp_pgsql_name }}",
"username": "{{ msp_pgsql_user }}",
"password": "{{ msp_pgsql_password }}",
"createSchema": true
"secrets": {
"adminTokenSecret": "{{ msp_admin_secret }}"
},
"grpcSetting": {
"proxyGrpcErrorDetails": true,
"enableOriginalProtoErrors": false
"logging": {
"logLevel": "debug",
"requestLogEnable": true,
"bodyLogEnable": false
},
"httpSetting": {
"maxRequestBodySizeBytes": 0
"caching": {
"authenticationDataInSec": 60,
"authorizationDataInSec": 60
},
"accountingSetting": {
"enable": false,
"snapshotTimeout": "15m",
"setting": [
],
"storing": {
"size": 10000,
"timeout": "10m"
}
},
"journalSetting": {
"journal": {
"filename": "/var/log/isp-gate-service/runtime.log",
"maxSizeMb": 512,
"enable": false,
"compress": true
}
},
"redis": {
"password": "{{ msp_redis_password }}",
"defaultDB": 0,
"address": {
"ip": "{{ msp_redis_address }}",
"port": "{{ msp_redis_port }}"
}
},
"metrics": {
"gc": true,
"memory": true,
"address": {
"path": "/metrics",
"port": "9553",
"ip": "0.0.0.0"
}
},
"tokensSetting": {
"applicationSecret": "{{ msp_app_secret }}",
"applicationVerify": false,
"adminSecret": "{{ msp_admin_secret }}"
},
"authCacheSetting": {
"enableCache": false,
"evictTimeout": "1m"
"http": {
"maxRequestBodySizeInMb": 64,
"proxyTimeoutInSec": 60
}
}
+17
View File
@@ -0,0 +1,17 @@
package conf
const (
HttpProtocol = "http"
GrpcProtocol = "grpc"
)
type Local struct {
Locations []Location
}
type Location struct {
SkipAuth bool
PathPrefix string `valid:"required"`
Protocol string `valid:"required,in(http|grpc)"`
TargetModule string `valid:"required"`
}
-34
View File
@@ -1,34 +0,0 @@
package conf
import (
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/structure"
)
type (
Configuration struct {
config.CommonLocalConfig
InstanceUuid string `valid:"required~Required"`
HttpOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"httpOuterAddress"`
HttpInnerAddress structure.AddressConfiguration `valid:"required~Required" json:"httpInnerAddress"`
Locations []Location
}
Location struct {
SkipAuth bool
SkipExistCheck bool
PathPrefix string `valid:"required~Required"`
Protocol string `valid:"required~Required"`
TargetModule string `valid:"required~Required"`
}
)
func GetLocationsByTargetModule(locations []Location) map[string][]Location {
requiredModules := make(map[string][]Location)
for _, loc := range locations {
requiredModules[loc.TargetModule] = append(requiredModules[loc.TargetModule], loc)
}
return requiredModules
}
+81
View File
@@ -0,0 +1,81 @@
package conf
import (
"reflect"
"github.com/integration-system/isp-kit/log"
"github.com/integration-system/isp-kit/rc/schema"
"github.com/integration-system/jsonschema"
"github.com/pkg/errors"
)
func init() {
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Type) {
t.Type = "string"
t.Enum = []interface{}{"debug", "info", "error", "fatal"}
})
}
type Remote struct {
Redis *Redis `schema:"Настройки Redis,обязательно, если используется механизм суточных ограничений или ограничений пропускной способности"`
Secrets Secrets `schema:"Настройки секретов"`
Http Http `schema:"Настройки HTTP"`
Logging Logging `schema:"Настройки логирования"`
Caching Caching `schema:"Настройки кеширования"`
DailyLimits []DailyLimit `schema:"Настройки суточных ограничений,сбрасываются раз в сутки в 00:00"`
Throttling []Throttling `schema:"Настройки пропускной способности"`
}
type Secrets struct {
AdminTokenSecret string `valid:"required" schema:"Секрет токена администратора"`
}
type Http struct {
MaxRequestBodySizeInMb int64 `valid:"required" schema:"Максимальная длинна тела запроса,в мегабайтах"`
ProxyTimeoutInSec int `valid:"required" schema:"Таймаут на проксирование,в секундах"`
}
type Logging struct {
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования,логирование запросов осуществляется на уровне debug"`
RequestLogEnable bool `schema:"Включить логирование запросов"`
BodyLogEnable bool `schema:"Включить логирование тел запросов и ответов,должно быть включено логирование запросов"`
}
type Caching struct {
AuthenticationDataInSec int `valid:"required" schema:"Время кеширования данных аутентификации,в секундах"`
AuthorizationDataInSec int `valid:"required" schema:"Время кеширования данных авторизации,в секундах"`
}
type DailyLimit struct {
ApplicationId int `valid:"required" schema:"ID приложения"`
RequestsPerDay int64 `valid:"required" schema:"Запросов в сутки"`
}
type Throttling struct {
ApplicationId int `valid:"required" schema:"ID приложения"`
RequestsPerSeconds int `valid:"required,range(1|1000)" schema:"Запросов в секунду,не конфликтует с суточными ограничениями, алгоритм не работает на значениях больше 1000"`
}
type Redis struct {
Address string `schema:"Адрес,обязателено, если sentinel не указан"`
Username string `schema:"Имя пользовтаеля"`
Password string `schema:"Пароль"`
Sentinel *RedisSentinel `schema:"Настройки sentinel,обязательно, если address не указан"`
}
type RedisSentinel struct {
Addresses []string `valid:"required" schema:"Адреса нод в кластере"`
MasterName string `valid:"required" schema:"Имя мастера"`
Username string `schema:"Имя пользовтаеля в sentinel"`
Password string `schema:"Пароль в sentinel"`
}
func (r Remote) Validate() error {
if (len(r.Throttling) > 0 || len(r.DailyLimits) > 0) && r.Redis == nil {
return errors.New("redis is required if dailyLimits or throttling were specified")
}
if r.Redis != nil && r.Redis.Sentinel == nil && r.Redis.Address == "" {
return errors.New("invalid redis config. sentinel or address are required")
}
return nil
}
-121
View File
@@ -1,121 +0,0 @@
package conf
import (
"time"
"github.com/integration-system/isp-lib/v2/structure"
)
const (
KB = int64(1024)
MB = int64(1 << 20)
defaultSyncTimeout = 30 * time.Second
defaultStreamTimeout = 60 * time.Second
defaultBufferSize = 4 * KB
defaultMaxRequestBodySize = 512 * MB
DefaultMaxResponseBodySize = 32 * MB
)
type (
RemoteConfig struct {
Database structure.DBConfiguration `schema:"Настройка подключения к базе данных"`
TokensSetting TokensSetting `schema:"Настройка секретов"`
HttpSetting HttpSetting `schema:"Настройка сервера"`
GrpcSetting GrpcSetting `schema:"Настройка grpc соединения"`
Metrics structure.MetricConfiguration `schema:"Настройка метрик"`
JournalSetting Journal `schema:"Настройка журалирования"`
Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"`
AccountingSetting Accounting `schema:"Настройка учета запросов"`
AuthCacheSetting Cache `schema:"Настройка кеширования данных аутентификации приложений" valid:"required~Required"`
}
Cache struct {
EnableCache bool `schema:"Кеширование,включает кеширования для токена приложения"`
EvictTimeout string `schema:"Время жизни записи в кеше"`
}
Journal struct {
Journal JorunalConfig `schema:"Настройка конфигурации"`
MethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"`
}
JorunalConfig struct {
Enable bool `schema:"Включение/отключение журналирования"`
Filename string `schema:"Имя файла,путь до файла в который будут записываться логи"`
MaxSizeMb int `schema:"Максимальный размер файла,ограничение по размеру файла после достижения которого логи будут записываться в новый файл"`
Compress bool `schema:"Сжатие логов,архивирует файлы в gzip"`
}
TokensSetting struct {
AdminSecret string `schema:"Секрет для проверки токена администратора"`
ApplicationSecret string `schema:"Секрет для проверки токена приложений"`
ApplicationVerify bool `schema:"Проверка подписи токена приложений"`
UserSecret string `schema:"Секрет для проверки токена пользователя"`
}
Accounting struct {
Enable bool `schema:"Учет запросов,включает/отключает учет запросов"`
SnapshotTimeout string `schema:"Частота выгрузки ограничений для приложений" valid:"required~Required"`
Setting []AccountingSetting `schema:"Настройка учета для приложений"`
Storing StoringSetting `schema:"Настройка хранения всех запросов"`
}
AccountingSetting struct {
ApplicationId int32 `valid:"required~Required" schema:"Идентификатор приложения"`
EnableStoring bool `schema:"Хранение запросов,если включено, каждый факт обработки запроса будет фиксироваться в БД"`
Limits []LimitSetting `schema:"Настройка ограничений на запросы"`
}
LimitSetting struct {
Pattern string `valid:"required~Required" schema:"Шаблон пути,указывается путь для которого будут применяется ограничения; поддерживается '/*' для неполного совпадения"`
MaxCount int `schema:"Количество запросов"`
Timeout string `schema:"Время жизни одного запроса"`
}
StoringSetting struct {
Size int `schema:"Размер буфера,размер буфера,при достижении которого данные сбрасываются в БД" valid:"required,range(1|1000000)"`
Timeout string `schema:"Частота выгрузки всех учтенных запросов,периодичность сброса данных в БД" valid:"required~Required"`
}
HttpSetting struct {
MaxRequestBodySizeBytes int64 `schema:"Максимальный размер тела запроса,в байтайх, по умолчанию: 512 MB"`
}
GrpcSetting struct {
EnableOriginalProtoErrors bool `schema:"Проксирование ошибок в протобаф,включение/отключение проксирования, по умолчанию отключено"`
ProxyGrpcErrorDetails bool `schema:"Проксирование первого элемента из details GRPC ошибки,включение/отключение проксирования, по умолчанию отключено"`
MultipartDataTransferBufferSizeBytes int64 `schema:"Размер буфера для передачи бинарных файлов,по умолчанию 4 KB"`
SyncInvokeMethodTimeoutMs int64 `schema:"Время ожидания вызова метода,значение в миллисекундах, по умолчанию: 30000"`
StreamInvokeMethodTimeoutMs int64 `schema:"Время ожидания передачи и обработки файла,значение в миллисекундах, по умолчанию: 60000"`
}
)
func (cfg GrpcSetting) GetSyncInvokeTimeout() time.Duration {
if cfg.SyncInvokeMethodTimeoutMs <= 0 {
return defaultSyncTimeout
}
return time.Duration(cfg.SyncInvokeMethodTimeoutMs) * time.Millisecond
}
func (cfg GrpcSetting) GetStreamInvokeTimeout() time.Duration {
if cfg.StreamInvokeMethodTimeoutMs <= 0 {
return defaultStreamTimeout
}
return time.Duration(cfg.StreamInvokeMethodTimeoutMs) * time.Millisecond
}
func (cfg GrpcSetting) GetTransferFileBufferSize() int64 {
if cfg.MultipartDataTransferBufferSizeBytes <= 0 {
return defaultBufferSize
}
return cfg.MultipartDataTransferBufferSizeBytes
}
func (cfg HttpSetting) GetMaxRequestBodySize() int64 {
if cfg.MaxRequestBodySizeBytes <= 0 {
return defaultMaxRequestBodySize
}
return cfg.MaxRequestBodySizeBytes
}
+8
View File
@@ -0,0 +1,8 @@
package domain
type AuthData struct {
SystemId int
DomainId int
ServiceId int
ApplicationId int
}
+9
View File
@@ -0,0 +1,9 @@
package domain
import (
"github.com/pkg/errors"
)
var (
ErrAuthenticationCacheMiss = errors.New("authentication not found in cache")
)
-30
View File
@@ -1,30 +0,0 @@
package domain
type ProxyResponse struct {
requestBody []byte
responseBody []byte
error error
}
func Create() ProxyResponse {
return ProxyResponse{requestBody: nil, responseBody: nil, error: nil}
}
func (p ProxyResponse) SetRequestBody(requestBody []byte) ProxyResponse {
p.requestBody = requestBody
return p
}
func (p ProxyResponse) SetResponseBody(responseBody []byte) ProxyResponse {
p.responseBody = responseBody
return p
}
func (p ProxyResponse) SetError(err error) ProxyResponse {
p.error = err
return p
}
func (p ProxyResponse) Get() (requestBody, responseBody []byte, err error) {
return p.requestBody, p.responseBody, p.error
}
+20
View File
@@ -0,0 +1,20 @@
package domain
type AuthenticateRequest struct {
Token string
}
type AuthenticateResponse struct {
Authenticated bool
ErrorReason string
AuthData *AuthData
}
type AuthorizeRequest struct {
ApplicationId int
Endpoint string
}
type AuthorizeResponse struct {
Authorized bool
}
+11
View File
@@ -0,0 +1,11 @@
package domain
import (
"time"
)
type RateLimitResult struct {
Allow bool
Remaining int
RetryAfter time.Duration
}
-21
View File
@@ -1,21 +0,0 @@
package entity
import (
"isp-gate-service/accounting/state"
"time"
)
type Snapshot struct {
TableName string `sql:"?db_schema.snapshot" json:"-"`
AppId int32 `sql:",pk"`
LimitState map[string]state.Snapshot
Version int64
}
type Request struct {
TableName string `sql:"?db_schema.requests" json:"-"`
Id int `sql:",pk"`
AppId int32
Method string
CreatedAt time.Time
}
+61 -19
View File
@@ -1,26 +1,68 @@
module isp-gate-service
go 1.16
go 1.17
require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/fasthttp/websocket v1.4.3-rc.7
github.com/go-pg/pg/v9 v9.2.1
github.com/go-redis/redis/v8 v8.8.2
github.com/golang/protobuf v1.5.2
github.com/integration-system/go-cmp v0.0.0-20190131081942-ac5582987a2f
github.com/integration-system/isp-kit v1.6.0
github.com/integration-system/isp-lib/v2 v2.8.7
github.com/integration-system/isp-log v1.1.8
github.com/json-iterator/go v1.1.12
github.com/go-redis/redis/v8 v8.11.5
github.com/go-redis/redis_rate/v9 v9.1.2
github.com/go-resty/resty/v2 v2.7.0
github.com/golang-jwt/jwt/v4 v4.4.2
github.com/google/uuid v1.1.2
github.com/integration-system/isp-kit v1.10.3
github.com/integration-system/jsonschema v1.0.1
github.com/pkg/errors v0.9.1
github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0
github.com/spf13/cast v1.4.1
github.com/stretchr/testify v1.7.1
github.com/valyala/fasthttp v1.28.0
golang.org/x/net v0.0.0-20220421235706-1d1ef9303861
google.golang.org/grpc v1.46.0
google.golang.org/protobuf v1.28.0
github.com/stretchr/testify v1.8.0
golang.org/x/net v0.0.0-20220708220712-1185a9018129
google.golang.org/grpc v1.48.0
)
replace google.golang.org/grpc v1.46.0 => google.golang.org/grpc v1.38.0
require (
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/fsnotify/fsnotify v1.5.4 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/gorilla/websocket v1.4.2 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/integration-system/bellows v1.0.1 // indirect
github.com/integration-system/isp-etp-go/v2 v2.1.3 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/julienschmidt/httprouter v1.3.0 // indirect
github.com/klauspost/compress v1.15.9 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.2 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_golang v1.12.2 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.37.0 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/spf13/afero v1.9.2 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.12.0 // indirect
github.com/subosito/gotenv v1.4.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.8.0 // indirect
go.uber.org/zap v1.21.0 // indirect
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f // indirect
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
golang.org/x/text v0.3.7 // indirect
google.golang.org/genproto v0.0.0-20220720214146-176da50484ac // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/ini.v1 v1.66.6 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
nhooyr.io/websocket v1.8.7 // indirect
)
+144 -538
View File
File diff suppressed because it is too large. Load diff
-139
View File
@@ -1,139 +0,0 @@
package handler
import (
"fmt"
"net/http"
"time"
"github.com/integration-system/isp-kit/log"
"github.com/integration-system/isp-lib/v2/config"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/accounting"
"isp-gate-service/authenticate"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/proxy"
"isp-gate-service/routing"
"isp-gate-service/service"
"isp-gate-service/service/matcher"
"isp-gate-service/utils"
)
const (
execution = 1e6
)
var errAccounting = errors.New("accounting error")
type Handler struct {
logger log.Logger
}
func New(logger log.Logger) *Handler {
return &Handler{
logger: logger,
}
}
func (h Handler) CompleteRequest(ctx *fasthttp.RequestCtx) {
currentTime := time.Now()
appId, adminId, path, resp := h.authenticateAccountingProxy(ctx)
executionTime := time.Since(currentTime) / execution
statusCode := ctx.Response.StatusCode()
service.Metrics.UpdateStatusCounter(h.setMetricStatus(statusCode))
if statusCode == http.StatusOK {
service.Metrics.UpdateMethodResponseTime(path, executionTime)
}
logEnable := config.GetRemote().(*conf.RemoteConfig).JournalSetting.Journal.Enable
// nolintlint
if logEnable && matcher.JournalMethods.Match(path) {
requestBody, responseBody, err := resp.Get()
fields := []log.Field{
log.ByteString("http_method", ctx.Method()),
log.String("remote_addr", ctx.RemoteAddr().String()),
log.ByteString("x_forwarded_for", ctx.Request.Header.Peek("X-Forwarded-For")),
log.Int("status_code", ctx.Response.StatusCode()),
log.String("path", path),
log.Int32("application_id", appId),
log.Int64("admin_id", adminId),
log.ByteString("request", requestBody),
log.ByteString("response", responseBody),
}
if err != nil {
fields = append(fields, log.Any("error", err))
h.logger.Error(ctx, "unsuccessful request", fields...)
} else {
h.logger.Info(ctx, "successful request", fields...)
}
}
}
func (h Handler) authenticateAccountingProxy(ctx *fasthttp.RequestCtx) (int32, int64, string, domain.ProxyResponse) {
var (
appId int32 = -1
adminId int64 = -1
initialPath = string(ctx.Path())
)
p, path := proxy.Find(initialPath)
if p == nil {
msg := fmt.Sprintf("unknown proxy for '%s'", initialPath)
utils.WriteError(ctx, msg, codes.NotFound, nil)
return appId, adminId, initialPath, domain.Create().SetError(errors.New(msg))
}
if !p.SkipExistCheck() {
if _, ok := routing.AllMethods[path]; !ok {
msg := "not implemented"
utils.WriteError(ctx, msg, codes.Unimplemented, nil)
return appId, adminId, path, domain.Create().SetError(errors.New(msg))
}
}
if !p.SkipAuth() {
var err error
appId, adminId, err = authenticate.Do(ctx, path)
if err != nil {
message := "unknown error"
status := codes.Unknown
details := make([]interface{}, 0)
if e, ok := err.(authenticate.ErrorDescription); ok {
message = e.Message()
status = e.ConvertToGrpcStatus()
details = e.Details()
}
utils.WriteError(ctx, message, status, details)
return appId, adminId, path, domain.Create().SetError(err)
}
if !accounting.AcceptRequest(appId, path) {
err := errAccounting
utils.WriteError(ctx, "too many requests", codes.ResourceExhausted, nil)
return appId, adminId, path, domain.Create().SetError(err)
}
}
return appId, adminId, path, p.ProxyRequest(ctx, path)
}
func (Handler) setMetricStatus(statusCode int) string {
metricStatus := "5xx"
switch {
case statusCode >= 100 && statusCode < 200:
metricStatus = "1xx"
case statusCode >= 200 && statusCode < 300:
metricStatus = "2xx"
case statusCode >= 300 && statusCode < 400:
metricStatus = "3xx"
case statusCode >= 400 && statusCode < 500:
metricStatus = "4xx"
case statusCode >= 500 && statusCode < 600:
metricStatus = "5xx"
}
return metricStatus
}
+41
View File
@@ -0,0 +1,41 @@
package httperrors
import (
"net/http"
"github.com/integration-system/isp-kit/json"
)
type HttpError struct {
statusCode int
userMessage string
details []interface{}
err error
}
func New(statusCode int, userMessage string, internalError error) HttpError {
return HttpError{
statusCode: statusCode,
userMessage: userMessage,
err: internalError,
}
}
func (e HttpError) Error() string {
return e.err.Error()
}
func (e HttpError) WriteError(w http.ResponseWriter) error {
w.Header().Set("content-type", "application/json")
w.WriteHeader(e.statusCode)
data := map[string]interface{}{
"errorCode": http.StatusText(e.statusCode),
"errorMessage": e.userMessage,
"details": e.details,
}
return json.NewEncoder(w).Encode(data)
}
func (e *HttpError) WithDetails(details ...interface{}) {
e.details = details
}
-25
View File
@@ -1,25 +0,0 @@
package log_code
const (
WarnHttpServerShutdown = 602
ErrorHttpServerListen = 603
WarnProxyGrpcHandler = 604 //metadata: {"typeData":"", "method":""}
WarnConvertErrorDataMarshalResponse = 605
ErrorClientGrpc = 606
WarnJournalCouldNotWriteToFile = 607
ErrorClientJournal = 608
ErrorClientRedis = 609
ErrorClientHttp = 611
ErrorAuthenticate = 612
ErrorClientDatabase = 615
ErrorSnapshotAccounting = 616
ErrorUnloadAccounting = 617
ErrorWebsocketProxy = 618
)
-22
View File
@@ -1,22 +0,0 @@
package log_code
const (
MdTypeData = "typeData"
MdMethod = "method"
)
var (
TypeData = typeData{
SendMultipart: "sendMultipart",
GetFile: "getFile",
JsonContent: "jsonContent",
}
)
type (
typeData struct {
SendMultipart string
GetFile string
JsonContent string
}
)
+19 -140
View File
@@ -1,158 +1,37 @@
package main
import (
"context"
"os"
"github.com/integration-system/go-cmp/cmp"
"github.com/integration-system/isp-kit/log"
"github.com/integration-system/isp-lib/v2/bootstrap"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/config/schema"
"github.com/integration-system/isp-lib/v2/metric"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils"
logrus "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
"github.com/pkg/errors"
"isp-gate-service/accounting"
"isp-gate-service/authenticate"
"github.com/integration-system/isp-kit/bootstrap"
"github.com/integration-system/isp-kit/shutdown"
"isp-gate-service/assembly"
"isp-gate-service/conf"
"isp-gate-service/proxy"
"isp-gate-service/redis"
"isp-gate-service/repository"
"isp-gate-service/routing"
"isp-gate-service/server"
"isp-gate-service/service"
"isp-gate-service/service/matcher"
)
var (
version = "0.1.0"
logger *log.Adapter
version = "1.0.0"
)
func main() {
cfg := config.InitConfig(&conf.Configuration{}).(*conf.Configuration)
boot := bootstrap.New(version, conf.Remote{}, nil)
app := boot.App
logger := app.Logger()
bs := bootstrap.
ServiceBootstrap(&conf.Configuration{}, &conf.RemoteConfig{}).
OnLocalConfigLoad(onLocalConfigLoad).
DefaultRemoteConfigPath(schema.ResolveDefaultConfigPath("default_remote_config.json")).
DeclareMe(makeDeclaration).
SocketConfiguration(socketConfiguration).
RequireRoutes(handleRouteUpdate).
SubscribeBroadcastEvent(bootstrap.ListenRestartEvent())
requiredModules, err := proxy.InitProxies(cfg.Locations)
assembly, err := assembly.New(boot)
if err != nil {
logrus.Fatal(stdcodes.ModuleInvalidLocalConfig, err)
logger.Fatal(app.Context(), err)
}
for module, consumer := range requiredModules {
bs.RequireModule(module, consumer, false)
}
bs.RequireModule(cfg.ModuleName, accounting.NewConnectionConsumer, false).
OnShutdown(onShutdown).
OnRemoteConfigReceive(onRemoteConfigReceive).
Run()
}
app.AddRunners(assembly.Runners()...)
app.AddClosers(assembly.Closers()...)
func onLocalConfigLoad(_ *conf.Configuration) {
shutdown.On(func() {
logger.Info(app.Context(), "starting shutdown")
app.Shutdown()
logger.Info(app.Context(), "shutdown completed")
})
}
func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
repository.DbClient.ReceiveConfiguration(remoteConfig.Database)
matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalSetting.MethodsPatterns)
redis.Client.ReceiveConfiguration(remoteConfig.Redis)
authenticate.ReceiveConfiguration(remoteConfig.AuthCacheSetting)
accounting.ReceiveConfiguration(remoteConfig.AccountingSetting)
metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics)
metric.InitHttpServer(remoteConfig.Metrics)
service.Metrics.Init()
oldLogger := setLogger(remoteConfig.JournalSetting.Journal, oldRemoteConfig.JournalSetting.Journal)
defer func() {
if oldLogger != nil {
_ = oldLogger.Close()
}
}()
isDifferentSettingForHttpServ :=
!cmp.Equal(remoteConfig.HttpSetting, oldRemoteConfig.HttpSetting) || oldLogger != nil
server.Http.Init(isDifferentSettingForHttpServ, remoteConfig.HttpSetting.GetMaxRequestBodySize(), logger)
}
func socketConfiguration(cfg interface{}) structure.SocketConfiguration {
appConfig := cfg.(*conf.Configuration)
return structure.SocketConfiguration{
Host: appConfig.ConfigServiceAddress.IP,
Port: appConfig.ConfigServiceAddress.Port,
Secure: false,
UrlParams: map[string]string{
"module_name": appConfig.ModuleName,
},
}
}
func onShutdown(_ context.Context, _ os.Signal) {
server.Http.Close()
accounting.Close()
proxy.Close()
_ = redis.Client.Close()
if logger != nil {
_ = logger.Close()
}
}
func handleRouteUpdate(configs structure.RoutingConfig) bool {
routing.InitRoutes(configs)
return true
}
func makeDeclaration(localConfig interface{}) bootstrap.ModuleInfo {
cfg := localConfig.(*conf.Configuration)
return bootstrap.ModuleInfo{
ModuleName: cfg.ModuleName,
ModuleVersion: version,
GrpcOuterAddress: cfg.HttpOuterAddress,
Endpoints: []structure.EndpointDescriptor{},
}
}
func setLogger(loggerCfg, oldLoggerCfg conf.JorunalConfig) *log.Adapter {
if cmp.Equal(loggerCfg, oldLoggerCfg) {
return nil
}
// temporary for file rotation. Selected based on max size 512 mb
maxBackups := 2
var err error
oldLogger := logger
loggerOpts := []log.Option{log.WithDevelopmentMode(), log.WithLevel(log.DebugLevel)}
isDev := utils.DEV
if !isDev {
loggerOpts = []log.Option{log.WithLevel(log.InfoLevel)}
logFilePath := loggerCfg.Filename
if logFilePath != "" {
rotation := log.Rotation{
File: logFilePath,
MaxSizeMb: loggerCfg.MaxSizeMb,
MaxDays: 0,
MaxBackups: maxBackups,
Compress: loggerCfg.Compress,
}
loggerOpts = append(loggerOpts, log.WithFileRotation(rotation))
}
}
logger, err = log.New(loggerOpts...)
err = app.Run()
if err != nil {
logrus.Fatal(stdcodes.ModuleRunFatalError, errors.WithMessage(err, "set logger"))
app.Shutdown()
logger.Fatal(app.Context(), err)
}
return oldLogger
}
+39
View File
@@ -0,0 +1,39 @@
package middleware
import (
"net/http"
"strings"
"github.com/pkg/errors"
"isp-gate-service/httperrors"
"isp-gate-service/request"
)
const (
adminAuthHeader = "x-auth-admin"
)
type AdminAuthenticator interface {
Authenticate(token string) (int, error)
}
func AdminAuthenticate(auth AdminAuthenticator) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
adminToken := strings.TrimSpace(ctx.Request().Header.Get(adminAuthHeader))
if adminToken == "" {
return next.Handle(ctx)
}
adminId, err := auth.Authenticate(adminToken)
if err != nil {
return httperrors.New(
http.StatusUnauthorized,
"invalid admin token",
errors.WithMessage(err, "admin authenticate: authenticate"),
)
}
ctx.AuthenticateAdmin(adminId, adminToken)
return next.Handle(ctx)
})
}
}
+32
View File
@@ -0,0 +1,32 @@
package middleware
import (
"net/http"
"github.com/pkg/errors"
"isp-gate-service/httperrors"
"isp-gate-service/request"
)
type AdminMethodStore interface {
IsInnerMethod(path string) bool
}
func AdminAuthorize(store AdminMethodStore) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
isInner := store.IsInnerMethod(ctx.Endpoint())
if !isInner {
return next.Handle(ctx)
}
if ctx.IsAdminAuthenticated() {
return next.Handle(ctx)
}
return httperrors.New(
http.StatusForbidden,
"admin authentication required",
errors.Errorf("admin authorization: admin authentication required for '%s'", ctx.Endpoint()),
)
})
}
}
+50
View File
@@ -0,0 +1,50 @@
package middleware
import (
"context"
"net/http"
"strings"
"github.com/pkg/errors"
"isp-gate-service/domain"
"isp-gate-service/httperrors"
"isp-gate-service/request"
)
const (
applicationTokenHeader = "x-application-token"
)
type Authenticator interface {
Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error)
}
func Authenticate(authenticator Authenticator) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
token := strings.TrimSpace(ctx.Request().Header.Get(applicationTokenHeader))
if token == "" {
return httperrors.New(
http.StatusUnauthorized,
"application token required",
errors.New("authenticate: application token required"),
)
}
resp, err := authenticator.Authenticate(ctx.Context(), token)
if err != nil {
return errors.WithMessagef(err, "authenticate: authenticate")
}
if !resp.Authenticated {
return httperrors.New(
http.StatusUnauthorized,
"invalid application token",
errors.WithMessage(errors.New(resp.ErrorReason), "authenticate: authenticate"),
)
}
ctx.Authenticate(request.AuthData(*resp.AuthData))
return next.Handle(ctx)
})
}
}
+49
View File
@@ -0,0 +1,49 @@
package middleware
import (
"context"
"net/http"
"github.com/integration-system/isp-kit/log"
"github.com/pkg/errors"
"isp-gate-service/httperrors"
"isp-gate-service/request"
)
type Authorizer interface {
Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error)
}
func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
authData, err := ctx.GetAuthData()
if err != nil {
return errors.WithMessage(err, "authorize: get auth data")
}
ok, err := authorizer.Authorize(ctx.Context(), authData.ApplicationId, ctx.Endpoint())
if err != nil {
return errors.WithMessage(err, "authorize: authorize")
}
if !ok && ctx.IsAdminAuthenticated() {
logger.Info(
ctx.Context(),
"bypassing unauthorized request because it has admin privilege",
log.Int("applicationId", authData.ApplicationId),
log.Int("adminId", ctx.AdminId()),
)
return next.Handle(ctx)
}
if !ok {
return httperrors.New(
http.StatusForbidden,
"endpoint is not allowed",
errors.Errorf("authorize: endpoint '%s' is not allowed for application '%d'", ctx.Endpoint(), authData.ApplicationId),
)
}
return next.Handle(ctx)
})
}
}
+39
View File
@@ -0,0 +1,39 @@
package middleware
import (
"context"
"net/http"
"github.com/pkg/errors"
"isp-gate-service/httperrors"
"isp-gate-service/request"
)
type DailyLimitChecker interface {
IncrementAndCheck(ctx context.Context, applicationId int) (bool, error)
}
func DailyLimit(checker DailyLimitChecker) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
authData, err := ctx.GetAuthData()
if err != nil {
return errors.WithMessage(err, "daily limit: get auth data")
}
ok, err := checker.IncrementAndCheck(ctx.Context(), authData.ApplicationId)
if err != nil {
return errors.WithMessage(err, "daily limit: increment and check")
}
if !ok {
return httperrors.New(
http.StatusTooManyRequests,
"daily requests limit has been reached",
errors.Errorf("daily limit: daily requests limit has been reached for application '%d'", authData.ApplicationId),
)
}
return next.Handle(ctx)
})
}
}
+26
View File
@@ -0,0 +1,26 @@
package middleware
import (
"fmt"
"net/http"
"strings"
"github.com/integration-system/isp-kit/log"
"github.com/pkg/errors"
"isp-gate-service/request"
)
func Entrypoint(maxReqBodySize int64, next Handler, pathPrefix string, logger log.Logger) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
req.Body = http.MaxBytesReader(writer, req.Body, maxReqBodySize)
prefix := fmt.Sprintf("%s/", pathPrefix)
endpoint := strings.TrimPrefix(req.URL.String(), prefix)
ctx := request.NewContext(req, writer, endpoint)
err := next.Handle(ctx)
if err != nil {
logger.Error(req.Context(), errors.WithMessage(err, "uncaught error"))
}
})
}
+35
View File
@@ -0,0 +1,35 @@
package middleware
import (
"net/http"
"github.com/integration-system/isp-kit/log"
"isp-gate-service/httperrors"
"isp-gate-service/request"
)
type HttpError interface {
WriteError(w http.ResponseWriter) error
}
func ErrorHandler(logger log.Logger) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
err := next.Handle(ctx)
if err == nil {
return nil
}
logger.Error(ctx.Context(), err)
httpErr, ok := err.(HttpError)
if ok {
return httpErr.WriteError(ctx.ResponseWriter())
}
return httperrors.
New(http.StatusInternalServerError, "internal service error", err).
WriteError(ctx.ResponseWriter())
})
}
}
+91
View File
@@ -0,0 +1,91 @@
package middleware
import (
"bytes"
"io/ioutil"
"net/http"
"github.com/integration-system/isp-kit/http/endpoint/buffer"
"github.com/integration-system/isp-kit/log"
"github.com/pkg/errors"
"isp-gate-service/request"
)
type scSource interface {
StatusCode() int
}
type writerWrapper struct {
http.ResponseWriter
statusCode int
}
func (w *writerWrapper) StatusCode() int {
if w.statusCode == 0 {
return http.StatusOK
}
return w.statusCode
}
func (w *writerWrapper) WriteHeader(statusCode int) {
w.statusCode = statusCode
w.ResponseWriter.WriteHeader(statusCode)
}
func Logger(logger log.Logger, enableRequestLogging bool, enableBodyLogging bool) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
if !enableRequestLogging {
return next.Handle(ctx)
}
r := ctx.Request()
var scSrc scSource
var buf *buffer.Buffer
if enableBodyLogging {
buf = buffer.Acquire(ctx.ResponseWriter())
defer buffer.Release(buf)
err := buf.ReadRequestBody(r.Body)
if err != nil {
return errors.WithMessage(err, "logger: read request body for logging")
}
err = r.Body.Close()
if err != nil {
return errors.WithMessage(err, "logger: close request reader")
}
r.Body = ioutil.NopCloser(bytes.NewBuffer(buf.RequestBody()))
scSrc = buf
ctx.SetResponseWriter(buf)
} else {
writer := &writerWrapper{ResponseWriter: ctx.ResponseWriter()}
scSrc = writer
ctx.SetResponseWriter(writer)
}
err := next.Handle(ctx)
authData, _ := ctx.GetAuthData()
fields := []log.Field{
log.String("http_method", r.Method),
log.String("remote_addr", r.RemoteAddr),
log.String("x_forwarded_for", r.Header.Get("X-Forwarded-For")),
log.Int("status_code", scSrc.StatusCode()),
log.String("path", r.URL.Path),
log.String("endpoint", ctx.Endpoint()),
log.Int("application_id", authData.ApplicationId),
log.Int("admin_id", ctx.AdminId()),
}
if enableBodyLogging {
fields = append(fields,
log.ByteString("request", buf.RequestBody()),
log.ByteString("response", buf.ResponseBody()),
)
}
logger.Debug(ctx.Context(), "log request", fields...)
return err
})
}
}
+24
View File
@@ -0,0 +1,24 @@
package middleware
import (
"isp-gate-service/request"
)
type Handler interface {
Handle(ctx *request.Context) error
}
type HandlerFunc func(ctx *request.Context) error
func (f HandlerFunc) Handle(ctx *request.Context) error {
return f(ctx)
}
type Middleware func(next Handler) Handler
func Chain(root Handler, middlewares ...Middleware) Handler {
for i := len(middlewares) - 1; i >= 0; i-- {
root = middlewares[i](root)
}
return root
}
+31
View File
@@ -0,0 +1,31 @@
package middleware
import (
"strings"
"github.com/integration-system/isp-kit/log"
"github.com/integration-system/isp-kit/requestid"
"isp-gate-service/request"
)
const (
requestIdHeader = "x-request-id"
)
func RequestId() Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
requestId := strings.TrimSpace(ctx.Request().Header.Get(requestIdHeader))
if requestId == "" {
requestId = requestid.Next()
}
context := requestid.ToContext(ctx.Context(), requestId)
context = log.ToContext(context, log.String("requestId", requestId))
ctx.SetContext(context)
return next.Handle(ctx)
})
}
}
+41
View File
@@ -0,0 +1,41 @@
package middleware
import (
"context"
"fmt"
"net/http"
"github.com/pkg/errors"
"isp-gate-service/domain"
"isp-gate-service/httperrors"
"isp-gate-service/request"
)
type Throttler interface {
AllowRateLimit(ctx context.Context, applicationId int) (*domain.RateLimitResult, error)
}
func Throttling(throttler Throttler) Middleware {
return func(next Handler) Handler {
return HandlerFunc(func(ctx *request.Context) error {
authData, err := ctx.GetAuthData()
if err != nil {
return errors.WithMessage(err, "throttling: get auth data")
}
result, err := throttler.AllowRateLimit(ctx.Context(), authData.ApplicationId)
if err != nil {
return errors.WithMessage(err, "throttling: allow rate limit")
}
if !result.Allow {
return httperrors.New(
http.StatusTooManyRequests,
fmt.Sprintf("rate limit has been reached, try after %dms", result.RetryAfter.Milliseconds()),
errors.Errorf("throttling: rate limit has been reached for application '%d'", authData.ApplicationId),
)
}
return next.Handle(ctx)
})
}
}
-9
View File
@@ -1,9 +0,0 @@
-- +goose Up
CREATE TABLE snapshot(
app_id INTEGER PRIMARY KEY,
limit_state JSONB
);
-- +goose Down
DROP SCHEMA IF EXISTS gate_service CASCADE;
@@ -1,12 +0,0 @@
-- +goose Up
CREATE TABLE requests
(
id SERIAL8 PRIMARY KEY,
app_id INT4 NOT NULL,
method VARCHAR(255) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT now()
);
-- +goose Down
DROP TABLE requests;
@@ -1,6 +0,0 @@
-- +goose Up
ALTER TABLE snapshot
ADD version BIGINT NOT NULL DEFAULT 0;
-- +goose Down
+162
View File
@@ -0,0 +1,162 @@
package proxy
import (
"context"
"io/ioutil"
"net/http"
"strconv"
"time"
"github.com/integration-system/isp-kit/grpc"
"github.com/integration-system/isp-kit/grpc/client"
"github.com/integration-system/isp-kit/grpc/isp"
"github.com/integration-system/isp-kit/json"
"github.com/integration-system/isp-kit/requestid"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"isp-gate-service/httperrors"
"isp-gate-service/request"
)
const (
adminAuthHeader = "x-auth-admin"
)
func init() {
for httpCode, grpcCode := range codeMap {
inverseCodeMap[grpcCode] = httpCode
}
}
var (
codeMap = map[int]codes.Code{
http.StatusOK: codes.OK,
http.StatusRequestTimeout: codes.Canceled,
http.StatusBadRequest: codes.InvalidArgument,
http.StatusGatewayTimeout: codes.DeadlineExceeded,
http.StatusNotFound: codes.NotFound,
http.StatusConflict: codes.AlreadyExists,
http.StatusForbidden: codes.PermissionDenied,
http.StatusUnauthorized: codes.Unauthenticated,
http.StatusTooManyRequests: codes.ResourceExhausted,
http.StatusPreconditionFailed: codes.FailedPrecondition,
http.StatusNotImplemented: codes.Unimplemented,
http.StatusInternalServerError: codes.Internal,
http.StatusServiceUnavailable: codes.Unavailable,
}
inverseCodeMap = map[codes.Code]int{}
)
type Grpc struct {
cli *client.Client
skipAuth bool
timeout time.Duration
}
func NewGrpc(cli *client.Client, skipAuth bool, timeout time.Duration) Grpc {
return Grpc{
cli: cli,
skipAuth: skipAuth,
timeout: timeout,
}
}
func (p Grpc) Handle(ctx *request.Context) error {
body, err := ioutil.ReadAll(ctx.Request().Body)
if err != nil {
return errors.WithMessage(err, "grpc: read body")
}
md := metadata.MD{
grpc.ProxyMethodNameHeader: {ctx.Endpoint()},
grpc.RequestIdHeader: {requestid.FromContext(ctx.Context())},
}
if !p.skipAuth {
authData, err := ctx.GetAuthData()
if err != nil {
return errors.WithMessage(err, "get auth data")
}
md[grpc.SystemIdHeader] = []string{strconv.Itoa(authData.SystemId)}
md[grpc.DomainIdHeader] = []string{strconv.Itoa(authData.DomainId)}
md[grpc.ServiceIdHeader] = []string{strconv.Itoa(authData.ServiceId)}
md[grpc.ApplicationIdHeader] = []string{strconv.Itoa(authData.ApplicationId)}
if ctx.IsAdminAuthenticated() {
md[adminAuthHeader] = []string{ctx.AdminToken()}
}
}
requestContext := metadata.NewOutgoingContext(ctx.Context(), md)
requestContext, cancel := context.WithTimeout(requestContext, p.timeout)
defer cancel()
result, err := p.cli.BackendClient().Request(requestContext, &isp.Message{
Body: &isp.Message_BytesBody{BytesBody: body},
})
if err != nil {
return p.handleError(err, ctx.ResponseWriter())
}
return p.writeResponse(http.StatusOK, result.GetBytesBody(), ctx.ResponseWriter())
}
func (p Grpc) handleError(err error, w http.ResponseWriter) error {
status, ok := status.FromError(err)
if !ok {
return httperrors.New(
http.StatusServiceUnavailable,
"upstream is not available",
errors.WithMessage(err, "grpc proxy"),
)
}
statusCode := p.codeToHttpStatus(status.Code())
for _, detail := range status.Details() {
switch typeOfDetail := detail.(type) {
case *isp.Message:
switch {
case typeOfDetail.GetBytesBody() != nil:
return p.writeResponse(statusCode, typeOfDetail.GetBytesBody(), w)
case typeOfDetail.GetListBody() != nil:
return p.writeProto(statusCode, typeOfDetail.GetListBody(), w)
case typeOfDetail.GetStructBody() != nil:
return p.writeProto(statusCode, typeOfDetail.GetStructBody(), w)
}
default:
return p.writeProto(statusCode, typeOfDetail, w)
}
}
return httperrors.New(
statusCode,
status.Message(),
status.Err(),
)
}
func (p Grpc) writeProto(statusCode int, proto interface{}, w http.ResponseWriter) error {
data, err := json.Marshal(proto)
if err != nil {
return errors.WithMessage(err, "marshal grpc details to json")
}
return p.writeResponse(statusCode, data, w)
}
func (p Grpc) writeResponse(statusCode int, data []byte, w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
_, err := w.Write(data)
if err != nil {
return errors.WithMessage(err, "response write")
}
return nil
}
func (p Grpc) codeToHttpStatus(code codes.Code) int {
s, ok := inverseCodeMap[code]
if !ok {
return http.StatusInternalServerError
}
return s
}
-50
View File
@@ -1,50 +0,0 @@
package grpc
import (
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/valyala/fasthttp"
"google.golang.org/grpc"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/proxy/grpc/handlers"
)
type grpcProxy struct {
client *backend.RxGrpcClient
skipAuth bool
skipExistCheck bool
}
func NewProxy(skipAuth, skipExistCheck bool) *grpcProxy {
return &grpcProxy{
client: backend.NewRxGrpcClient(
backend.WithDialOptions(
grpc.WithInsecure(),
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(int(conf.DefaultMaxResponseBodySize))),
grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(int(conf.DefaultMaxResponseBodySize))),
)),
skipAuth: skipAuth,
skipExistCheck: skipExistCheck,
}
}
func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
return handlers.Handler.Get(ctx).Complete(ctx, path, p.client)
}
func (p *grpcProxy) Consumer(addr []structure.AddressConfiguration) bool {
return p.client.ReceiveAddressList(addr)
}
func (p *grpcProxy) SkipAuth() bool {
return p.skipAuth
}
func (p *grpcProxy) SkipExistCheck() bool {
return p.skipExistCheck
}
func (p *grpcProxy) Close() {
_ = p.client.Close()
}
-165
View File
@@ -1,165 +0,0 @@
package handlers
import (
"bytes"
"io"
"net/http"
"time"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/config"
http2 "github.com/integration-system/isp-lib/v2/http"
"github.com/integration-system/isp-lib/v2/isp"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
jsoniter "github.com/json-iterator/go"
"github.com/valyala/fasthttp"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/log_code"
utils2 "isp-gate-service/utils"
)
const (
headerKeyContentDisposition = "Content-Disposition"
headerKeyContentType = "Content-Type"
headerKeyContentLength = "Content-Length"
headerKeyTransferEncoding = "Transfer-Encoding"
errorMsgInternal = "Internal server error"
errorMsgInvalidArg = "Not able to read request body"
metadataSize = 5
)
var json = jsoniter.ConfigFastest
func convertError(err error) ([]byte, int) {
s, ok := status.FromError(err)
if !ok {
return []byte(utils.ServiceError), http.StatusServiceUnavailable
}
cfg := config.GetRemote().(*conf.RemoteConfig).GrpcSetting
if cfg.EnableOriginalProtoErrors {
body, err := proto.Marshal(s.Proto())
if err != nil {
return []byte(utils.ServiceError), http.StatusServiceUnavailable
}
return body, http2.CodeToHttpStatus(s.Code())
}
details := s.Details()
newDetails := make([]interface{}, len(details))
for i, detail := range details {
switch typeOfDetail := detail.(type) {
case *structpb.Struct:
newDetails[i] = utils.ConvertGrpcStructToInterface(
&structpb.Value{Kind: &structpb.Value_StructValue{StructValue: typeOfDetail}},
)
case *isp.Message:
newDetails[i] = utils.ConvertGrpcStructToInterface(
backend.ResolveBody(typeOfDetail),
)
default:
newDetails[i] = typeOfDetail
}
}
var respBody interface{}
if cfg.ProxyGrpcErrorDetails && len(newDetails) > 0 {
respBody = newDetails[0]
} else {
respBody = structure.GrpcError{ErrorMessage: s.Message(), ErrorCode: s.Code().String(), Details: newDetails}
}
errorData, err := json.Marshal(respBody)
if err != nil {
log.Warn(log_code.WarnConvertErrorDataMarshalResponse, err)
return []byte(utils.ServiceError), http.StatusServiceUnavailable
}
return errorData, http2.CodeToHttpStatus(s.Code())
}
func getResponse(msg *isp.Message, err error) ([]byte, int, error) {
if err != nil {
errorBody, errorStatus := convertError(err)
return errorBody, errorStatus, nil
}
bytes := msg.GetBytesBody()
if bytes != nil {
return bytes, http.StatusOK, nil
}
result := backend.ResolveBody(msg)
data := utils.ConvertGrpcStructToInterface(result)
byteResponse, err := json.Marshal(data)
return byteResponse, http.StatusOK, err
}
func logHandlerError(typeData, method string, err error) {
log.WithMetadata(map[string]interface{}{
log_code.MdTypeData: typeData,
log_code.MdMethod: method,
}).Warn(log_code.WarnProxyGrpcHandler, err)
}
func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Duration, client *backend.RxGrpcClient) (
isp.BackendService_RequestStreamClient, context.CancelFunc, error) {
cli := client.Conn()
md, _ := makeMetadata(headers, method)
ctx := metadata.NewOutgoingContext(context.Background(), md)
ctx, cancel := context.WithTimeout(ctx, timeout)
stream, err := cli.RequestStream(ctx)
if err != nil {
return nil, nil, err
}
return stream, cancel, nil
}
func makeMetadata(r *fasthttp.RequestHeader, method string) (metadata.MD, string) {
md := make(metadata.MD, metadataSize)
md[utils.ProxyMethodNameHeader] = []string{method}
r.VisitAll(func(key, v []byte) {
lowerHeader := bytes.ToLower(key)
if len(v) > 0 && bytes.HasPrefix(lowerHeader, []byte("x-")) {
md[string(lowerHeader)] = []string{string(v)}
}
})
return md, method
}
func checkError(err error, ctx *fasthttp.RequestCtx, method string) (bool, bool, domain.ProxyResponse) {
var (
ok = true
eof = false
resp = domain.ProxyResponse{}
msg = errorMsgInternal
code = codes.Internal
details []interface{} = nil
)
if err != nil {
if err != io.EOF {
s, itStatus := status.FromError(err)
if itStatus {
msg = s.Message()
code = s.Code()
details = s.Details()
}
logHandlerError(log_code.TypeData.GetFile, method, err)
utils2.WriteError(ctx, msg, code, details)
resp = domain.Create().SetError(err)
ok, eof = false, false
} else {
ok, eof = true, true
}
}
return ok, eof, resp
}
-51
View File
@@ -1,51 +0,0 @@
package handlers
import (
"github.com/integration-system/isp-lib/v2/backend"
u "github.com/integration-system/isp-lib/v2/utils"
"github.com/valyala/fasthttp"
"isp-gate-service/domain"
"isp-gate-service/utils"
"mime"
)
var Handler handlerHelper
type (
handlerHelper struct{}
handler interface {
Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse
}
)
func (h handlerHelper) Get(ctx *fasthttp.RequestCtx) handler {
isMultipart := h.isMultipart(ctx)
isExpectFile := string(ctx.Request.Header.Peek(u.ExpectFileHeader)) == "true"
if isMultipart {
ctx.Response.Header.SetContentTypeBytes(utils.JsonContentType)
return sendMultipartData
}
if isExpectFile {
return getFile
}
ctx.Response.Header.SetContentTypeBytes(utils.JsonContentType)
return handleJson
}
func (h handlerHelper) isMultipart(ctx *fasthttp.RequestCtx) bool {
if !ctx.IsPost() {
return false
}
v := string(ctx.Request.Header.ContentType())
if v == "" {
return false
}
d, params, err := mime.ParseMediaType(v)
if err != nil || d != "multipart/form-data" {
return false
}
_, ok := params["boundary"]
return ok
}
-138
View File
@@ -1,138 +0,0 @@
package handlers
import (
"fmt"
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/isp"
s "github.com/integration-system/isp-lib/v2/streaming"
u "github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"io"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
"strconv"
)
var (
errInvalidJson = errors.New("invalid json format. Expected object or array")
getFile getFileDesc
)
type getFileDesc struct{}
func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse {
req, err := g.readJsonBody(ctx)
if err != nil {
return g.formError(ctx, err, method, err.Error(), codes.InvalidArgument)
}
timeout := config.GetRemote().(*conf.RemoteConfig).GrpcSetting.GetStreamInvokeTimeout()
stream, cancel, err := openStream(&ctx.Request.Header, method, timeout, client)
defer func() {
if cancel != nil {
cancel()
}
}()
if err != nil {
return g.formError(ctx, err, method, errorMsgInternal, codes.Internal)
}
if req != nil {
value := u.ConvertInterfaceToGrpcStruct(req)
err := stream.Send(backend.WrapBody(value))
if err != nil {
return g.formError(ctx, err, method, errorMsgInternal, codes.Internal)
}
}
msg, err := stream.Recv()
if err != nil {
response, status, err := getResponse(nil, err)
if err == nil {
ctx.SetStatusCode(status)
ctx.SetBody(response)
}
return domain.Create().SetError(err)
}
bf := s.BeginFile{}
err = bf.FromMessage(msg)
if err != nil {
response, status, err := getResponse(nil, err)
if err == nil {
ctx.SetStatusCode(status)
ctx.SetBody(response)
}
return domain.Create().SetError(err)
}
header := &ctx.Response.Header
header.Set(headerKeyContentDisposition, fmt.Sprintf("attachment; filename=%s", bf.FileName))
header.Set(headerKeyContentType, bf.ContentType)
if bf.ContentLength > 0 {
header.Set(headerKeyContentLength, strconv.Itoa(int(bf.ContentLength)))
} else {
header.Set(headerKeyTransferEncoding, "chunked")
}
err = g.write(ctx, stream, method)
return domain.Create().SetError(err)
}
func (getFileDesc) write(ctx *fasthttp.RequestCtx, stream isp.BackendService_RequestStreamClient, method string) error {
for {
msg, err := stream.Recv()
if s.IsEndOfFile(msg) || err == io.EOF {
return nil
}
if err != nil {
logHandlerError(log_code.TypeData.GetFile, method, err)
return err
}
bytes := msg.GetBytesBody()
if bytes == nil {
log.WithMetadata(map[string]interface{}{
log_code.MdTypeData: log_code.TypeData.GetFile,
log_code.MdMethod: method,
}).Errorf(log_code.WarnProxyGrpcHandler, "Method %s. Expected bytes array", method)
return nil
}
_, err = ctx.Write(bytes)
if err != nil {
logHandlerError(log_code.TypeData.GetFile, method, err)
return err
}
}
}
func (getFileDesc) readJsonBody(ctx *fasthttp.RequestCtx) (interface{}, error) {
requestBody := ctx.Request.Body()
var body interface{}
if len(requestBody) == 0 {
requestBody = []byte("{}")
}
switch requestBody[0] {
case '{':
body = make(map[string]interface{})
case '[':
body = make([]interface{}, 0)
default:
return nil, errInvalidJson
}
err := json.Unmarshal(requestBody, &body)
if err != nil {
return nil, err
}
return body, err
}
func (getFileDesc) formError(ctx *fasthttp.RequestCtx, err error, method, msg string, code codes.Code) domain.ProxyResponse {
logHandlerError(log_code.TypeData.GetFile, method, err)
utils.WriteError(ctx, msg, code, nil)
return domain.Create().SetError(err)
}
-50
View File
@@ -1,50 +0,0 @@
package handlers
import (
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/isp"
"github.com/valyala/fasthttp"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
)
var handleJson handleJsonDesc
type handleJsonDesc struct{}
func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse {
body := c.Request.Body()
md, methodName := makeMetadata(&c.Request.Header, method)
ctx := metadata.NewOutgoingContext(context.Background(), md)
grpcSetting := config.GetRemote().(*conf.RemoteConfig).GrpcSetting
ctx, cancel := context.WithTimeout(ctx, grpcSetting.GetSyncInvokeTimeout())
defer cancel()
cli := client.Conn()
msg, invokerErr := cli.Request(
ctx,
&isp.Message{
Body: &isp.Message_BytesBody{BytesBody: body},
},
)
if response, status, err := getResponse(msg, invokerErr); err == nil {
c.SetStatusCode(status)
c.SetContentTypeBytes(utils.JsonContentType)
c.Response.Header.SetContentLength(len(response))
_, _ = c.Write(response)
return domain.Create().SetRequestBody(body).SetResponseBody(c.Response.Body()).SetError(invokerErr)
} else {
logHandlerError(log_code.TypeData.JsonContent, methodName, err)
utils.WriteError(c, errorMsgInternal, codes.Internal, nil)
return domain.Create().SetRequestBody(body).SetResponseBody(c.Response.Body()).SetError(err)
}
}
@@ -1,158 +0,0 @@
package handlers
import (
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/isp"
s "github.com/integration-system/isp-lib/v2/streaming"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
"mime/multipart"
"strings"
)
var sendMultipartData sendMultipartDataDesc
type sendMultipartDataDesc struct{}
func (h sendMultipartDataDesc) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse {
cfg := config.GetRemote().(*conf.RemoteConfig).GrpcSetting
timeout := cfg.GetStreamInvokeTimeout()
stream, cancel, err := openStream(&c.Request.Header, method, timeout, client)
defer func() {
if cancel != nil {
cancel()
}
}()
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
utils.WriteError(c, errorMsgInternal, codes.Internal, nil)
return domain.Create().SetError(err)
}
form, err := c.MultipartForm()
defer func() {
if form != nil {
_ = form.RemoveAll()
}
}()
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
utils.WriteError(c, errorMsgInvalidArg, codes.InvalidArgument, nil)
return domain.Create().SetError(err)
}
resp, proxyResp, ok := h.formResponse(c, stream, form, method)
err = stream.CloseSend()
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
}
if ok {
arrayBody := strings.Join(resp, ",")
_, err = c.WriteString("[" + arrayBody + "]")
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
}
}
return proxyResp
}
func (h sendMultipartDataDesc) formResponse(c *fasthttp.RequestCtx, stream isp.BackendService_RequestStreamClient,
form *multipart.Form, method string) ([]string, domain.ProxyResponse, bool) {
formData := make(map[string]interface{}, len(form.Value))
for k, v := range form.Value {
if len(v) > 0 {
formData[k] = v[0]
}
}
var (
resp = make([]string, 0)
buffer = make([]byte, config.GetRemote().(*conf.RemoteConfig).GrpcSetting.GetTransferFileBufferSize())
proxyResp domain.ProxyResponse
ok = true
eof bool
err error
)
for formDataName, files := range form.File {
if len(files) == 0 {
continue
}
file := files[0]
fileName := file.Filename
contentType := file.Header.Get(headerKeyContentType)
contentLength := file.Size
bf := s.BeginFile{
FileName: fileName,
FormDataName: formDataName,
ContentType: contentType,
ContentLength: contentLength,
FormData: formData,
}
err = stream.Send(bf.ToMessage())
ok, eof, proxyResp = checkError(err, c, method)
if !ok || eof {
break
}
f, err := file.Open()
ok, eof, proxyResp = checkError(err, c, method)
if !ok || eof {
break
}
ok, eof, proxyResp = h.transferFile(f, stream, buffer, c, method)
if !ok || eof {
break
}
msg, invokeErr := stream.Recv()
ok, eof, proxyResp = checkError(invokeErr, c, method)
if !ok || eof {
break
}
response, _, err := getResponse(msg, invokeErr)
if err != nil {
ok = false
break
}
resp = append(resp, string(response))
}
return resp, proxyResp, ok
}
func (sendMultipartDataDesc) transferFile(f multipart.File, stream isp.BackendService_RequestStreamClient,
buffer []byte, ctx *fasthttp.RequestCtx, method string) (bool, bool, domain.ProxyResponse) {
var (
ok = true
eof bool
proxyResp domain.ProxyResponse
)
for {
n, err := f.Read(buffer)
if n > 0 {
err = stream.Send(&isp.Message{Body: &isp.Message_BytesBody{BytesBody: buffer[:n]}})
ok, eof, proxyResp = checkError(err, ctx, method)
if !ok || eof {
break
}
}
if err != nil {
ok, eof, proxyResp = checkError(err, ctx, method)
if ok && eof {
err = stream.Send(s.FileEnd())
ok, eof, proxyResp = checkError(err, ctx, method)
}
break
}
}
return ok, eof, proxyResp
}
-38
View File
@@ -1,38 +0,0 @@
package health_check
import (
"github.com/integration-system/isp-lib/v2/structure"
"github.com/valyala/fasthttp"
"isp-gate-service/domain"
)
type healthCheckProxy struct {
skipAuth bool
skipExistCheck bool
}
func NewProxy(skipAuth, skipExistCheck bool) *healthCheckProxy {
return &healthCheckProxy{skipAuth: skipAuth, skipExistCheck: skipExistCheck}
}
func (p *healthCheckProxy) Consumer(addressList []structure.AddressConfiguration) bool {
return true
}
func (p *healthCheckProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
ctx.Response.SetBody(ctx.Request.Body())
ctx.Request.SetRequestURI(path)
return domain.Create()
}
func (p *healthCheckProxy) SkipAuth() bool {
return p.skipAuth
}
func (p *healthCheckProxy) SkipExistCheck() bool {
return p.skipExistCheck
}
func (p *healthCheckProxy) Close() {
}
+82
View File
@@ -0,0 +1,82 @@
package proxy
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
"time"
"github.com/integration-system/isp-kit/grpc"
"github.com/integration-system/isp-kit/requestid"
"github.com/pkg/errors"
"golang.org/x/net/context"
"isp-gate-service/httperrors"
"isp-gate-service/request"
)
type HttpHostManager interface {
Next() (string, error)
}
type Http struct {
hostManager HttpHostManager
skipAuth bool
timeout time.Duration
}
func NewHttp(hostManager HttpHostManager, skipAuth bool, timeout time.Duration) Http {
return Http{
hostManager: hostManager,
skipAuth: skipAuth,
timeout: timeout,
}
}
func (p Http) Handle(ctx *request.Context) error {
host, err := p.hostManager.Next()
if err != nil {
return errors.WithMessage(err, "http: next host")
}
rawUrl := fmt.Sprintf("http://%s", host) // secure HTTP links are reset connection
target, err := url.Parse(rawUrl)
if err != nil {
return errors.WithMessage(err, "http: parse url")
}
request := ctx.Request()
request.URL.Path = ctx.Endpoint()
request.Header.Set(grpc.RequestIdHeader, requestid.FromContext(ctx.Context()))
if !p.skipAuth {
authData, err := ctx.GetAuthData()
if err != nil {
return errors.WithMessage(err, "http: get auth data")
}
request.Header.Set(grpc.SystemIdHeader, strconv.Itoa(authData.SystemId))
request.Header.Set(grpc.DomainIdHeader, strconv.Itoa(authData.DomainId))
request.Header.Set(grpc.ServiceIdHeader, strconv.Itoa(authData.ServiceId))
request.Header.Set(grpc.ApplicationIdHeader, strconv.Itoa(authData.ApplicationId))
if ctx.IsAdminAuthenticated() {
request.Header.Set(adminAuthHeader, ctx.AdminToken())
}
}
reverseProxy := httputil.NewSingleHostReverseProxy(target)
var resultError error
reverseProxy.ErrorHandler = func(writer http.ResponseWriter, request *http.Request, err error) {
resultError = httperrors.New(
http.StatusServiceUnavailable,
"upstream is not available",
errors.WithMessagef(err, "http proxy to %s", host),
)
}
context, cancel := context.WithTimeout(request.Context(), p.timeout)
defer cancel()
request = request.WithContext(context)
reverseProxy.ServeHTTP(ctx.ResponseWriter(), request)
return resultError
}
-86
View File
@@ -1,86 +0,0 @@
package http
import (
"errors"
"net"
"strings"
"github.com/integration-system/isp-lib/v2/structure"
log "github.com/integration-system/isp-log"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
)
var (
errNotInitialized = errors.New("http proxy not initialized")
)
type httpProxy struct {
client *fasthttp.HostClient
skipAuth bool
skipExistCheck bool
}
func NewProxy(skipAuth, skipExistCheck bool) *httpProxy {
return &httpProxy{client: nil, skipAuth: skipAuth, skipExistCheck: skipExistCheck}
}
func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool {
if len(addressList) == 0 {
p.client = nil
return true
}
addresses := make([]string, len(addressList))
for key, addr := range addressList {
addresses[key] = addr.GetAddress()
}
p.client = &fasthttp.HostClient{
Addr: strings.Join(addresses, `,`),
}
return true
}
func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
client := p.client
if client == nil {
log.Error(log_code.ErrorClientHttp, errNotInitialized)
utils.WriteError(ctx, errNotInitialized.Error(), codes.Internal, nil)
return domain.Create().
SetRequestBody(ctx.Request.Body()).
SetResponseBody(ctx.Response.Body()).
SetError(errNotInitialized)
}
req := &ctx.Request
res := &ctx.Response
req.URI().SetPath("/" + path)
if addr, _, err := net.SplitHostPort(ctx.RemoteAddr().String()); err == nil {
req.Header.Add("X-Forwarded-For", addr)
}
err := client.Do(req, res)
if err != nil {
log.Error(log_code.ErrorClientHttp, err)
}
return domain.Create().
SetRequestBody(ctx.Request.Body()).
SetResponseBody(ctx.Response.Body()).
SetError(err)
}
func (p *httpProxy) SkipAuth() bool {
return p.skipAuth
}
func (p *httpProxy) SkipExistCheck() bool {
return p.skipExistCheck
}
func (p *httpProxy) Close() {
p.client = nil
}
-121
View File
@@ -1,121 +0,0 @@
package proxy
import (
"isp-gate-service/conf"
"sort"
"strings"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"isp-gate-service/domain"
"isp-gate-service/proxy/grpc"
"isp-gate-service/proxy/health_check"
"isp-gate-service/proxy/http"
"isp-gate-service/proxy/websocket"
)
var (
store = make([]storeItem, 0)
)
const (
httpProtocol = "http"
websocketProtocol = "websocket"
grpcProtocol = "grpc"
healthCheckProtocol = "healthсheck"
)
type (
Proxy interface {
ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse
Consumer([]structure.AddressConfiguration) bool
SkipAuth() bool
SkipExistCheck() bool
Close()
}
storeItem struct {
pathPrefix string
proxy Proxy
}
)
func InitProxies(locations []conf.Location) (map[string]func([]structure.AddressConfiguration) bool, error) {
locationsByTargetModule := conf.GetLocationsByTargetModule(locations)
requiredModules := make(map[string]func([]structure.AddressConfiguration) bool)
for targetModule, locations := range locationsByTargetModule {
consumerStorage := make([]func([]structure.AddressConfiguration) bool, len(locations))
for i, location := range locations {
if location.PathPrefix[0] != '/' {
return nil, errors.Errorf("path must begin with '/' in path '%s'", location.PathPrefix)
}
p, err := makeProxy(location.Protocol, location.SkipAuth, location.SkipExistCheck)
if err != nil {
return nil, err
}
store = append(store, storeItem{
pathPrefix: location.PathPrefix,
proxy: p,
})
consumerStorage[i] = p.Consumer
}
requiredModules[targetModule] = aggregateConsumers(consumerStorage...)
}
sort.Slice(store, func(i, j int) bool {
return store[i].pathPrefix > store[j].pathPrefix
})
return requiredModules, nil
}
func makeProxy(protocol string, skipAuth, skipExistCheck bool) (Proxy, error) {
var proxy Proxy
switch protocol {
case httpProtocol:
proxy = http.NewProxy(skipAuth, skipExistCheck)
case grpcProtocol:
proxy = grpc.NewProxy(skipAuth, skipExistCheck)
case healthCheckProtocol:
proxy = health_check.NewProxy(skipAuth, skipExistCheck)
case websocketProtocol:
proxy = websocket.NewProxy(skipAuth, skipExistCheck)
default:
return nil, errors.Errorf("unknown protocol '%s'", protocol)
}
return proxy, nil
}
func Find(path string) (Proxy, string) {
for _, item := range store {
if strings.HasPrefix(path, item.pathPrefix) {
return item.proxy, getPathWithoutPrefix(path, item.pathPrefix)
}
}
return nil, ""
}
func Close() {
for _, p := range store {
p.proxy.Close()
}
}
func getPathWithoutPrefix(path, prefix string) string {
s := strings.TrimPrefix(path, prefix)
if len(s) > 0 && s[0] == '/' {
return s[1:]
}
return s
}
func aggregateConsumers(consumers ...func([]structure.AddressConfiguration) bool) func([]structure.AddressConfiguration) bool {
return func(list []structure.AddressConfiguration) bool {
for _, consumer := range consumers {
consumer(list)
}
return true
}
}
-34
View File
@@ -1,34 +0,0 @@
package proxy
import (
"testing"
)
func Test_getPathWithoutPrefix(t *testing.T) {
type args struct {
path string
prefix string
}
tests := []struct {
name string
args args
want string
}{
{name: "#1", args: args{
path: "/api/some/11/22",
prefix: "/api/some",
}, want: "11/22"},
{name: "#2", args: args{
path: "/api/service/group/method",
prefix: "/api",
}, want: "service/group/method"},
}
for _, test := range tests {
tt := test
t.Run(tt.name, func(t *testing.T) {
if got := getPathWithoutPrefix(tt.args.path, tt.args.prefix); got != tt.want {
t.Errorf("getPathWithoutPrefix() = %v, want %v", got, tt.want)
}
})
}
}
-28
View File
@@ -1,28 +0,0 @@
package websocket
import (
"github.com/integration-system/isp-lib/v2/structure"
"sync"
)
type RoundRobinAddrs struct {
mu *sync.Mutex
addrs []structure.AddressConfiguration
index int
}
func (u *RoundRobinAddrs) Get() structure.AddressConfiguration {
u.mu.Lock()
u.index = (u.index + 1) % len(u.addrs)
addr := u.addrs[u.index]
u.mu.Unlock()
return addr
}
func NewRoundRobinAddrs(addrs []structure.AddressConfiguration) *RoundRobinAddrs {
return &RoundRobinAddrs{
addrs: addrs,
index: -1,
mu: new(sync.Mutex),
}
}
-174
View File
@@ -1,174 +0,0 @@
package websocket
import (
"errors"
"io"
"net"
"net/http"
"net/http/cookiejar"
"net/url"
"sync"
"github.com/fasthttp/websocket"
"github.com/integration-system/isp-lib/v2/structure"
log "github.com/integration-system/isp-log"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
)
const (
writeBufSize = 4 << 10
readBufSize = 4 << 10
)
var (
errNoAddresses = errors.New("no available address")
pool = &sync.Pool{New: func() interface{} {
buf := make([]byte, readBufSize)
return &buf
}}
)
// used to filter client request headers
//
var forbiddenDuplicateHeaders = map[string]struct{}{
"Upgrade": {},
"Connection": {},
"Sec-Websocket-Key": {},
"Sec-Websocket-Version": {},
"Sec-Websocket-Extensions": {},
"Sec-Websocket-Protocol": {},
}
var upgrader = websocket.FastHTTPUpgrader{
ReadBufferSize: readBufSize,
WriteBufferSize: writeBufSize,
CheckOrigin: func(ctx *fasthttp.RequestCtx) bool {
return true
},
}
type websocketProxy struct {
addrs *RoundRobinAddrs
skipAuth bool
skipExistCheck bool
}
func NewProxy(skipAuth, skipExistCheck bool) *websocketProxy {
return &websocketProxy{addrs: nil, skipAuth: skipAuth, skipExistCheck: skipExistCheck}
}
func (p *websocketProxy) Consumer(addressList []structure.AddressConfiguration) bool {
if len(addressList) == 0 {
p.addrs = nil
} else {
p.addrs = NewRoundRobinAddrs(addressList)
}
return true
}
func (p *websocketProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
addrs := p.addrs
if addrs == nil {
msg := errNoAddresses
log.Error(log_code.ErrorWebsocketProxy, msg)
utils.WriteError(ctx, msg.Error(), codes.Internal, nil)
return domain.Create().
SetRequestBody(ctx.Request.Body()).
SetResponseBody(ctx.Response.Body()).
SetError(errNoAddresses)
}
reqHeaders := fasthttp.RequestHeader{}
ctx.Request.Header.CopyTo(&reqHeaders)
reqHost := string(ctx.Request.URI().Host())
reqScheme := string(ctx.Request.URI().Scheme())
if addr, _, err := net.SplitHostPort(ctx.RemoteAddr().String()); err == nil {
reqHeaders.Add("X-Forwarded-For", addr)
}
err := upgrader.Upgrade(ctx, func(incomingConn *websocket.Conn) {
outgoingDialer := websocket.Dialer{
ReadBufferSize: readBufSize,
WriteBufferSize: writeBufSize,
NetDial: net.Dial,
}
addr := addrs.Get()
uri := ctx.Request.URI()
uri.SetSchemeBytes([]byte("ws"))
uri.SetHost(addr.GetAddress())
uri.SetPath("/" + path)
header := http.Header{}
reqHeaders.VisitAll(func(key, value []byte) {
keyStr := string(key)
if _, forbidden := forbiddenDuplicateHeaders[keyStr]; !forbidden {
header.Add(keyStr, string(value))
}
})
cookie := make([]*http.Cookie, 0)
reqHeaders.VisitAllCookie(func(key, value []byte) {
cookie = append(cookie, &http.Cookie{Domain: reqHost, Name: string(key), Value: string(value)})
})
cookies := &cookiejar.Jar{}
cookies.SetCookies(&url.URL{Host: reqHost, Scheme: reqScheme}, cookie)
outgoingDialer.Jar = cookies
//nolint
outgoingConn, _, err := outgoingDialer.Dial(uri.String(), header)
if err == nil {
go func() {
_ = p.proxyConn(outgoingConn, incomingConn)
}()
_ = p.proxyConn(incomingConn, outgoingConn)
} else {
log.Errorf(log_code.ErrorWebsocketProxy, "unable to connect to service %s: %v", uri.String(), err)
_ = incomingConn.Close()
_ = outgoingConn.Close()
}
})
return domain.Create().SetError(err)
}
func (p *websocketProxy) SkipAuth() bool {
return p.skipAuth
}
func (p *websocketProxy) SkipExistCheck() bool {
return p.skipExistCheck
}
func (p *websocketProxy) Close() {
}
func (p *websocketProxy) proxyConn(from, to *websocket.Conn) error {
buf := pool.Get().(*[]byte)
defer func() {
_ = from.Close()
_ = to.Close()
pool.Put(buf)
}()
for {
msgType, reader, err := from.NextReader()
if err != nil {
return err
}
writer, err := to.NextWriter(msgType)
if err != nil {
return err
}
if _, err := io.CopyBuffer(writer, reader, *buf); err != nil {
return err
}
if err := writer.Close(); err != nil {
return err
}
}
}
-16
View File
@@ -1,16 +0,0 @@
package redis
import (
rd "github.com/integration-system/isp-lib/v2/redis"
log "github.com/integration-system/isp-log"
"isp-gate-service/log_code"
)
var (
Client = rd.NewRxClient(
rd.WithInitHandler(func(c *rd.Client, err error) {
if err != nil {
log.Fatal(log_code.ErrorClientRedis, err)
}
}))
)
+49
View File
@@ -0,0 +1,49 @@
package repository
import (
"context"
"time"
"github.com/integration-system/isp-kit/json"
"github.com/pkg/errors"
"isp-gate-service/cache"
"isp-gate-service/domain"
)
type AuthenticationCache struct {
cache *cache.Cache
duration time.Duration
}
func NewAuthenticationCache(duration time.Duration) AuthenticationCache {
return AuthenticationCache{
duration: duration,
cache: cache.New(),
}
}
func (r AuthenticationCache) Get(ctx context.Context, token string) (*domain.AuthData, error) {
data, ok := r.cache.Get(token)
if !ok {
return nil, domain.ErrAuthenticationCacheMiss
}
result := domain.AuthData{}
err := json.Unmarshal(data, &result)
if err != nil {
return nil, errors.WithMessage(err, "json unmarshal auth data")
}
return &result, nil
}
func (r AuthenticationCache) Set(ctx context.Context, token string, data domain.AuthData) error {
value, err := json.Marshal(data)
if err != nil {
return errors.WithMessage(err, "json marshal auth data")
}
r.cache.Set(token, value, r.duration)
return nil
}
+37
View File
@@ -0,0 +1,37 @@
package repository
import (
"context"
"fmt"
"time"
"isp-gate-service/cache"
)
type AuthorizationCache struct {
duration time.Duration
cache *cache.Cache
}
func NewAuthorizationCache(duration time.Duration) *AuthorizationCache {
return &AuthorizationCache{
duration: duration,
cache: cache.New(),
}
}
func (r AuthorizationCache) Get(ctx context.Context, applicationId int, endpoint string) (bool, error) {
key := r.key(applicationId, endpoint)
_, ok := r.cache.Get(key)
return ok, nil
}
func (r AuthorizationCache) SetAuthorized(ctx context.Context, applicationId int, endpoint string) error {
key := r.key(applicationId, endpoint)
r.cache.Set(key, nil, r.duration)
return nil
}
func (r AuthorizationCache) key(applicationId int, endpoint string) string {
return fmt.Sprintf("%d:%s", applicationId, endpoint)
}
-20
View File
@@ -1,20 +0,0 @@
package repository
import (
"github.com/integration-system/isp-lib/v2/database"
log "github.com/integration-system/isp-log"
"isp-gate-service/log_code"
)
var (
DbClient = database.NewRxDbClient(
database.WithSchemaEnsuring(),
database.WithSchemaAutoInjecting(),
database.WithMigrationsEnsuring(),
database.WithInitializingErrorHandler(func(err *database.ErrorEvent) {
log.Error(log_code.ErrorClientDatabase, err)
}))
SnapshotRep SnapshotRepository = snapshotRepository{rxClient: DbClient}
RequestsRep RequestsRepository = requestsRepository{rxClient: DbClient}
)
+42
View File
@@ -0,0 +1,42 @@
package repository
import (
"context"
"fmt"
"time"
"github.com/go-redis/redis/v8"
"github.com/pkg/errors"
)
type DailyLimit struct {
cli redis.UniversalClient
}
func NewDailyLimit(cli redis.UniversalClient) DailyLimit {
return DailyLimit{
cli: cli,
}
}
func (r DailyLimit) Increment(ctx context.Context, applicationId int, today time.Time) (int64, error) {
key := r.key(applicationId, today)
value, err := r.cli.Incr(ctx, key).Result()
if err != nil {
return 0, errors.WithMessage(err, "incr")
}
if value == 1 {
err := r.cli.ExpireNX(ctx, key, 24*time.Hour).Err() //nolint:gomnd
if err != nil {
return 0, errors.WithMessage(err, "expire nx")
}
}
return value, nil
}
func (r DailyLimit) key(applicationId int, today time.Time) string {
y, m, d := today.Date()
return fmt.Sprintf("daily_limit:%d:%d-%d-%d", applicationId, y, m, d)
}
-30
View File
@@ -1,30 +0,0 @@
package repository
import (
"github.com/go-pg/pg/v9/orm"
"github.com/integration-system/isp-lib/v2/database"
"isp-gate-service/entity"
)
type (
RequestsRepository interface {
Insert([]entity.Request) error
}
requestsRepository struct {
DB orm.DB
rxClient *database.RxDbClient
}
)
func (r requestsRepository) Insert(model []entity.Request) error {
_, err := r.getDb().Model(&model).Insert()
return err
}
func (r requestsRepository) getDb() orm.DB {
if r.DB != nil {
return r.DB
}
return r.rxClient.Unsafe()
}
-50
View File
@@ -1,50 +0,0 @@
package repository
import (
"github.com/go-pg/pg/v9"
"github.com/integration-system/isp-lib/v2/database"
"isp-gate-service/entity"
"github.com/go-pg/pg/v9/orm"
)
type (
SnapshotRepository interface {
GetByApplication(int32) (*entity.Snapshot, error)
Update([]entity.Snapshot) error
}
snapshotRepository struct {
DB orm.DB
rxClient *database.RxDbClient
}
)
func (r snapshotRepository) Update(list []entity.Snapshot) error {
_, err := r.getDb().Model(&list).OnConflict("(app_id) DO UPDATE").
Set("version = EXCLUDED.version").
Set("app_id = EXCLUDED.app_id").
Set("limit_state = EXCLUDED.limit_state").
Where("snapshot.version < EXCLUDED.version").
Insert()
return err
}
func (r snapshotRepository) GetByApplication(appId int32) (*entity.Snapshot, error) {
model := new(entity.Snapshot)
if err := r.getDb().Model(model).Where("app_id = ?", appId).Select(); err != nil {
if err == pg.ErrNoRows {
return nil, nil
}
return nil, err
} else {
return model, nil
}
}
func (r snapshotRepository) getDb() orm.DB {
if r.DB != nil {
return r.DB
}
return r.rxClient.Unsafe()
}
+48
View File
@@ -0,0 +1,48 @@
package repository
import (
"context"
"github.com/integration-system/isp-kit/grpc/client"
"github.com/pkg/errors"
"isp-gate-service/domain"
)
const (
authenticate = "system/secure/authenticate"
authorize = "system/secure/authorize"
)
type System struct {
cli *client.Client
}
func NewSystem(cli *client.Client) System {
return System{
cli: cli,
}
}
func (r System) Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) {
resp := domain.AuthenticateResponse{}
err := r.cli.Invoke(authenticate).
JsonRequestBody(domain.AuthenticateRequest{Token: token}).
ReadJsonResponse(&resp).
Do(ctx)
if err != nil {
return nil, errors.WithMessagef(err, "grpc client invoke: %s", authenticate)
}
return &resp, nil
}
func (r System) Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error) {
resp := domain.AuthorizeResponse{}
err := r.cli.Invoke(authorize).
JsonRequestBody(domain.AuthorizeRequest{ApplicationId: applicationId, Endpoint: endpoint}).
ReadJsonResponse(&resp).
Do(ctx)
if err != nil {
return false, errors.WithMessagef(err, "grpc client invoke: %s", authorize)
}
return resp.Authorized, nil
}
+37
View File
@@ -0,0 +1,37 @@
package repository
import (
"context"
"fmt"
"github.com/go-redis/redis/v8"
"github.com/go-redis/redis_rate/v9"
"github.com/pkg/errors"
"isp-gate-service/domain"
)
type Throttling struct {
cli *redis_rate.Limiter
}
func NewThrottling(cli redis.UniversalClient) Throttling {
return Throttling{
cli: redis_rate.NewLimiter(cli),
}
}
func (r Throttling) IsAllowRequestPerSecond(ctx context.Context, applicationId int, rate int) (*domain.RateLimitResult, error) {
result, err := r.cli.Allow(ctx, r.key(applicationId), redis_rate.PerSecond(rate))
if err != nil {
return nil, errors.WithMessage(err, "redis_rate/Allow")
}
return &domain.RateLimitResult{
Allow: result.Allowed > 0,
Remaining: result.Remaining,
RetryAfter: result.RetryAfter,
}, nil
}
func (r Throttling) key(applicationId int) string {
return fmt.Sprintf("throttling:%d", applicationId)
}
+75
View File
@@ -0,0 +1,75 @@
package unused
import (
"context"
"time"
"github.com/go-redis/redis/v8"
"github.com/integration-system/isp-kit/json"
"github.com/pkg/errors"
"isp-gate-service/domain"
)
type RedisAuthCache struct {
cli redis.UniversalClient
duration time.Duration
db int
}
func NewRedisAuthCache(cli redis.UniversalClient, duration time.Duration, db int) RedisAuthCache {
return RedisAuthCache{
cli: cli,
duration: duration,
db: db,
}
}
func (r RedisAuthCache) Get(ctx context.Context, token string) (*domain.AuthData, error) {
results, err := r.cli.Pipelined(ctx, func(p redis.Pipeliner) error {
p.Select(ctx, r.db)
p.Get(ctx, token)
return nil
})
if err != nil && err != redis.Nil {
return nil, errors.WithMessage(err, "pipelined")
}
data, err := results[1].(*redis.StringCmd).Result()
if errors.Is(err, redis.Nil) {
return nil, domain.ErrAuthenticationCacheMiss
}
if err != nil {
return nil, errors.WithMessage(err, "get")
}
result := domain.AuthData{}
err = json.Unmarshal([]byte(data), &result)
if err != nil {
return nil, errors.WithMessage(err, "json unmarshal auth data")
}
return &result, nil
}
func (r RedisAuthCache) Set(ctx context.Context, token string, data domain.AuthData) error {
value, err := json.Marshal(data)
if err != nil {
return errors.WithMessage(err, "json marshal auth data")
}
results, err := r.cli.Pipelined(ctx, func(p redis.Pipeliner) error {
p.Select(ctx, r.db)
p.SetEX(ctx, token, string(value), r.duration)
return nil
})
if err != nil {
return errors.WithMessage(err, "pipelined")
}
err = results[1].Err()
if err != nil {
return errors.WithMessage(err, "set ex")
}
return nil
}
+66
View File
@@ -0,0 +1,66 @@
package unused
import (
"context"
"fmt"
"time"
"github.com/go-redis/redis/v8"
"github.com/pkg/errors"
)
type RedisAuthzCache struct {
cli redis.UniversalClient
duration time.Duration
db int
}
func NewRedisAuthzCache(cli redis.UniversalClient, duration time.Duration, db int) *RedisAuthzCache {
return &RedisAuthzCache{
cli: cli,
duration: duration,
db: db,
}
}
func (r RedisAuthzCache) Get(ctx context.Context, applicationId int, endpoint string) (bool, error) {
result, err := r.cli.Pipelined(ctx, func(p redis.Pipeliner) error {
p.Select(ctx, r.db)
p.Get(ctx, r.key(applicationId, endpoint))
return nil
})
if err != nil && err != redis.Nil {
return false, errors.WithMessage(err, "pipelined")
}
_, err = result[1].(*redis.StringCmd).Result()
if errors.Is(err, redis.Nil) {
return false, nil
}
if err != nil {
return false, errors.WithMessage(err, "get")
}
return true, nil
}
func (r RedisAuthzCache) SetAuthorized(ctx context.Context, applicationId int, endpoint string) error {
result, err := r.cli.Pipelined(ctx, func(p redis.Pipeliner) error {
p.Select(ctx, r.db)
p.SetEX(ctx, r.key(applicationId, endpoint), "authorized", r.duration)
return nil
})
if err != nil {
return errors.WithMessage(err, "pipelined")
}
err = result[1].Err()
if err != nil {
return errors.WithMessage(err, "set ex")
}
return nil
}
func (r RedisAuthzCache) key(applicationId int, endpoint string) string {
return fmt.Sprintf("%d:%s", applicationId, endpoint)
}
+95
View File
@@ -0,0 +1,95 @@
package request
import (
"context"
"net/http"
"github.com/pkg/errors"
)
var (
ErrNotAuthenticated = errors.New("not authenticated")
)
type AuthData struct {
SystemId int
DomainId int
ServiceId int
ApplicationId int
}
type Context struct {
request *http.Request
responseWriter http.ResponseWriter
endpoint string
authenticated bool
authData *AuthData
adminAuthenticated bool
adminId int
adminToken string
}
func NewContext(request *http.Request, response http.ResponseWriter, endpoint string) *Context {
return &Context{
request: request,
responseWriter: response,
endpoint: endpoint,
}
}
func (c *Context) Request() *http.Request {
return c.request
}
func (c *Context) ResponseWriter() http.ResponseWriter {
return c.responseWriter
}
func (c *Context) SetResponseWriter(writer http.ResponseWriter) {
c.responseWriter = writer
}
func (c *Context) Endpoint() string {
return c.endpoint
}
func (c *Context) Authenticate(authData AuthData) {
c.authenticated = true
c.authData = &authData
}
func (c *Context) GetAuthData() (AuthData, error) {
if !c.authenticated {
return AuthData{}, ErrNotAuthenticated
}
return *c.authData, nil
}
func (c *Context) IsAdminAuthenticated() bool {
return c.adminAuthenticated
}
func (c *Context) AdminId() int {
return c.adminId
}
func (c *Context) AdminToken() string {
return c.adminToken
}
func (c *Context) AuthenticateAdmin(adminId int, adminToken string) {
c.adminAuthenticated = true
c.adminId = adminId
c.adminToken = adminToken
}
func (c *Context) Context() context.Context {
return c.request.Context()
}
func (c *Context) SetContext(ctx context.Context) {
c.request = c.request.WithContext(ctx)
}
+36
View File
@@ -0,0 +1,36 @@
package routes
import (
"context"
"github.com/integration-system/isp-kit/cluster"
)
type Routes struct {
innerMethods map[string]bool
}
func NewRoutes() *Routes {
return &Routes{
innerMethods: make(map[string]bool),
}
}
func (s *Routes) ReceiveRoutes(ctx context.Context, routes cluster.RoutingConfig) error {
newInnerMethods := make(map[string]bool)
for _, backend := range routes {
for _, v := range backend.Endpoints {
if v.Inner {
newInnerMethods[v.Path] = true
}
}
}
s.innerMethods = newInnerMethods
return nil
}
func (s *Routes) IsInnerMethod(path string) bool {
return s.innerMethods[path]
}
-35
View File
@@ -1,35 +0,0 @@
package routing
import (
"github.com/integration-system/isp-lib/v2/structure"
)
var (
InnerMethods = make(map[string]bool)
AllMethods = make(map[string]bool)
AuthUserMethods = make(map[string]bool)
)
func InitRoutes(configs structure.RoutingConfig) {
newAddressMap := make(map[string]bool)
newInnerAddressMap := make(map[string]bool)
newAuthUserAddressMap := make(map[string]bool)
for i := range configs {
backend := &configs[i]
if backend.Address.IP == "" || backend.Address.Port == "" || len(backend.Endpoints) == 0 {
continue
}
for _, v := range backend.Endpoints {
newAddressMap[v.Path] = true
if v.Inner {
newInnerAddressMap[v.Path] = true
}
if v.UserAuthRequired {
newAuthUserAddressMap[v.Path] = true
}
}
}
AllMethods = newAddressMap
InnerMethods = newInnerAddressMap
AuthUserMethods = newAuthUserAddressMap
}
-69
View File
@@ -1,69 +0,0 @@
package server
import (
"sync"
"time"
"github.com/integration-system/isp-kit/log"
"github.com/integration-system/isp-lib/v2/config"
logrus "github.com/integration-system/isp-log"
"github.com/valyala/fasthttp"
"isp-gate-service/conf"
"isp-gate-service/handler"
"isp-gate-service/log_code"
)
const defaultTimeout = 60 * time.Second
var Http = &httpSrv{mx: sync.Mutex{}}
type httpSrv struct {
working bool
srv *fasthttp.Server
mx sync.Mutex
logger log.Logger
}
func (s *httpSrv) Init(isDifferentSetting bool, bodySize int64, logger log.Logger) {
s.logger = logger
if s.working {
if isDifferentSetting {
s.run(bodySize)
}
} else {
s.run(bodySize)
}
}
func (s *httpSrv) run(maxRequestBodySize int64) {
s.mx.Lock()
s.working = true
if s.srv != nil {
if err := s.srv.Shutdown(); err != nil {
logrus.Warn(log_code.WarnHttpServerShutdown, err)
}
}
localConfig := config.Get().(*conf.Configuration)
restAddress := localConfig.HttpInnerAddress.GetAddress()
s.srv = &fasthttp.Server{
Handler: handler.New(s.logger).CompleteRequest,
WriteTimeout: defaultTimeout,
ReadTimeout: defaultTimeout,
MaxRequestBodySize: int(maxRequestBodySize),
}
go func() {
if err := s.srv.ListenAndServe(restAddress); err != nil {
logrus.Error(log_code.ErrorHttpServerListen, err)
}
}()
s.mx.Unlock()
}
func (s *httpSrv) Close() {
if s.srv != nil {
s.working = false
if err := s.srv.Shutdown(); err != nil {
logrus.Warn(log_code.WarnHttpServerShutdown, err)
}
}
}
+54
View File
@@ -0,0 +1,54 @@
package service
import (
"github.com/golang-jwt/jwt/v4"
"github.com/pkg/errors"
)
type adminClaims struct {
*jwt.RegisteredClaims
Id int64
}
type Admin struct {
secret string
}
func NewAdmin(secret string) Admin {
return Admin{
secret: secret,
}
}
func (s Admin) Authenticate(token string) (int, error) {
parsed, err := s.parseToken(token, &adminClaims{RegisteredClaims: &jwt.RegisteredClaims{}})
if err != nil {
return 0, errors.WithMessage(err, "parse token")
}
claims, ok := parsed.Claims.(*adminClaims)
if !ok {
return 0, errors.New("invalid token")
}
return int(claims.Id), nil
}
func (s Admin) parseToken(token string, claims jwt.Claims) (*jwt.Token, error) {
parsed, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
_, ok := token.Method.(*jwt.SigningMethodHMAC)
if !ok {
return nil, errors.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(s.secret), nil
})
if err != nil {
return nil, errors.WithMessage(err, "jwt parse with claims")
}
if !parsed.Valid {
return nil, errors.New("invalid token")
}
return parsed, nil
}
+55
View File
@@ -0,0 +1,55 @@
package service
import (
"context"
"github.com/pkg/errors"
"isp-gate-service/domain"
)
type AuthenticationCache interface {
Get(ctx context.Context, token string) (*domain.AuthData, error)
Set(ctx context.Context, token string, data domain.AuthData) error
}
type AuthenticationRepo interface {
Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error)
}
type Auth struct {
cache AuthenticationCache
repo AuthenticationRepo
}
func NewAuthentication(cache AuthenticationCache, repo AuthenticationRepo) Auth {
return Auth{
cache: cache,
repo: repo,
}
}
func (s Auth) Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) {
authData, err := s.cache.Get(ctx, token)
if errors.Is(err, domain.ErrAuthenticationCacheMiss) {
resp, err := s.repo.Authenticate(ctx, token)
if err != nil {
return nil, errors.WithMessage(err, "auth repo authenticate")
}
if !resp.Authenticated {
return resp, nil
}
err = s.cache.Set(ctx, token, *resp.AuthData)
if err != nil {
return nil, errors.WithMessage(err, "auth cache set")
}
return resp, nil
}
if err != nil {
return nil, errors.WithMessage(err, "auth cache get")
}
return &domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: authData,
}, nil
}
+51
View File
@@ -0,0 +1,51 @@
package service
import (
"context"
"github.com/pkg/errors"
)
type AuthorizationCache interface {
Get(ctx context.Context, applicationId int, endpoint string) (bool, error)
SetAuthorized(ctx context.Context, applicationId int, endpoint string) error
}
type AuthorizationRepo interface {
Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error)
}
type Authorization struct {
cache AuthorizationCache
repo AuthorizationRepo
}
func NewAuthorization(cache AuthorizationCache, repo AuthorizationRepo) Authorization {
return Authorization{
cache: cache,
repo: repo,
}
}
func (s Authorization) Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error) {
ok, err := s.cache.Get(ctx, applicationId, endpoint)
if err != nil {
return false, errors.WithMessage(err, "authz cache get")
}
if ok {
return ok, nil
}
ok, err = s.repo.Authorize(ctx, applicationId, endpoint)
if err != nil {
return false, errors.WithMessagef(err, "authz repo authorize")
}
if ok {
err = s.cache.SetAuthorized(ctx, applicationId, endpoint)
if err != nil {
return false, errors.WithMessagef(err, "authz cache set")
}
}
return ok, nil
}
+43
View File
@@ -0,0 +1,43 @@
package service
import (
"context"
"time"
"github.com/pkg/errors"
"isp-gate-service/conf"
)
type DailyLimitRepo interface {
Increment(ctx context.Context, applicationId int, today time.Time) (int64, error)
}
type DailyLimit struct {
repo DailyLimitRepo
limits map[int]int64
}
func NewDailyLimit(repo DailyLimitRepo, configs []conf.DailyLimit) DailyLimit {
limits := make(map[int]int64)
for _, config := range configs {
limits[config.ApplicationId] = config.RequestsPerDay
}
return DailyLimit{
repo: repo,
limits: limits,
}
}
func (s DailyLimit) IncrementAndCheck(ctx context.Context, applicationId int) (bool, error) {
max, ok := s.limits[applicationId]
if !ok {
return true, nil
}
newValue, err := s.repo.Increment(ctx, applicationId, time.Now())
if err != nil {
return false, errors.WithMessage(err, "increment")
}
return newValue <= max, nil
}
-33
View File
@@ -1,33 +0,0 @@
package matcher
import "sync"
type atLeastOneMatcher struct {
cache map[string]bool
lock sync.RWMutex
rm runtimeMatcher
}
func (mm *atLeastOneMatcher) Match(method string) bool {
if len(mm.rm.patterns) == 0 {
return false
}
mm.lock.RLock()
matched, ok := mm.cache[method]
mm.lock.RUnlock()
if ok {
return matched
}
mm.lock.Lock()
defer mm.lock.Unlock()
if matched, ok = mm.cache[method]; ok {
return matched
} else {
arrayPattern := mm.rm.Match(method)
matched = len(arrayPattern) > 0
}
mm.cache[method] = matched
return matched
}
-32
View File
@@ -1,32 +0,0 @@
package matcher
import "sync"
type cacheableMatcher struct {
cache map[string][]string
lock sync.RWMutex
rm runtimeMatcher
}
func (mm *cacheableMatcher) Match(method string) []string {
if len(mm.rm.patterns) == 0 {
return []string{}
}
mm.lock.RLock()
arrayPattern, ok := mm.cache[method]
mm.lock.RUnlock()
if ok {
return arrayPattern
}
mm.lock.Lock()
defer mm.lock.Unlock()
if arrayPattern, ok = mm.cache[method]; ok {
return arrayPattern
} else if arrayPattern = mm.rm.Match(method); len(arrayPattern) > 0 {
mm.cache[method] = arrayPattern
}
return arrayPattern
}
-31
View File
@@ -1,31 +0,0 @@
package matcher
var JournalMethods AtLeastOneMatcher = &atLeastOneMatcher{}
type Matcher interface {
Match(method string) []string
}
type AtLeastOneMatcher interface {
Match(method string) bool
}
func NewRuntimeMatcher(patterns []string) Matcher {
return &runtimeMatcher{
patterns: patterns,
}
}
func NewCacheableMatcher(patterns []string) Matcher {
return &cacheableMatcher{
cache: make(map[string][]string),
rm: runtimeMatcher{patterns: patterns},
}
}
func NewAtLeastOneMatcher(patterns []string) AtLeastOneMatcher {
return &atLeastOneMatcher{
cache: make(map[string]bool),
rm: runtimeMatcher{patterns: patterns},
}
}
-65
View File
@@ -1,65 +0,0 @@
package matcher
import (
"testing"
)
var (
patterns = []string{
"mdm-master/group/method",
"mdm-master/group/*",
"mdm-master/group2/method",
"mdm-master/group3/*",
}
cases = []struct {
method string
coincidence int
atLeastOne bool
}{
{method: "mdm-master/group/method", coincidence: 2, atLeastOne: true},
{method: "mdm-master/group/method2", coincidence: 1, atLeastOne: true},
{method: "mdm-master/group2/", coincidence: 0, atLeastOne: false},
{method: "mdm-master/group2/method3", coincidence: 0, atLeastOne: false},
{method: "mdm-master/group2/method", coincidence: 1, atLeastOne: true},
{method: "mdm-master/group3/some", coincidence: 1, atLeastOne: true},
{method: "mdm-master/group3/", coincidence: 1, atLeastOne: true},
}
)
func TestCacheableMatcher_Match(t *testing.T) {
matcher := NewCacheableMatcher(patterns)
for _, c := range cases {
res := matcher.Match(c.method)
if c.coincidence != len(res) {
t.Error(c)
}
}
}
func TestAtLeastOneMatcher_Match(t *testing.T) {
matcher := NewAtLeastOneMatcher(patterns)
for _, c := range cases {
res := matcher.Match(c.method)
if c.atLeastOne != res {
t.Error(c)
}
}
}
func BenchmarkCacheableMatcher_Match(b *testing.B) {
matcher := NewCacheableMatcher(patterns)
for i := 0; i < b.N; i++ {
for _, c := range cases {
_ = matcher.Match(c.method)
}
}
}
func BenchmarkRuntimeMatcher_Match(b *testing.B) {
matcher := NewRuntimeMatcher(patterns)
for i := 0; i < b.N; i++ {
for _, c := range cases {
_ = matcher.Match(c.method)
}
}
}
-24
View File
@@ -1,24 +0,0 @@
package matcher
import (
"strings"
)
type runtimeMatcher struct {
patterns []string
}
func (mm runtimeMatcher) Match(method string) []string {
resp := make([]string, 0)
for _, pattern := range mm.patterns {
patternLen := len(pattern)
if patternLen > 0 && pattern[patternLen-1] == '*' {
if strings.HasPrefix(method, pattern[:patternLen-1]) {
resp = append(resp, pattern)
}
} else if strings.EqualFold(method, pattern) {
resp = append(resp, pattern)
}
}
return resp
}
-90
View File
@@ -1,90 +0,0 @@
package service
import (
"github.com/integration-system/isp-lib/v2/metric"
"github.com/rcrowley/go-metrics"
"sync"
"time"
)
const (
defaultSampleSize = 2048
)
var Metrics = &metricService{mh: nil}
type (
metricService struct {
mh *metricHolder
}
metricHolder struct {
methodHistograms map[string]metrics.Histogram
methodLock sync.RWMutex
statusCounters map[string]metrics.Counter
statusLock sync.RWMutex
}
)
func (m *metricService) Init() {
m.mh = &metricHolder{
methodHistograms: make(map[string]metrics.Histogram),
statusCounters: make(map[string]metrics.Counter),
}
}
func (m *metricService) UpdateMethodResponseTime(uri string, time time.Duration) {
if m.notEmptyHolder() {
m.getOrRegisterHistogram(uri).Update(int64(time))
}
}
func (m *metricService) UpdateStatusCounter(status string) {
if m.notEmptyHolder() {
m.getOrRegisterCounter(status).Inc(1)
}
}
func (m *metricService) getOrRegisterHistogram(uri string) metrics.Histogram {
m.mh.methodLock.RLock()
histogram, ok := m.mh.methodHistograms[uri]
m.mh.methodLock.RUnlock()
if ok {
return histogram
}
m.mh.methodLock.Lock()
defer m.mh.methodLock.Unlock()
if d, ok := m.mh.methodHistograms[uri]; ok {
return d
}
histogram = metrics.GetOrRegisterHistogram(
"http.response.time_"+uri,
metric.GetRegistry(),
metrics.NewUniformSample(defaultSampleSize),
)
m.mh.methodHistograms[uri] = histogram
return histogram
}
func (m *metricService) getOrRegisterCounter(status string) metrics.Counter {
m.mh.statusLock.RLock()
d, ok := m.mh.statusCounters[status]
m.mh.statusLock.RUnlock()
if ok {
return d
}
m.mh.statusLock.Lock()
defer m.mh.statusLock.Unlock()
if d, ok := m.mh.statusCounters[status]; ok {
return d
}
d = metrics.GetOrRegisterCounter("http.response.count."+status, metric.GetRegistry())
m.mh.statusCounters[status] = d
return d
}
func (m *metricService) notEmptyHolder() bool {
return m.mh != nil
}
+47
View File
@@ -0,0 +1,47 @@
package service
import (
"context"
"github.com/pkg/errors"
"isp-gate-service/conf"
"isp-gate-service/domain"
)
type ThrottlingRepo interface {
IsAllowRequestPerSecond(ctx context.Context, applicationId int, rate int) (*domain.RateLimitResult, error)
}
type Throttling struct {
repo ThrottlingRepo
limits map[int]int
}
func NewThrottling(repo ThrottlingRepo, configs []conf.Throttling) Throttling {
limits := make(map[int]int)
for _, config := range configs {
limits[config.ApplicationId] = config.RequestsPerSeconds
}
return Throttling{
repo: repo,
limits: limits,
}
}
func (s Throttling) AllowRateLimit(ctx context.Context, applicationId int) (*domain.RateLimitResult, error) {
rate, ok := s.limits[applicationId]
if !ok {
return &domain.RateLimitResult{
Allow: true,
Remaining: -1,
RetryAfter: -1,
}, nil
}
result, err := s.repo.IsAllowRequestPerSecond(ctx, applicationId, rate)
if err != nil {
return nil, errors.WithMessage(err, "is allow request per second")
}
return result, nil
}
@@ -1,62 +0,0 @@
package veritification
import (
"sync"
"time"
)
const identitiesCount = 4
type (
cacheablesVerify struct {
cache map[string]cacheInfo
timeout time.Duration
rv *runtimeVerify
lock sync.RWMutex
}
cacheInfo struct {
created time.Time
identity map[string]string
}
)
func (cv *cacheablesVerify) ApplicationToken(token string) (map[string]string, error) {
cv.lock.RLock()
cache, ok := cv.cache[token]
cv.lock.RUnlock()
if ok {
if time.Since(cache.created) < cv.timeout {
return cv.copyCache(cache.identity), nil
}
}
cv.lock.Lock()
defer cv.lock.Unlock()
cache, ok = cv.cache[token]
if ok {
if time.Since(cache.created) < cv.timeout {
return cv.copyCache(cache.identity), nil
}
delete(cv.cache, token)
}
identity, err := cv.rv.ApplicationToken(token)
if err != nil {
return nil, err
}
cv.cache[token] = cacheInfo{created: time.Now(), identity: identity}
return cv.copyCache(identity), nil
}
func (cv *cacheablesVerify) Identity(identity map[string]string, uri string) (map[string]string, error) {
return cv.rv.Identity(identity, uri)
}
func (cv *cacheablesVerify) copyCache(cache map[string]string) map[string]string {
resp := make(map[string]string, identitiesCount)
for key, value := range cache {
resp[key] = value
}
return resp
}
-9
View File
@@ -1,9 +0,0 @@
package veritification
import "errors"
var (
ErrorInvalidUserId = errors.New("received unexpected user identity")
ErrorPermittedToCallApplication = errors.New("application has no rights to call this method")
ErrorPermittedToCallUser = errors.New("user has no rights to call this method")
)
-168
View File
@@ -1,168 +0,0 @@
package veritification
import (
"context"
rd "github.com/go-redis/redis/v8"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/redis"
"github.com/integration-system/isp-lib/v2/utils"
"github.com/pkg/errors"
"isp-gate-service/conf"
rdClient "isp-gate-service/redis"
)
const (
permittedToCallInfo = "0"
appIdArrayKey = 1
userTokenArrayKey = 3
userIdArrayKey = 5
deviceTokenArrayKey = 7
)
var (
errNoRedisCmd = errors.New("no redis cmd")
errUnexpectedCmd = errors.New("expected StringCmd")
headerKeyByRedisIdentity = map[string]string{
"1": utils.SystemIdHeader,
"2": utils.DomainIdHeader,
"3": utils.ServiceIdHeader,
"4": utils.ApplicationIdHeader,
}
)
type runtimeVerify struct{}
func (v *runtimeVerify) ApplicationToken(token string) (map[string]string, error) {
instanceUuid := config.Get().(*conf.Configuration).InstanceUuid
key := makeDbKey(token, instanceUuid)
resp, err := rdClient.Client.UseDb(redis.ApplicationTokenDb, func(p rd.Pipeliner) error {
if cmd := p.HGetAll(context.Background(), key); v.isError(cmd.Err()) {
return cmd.Err()
}
return nil
})
if err != nil {
return nil, err
}
if len(resp) < 2 || resp[1].Err() == rd.Nil {
return nil, nil
} else if resp[1].Err() != nil {
return nil, err
} else if stringStringMapCmd, ok := resp[1].(*rd.StringStringMapCmd); !ok {
return nil, errUnexpectedCmd
} else {
vals := stringStringMapCmd.Val()
identityMap := make(map[string]string, len(vals))
for i, value := range vals {
identityMap[headerKeyByRedisIdentity[i]] = value
}
return identityMap, nil
}
}
func (v *runtimeVerify) Identity(t map[string]string, uri string) (map[string]string, error) {
secondDbKey := makeDbKey(t[utils.ApplicationIdHeader], uri)
thirdDbKey := makeDbKey(t[utils.UserTokenHeader], t[utils.DomainIdHeader])
fourthDbKey := makeDbKey(t[utils.UserIdHeader], uri)
fifthDbKey := makeDbKey(t[utils.DeviceTokenHeader], t[utils.DomainIdHeader])
resp, err := rdClient.Client.Pipelined(context.Background(), func(p rd.Pipeliner) error {
if _, err := p.Select(context.Background(), int(redis.ApplicationPermissionDb)).Result(); v.isError(err) {
return err
}
if _, err := p.Get(context.Background(), secondDbKey).Result(); v.isError(err) {
return err
}
if _, err := p.Select(context.Background(), int(redis.UserTokenDb)).Result(); v.isError(err) {
return err
}
if _, err := p.Get(context.Background(), thirdDbKey).Result(); v.isError(err) {
return err
}
if _, err := p.Select(context.Background(), int(redis.UserPermissionDb)).Result(); v.isError(err) {
return err
}
if _, err := p.Get(context.Background(), fourthDbKey).Result(); v.isError(err) {
return err
}
if _, err := p.Select(context.Background(), int(redis.DeviceTokenDb)).Result(); v.isError(err) {
return err
}
if _, err := p.Get(context.Background(), fifthDbKey).Result(); v.isError(err) {
return err
}
return nil
})
if v.isError(err) {
return t, err
}
// ===== NOT PERMITTED BY APPLICATION ID =====
msg, err := v.findStringCmd(resp, appIdArrayKey)
if err != nil {
return t, err
}
if msg == permittedToCallInfo {
return t, ErrorPermittedToCallApplication
}
// ===== CHECK USER TOKEN =====
msg, err = v.findStringCmd(resp, userTokenArrayKey)
if err != nil {
return t, err
}
userIdentity, found := t[utils.UserIdHeader]
if found && msg != userIdentity {
return t, ErrorInvalidUserId
}
// ===== NOT PERMITTED BY USER ID =====
msg, err = v.findStringCmd(resp, userIdArrayKey)
if err != nil {
return t, err
}
if msg == permittedToCallInfo {
return t, ErrorPermittedToCallUser
}
// ===== CHECK DEVICE TOKEN =====
msg, err = v.findStringCmd(resp, deviceTokenArrayKey)
if err != nil {
return t, err
}
t[utils.DeviceIdHeader] = msg
return t, nil
}
func (v *runtimeVerify) isError(err error) bool {
return err != nil && err != rd.Nil
}
func (v *runtimeVerify) findStringCmd(cmders []rd.Cmder, arrayKey int) (string, error) {
if len(cmders) <= arrayKey {
return "", errNoRedisCmd
}
cmd := cmders[arrayKey]
if cmd == nil {
return "", errNoRedisCmd
}
if v.isError(cmd.Err()) {
return "", cmd.Err()
}
if stringCmd, ok := cmd.(*rd.StringCmd); !ok {
return "", errUnexpectedCmd
} else {
return stringCmd.Val(), nil
}
}
func makeDbKey(key, val string) string {
return key + "|" + val
}
-22
View File
@@ -1,22 +0,0 @@
package veritification
import (
"time"
)
type Verify interface {
ApplicationToken(string) (map[string]string, error)
Identity(map[string]string, string) (map[string]string, error)
}
func NewRuntimeVerify() Verify {
return &runtimeVerify{}
}
func NewCacheablesVerify(timeout time.Duration) Verify {
return &cacheablesVerify{
cache: make(map[string]cacheInfo),
timeout: timeout,
rv: &runtimeVerify{},
}
}
+185
View File
@@ -0,0 +1,185 @@
package tests
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"testing"
"github.com/go-redis/redis/v8"
"github.com/go-resty/resty/v2"
"github.com/google/uuid"
"github.com/integration-system/isp-kit/grpc"
"github.com/integration-system/isp-kit/grpc/client"
"github.com/integration-system/isp-kit/lb"
"github.com/integration-system/isp-kit/log"
"github.com/integration-system/isp-kit/requestid"
"github.com/integration-system/isp-kit/test"
"github.com/integration-system/isp-kit/test/grpct"
"github.com/integration-system/isp-kit/test/httpt"
"github.com/stretchr/testify/suite"
"isp-gate-service/assembly"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/routes"
)
type request struct {
Id string
}
type response struct {
Id string
}
type HappyPathTestSuite struct {
suite.Suite
}
func (s *HappyPathTestSuite) TestGrpcProxy() {
test, require := test.New(s.T())
config, redisCli, systemCli := s.commonDependencies(test)
requestId := requestid.Next()
targetService, targetCli := grpct.NewMock(test)
targetService.Mock("endpoint", func(ctx context.Context, authData grpc.AuthData, req request) response {
systemId, err := authData.SystemId()
require.NoError(err)
domainId, err := authData.DomainId()
require.NoError(err)
serviceId, err := authData.ServiceId()
require.NoError(err)
applicationId, err := authData.ApplicationId()
require.NoError(err)
require.EqualValues(requestId, requestid.FromContext(ctx))
require.EqualValues(1, systemId)
require.EqualValues(2, domainId)
require.EqualValues(3, serviceId)
require.EqualValues(4, applicationId)
return response{Id: req.Id} //nolint:gosimple
})
targetClients := map[string]*client.Client{"target": targetCli}
logger, err := log.New(log.WithLevel(log.DebugLevel))
require.NoError(err)
locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(), systemCli)
locations := []conf.Location{{
SkipAuth: false,
PathPrefix: "/api",
Protocol: "grpc",
TargetModule: "target",
}}
handler, err := locator.Handler(config, locations, redisCli)
require.NoError(err)
srv := httptest.NewServer(handler)
cli := resty.NewWithClient(srv.Client()).SetBaseURL(srv.URL)
req := request{Id: uuid.New().String()}
resp := response{}
_, err = cli.R().
SetHeader("x-application-token", "token").
SetHeader("x-request-id", requestId).
SetBody(req).
SetResult(&resp).
Post("/api/endpoint")
require.NoError(err)
require.EqualValues(req.Id, resp.Id)
}
func (s *HappyPathTestSuite) TestHttpProxy() {
test, require := test.New(s.T())
config, redisCli, systemCli := s.commonDependencies(test)
requestId := requestid.Next()
targetService := httpt.NewMock(test)
targetService.POST("/endpoint", func(ctx context.Context, httpReq *http.Request, req request) response {
systemId, err := strconv.Atoi(httpReq.Header.Get("x-system-identity"))
require.NoError(err)
domainId, err := strconv.Atoi(httpReq.Header.Get("x-domain-identity"))
require.NoError(err)
serviceId, err := strconv.Atoi(httpReq.Header.Get("x-service-identity"))
require.NoError(err)
applicationId, err := strconv.Atoi(httpReq.Header.Get("x-application-identity"))
require.NoError(err)
require.EqualValues(requestId, requestid.FromContext(ctx))
require.EqualValues(1, systemId)
require.EqualValues(2, domainId)
require.EqualValues(3, serviceId)
require.EqualValues(4, applicationId)
return response{Id: req.Id} //nolint:gosimple
})
targetUrl, err := url.Parse(targetService.BaseURL())
require.NoError(err)
rr := lb.NewRoundRobin([]string{targetUrl.Host})
targetClients := map[string]*lb.RoundRobin{"target": rr}
locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes.NewRoutes(), systemCli)
locations := []conf.Location{{
SkipAuth: false,
PathPrefix: "/api",
Protocol: "http",
TargetModule: "target",
}}
handler, err := locator.Handler(config, locations, redisCli)
require.NoError(err)
srv := httptest.NewServer(handler)
cli := resty.NewWithClient(srv.Client()).SetBaseURL(srv.URL)
req := request{Id: uuid.New().String()}
resp := response{}
_, err = cli.R().
SetHeader("x-application-token", "token").
SetHeader("x-request-id", requestId).
SetBody(req).
SetResult(&resp).
Post("/api/endpoint")
require.NoError(err)
require.EqualValues(req.Id, resp.Id)
}
func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, redis.UniversalClient, *client.Client) {
require := test.Assert()
redisCli := NewRedis(test)
ctx := context.Background()
s.T().Cleanup(func() {
_, err := redisCli.Pipelined(ctx, func(p redis.Pipeliner) error {
p.Select(ctx, 0)
p.FlushDB(ctx)
p.Select(ctx, 1)
p.FlushDB(ctx)
p.Select(ctx, 2)
p.FlushDB(ctx)
return nil
})
require.NoError(err)
})
config := conf.Remote{
Redis: &conf.Redis{Address: redisCli.address},
Secrets: conf.Secrets{AdminTokenSecret: "secret"},
Http: conf.Http{MaxRequestBodySizeInMb: 1, ProxyTimeoutInSec: 15},
Logging: conf.Logging{LogLevel: log.DebugLevel, RequestLogEnable: true, BodyLogEnable: true},
Caching: conf.Caching{AuthorizationDataInSec: 1, AuthenticationDataInSec: 1},
DailyLimits: []conf.DailyLimit{{ApplicationId: 1, RequestsPerDay: 100}},
Throttling: []conf.Throttling{{ApplicationId: 1, RequestsPerSeconds: 100}},
}
systemService, systemCli := grpct.NewMock(test)
systemService.Mock("system/secure/authenticate", func() domain.AuthenticateResponse {
return domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: &domain.AuthData{
SystemId: 1,
DomainId: 2,
ServiceId: 3,
ApplicationId: 4,
},
}
}).Mock("system/secure/authorize", func() domain.AuthorizeResponse {
return domain.AuthorizeResponse{Authorized: true}
})
return config, redisCli, systemCli
}
func TestHappyPathTestSuite(t *testing.T) {
suite.Run(t, new(HappyPathTestSuite))
}
+131
View File
@@ -0,0 +1,131 @@
package main
import (
"context"
"net"
"net/http"
"github.com/go-redis/redis/v8"
"github.com/integration-system/isp-kit/grpc"
"github.com/integration-system/isp-kit/grpc/client"
endpoint2 "github.com/integration-system/isp-kit/grpc/endpoint"
"github.com/integration-system/isp-kit/grpc/isp"
"github.com/integration-system/isp-kit/log"
"isp-gate-service/assembly"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/routes"
)
type request struct {
Id string
}
type response struct {
Id string
}
//nolint
func main() {
redisCli := redis.NewClient(&redis.Options{})
ctx := context.Background()
logger, err := log.New()
if err != nil {
panic(err)
}
defer func() {
_, _ = redisCli.Pipelined(ctx, func(p redis.Pipeliner) error {
p.Select(ctx, 0)
p.FlushDB(ctx)
p.Select(ctx, 1)
p.FlushDB(ctx)
p.Select(ctx, 2)
p.FlushDB(ctx)
return nil
})
}()
config := conf.Remote{
Redis: &conf.Redis{Address: "localhost:6379"},
Secrets: conf.Secrets{AdminTokenSecret: "secret"},
Http: conf.Http{MaxRequestBodySizeInMb: 1, ProxyTimeoutInSec: 15},
Logging: conf.Logging{LogLevel: log.DebugLevel, RequestLogEnable: true, BodyLogEnable: true},
Caching: conf.Caching{AuthorizationDataInSec: 15, AuthenticationDataInSec: 15},
DailyLimits: []conf.DailyLimit{{ApplicationId: 1, RequestsPerDay: 100000000}},
Throttling: []conf.Throttling{{ApplicationId: 1, RequestsPerSeconds: 5000}},
}
systemService, systemCli := NewMock(logger)
systemService.Mock("system/secure/authenticate", func() domain.AuthenticateResponse {
return domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: &domain.AuthData{
SystemId: 1,
DomainId: 1,
ServiceId: 1,
ApplicationId: 1,
},
}
}).Mock("system/secure/authorize", func() domain.AuthorizeResponse {
return domain.AuthorizeResponse{Authorized: true}
})
targetService, targetCli := NewMock(logger)
targetService.Mock("endpoint", func(req request) response {
return response{Id: req.Id}
})
targetClients := map[string]*client.Client{"target": targetCli}
logger, _ = log.New(log.WithLevel(log.DebugLevel))
locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(), systemCli)
locations := []conf.Location{{
SkipAuth: false,
PathPrefix: "/api",
Protocol: "grpc",
TargetModule: "target",
}}
handler, _ := locator.Handler(config, locations, redisCli)
srv := &http.Server{
Addr: "localhost:8000",
Handler: handler,
}
srv.ListenAndServe()
}
func TestServer(service isp.BackendServiceServer) (*grpc.Server, *client.Client) {
listener, _ := net.Listen("tcp", "127.0.0.1:")
srv := grpc.NewServer()
cli, _ := client.Default()
srv.Upgrade(service)
go func() {
_ = srv.Serve(listener)
}()
cli.Upgrade([]string{listener.Addr().String()})
return srv, cli
}
type MockServer struct {
srv *grpc.Server
logger log.Logger
mockEndpoints map[string]interface{}
}
func NewMock(logger log.Logger) (*MockServer, *client.Client) {
srv, cli := TestServer(grpc.NewMux())
return &MockServer{
srv: srv,
logger: logger,
mockEndpoints: make(map[string]interface{}),
}, cli
}
func (m *MockServer) Mock(endpoint string, handler interface{}) *MockServer {
m.mockEndpoints[endpoint] = handler
wrapper := endpoint2.DefaultWrapper(m.logger)
muxer := grpc.NewMux()
for e, handler := range m.mockEndpoints {
muxer.Handle(e, wrapper.Endpoint(handler))
}
m.srv.Upgrade(muxer)
return m
}
+3
View File
@@ -0,0 +1,3 @@
{
"id": "GO4IIZW5uav4cSo2zyR6i41LdalKytNH628yDhC92jXQF07gu4LS75JuzQgc6d3Dly48fwla9iHK6LPTJcvFbOcklXp7Zr9g3b180s0H3dVgaYGcO8BrAFxMVb2KcHyu"
}
+2
View File
@@ -0,0 +1,2 @@
bombardier -c 128 -t 1s -d 60s --fasthttp -H "x-application-token: token" -m POST -f body.json http://localhost:8000/api/endpoint
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more