Skip to content

Commit

Permalink
fix: token endpoint rate limiting
Browse files Browse the repository at this point in the history
  • Loading branch information
nsklikas committed Mar 29, 2024
1 parent a42695b commit 3c6783b
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions handler/rfc8628/strategy_hmacsha.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
enigma "github.com/ory/fosite/token/hmac"
)

const POLLING_RATE_LIMITING_LEEWAY = 200

// DeviceFlowSession is a fosite.Session container specific for the device flow.
type DeviceFlowSession interface {
// GetBrowserFlowCompleted returns the flag indicating whether user has completed the browser flow or not.
Expand Down Expand Up @@ -182,10 +184,10 @@ func (h *DefaultDeviceStrategy) ShouldRateLimit(context context.Context, code st
timer.NotUntil = h.getExpirationTime(context, 1)
exp, err := h.serializeExpiration(timer)
if err != nil {
return false, err
return false, errorsx.WithStack(fosite.ErrServerError.WithHintf("Failed to serialize expiration struct %s", err))
}
// Set the expiration time as value, and use the lifespan of the device code as TTL.
h.RateLimiterCache.Set(keyBytes, exp, int(h.Config.GetDeviceAndUserCodeLifespan(context)))
h.RateLimiterCache.Set(keyBytes, exp, int(h.Config.GetDeviceAndUserCodeLifespan(context).Seconds()))
return false, nil
}

Expand All @@ -195,13 +197,13 @@ func (h *DefaultDeviceStrategy) ShouldRateLimit(context context.Context, code st
}

// The code is valid and enough time has passed since the last call.
if expiration.NotUntil.Before(time.Now()) {
if time.Since(expiration.NotUntil).Milliseconds() > -POLLING_RATE_LIMITING_LEEWAY {
expiration.NotUntil = h.getExpirationTime(context, expiration.Counter)
exp, err := h.serializeExpiration(expiration)
if err != nil {
return false, err
return false, errorsx.WithStack(fosite.ErrServerError.WithHintf("Failed to serialize expiration struct %s", err))
}
h.RateLimiterCache.Set(keyBytes, exp, int(h.Config.GetDeviceAndUserCodeLifespan(context)))
h.RateLimiterCache.Set(keyBytes, exp, int(h.Config.GetDeviceAndUserCodeLifespan(context).Seconds()))
return false, nil
}

Expand All @@ -210,9 +212,9 @@ func (h *DefaultDeviceStrategy) ShouldRateLimit(context context.Context, code st
expiration.Counter += 1
exp, err := h.serializeExpiration(expiration)
if err != nil {
return false, err
return false, errorsx.WithStack(fosite.ErrServerError.WithHintf("Failed to serialize expiration struct %s", err))
}
h.RateLimiterCache.Set(keyBytes, exp, int(h.Config.GetDeviceAndUserCodeLifespan(context)))
h.RateLimiterCache.Set(keyBytes, exp, int(h.Config.GetDeviceAndUserCodeLifespan(context).Seconds()))

return true, nil
}
Expand Down

0 comments on commit 3c6783b

Please sign in to comment.