forked from mtusi2026/mtusi2026lab7
This commit is contained in:
@@ -6,7 +6,6 @@ import (
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -153,22 +152,6 @@ func attachmentVariant(query url.Values) (string, bool) {
|
||||
}
|
||||
}
|
||||
|
||||
var traceparentPattern = regexp.MustCompile(`^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$`)
|
||||
|
||||
func traceparent(value string) string {
|
||||
if traceparentPattern.MatchString(value) {
|
||||
return value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func tracestate(value string) string {
|
||||
if len(value) <= 512 {
|
||||
return value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func attachmentIDFromRequest(r *http.Request) (string, *apiError) {
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
attachmentID, valid := canonicalID(parts[3])
|
||||
|
||||
@@ -37,7 +37,7 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
|
||||
credentials, err := s.userRepository.UserByUsername(r.Context(), username)
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
|
||||
return internalError()
|
||||
return passwordOperationError(verifyErr)
|
||||
}
|
||||
return unauthorized()
|
||||
}
|
||||
@@ -46,7 +46,7 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
|
||||
}
|
||||
verified, err := s.passwords.Verify(passwordValue, credentials.PasswordHash)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
return passwordOperationError(err)
|
||||
}
|
||||
if !verified {
|
||||
return unauthorized()
|
||||
@@ -70,14 +70,14 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
|
||||
func (s *Server) rehashPassword(ctx context.Context, credentials model.UserCredentials, passwordValue string) *apiError {
|
||||
needsRehash, err := s.passwords.NeedsRehash(credentials.PasswordHash)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
return passwordOperationError(err)
|
||||
}
|
||||
if !needsRehash {
|
||||
return nil
|
||||
}
|
||||
passwordHash, err := s.passwords.Hash(passwordValue)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
return passwordOperationError(err)
|
||||
}
|
||||
updated, err := s.userRepository.UpdatePasswordHash(ctx, credentials.ID, credentials.PasswordHash, passwordHash)
|
||||
if err != nil {
|
||||
@@ -95,7 +95,7 @@ func (s *Server) rehashPassword(ctx context.Context, credentials model.UserCrede
|
||||
}
|
||||
verified, err := s.passwords.Verify(passwordValue, current.PasswordHash)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
return passwordOperationError(err)
|
||||
}
|
||||
if !verified {
|
||||
return unauthorized()
|
||||
|
||||
@@ -2,7 +2,10 @@ package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/password"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -40,6 +43,13 @@ func rateLimited() *apiError {
|
||||
return &apiError{http.StatusTooManyRequests, errorCodeRateLimited, "too many requests"}
|
||||
}
|
||||
|
||||
func passwordOperationError(err error) *apiError {
|
||||
if errors.Is(err, password.ErrBusy) {
|
||||
return rateLimited()
|
||||
}
|
||||
return internalError()
|
||||
}
|
||||
|
||||
func notFound() *apiError {
|
||||
return &apiError{http.StatusNotFound, errorCodeNotFound, "resource not found"}
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ func (s *Server) users(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
}
|
||||
passwordHash, err := s.passwords.Hash(input.Password)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
return passwordOperationError(err)
|
||||
}
|
||||
user, err := s.userRepository.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
|
||||
if errors.Is(err, model.ErrConflict) {
|
||||
|
||||
@@ -115,6 +115,7 @@ func (s *Server) MetricsHandler() http.Handler {
|
||||
}
|
||||
|
||||
func (s *Server) serveHealth(w http.ResponseWriter, r *http.Request, handler requestHandler) {
|
||||
w.Header().Set("X-Instance-Id", s.instanceID)
|
||||
if err := handler(w, r); err != nil {
|
||||
writeError(w, "", err)
|
||||
}
|
||||
@@ -168,6 +169,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
|
||||
if apiErr.status == http.StatusUnauthorized {
|
||||
wrapped.Header().Set("WWW-Authenticate", authenticationChallenge(r))
|
||||
}
|
||||
if apiErr.status == http.StatusTooManyRequests && wrapped.Header().Get("Retry-After") == "" {
|
||||
wrapped.Header().Set("Retry-After", "1")
|
||||
}
|
||||
writeError(wrapped, requestID, apiErr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/password"
|
||||
)
|
||||
|
||||
var errDependency = errors.New("dependency unavailable")
|
||||
@@ -254,6 +255,22 @@ func (s *MessengerSuite) TestSessionCreationReturnsRateLimitWithRetryAfter() {
|
||||
s.Contains(response.Body.String(), `"code":"rate_limited"`)
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestPasswordOperationLimitReturnsRateLimit() {
|
||||
registration := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{hashErr: password.ErrBusy})
|
||||
response := serveRequest(registration, http.MethodPost, "/api/v1/users", `{"username":"student","display_name":"Student","password":"T3st-password-123"}`)
|
||||
s.Equal(http.StatusTooManyRequests, response.Code)
|
||||
s.Equal("1", response.Header().Get("Retry-After"))
|
||||
|
||||
store := messengerStoreStub{credentials: model.UserCredentials{PasswordHash: "hash"}}
|
||||
login := s.newTestServer(store, sessionStub{}, passwordsStub{err: password.ErrBusy})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("student", "T3st-password-123")
|
||||
response = httptest.NewRecorder()
|
||||
login.Handler().ServeHTTP(response, request)
|
||||
s.Equal(http.StatusTooManyRequests, response.Code)
|
||||
s.Equal("1", response.Header().Get("Retry-After"))
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestSessionCreationRehashesPasswordWithCompareAndSwap() {
|
||||
var updated []string
|
||||
store := messengerStoreStub{
|
||||
|
||||
Reference in New Issue
Block a user