forked from mtusi2026/mtusi2026lab7
feat: secure messenger ingress and rate-limit logins
This commit is contained in:
@@ -34,9 +34,6 @@ ENV APP_PORT=8080
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD ["./messenger", "healthcheck"]
|
||||
|
||||
USER app:app
|
||||
|
||||
CMD ["./messenger"]
|
||||
|
||||
@@ -35,6 +35,10 @@ func serverAddress() string {
|
||||
}
|
||||
|
||||
func RunHTTP() error {
|
||||
tlsConfig, err := ingressTLS()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := repositories.UploadCleanupGrace(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -100,6 +104,7 @@ func RunHTTP() error {
|
||||
|
||||
server := &http.Server{
|
||||
Addr: serverAddress(),
|
||||
TLSConfig: tlsConfig,
|
||||
Handler: signals.HTTP(mux),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
@@ -119,7 +124,7 @@ func RunHTTP() error {
|
||||
go func() {
|
||||
log.Printf("server is listening on %s", server.Addr)
|
||||
|
||||
if err := server.ListenAndServe(); err != nil &&
|
||||
if err := server.ListenAndServeTLS(os.Getenv("TLS_CERT_FILE"), os.Getenv("TLS_KEY_FILE")); err != nil &&
|
||||
!errors.Is(err, http.ErrServerClosed) {
|
||||
serverErrors <- err
|
||||
}
|
||||
@@ -127,7 +132,7 @@ func RunHTTP() error {
|
||||
|
||||
select {
|
||||
case err := <-serverErrors:
|
||||
log.Printf("server error: %v", err)
|
||||
return err
|
||||
|
||||
case <-shutdownContext.Done():
|
||||
log.Printf("shutdown signal received")
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
func ingressTLS() (*tls.Config, error) {
|
||||
ca, err := os.ReadFile(os.Getenv("TLS_CA_FILE"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
if !roots.AppendCertsFromPEM(ca) {
|
||||
return nil, errors.New("invalid ingress client CA")
|
||||
}
|
||||
return &tls.Config{
|
||||
MinVersion: tls.VersionTLS12,
|
||||
ClientAuth: tls.RequireAndVerifyClientCert,
|
||||
ClientCAs: roots,
|
||||
VerifyConnection: func(state tls.ConnectionState) error {
|
||||
for _, identity := range state.PeerCertificates[0].URIs {
|
||||
if identity.String() == "urn:lab7:load-balancer" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("client certificate does not identify the load balancer")
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
@@ -3,7 +3,9 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -57,6 +59,24 @@ func sessionHandler(sessions *services.SessionService) http.HandlerFunc {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
// HAProxy overwrites this header and is the only mTLS identity allowed to reach the API.
|
||||
if r.TLS != nil {
|
||||
source := net.ParseIP(r.Header.Get("X-Forwarded-For"))
|
||||
if source == nil {
|
||||
writeError(w, 503, "unavailable", "missing ingress client address", requestID)
|
||||
return
|
||||
}
|
||||
retryAfter, err := sessions.LoginRetryAfter(r.Context(), source.String())
|
||||
if err != nil {
|
||||
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
||||
return
|
||||
}
|
||||
if retryAfter > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
|
||||
writeError(w, 429, "rate_limited", "too many login attempts", requestID)
|
||||
return
|
||||
}
|
||||
}
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || r.ContentLength > 0 {
|
||||
unauthorized(w, "Basic", requestID)
|
||||
|
||||
@@ -54,3 +54,19 @@ func (s *SessionStore) Revoke(ctx context.Context, tokenHash []byte) error {
|
||||
func (s *SessionStore) Ping(ctx context.Context) error {
|
||||
return s.client.Ping(ctx).Err()
|
||||
}
|
||||
|
||||
// Apply the expiry and increment atomically across replicas.
|
||||
var loginWindow = redis.NewScript(`
|
||||
local count = redis.call('INCR', KEYS[1])
|
||||
if count == 1 then
|
||||
redis.call('EXPIRE', KEYS[1], 60)
|
||||
end
|
||||
if count <= 12 then
|
||||
return 0
|
||||
end
|
||||
return math.max(1, redis.call('TTL', KEYS[1]))
|
||||
`)
|
||||
|
||||
func (s *SessionStore) LoginRetryAfter(ctx context.Context, source string) (int, error) {
|
||||
return loginWindow.Run(ctx, s.client, []string{"messenger:login:" + source}).Int()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package services
|
||||
|
||||
import "testing"
|
||||
|
||||
func BenchmarkPasswordVerification(b *testing.B) {
|
||||
const password = "synthetic-benchmark-password"
|
||||
hash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
ok, err := VerifyPassword(password, hash)
|
||||
if err != nil || !ok {
|
||||
b.Fatalf("verification failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,3 +81,7 @@ func (s *SessionService) Revoke(ctx context.Context, token string) error {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
return s.sessions.Revoke(ctx, hash[:])
|
||||
}
|
||||
|
||||
func (s *SessionService) LoginRetryAfter(ctx context.Context, source string) (int, error) {
|
||||
return s.sessions.LoginRetryAfter(ctx, source)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user