Skip to content

Commit 3aca96d

Browse files
committed
ama: limit auth attempts per user auth, or use client ip if user auth is not set
1 parent 5f59c0e commit 3aca96d

1 file changed

Lines changed: 31 additions & 29 deletions

File tree

model/auth_model_attempt.go

Lines changed: 31 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ func maxUserAuthAttemptsError() error {
1515
return errors.New("503 User auth attempts exceeded limits.")
1616
}
1717

18-
const AttemptLookback = 5 * time.Minute
18+
const AttemptLookback = 1 * time.Minute
1919
const AttemptFailedCountThreshold = 10
2020

2121
func UserAuthAttempt(
@@ -78,7 +78,7 @@ func UserAuthAttempt(
7878
}
7979

8080
if userAuth != nil {
81-
// lookback by user auth
81+
// lookback by user auth and client ip hash
8282
var attempts []UserAuthAttemptResult
8383
result, err := tx.Query(
8484
session.Ctx,
@@ -89,12 +89,40 @@ func UserAuthAttempt(
8989
FROM user_auth_attempt
9090
WHERE
9191
user_auth = $1 AND
92-
now() - INTERVAL '1 seconds' * $2 <= attempt_time AND
92+
client_address_hash = $2 AND
93+
now() - INTERVAL '1 seconds' * $3 <= attempt_time AND
9394
success = false
9495
ORDER BY attempt_time DESC
9596
LIMIT $3
9697
`,
9798
userAuth,
99+
clientAddressHash[:],
100+
AttemptLookback/time.Second,
101+
AttemptFailedCountThreshold,
102+
)
103+
server.WithPgResult(result, err, func() {
104+
attempts = parseAttempts(result)
105+
})
106+
if !passesThreshold(attempts) {
107+
return
108+
}
109+
} else {
110+
var attempts []UserAuthAttemptResult
111+
result, err := tx.Query(
112+
session.Ctx,
113+
`
114+
SELECT
115+
attempt_time,
116+
success
117+
FROM user_auth_attempt
118+
WHERE
119+
client_address_hash = $1 AND
120+
now() - INTERVAL '1 seconds' * $2 <= attempt_time AND
121+
success = false
122+
ORDER BY attempt_time DESC
123+
LIMIT $3
124+
`,
125+
clientAddressHash[:],
98126
AttemptLookback/time.Second,
99127
AttemptFailedCountThreshold,
100128
)
@@ -104,32 +132,6 @@ func UserAuthAttempt(
104132
if !passesThreshold(attempts) {
105133
return
106134
}
107-
}
108-
109-
var attempts []UserAuthAttemptResult
110-
result, err := tx.Query(
111-
session.Ctx,
112-
`
113-
SELECT
114-
attempt_time,
115-
success
116-
FROM user_auth_attempt
117-
WHERE
118-
client_address_hash = $1 AND
119-
now() - INTERVAL '1 seconds' * $2 <= attempt_time AND
120-
success = false
121-
ORDER BY attempt_time DESC
122-
LIMIT $3
123-
`,
124-
clientAddressHash[:],
125-
AttemptLookback/time.Second,
126-
AttemptFailedCountThreshold,
127-
)
128-
server.WithPgResult(result, err, func() {
129-
attempts = parseAttempts(result)
130-
})
131-
if !passesThreshold(attempts) {
132-
return
133135
}
134136

135137
allow = true

0 commit comments

Comments
 (0)