Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EX-3238-require-dev-license #25

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions charts/token-exchange-api/values-prod.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ env:
USERS_API_GRPC_ADDRESS: users-api-prod:8086
CONTRACT_ADDRESS_WHITELIST: 0xba5738a18d83d41847dffbdc6101d37c69c9b0cf,0x3b07e2A2ABdd0A9B8F7878bdE6487c502164B9dd
CONTRACT_ADDRESS_SACD: '0x3c152B5d96769661008Ff404224d6530FCAC766d'
IDENTITY_URL: 'http://identity-api:8080/query'
DEV_LICENSE_VALIDATOR_FEATURE_FLAG: true
resources:
limits:
cpu: 1
Expand Down
2 changes: 2 additions & 0 deletions charts/token-exchange-api/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ env:
USERS_API_GRPC_ADDRESS: users-api-dev:8086
CONTRACT_ADDRESS_WHITELIST: 0x45fbcd3ef7361d156e8b16f5538ae36dedf61da8,0xA4ad0F9c722588910791A9BAC63ADbB365614Bc7
CONTRACT_ADDRESS_SACD: '0x4E5F9320b1c7cB3DE5ebDD760aD67375B66cF8a3'
IDENTITY_URL: 'http://identity-api-dev:8080/query'
DEV_LICENSE_VALIDATOR_FEATURE_FLAG: true
service:
type: ClusterIP
ports:
Expand Down
11 changes: 10 additions & 1 deletion cmd/token-exchange-api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"syscall"

"github.com/DIMO-Network/token-exchange-api/internal/contracts"
"github.com/DIMO-Network/token-exchange-api/internal/middleware"
"github.com/ethereum/go-ethereum/common"

