From fff1126990f9b64243130a904b934f9ec64a0bb3 Mon Sep 17 00:00:00 2001 From: "vforfreedom96@gmail.com" Date: Wed, 22 May 2024 18:02:12 +0800 Subject: [PATCH] chore:add biz unit test --- go.sum | 37 ------------ internal/biz/aksk.go | 2 +- internal/biz/aksk_test.go | 42 ++++++++++++++ internal/biz/app_test.go | 116 ++++++++++++++++++++++++++++++++++++- internal/biz/authz.go | 2 +- internal/biz/authz_test.go | 73 ++++++++++++++++++++++- internal/biz/data.go | 28 ++++----- internal/biz/data_test.go | 97 +++++++++++++++++++++++++++++++ internal/biz/user_test.go | 65 ++++++++++++++++++++- internal/data/data.go | 1 + internal/data/wire.go | 5 ++ internal/data/wire_gen.go | 8 +++ internal/data/wire_test.go | 34 +++++++++++ 13 files changed, 449 insertions(+), 61 deletions(-) create mode 100644 internal/data/wire_test.go diff --git a/go.sum b/go.sum index c40e5b0..b7c4927 100644 --- a/go.sum +++ b/go.sum @@ -15,34 +15,13 @@ github.com/agiledragon/gomonkey/v2 v2.11.0/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoa github.com/allegro/bigcache/v3 v3.1.0 h1:H2Vp8VOvxcrB91o86fUSVJFqeuz8kpyyB02eH3bSzwk= github.com/allegro/bigcache/v3 v3.1.0/go.mod h1:aPyh7jEvrog9zAwx5N7+JUQX5dZTSGpxF1LAR4dr35I= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8= -github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/begonia-org/go-layered-cache v0.0.0-20240510102605-41bdb7aa07fa h1:DHjhGvN6SYMA2Vf2D0/kILQKcSiFQH6OqNMivYebFag= github.com/begonia-org/go-layered-cache v0.0.0-20240510102605-41bdb7aa07fa/go.mod h1:xEqoca1vNGqH8CV7X9EzhDV5Ihtq9J95p7ZipzUB6pc= -github.com/begonia-org/go-loadbalancer v0.0.0-20240408092223-42b5fab476ce h1:qLUMzfJuPyWVeIs9d4FaootUIQzWs4xfFwkI6R6IH40= -github.com/begonia-org/go-loadbalancer v0.0.0-20240408092223-42b5fab476ce/go.mod h1:crPS67sfgmgv47psftwfmTMbmTfdepVm8MPeqApINlI= -github.com/begonia-org/go-loadbalancer v0.0.0-20240515153502-b1d83dda8ae3 h1:0BxtLwjHi9tQiQ8l+rEqIqTY0WqngC3RptORz7edTHU= -github.com/begonia-org/go-loadbalancer v0.0.0-20240515153502-b1d83dda8ae3/go.mod h1:crPS67sfgmgv47psftwfmTMbmTfdepVm8MPeqApINlI= github.com/begonia-org/go-loadbalancer v0.0.0-20240519060752-71ca464f0f1a h1:Mpw7T+90KC5QW7yCa8Nn/5psnlvsexipAOrQAcc7YE0= github.com/begonia-org/go-loadbalancer v0.0.0-20240519060752-71ca464f0f1a/go.mod h1:crPS67sfgmgv47psftwfmTMbmTfdepVm8MPeqApINlI= -github.com/begonia-org/go-sdk v0.0.0-20240515083527-ef2ff6b73539 h1:M7pPon2kyX2MlJM8R6+TGqGAFhWzSzAd8VqCZ9/bm3g= -github.com/begonia-org/go-sdk v0.0.0-20240515083527-ef2ff6b73539/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y= -github.com/begonia-org/go-sdk v0.0.0-20240516160356-c90fe583fd2e h1:VwPf1HI//SopJpJtWHtQd6JreryTtu8s1m0zQo+Jeqc= -github.com/begonia-org/go-sdk v0.0.0-20240516160356-c90fe583fd2e/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y= -github.com/begonia-org/go-sdk v0.0.0-20240517035447-b6ee0a94bc66 h1:ejdny9b1oeioMFd8IWQcY9uDpDOAlTnMAJvhsalHdjs= -github.com/begonia-org/go-sdk v0.0.0-20240517035447-b6ee0a94bc66/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y= -github.com/begonia-org/go-sdk v0.0.0-20240517084829-c3cdf5e5e1eb h1:H58fLjtWA5CZSl20GLyi+3xnQiRiP47aEub7YWFjuQc= -github.com/begonia-org/go-sdk v0.0.0-20240517084829-c3cdf5e5e1eb/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y= -github.com/begonia-org/go-sdk v0.0.0-20240517093020-2a19277f4cd0 h1:PRMFCCLybAmO0gnaU3pZhY1koi1N1so3iMBdbLEfCOU= -github.com/begonia-org/go-sdk v0.0.0-20240517093020-2a19277f4cd0/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y= -github.com/begonia-org/go-sdk v0.0.0-20240519143740-d09416b7b751 h1:ku84LpIO8hZ54BzE089pfTB1Op7YIA3GMLEcN49VoUI= -github.com/begonia-org/go-sdk v0.0.0-20240519143740-d09416b7b751/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y= -github.com/begonia-org/go-sdk v0.0.0-20240520034852-0b45d3942779 h1:iL/WWH9anPFbGJWYIhqPIcVAkWKfPq0HntG5NkHI2uk= -github.com/begonia-org/go-sdk v0.0.0-20240520034852-0b45d3942779/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y= -github.com/begonia-org/go-sdk v0.0.0-20240520090120-64e22f6f7a4d h1:yJ0+f8SDNyA2GSf1XvLN2R4BK60ruNU7+V328BBCDYw= -github.com/begonia-org/go-sdk v0.0.0-20240520090120-64e22f6f7a4d/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y= github.com/begonia-org/go-sdk v0.0.0-20240521170528-b02c5a54f25e h1:QIlVvEUYC2t+ctxzKMFtMw0a1eXauR87pimm2D55guQ= github.com/begonia-org/go-sdk v0.0.0-20240521170528-b02c5a54f25e/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y= github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= @@ -135,7 +114,6 @@ github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7Fsg github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= @@ -176,7 +154,6 @@ github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCy github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU= github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU= github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= -github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= @@ -214,7 +191,6 @@ github.com/r3labs/sse/v2 v2.10.0 h1:hFEkLLFY4LDifoHdiCN/LlGBAdVJYsANaLqNYa1l/v0= github.com/r3labs/sse/v2 v2.10.0/go.mod h1:Igau6Whc+F17QUgML1fYe1VPZzTV6EMCnYktEmkNJ7I= github.com/redis/go-redis/v9 v9.5.1 h1:H1X4D3yHPaYrkL5X06Wh6xNVM/pX0Ft4RV0vMGvLBh8= github.com/redis/go-redis/v9 v9.5.1/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M= -github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= @@ -240,10 +216,6 @@ github.com/smartystreets/goconvey v1.8.1 h1:qGjIddxOk4grTu9JPOU31tVfq3cNdBlNa5sS github.com/smartystreets/goconvey v1.8.1/go.mod h1:+/u4qLyY6x1jReYOp7GOM2FSt8aP9CzCZL03bI28W60= github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= -github.com/spark-lence/tiga v0.0.0-20240510102710-93bf07b60b07 h1:BLvfdUv/NKsRirhQbUum2eduFHfu0tcWyF4fHhP62zY= -github.com/spark-lence/tiga v0.0.0-20240510102710-93bf07b60b07/go.mod h1:jo3Qr3EkFkOX0GUD6c4YyLoJESTYtd2hfYP9HZk8s8I= -github.com/spark-lence/tiga v0.0.0-20240517030839-e2e8385d3629 h1:J5qEeswukKY+wAnQLgHFz8T9/vItTF4lga7JDjwz8fE= -github.com/spark-lence/tiga v0.0.0-20240517030839-e2e8385d3629/go.mod h1:MSL8X9t+qvpQ4Tq3vVPKncq9RJcCzF2XGEWkCuNhm6Q= github.com/spark-lence/tiga v0.0.0-20240517061929-e81eba889226 h1:WKMb1r+0r5lDKrynMlC9v62EajmtLXMIIk6NzrVbcNs= github.com/spark-lence/tiga v0.0.0-20240517061929-e81eba889226/go.mod h1:MSL8X9t+qvpQ4Tq3vVPKncq9RJcCzF2XGEWkCuNhm6Q= github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= @@ -412,16 +384,8 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/genproto/googleapis/api v0.0.0-20240513163218-0867130af1f8 h1:W5Xj/70xIA4x60O/IFyXivR5MGqblAb8R3w26pnD6No= -google.golang.org/genproto/googleapis/api v0.0.0-20240513163218-0867130af1f8/go.mod h1:vPrPUTsDCYxXWjP7clS81mZ6/803D8K4iM9Ma27VKas= -google.golang.org/genproto/googleapis/api v0.0.0-20240515191416-fc5f0ca64291 h1:4HZJ3Xv1cmrJ+0aFo304Zn79ur1HMxptAE7aCPNLSqc= -google.golang.org/genproto/googleapis/api v0.0.0-20240515191416-fc5f0ca64291/go.mod h1:RGnPtTG7r4i8sPlNyDeikXF99hMM+hN6QMm4ooG9g2g= google.golang.org/genproto/googleapis/api v0.0.0-20240520151616-dc85e6b867a5 h1:P8OJ/WCl/Xo4E4zoe4/bifHpSmmKwARqyqE4nW6J2GQ= google.golang.org/genproto/googleapis/api v0.0.0-20240520151616-dc85e6b867a5/go.mod h1:RGnPtTG7r4i8sPlNyDeikXF99hMM+hN6QMm4ooG9g2g= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240513163218-0867130af1f8 h1:mxSlqyb8ZAHsYDCfiXN1EDdNTdvjUJSLY+OnAUtYNYA= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240513163218-0867130af1f8/go.mod h1:I7Y+G38R2bu5j1aLzfFmQfTcU/WnFuqDwLZAbvKTKpM= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240515191416-fc5f0ca64291 h1:AgADTJarZTBqgjiUzRgfaBchgYB3/WFTC80GPwsMcRI= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240515191416-fc5f0ca64291/go.mod h1:EfXuqaE1J41VCDicxHzUDm+8rk+7ZdXzHV0IhO/I6s0= google.golang.org/genproto/googleapis/rpc v0.0.0-20240520151616-dc85e6b867a5 h1:Q2RxlXqh1cgzzUgV261vBO2jI5R/3DD1J2pM0nI4NhU= google.golang.org/genproto/googleapis/rpc v0.0.0-20240520151616-dc85e6b867a5/go.mod h1:EfXuqaE1J41VCDicxHzUDm+8rk+7ZdXzHV0IhO/I6s0= google.golang.org/grpc v1.64.0 h1:KH3VH9y/MgNQg1dE7b3XfVK0GsPSIzJwdF617gUSbvY= @@ -433,7 +397,6 @@ gopkg.in/cenkalti/backoff.v1 v1.1.0/go.mod h1:J6Vskwqd+OMVJl8C33mmtxTBs2gyzfv7UD gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= diff --git a/internal/biz/aksk.go b/internal/biz/aksk.go index 15494cd..528edd6 100644 --- a/internal/biz/aksk.go +++ b/internal/biz/aksk.go @@ -74,7 +74,7 @@ func (a *AccessKeyAuth) AppValidator(ctx context.Context, req *gosdk.GatewayRequ return "", gosdk.NewError(errors.ErrRequestExpired, int32(api.APPSvrCode_APP_REQUEST_EXPIRED_ERR), codes.DeadlineExceeded, "app_timestamp") } - secret, err := a.app.GetSecret(ctx, accessKey) + secret, err := a.GetSecret(ctx, accessKey) if err != nil { return "", gosdk.NewError(err, int32(api.APPSvrCode_APP_UNKNOWN), codes.Unauthenticated, "app_secret") } diff --git a/internal/biz/aksk_test.go b/internal/biz/aksk_test.go index f544f7a..5a989c0 100644 --- a/internal/biz/aksk_test.go +++ b/internal/biz/aksk_test.go @@ -16,8 +16,10 @@ import ( "github.com/begonia-org/begonia/internal/data" cfg "github.com/begonia-org/begonia/internal/pkg/config" "github.com/begonia-org/begonia/internal/pkg/errors" + "github.com/begonia-org/begonia/internal/pkg/routers" "github.com/begonia-org/begonia/internal/pkg/utils" gosdk "github.com/begonia-org/go-sdk" + api "github.com/begonia-org/go-sdk/api/app/v1" c "github.com/smartystreets/goconvey/convey" "github.com/spark-lence/tiga" @@ -114,7 +116,18 @@ func testGetAPPID(t *testing.T) { c.So(appid, c.ShouldBeEmpty) }) } +func testIfNeedValidate(t *testing.T) { + c.Convey("test if need validate", t, func() { + ok := biz.IfNeedValidate(context.TODO(), akskAccess) + c.So(ok, c.ShouldBeFalse) + patch := gomonkey.ApplyFuncReturn((*routers.HttpURIRouteToSrvMethod).GetRouteByGrpcMethod, &routers.APIMethodDetails{AuthRequired: true}) + defer patch.Reset() + ok = biz.IfNeedValidate(context.TODO(), akskAccess) + c.So(ok, c.ShouldBeTrue) + patch.Reset() + }) +} func testValidator(t *testing.T) { signer := gosdk.NewAppAuthSigner(akskAccess, akskSecret) c.Convey("test validator success", t, func() { @@ -184,10 +197,39 @@ func testValidator(t *testing.T) { c.So(err, c.ShouldNotBeNil) c.So(err.Error(), c.ShouldContainSubstring, errors.ErrAppSignatureInvalid.Error()) }) + + c.Convey("test validator fail with invalidate sk ak", t, func() { + req, err := http.NewRequest(http.MethodPost, "http://127.0.0.1:1949/api/v1/helloworld", strings.NewReader(`{"msg":"hello"}`)) + if err != nil { + t.Error(err) + return + } + req.Header.Add("content-type", "application/json") + + gw, err := gosdk.NewGatewayRequestFromHttp(req) + c.So(err, c.ShouldBeNil) + err = signer.SignRequest(gw) + c.So(err, c.ShouldBeNil) + patch := gomonkey.ApplyFuncReturn((*biz.AccessKeyAuth).GetSecret, "", fmt.Errorf("sk not found")) + defer patch.Reset() + aksk := newAKSK() + _, err = aksk.AppValidator(context.TODO(), gw) + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, "sk not found") + patch.Reset() + + patch2 := gomonkey.ApplyFuncReturn((*gosdk.AppAuthSignerImpl).Sign, "", fmt.Errorf("sign error")) + defer patch2.Reset() + _, err = aksk.AppValidator(context.TODO(), gw) + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, "sign error") + patch2.Reset() + }) } func TestAKSK(t *testing.T) { t.Run("get secret", testGetSecret) t.Run("get appid", testGetAPPID) t.Run("validator", testValidator) + t.Run("if need validate", testIfNeedValidate) } diff --git a/internal/biz/app_test.go b/internal/biz/app_test.go index 899aa6a..dec37f1 100644 --- a/internal/biz/app_test.go +++ b/internal/biz/app_test.go @@ -2,10 +2,12 @@ package biz_test import ( "context" + "crypto/rand" "fmt" "testing" "time" + "github.com/agiledragon/gomonkey/v2" "github.com/begonia-org/begonia" "github.com/begonia-org/begonia/config" "github.com/begonia-org/begonia/gateway" @@ -109,6 +111,36 @@ func testPutApp(t *testing.T) { err = appBiz.Put(context.TODO(), app2, "396870469984194560") c.So(err, c.ShouldNotBeNil) c.So(err.Error(), c.ShouldContainSubstring, "Duplicate entry") + + patch := gomonkey.ApplyFuncReturn(rand.Read, 0, fmt.Errorf("read error")) + defer patch.Reset() + _, err = appBiz.CreateApp(context.TODO(), &api.AppsRequest{ + Name: appName, + Description: "test", + Tags: []string{"test-app"}, + }, "396870469984194560") + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, "read error") + patch.Reset() + + patch2 := gomonkey.ApplyFuncReturn(biz.GenerateAppSecret, "", fmt.Errorf("generate secret error")) + defer patch2.Reset() + _, err = appBiz.CreateApp(context.TODO(), &api.AppsRequest{ + Name: appName, + Description: "test", + Tags: []string{"test-app"}, + }, "396870469984194560") + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, "generate secret error") + patch2.Reset() + + _, err = appBiz.CreateApp(context.TODO(), &api.AppsRequest{ + Name: appName, + Description: "test", + Tags: []string{"test-app"}, + }, "396870469984194560") + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, "Duplicate entry") }) } @@ -178,6 +210,23 @@ func testPatchApp(t *testing.T) { c.So(err, c.ShouldNotBeNil) c.So(err.Error(), c.ShouldContainSubstring, "Duplicate entry") + env := "dev" + if begonia.Env != "" { + env = begonia.Env + } + config := config.ReadConfig(env) + repo := data.NewAppRepo(config, gateway.Log) + + patch := gomonkey.ApplyMethodReturn(repo, "Patch", fmt.Errorf("patch error")) + defer patch.Reset() + _, err = appBiz.Patch(context.TODO(), &api.AppsRequest{ + Appid: appid, + Name: appName2, + UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"name"}}, + }, "") + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, "patch error") + patch.Reset() }) } @@ -203,24 +252,89 @@ func testListApp(t *testing.T) { }) c.So(len(apps), c.ShouldEqual, 0) c.So(err, c.ShouldBeNil) + + env := "dev" + if begonia.Env != "" { + env = begonia.Env + } + config := config.ReadConfig(env) + repo := data.NewAppRepo(config, gateway.Log) + + patch := gomonkey.ApplyMethodReturn(repo, "List",nil, fmt.Errorf("list error")) + defer patch.Reset() + _, err = appBiz.List(context.TODO(), &api.AppsListRequest{ + PageSize: 10, + Page: 1, + Tags: []string{"not-exist"}, + Status: []api.APPStatus{api.APPStatus_APP_DISABLED}, + }) + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, "list error") + patch.Reset() + }) } func testDelApp(t *testing.T) { + appBiz := newAppBiz() + c.Convey("test app del success", t, func() { - appBiz := newAppBiz() err := appBiz.Del(context.TODO(), appid) c.So(err, c.ShouldBeNil) _, err = appBiz.Get(context.TODO(), appid) c.So(err, c.ShouldNotBeNil) c.So(err.Error(), c.ShouldContainSubstring, "not found") }) + c.Convey("test app del failed", t, func() { + err := appBiz.Del(context.TODO(), "123456") + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, "not found") + env := "dev" + if begonia.Env != "" { + env = begonia.Env + } + config := config.ReadConfig(env) + repo := data.NewAppRepo(config, gateway.Log) + + patch := gomonkey.ApplyMethodReturn(repo, "Del", fmt.Errorf("del error")) + defer patch.Reset() + err = appBiz.Del(context.TODO(), appid) + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, "del error") + }) } +func testCache(t *testing.T) { + appBiz := newAppBiz() + + c.Convey("test app cache success", t, func() { + appName2 = fmt.Sprintf("app-biz-2-%s", time.Now().Format("20060102150405")) + access2, _ := utils.GenerateRandomString(32) + secret2, _ := utils.GenerateRandomString(64) + snk, _ := tiga.NewSnowflake(1) + app2 := &api.Apps{ + Appid: snk.GenerateIDString(), + AccessKey: access2, + Secret: secret2, + Status: api.APPStatus_APP_ENABLED, + IsDeleted: false, + Name: appName2, + Description: "test", + CreatedAt: timestamppb.New(time.Now()), + UpdatedAt: timestamppb.New(time.Now()), + } + err := appBiz.Cache(context.Background(), "app:test:prefix", app2, 3*time.Second) + c.So(err, c.ShouldBeNil) + + // app, err := appBiz.Get(context.Background(), app2.Appid) + + }) +} func TestAppBiz(t *testing.T) { t.Run("testPutApp", testPutApp) t.Run("testGetApp", testGetApp) t.Run("testPatchApp", testPatchApp) t.Run("testListApp", testListApp) + t.Run("testCache", testCache) t.Run("testDelApp", testDelApp) } diff --git a/internal/biz/authz.go b/internal/biz/authz.go index 011e2e1..e775ae3 100644 --- a/internal/biz/authz.go +++ b/internal/biz/authz.go @@ -161,7 +161,7 @@ func (u *AuthzUsecase) Logout(ctx context.Context, req *api.LogoutAPIRequest) er if len(token) == 0 { return gosdk.NewError(errors.ErrTokenMissing, int32(common.Code_TOKEN_NOT_FOUND), codes.InvalidArgument, "token_missing") } - err := u.repo.PutBlackList(ctx, tiga.GetMd5(token[0])) + err := u.PutBlackList(ctx, tiga.GetMd5(token[0])) if err != nil { return gosdk.NewError(err, int32(common.Code_AUTH_ERROR), codes.Internal, "add_black_list") } diff --git a/internal/biz/authz_test.go b/internal/biz/authz_test.go index d043c64..81c27f5 100644 --- a/internal/biz/authz_test.go +++ b/internal/biz/authz_test.go @@ -61,6 +61,15 @@ func testAuthSeed(t *testing.T) { seedTimestampToken = fmt.Sprintf("%d", token) c.So(err, c.ShouldBeNil) seedAuthToken = seed + + patch := gomonkey.ApplyFuncReturn((crypto.UsersAuth).GenerateAuthSeed, "", fmt.Errorf("error auth seed")) + defer patch.Reset() + _, err = authzBiz.AuthSeed(context.TODO(), &v1.AuthLogAPIRequest{ + Token: fmt.Sprintf("%d", token), + }) + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, "error auth seed") + }) } @@ -207,6 +216,41 @@ func testLogin(t *testing.T) { c.So(err, c.ShouldNotBeNil) c.So(err.Error(), c.ShouldContainSubstring, errors.ErrTokenExpired.Error()) }) + c.Convey("test login failed with invalid UserAuth", t, func() { + patch := gomonkey.ApplyFuncReturn(json.Marshal, nil, fmt.Errorf("error marshal")) + defer patch.Reset() + _, err := getUserAuth(adminUser, adminPasswd, pubKey, seedAuthToken, seedTimestampToken) + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, "error marshal") + patch.Reset() + }) + c.Convey("test login failed with invalid EncryptAES", t, func() { + patch := gomonkey.ApplyFuncReturn(tiga.EncryptAES, "", fmt.Errorf("error encryptAES")) + defer patch.Reset() + info, _ := getUserAuth(adminUser, adminPasswd, pubKey, seedAuthToken, seedTimestampToken) + _, err := authzBiz.Login(context.TODO(), info) + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, errors.ErrEncrypt.Error()) + patch.Reset() + + }) + + c.Convey("test login failed with invalid user status", t, func() { + mockUser := &v1.Users{ + Password: adminPasswd, + Name: adminUser, + Status: v1.USER_STATUS_LOCKED, + } + repo := data.NewUserRepo(config, gateway.Log) + patch := gomonkey.ApplyMethodReturn(repo, "Get", mockUser, nil) + defer patch.Reset() + info, err := getUserAuth(adminUser, adminPasswd, pubKey, seedAuthToken, seedTimestampToken) + c.So(err, c.ShouldBeNil) + _, err = authzBiz.Login(context.TODO(), info) + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, errors.ErrUserDisabled.Error()) + patch.Reset() + }) } @@ -231,12 +275,39 @@ func testLogout(t *testing.T) { c.So(err, c.ShouldNotBeNil) c.So(err.Error(), c.ShouldContainSubstring, errors.ErrNoMetadata.Error()) + + patch := gomonkey.ApplyFuncReturn((*biz.AuthzUsecase).PutBlackList, fmt.Errorf("error PutBlackList")) + defer patch.Reset() + ctx = metadata.NewIncomingContext(context.Background(), metadata.Pairs("x-token", authzStr)) + err = authzBiz.Logout(ctx, &v1.LogoutAPIRequest{}) + c.So(err, c.ShouldNotBeNil) + c.So(err.Error(), c.ShouldContainSubstring, "error PutBlackList") + }) } +func testDelToken(t *testing.T) { + c.Convey("test del token", t, func() { + authzBiz := newAuthzBiz() + err := authzBiz.DelToken(context.TODO(), authzStr) + c.So(err, c.ShouldBeNil) + }) +} +func testPutBlackList(t *testing.T) { + authzBiz := newAuthzBiz() + c.Convey("test put black list", t, func() { + token := tiga.GetMd5("test") + err := authzBiz.PutBlackList(context.TODO(), token) + c.So(err, c.ShouldBeNil) + ok, err := authzBiz.CheckInBlackList(context.TODO(), token) + c.So(err, c.ShouldBeNil) + c.So(ok, c.ShouldBeTrue) + }) +} func TestAuthz(t *testing.T) { t.Run("test auth seed", testAuthSeed) t.Run("test login", testLogin) t.Run("test logout", testLogout) - + t.Run("test del token", testDelToken) + t.Run("test put black list", testPutBlackList) } diff --git a/internal/biz/data.go b/internal/biz/data.go index 6376065..9740b36 100644 --- a/internal/biz/data.go +++ b/internal/biz/data.go @@ -14,7 +14,6 @@ import ( "github.com/begonia-org/go-sdk/logger" "github.com/bsm/redislock" "go.etcd.io/etcd/api/v3/mvccpb" - "google.golang.org/grpc/status" ) type DataLock interface { @@ -54,20 +53,23 @@ func (d *DataOperatorUsecase) Do(ctx context.Context) { if err != nil { d.log.Error(ctx, err) } + if err := d.doWatchEndpoint(ctx); err != nil { + d.log.Error(ctx, err) + + } }() d.log.Info(ctx, "start watch") - d.handle(ctx) + d.Handle(ctx) time.Sleep(3 * time.Second) } -func (d *DataOperatorUsecase) handle(ctx context.Context) { +func (d *DataOperatorUsecase) Handle(ctx context.Context) { errChan := make(chan error, 3) wg := &sync.WaitGroup{} actions := []operationAction{ d.loadUsersBlacklist, d.loadApps, - d.doWatchEndpoint, // d.loadLocalBloom, } for _, action := range actions { @@ -82,9 +84,6 @@ func (d *DataOperatorUsecase) handle(ctx context.Context) { go func() { for err := range errChan { if err != nil { - if st, ok := status.FromError(err); ok { - st.Details() - } d.log.Error(ctx, err) } @@ -104,8 +103,8 @@ func (d *DataOperatorUsecase) loadUsersBlacklist(ctx context.Context) error { // d.log.Infof(ctx, "lock key:%d", exp) lock, err := d.repo.Locker(ctx, lockKey, time.Second*time.Duration(exp)) if err != nil { - // d.log.Error("get lock error", err) - return fmt.Errorf("get lock error: %w", err) + d.log.Errorf(ctx, "get lock error:%s", err.Error()) + return fmt.Errorf("get lock error:%w", err) } @@ -114,7 +113,6 @@ func (d *DataOperatorUsecase) loadUsersBlacklist(ctx context.Context) error { return fmt.Errorf("lock error: %w", err) } defer func() { - err = lock.UnLock(ctx) if err != nil { // d.log.Error("unlock error", err) @@ -125,7 +123,6 @@ func (d *DataOperatorUsecase) loadUsersBlacklist(ctx context.Context) error { }() prefix := d.config.GetUserBlackListPrefix() lastUpdate, err := d.repo.LastUpdated(ctx, prefix) - // d.log.Infof("last update:%v", lastUpdate.Unix()) // 如果缓存时间小于3秒,说明刚刚更新过,不需要再次更新 // 直接加载远程缓存到本地 // lastUpdate ttl