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

validate blinded tokens submitted for tlv2 #2158

Merged
merged 6 commits into from
Oct 20, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
90 changes: 90 additions & 0 deletions services/skus/controllers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1601,6 +1601,96 @@ func (suite *ControllersTestSuite) TestE2E_CreateOrderCreds_StoreSignedOrderCred
suite.Assert().NotEmpty(response[0].SignedCreds)
}

func (suite *ControllersTestSuite) TestE2E_CreateOrderCreds_TooManyBlindedTokens_TimeLimitedV2() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

env := os.Getenv("ENV")
ctx = context.WithValue(ctx, appctx.EnvironmentCTXKey, env)

// setup kafka
kafkaUnsignedOrderCredsTopic = os.Getenv("GRANT_CBP_SIGN_CONSUMER_TOPIC")
kafkaSignedOrderCredsDLQTopic = os.Getenv("GRANT_CBP_SIGN_CONSUMER_TOPIC_DLQ")
kafkaSignedOrderCredsTopic = os.Getenv("GRANT_CBP_SIGN_PRODUCER_TOPIC")
kafkaSignedRequestReaderGroupID = test.RandomString()
ctx = skustest.SetupKafka(ctx, suite.T(), kafkaUnsignedOrderCredsTopic,
kafkaSignedOrderCredsDLQTopic, kafkaSignedOrderCredsTopic)

// create macaroon token for sku and whitelist
sku := test.RandomString()
price := 0
token := suite.CreateMacaroon(sku, price) // create macaroon has a buffer of 3 hardcoded, no overlap
ctx = context.WithValue(ctx, appctx.WhitelistSKUsCTXKey, []string{token})

// create order with order items
request := model.CreateOrderRequest{
Email: test.RandomString(),
Items: []model.OrderItemRequest{
{
SKU: token,
Quantity: 1,
},
},
}
client, err := cbr.New()
suite.Require().NoError(err)

retryPolicy = retrypolicy.NoRetry // set this so we fail fast

service := &Service{
issuerRepo: repository.NewIssuer(),
Datastore: suite.storage,
cbClient: client,
retry: backoff.Retry,
}

order, err := service.CreateOrderFromRequest(ctx, request)
suite.Require().NoError(err)

err = service.Datastore.UpdateOrder(order.ID, OrderStatusPaid) // to update the last paid at
suite.Require().NoError(err)

// Create order credentials for the newly create order
data := CreateOrderCredsRequest{
ItemID: order.Items[0].ID,
// these are already base64 encoded
BlindedCreds: []string{ // using 7 tokens should be too many for intervals 3, num per interval 2
"HLLrM7uBm4gVWr8Bsgx3M/yxDHVJX3gNow8Sx6sAPAY=",
"HLLrM7uBm4gVWr8Bsgx3M/yxDHVJX3gNow8Sx6sAPAY=",
"HLLrM7uBm4gVWr8Bsgx3M/yxDHVJX3gNow8Sx6sAPAY=",
"HLLrM7uBm4gVWr8Bsgx3M/yxDHVJX3gNow8Sx6sAPAY=",
"HLLrM7uBm4gVWr8Bsgx3M/yxDHVJX3gNow8Sx6sAPAY=",
"Hi1j/9Pen5vRvGSLn6eZCxgtkgZX7LU9edmOD2w5CWo=",
"YG07TqExOSoo/46SIWK42OG0of3z94Y5SzCswW6sYSw="},
}

payload, err := json.Marshal(data)
suite.Require().NoError(err)

requestID := uuid.NewV4().String()
ctx = context.WithValue(ctx, requestutils.RequestID, requestID)

r := httptest.NewRequest(http.MethodPost, fmt.Sprintf("/%s/credentials",
order.ID), bytes.NewBuffer(payload)).WithContext(ctx)

rw := httptest.NewRecorder()

skuService, err := InitService(ctx, suite.storage, nil, repository.NewOrder(), repository.NewIssuer())
suite.Require().NoError(err)

authMwr := NewAuthMwr(skuService)
instrumentHandler := func(name string, h http.Handler) http.Handler {
return h
}

router := Router(skuService, authMwr, instrumentHandler, newCORSOptsEnv())

server := &http.Server{Addr: ":8080", Handler: router}
server.Handler.ServeHTTP(rw, r)

suite.Require().Equal(http.StatusBadRequest, rw.Code) // should get 400 back too many credentials
}

// This test performs a full e2e test using challenge bypass server to sign time limited v2 order credentials.
// It uses three tokens and expects three signing results (which is determined by the issuer buffer/overlap and CBR)
// which translates to three time limited v2 order credentials being stored for the single order containing
Expand Down
26 changes: 25 additions & 1 deletion services/skus/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,14 @@ type TimeLimitedCreds struct {
Token string `json:"token"`
}

var (
numPerInterval = "numPerInterval"
numIntervals = "numIntervals"
errNumPerIntervalNotSet = errors.New("bad order: numPerInterval not set in order metadata")
errNumIntervalsNotSet = errors.New("bad order: numIntervals not set in order metadata")
errInvalidNumTokens = errors.New("submitted more blinded creds than allowed for order")
)

// CreateOrderItemCredentials creates the order credentials for the given order id using the supplied blinded credentials.
// If the order is unpaid an error ErrOrderUnpaid is returned.
func (s *Service) CreateOrderItemCredentials(ctx context.Context, orderID uuid.UUID, itemID uuid.UUID, blindedCreds []string) error {
Expand Down Expand Up @@ -247,12 +255,28 @@ func (s *Service) CreateOrderItemCredentials(ctx context.Context, orderID uuid.U
return errors.New("order item does not exist for order")
}

if orderItem.CredentialType == "single-use" {
if orderItem.CredentialType == singleUse {
if len(blindedCreds) > orderItem.Quantity {
return errors.New("submitted more blinded creds than quantity of order item")
}
}

if orderItem.CredentialType == timeLimitedV2 {
// check order "numPerInterval" from metadata and multiply it by the buffer added to offset
numPerInterval, ok := order.Metadata[numPerInterval].(float64)
if !ok {
return errNumPerIntervalNotSet
}
numIntervals, ok := order.Metadata[numIntervals].(float64)
if !ok {
return errNumIntervalsNotSet
}

if len(blindedCreds) > int(numPerInterval*numIntervals) {
return errInvalidNumTokens
}
}

issuerID, err := encodeIssuerID(order.MerchantID, orderItem.SKU)
if err != nil {
return errorutils.Wrap(err, "error encoding issuer name")
Expand Down
Loading