"github.com/DIMO-Network/token-exchange-api/internal/api"
Expand Down Expand Up @@ -48,6 +49,9 @@ func startWebAPI(ctx context.Context, logger zerolog.Logger, settings *config.Se
contractsMgr := contracts.NewContractsManager()
contractsInit := contracts.NewContractsCallInitializer()
vtxController := vtx.NewTokenExchangeController(&logger, settings, dxS, userService, contractsMgr, contractsInit)
idSvc := services.NewIdentityController(&logger, settings)

devLicenseMiddleware := middleware.NewDevLicenseValidator(idSvc, logger)

ctrAddressesWhitelist, err := getContractWhitelistedAddresses(settings.ContractAddressWhitelist)
if err != nil {
Expand Down Expand Up @@ -82,10 +86,15 @@ func startWebAPI(ctx context.Context, logger zerolog.Logger, settings *config.Se
JWKSetURLs: []string{settings.JWKKeySetURL},
})

handlers := []fiber.Handler{jwtAuth}
if settings.DevLiscFeatureFlag {
handlers = append(handlers, devLicenseMiddleware)
}

// All api routes should be under v1
v1Route := app.Group("/v1")
// Token routes
tokenRoutes := v1Route.Group("/tokens", jwtAuth)
tokenRoutes := v1Route.Group("/tokens", handlers...)
ctrWhitelistWare := mware.NewContractWhiteList(settings, logger, ctrAddressesWhitelist)

tokenRoutes.Post("/exchange", ctrWhitelistWare, vtxController.GetDeviceCommandPermissionWithScope)
Expand Down
7 changes: 4 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ require (
github.com/rs/zerolog v1.32.0
github.com/stretchr/testify v1.8.4
github.com/swaggo/swag v1.16.3
github.com/tidwall/gjson v1.17.1
github.com/tidwall/gjson v1.18.0
go.uber.org/mock v0.4.0
golang.org/x/exp v0.0.0-20240213143201-ec583247a57a
google.golang.org/grpc v1.61.1
Expand Down Expand Up @@ -52,10 +52,11 @@ require (
github.com/supranational/blst v0.3.11 // indirect
github.com/swaggo/files/v2 v2.0.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
golang.org/x/mod v0.15.0 // indirect
golang.org/x/sync v0.6.0 // indirect
golang.org/x/time v0.5.0 // indirect
golang.org/x/tools v0.18.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240213162025-012b6fc9bca9 // indirect
rsc.io/tmplfunc v0.0.3 // indirect
Expand Down Expand Up @@ -92,6 +93,6 @@ require (
golang.org/x/net v0.21.0 // indirect
golang.org/x/sys v0.17.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/protobuf v1.32.0 // indirect
google.golang.org/protobuf v1.32.0
gopkg.in/yaml.v3 v3.0.1 // indirect
)
11 changes: 5 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -207,13 +207,12 @@ github.com/swaggo/swag v1.16.3 h1:PnCYjPCah8FK4I26l2F/KQ4yz3sILcVUN3cTlBFA9Pg=
github.com/swaggo/swag v1.16.3/go.mod h1:DImHIuOFXKpMFAQjcC7FG4m3Dg4+QuUgUzJmKjI/gRk=
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY=
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc=
github.com/tidwall/gjson v1.17.1 h1:wlYEnwqAHgzmhNUFfw7Xalt2JzQvsMx2Se4PcoFCT/U=
github.com/tidwall/gjson v1.17.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tklauser/go-sysconf v0.3.13 h1:GBUpcahXSpR2xN01jhkNAbTLRk2Yzgggk8IM08lq3r4=
github.com/tklauser/go-sysconf v0.3.13/go.mod h1:zwleP4Q4OehZHGn4CYZDipCgg9usW5IJePewFCGVEa0=
github.com/tklauser/numcpus v0.7.0 h1:yjuerZP127QG9m5Zh/mSO4wqurYil27tHrqwRoRjpr4=
Expand Down Expand Up @@ -253,8 +252,8 @@ golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.18.0 h1:k8NLag8AGHnn+PHbl7g43CtqZAwG60vZkLqgyZgIHgQ=
golang.org/x/tools v0.18.0/go.mod h1:GL7B4CwcLLeo59yx/9UWWuNOW1n3VZ4f5axWfML7Lcg=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
Expand Down
2 changes: 2 additions & 0 deletions internal/config/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ type Settings struct {
UsersAPIGRPCAddress string `yaml:"USERS_API_GRPC_ADDRESS"`
ContractAddressWhitelist string `yaml:"CONTRACT_ADDRESS_WHITELIST"`
ContractAddressSacd string `yaml:"CONTRACT_ADDRESS_SACD"`
IdentityURL string `yaml:"IDENTITY_URL"`
Allyson-English marked this conversation as resolved.
Show resolved Hide resolved
DevLiscFeatureFlag bool `yaml:"DEV_LICENSE_VALIDATOR_FEATURE_FLAG"`
}
96 changes: 89 additions & 7 deletions internal/controllers/token_exchange_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (

"github.com/DIMO-Network/token-exchange-api/internal/config"
mock_contracts "github.com/DIMO-Network/token-exchange-api/internal/contracts/mocks"
"github.com/DIMO-Network/token-exchange-api/internal/middleware"
mock_middleware "github.com/DIMO-Network/token-exchange-api/internal/middleware/mocks"
"github.com/DIMO-Network/token-exchange-api/internal/services"
mock_services "github.com/DIMO-Network/token-exchange-api/internal/services/mocks"
"github.com/DIMO-Network/users-api/pkg/grpc"
Expand Down Expand Up @@ -70,14 +72,14 @@ func TestTokenExchangeController_GetDeviceCommandPermissionWithScope(t *testing.
permissionTokenRequest: &PermissionTokenRequest{
TokenID: 123,
Privileges: []int64{4},
NFTContractAddress: "0x90c4d6113ec88dd4bdf12f26db2b3998fd13a144",
NFTContractAddress: "0x90C4D6113Ec88dd4BDf12f26DB2b3998fd13A144",
Comment on lines -73 to +75
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nothing wrong here but because I am lazy I often do this to get the correct check sum string in tests

common.HexToAddress("0x90c4d6113ec88dd4bdf12f26db2b3998fd13a144").String()

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this matter? Are we doing string equality anywhere?

},
mockSetup: func() {
dexService.EXPECT().SignPrivilegePayload(gomock.Any(), services.PrivilegeTokenDTO{
UserEthAddress: userEthAddr.Hex(),
TokenID: strconv.FormatInt(123, 10),
PrivilegeIDs: []int64{4},
NFTContractAddress: "0x90c4d6113ec88dd4bdf12f26db2b3998fd13a144",
NFTContractAddress: "0x90C4D6113Ec88dd4BDf12f26DB2b3998fd13A144",
Audience: defaultAudience,
}).Return("jwt", nil)
mockMultiPriv.EXPECT().HasPrivilege(nil, big.NewInt(123), big.NewInt(4), userEthAddr).
Expand All @@ -95,14 +97,14 @@ func TestTokenExchangeController_GetDeviceCommandPermissionWithScope(t *testing.
permissionTokenRequest: &PermissionTokenRequest{
TokenID: 123,
Privileges: []int64{4},
NFTContractAddress: "0x90c4d6113ec88dd4bdf12f26db2b3998fd13a144",
NFTContractAddress: "0x90C4D6113Ec88dd4BDf12f26DB2b3998fd13A144",
},
mockSetup: func() {
dexService.EXPECT().SignPrivilegePayload(gomock.Any(), services.PrivilegeTokenDTO{
UserEthAddress: userEthAddr.Hex(),
TokenID: strconv.FormatInt(123, 10),
PrivilegeIDs: []int64{4},
NFTContractAddress: "0x90c4d6113ec88dd4bdf12f26db2b3998fd13a144",
NFTContractAddress: "0x90C4D6113Ec88dd4BDf12f26DB2b3998fd13A144",
Audience: defaultAudience,
}).Return("jwt", nil)
mockMultiPriv.EXPECT().HasPrivilege(nil, big.NewInt(123), big.NewInt(4), userEthAddr).
Expand All @@ -125,15 +127,15 @@ func TestTokenExchangeController_GetDeviceCommandPermissionWithScope(t *testing.
permissionTokenRequest: &PermissionTokenRequest{
TokenID: 123,
Privileges: []int64{4},
NFTContractAddress: "0x90c4d6113ec88dd4bdf12f26db2b3998fd13a144",
NFTContractAddress: "0x90C4D6113Ec88dd4BDf12f26DB2b3998fd13A144",
Audience: []string{"my-app", "foo"},
},
mockSetup: func() {
dexService.EXPECT().SignPrivilegePayload(gomock.Any(), services.PrivilegeTokenDTO{
UserEthAddress: userEthAddr.Hex(),
TokenID: strconv.FormatInt(123, 10),
PrivilegeIDs: []int64{4},
NFTContractAddress: "0x90c4d6113ec88dd4bdf12f26db2b3998fd13a144",
NFTContractAddress: "0x90C4D6113Ec88dd4BDf12f26DB2b3998fd13A144",
Audience: []string{"my-app", "foo"},
}).Return("jwt", nil)
mockMultiPriv.EXPECT().HasPrivilege(nil, big.NewInt(123), big.NewInt(4), userEthAddr).
Expand All @@ -151,7 +153,7 @@ func TestTokenExchangeController_GetDeviceCommandPermissionWithScope(t *testing.
permissionTokenRequest: &PermissionTokenRequest{
TokenID: 123,
Privileges: []int64{4},
NFTContractAddress: "0x90c4d6113ec88dd4bdf12f26db2b3998fd13a144",
NFTContractAddress: "0x90C4D6113Ec88dd4BDf12f26DB2b3998fd13A144",
},
mockSetup: func() {
usersSvc.EXPECT().GetUserByID(gomock.Any(), "user-id-123").Return(nil, fmt.Errorf("not found"))
Expand Down Expand Up @@ -186,6 +188,86 @@ func TestTokenExchangeController_GetDeviceCommandPermissionWithScope(t *testing.
}
}

const (
developerAuthToken = `Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6ImRkNTFkNDkwYjc1Y2VhOTNlMGI3YWI2YzcwODczNWVlN2FmZDBmMDgifQ.eyJpc3MiOiJodHRwczovL2F1dGguZGltby56b25lIiwicHJvdmlkZXJfaWQiOiJ3ZWIzIiwic3ViIjoiQ2lvd2VEWmxNMlk1Um1FME1VUTFOV1kzTWpZd05UQkRNelZsWVRaQlJtVmtOalZsTURZME1XSTVOVGNTQkhkbFlqTSI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joiN29RUmZoRi1meFAwQWNPbEE0N2ZJdyIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiZXRoZXJldW1fYWRkcmVzcyI6IjB4YTkzYjdiYzFFMzU2ODYyNzk0ODA0NkYwZTQ4MDRDYzlBZkMxMjc3ZSJ9.yQmArmywbuZm2LvNSvmretbg18cfBZmqR7FBEtJJy47YuqasyiNCjtnb1MM2yTnk_DWnMfEvtbKX8wG3fVfv777lcmwXzZZqVbZ0R9ekUXxi3mvSvgPe82C1OIa-B1Tep6PweW0oqr5OU_L17yxBEpFJ8lRVBYdLCPScVCWFHovLFulG2uEGWheuNcjAKxuB1yGzqGMK7JlpgzKPgUSuRweL3sR6Z7WKrefaZiHNwmknOfuZHMHO0z4EbEnemYvH6uNaGDbExd3VbOOXjzAOQMDeuluftCLAWuq0xIu4uLHfeQvkVzjnq7rVEM6lTOSITIdeapP2IDEKDTJY5Tx0qg`
)

func TestDevLicenseMiddleware(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()

logger := zerolog.New(os.Stdout).With().
Timestamp().
Str("app", "token-exchange-api").
Logger()

idSvc := mock_middleware.NewMockIdentityService(mockCtrl)

tests := []struct {
name string
token string
validDevLicense bool
developerLicense common.Address
dimoMobile bool
expectedCode int
}{
{
name: "DIMO mobile",
token: mobileAuthToken,
dimoMobile: true,
expectedCode: fiber.StatusOK,
},
{
name: "Developer license",
token: developerAuthToken,
validDevLicense: true,
developerLicense: common.HexToAddress("0x6e3f9Fa41D55f726050C35ea6AFed65e0641b957"),
expectedCode: fiber.StatusOK,
},
{
name: "Invalid developer license",
token: developerAuthToken,
developerLicense: common.HexToAddress("0x6e3f9Fa41D55f726050C35ea6AFed65e0641b957"),
expectedCode: fiber.StatusForbidden,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
devLicenseMiddleware := middleware.NewDevLicenseValidator(idSvc, logger)
app := fiber.New()
app.Get("/",
func(c *fiber.Ctx) error {
authHeader := c.Get("Authorization")
tk := strings.TrimPrefix(authHeader, "Bearer ")
token, _, _ := new(jwt.Parser).ParseUnverified(tk, jwt.MapClaims{})
c.Locals("user", token)
return c.Next()
},

devLicenseMiddleware,

func(c *fiber.Ctx) error { return c.SendStatus(fiber.StatusOK) })

if !tc.dimoMobile {
if tc.validDevLicense {
idSvc.EXPECT().IsDevLicense(gomock.Any(), tc.developerLicense).Return(true, nil)
} else {
idSvc.EXPECT().IsDevLicense(gomock.Any(), tc.developerLicense).Return(false, nil)
}
}

request := buildRequest("GET", "/", "")
request.Header.Set("Authorization", tc.token)
response, err := app.Test(request)
require.NoError(t, err)

assert.Equal(t, tc.expectedCode, response.StatusCode)

})
}
}

func buildRequest(method, url, body string) *http.Request {
req, _ := http.NewRequest(
method,
Expand Down
Loading
Loading