forked from mtusi2026/mtusi2026lab7
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8edaf058d |
@@ -37,7 +37,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
go-version: "1.26.10"
|
||||
cache: false
|
||||
|
||||
- name: Check contract
|
||||
@@ -108,6 +108,10 @@ jobs:
|
||||
make test-worker-compromise ENV_FILE=.env
|
||||
make scan-security
|
||||
ENV_FILE=.env CA_FILE=.runtime/security/public-ca/ca.crt PROMETHEUS_URL=http://prometheus:9090 TEMPO_URL=http://tempo:3200 LOKI_URL=http://loki:3100 make test-lab6-smoke BASE_URL=https://nginx:8443
|
||||
mkdir -p evidence/runtime
|
||||
api_restart_counts=$(docker inspect --format '{{.RestartCount}}' $(docker compose ps -q api))
|
||||
go run ./cmd/loginburst -base-url=https://nginx:8443 -ca-file=.runtime/security/public-ca/ca.crt > evidence/runtime/login-burst.json
|
||||
test "$(docker inspect --format '{{.RestartCount}}' $(docker compose ps -q api))" = "$api_restart_counts"
|
||||
|
||||
- name: Container logs
|
||||
if: failure()
|
||||
@@ -123,6 +127,7 @@ jobs:
|
||||
path: |
|
||||
${{ env.CI_WORKSPACE }}/evidence/lab7-*.json
|
||||
${{ env.CI_WORKSPACE }}/evidence/runtime/security-scan
|
||||
${{ env.CI_WORKSPACE }}/evidence/runtime/login-burst.json
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
@@ -131,6 +136,7 @@ jobs:
|
||||
run: |
|
||||
test -d "$CI_WORKSPACE" || exit 0
|
||||
cd "$CI_WORKSPACE"
|
||||
trap './scripts/sync-docker-workspace.sh --clean' EXIT
|
||||
docker network disconnect "${COMPOSE_PROJECT_NAME}_secrets" "$HOSTNAME" 2>/dev/null || true
|
||||
docker network disconnect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME" 2>/dev/null || true
|
||||
docker network disconnect "${COMPOSE_PROJECT_NAME}_data" "$HOSTNAME" 2>/dev/null || true
|
||||
|
||||
@@ -51,7 +51,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
go-version: "1.26.10"
|
||||
cache: false
|
||||
|
||||
- name: Check contract
|
||||
@@ -120,6 +120,10 @@ jobs:
|
||||
make test-lab5-acceptance
|
||||
make test-worker-compromise ENV_FILE=.env
|
||||
ENV_FILE=.env CA_FILE=.runtime/security/public-ca/ca.crt PROMETHEUS_URL=http://prometheus:9090 TEMPO_URL=http://tempo:3200 LOKI_URL=http://loki:3100 make test-lab6-smoke BASE_URL=https://nginx:8443
|
||||
mkdir -p evidence/runtime
|
||||
api_restart_counts=$(docker inspect --format '{{.RestartCount}}' $(docker compose ps -q api))
|
||||
go run ./cmd/loginburst -base-url=https://nginx:8443 -ca-file=.runtime/security/public-ca/ca.crt > evidence/runtime/login-burst.json
|
||||
test "$(docker inspect --format '{{.RestartCount}}' $(docker compose ps -q api))" = "$api_restart_counts"
|
||||
|
||||
- name: Publish verified images
|
||||
id: publish
|
||||
@@ -157,6 +161,7 @@ jobs:
|
||||
run: |
|
||||
test -d "$CI_WORKSPACE" || exit 0
|
||||
cd "$CI_WORKSPACE"
|
||||
trap './scripts/sync-docker-workspace.sh --clean' EXIT
|
||||
docker network disconnect "${COMPOSE_PROJECT_NAME}_secrets" "$HOSTNAME" 2>/dev/null || true
|
||||
docker network disconnect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME" 2>/dev/null || true
|
||||
docker network disconnect "${COMPOSE_PROJECT_NAME}_data" "$HOSTNAME" 2>/dev/null || true
|
||||
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
go-version: "1.26.10"
|
||||
cache: false
|
||||
|
||||
- name: Prepare stack
|
||||
@@ -88,6 +88,7 @@ jobs:
|
||||
run: |
|
||||
test -d "$CI_WORKSPACE" || exit 0
|
||||
cd "$CI_WORKSPACE"
|
||||
trap './scripts/sync-docker-workspace.sh --clean' EXIT
|
||||
docker network disconnect "${COMPOSE_PROJECT_NAME}_secrets" "$HOSTNAME" 2>/dev/null || true
|
||||
docker network disconnect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME" 2>/dev/null || true
|
||||
docker network disconnect "${COMPOSE_PROJECT_NAME}_data" "$HOSTNAME" 2>/dev/null || true
|
||||
|
||||
@@ -82,7 +82,9 @@ PostgreSQL использует `verify-full` и отдельные роли API
|
||||
|
||||
Пароли хешируются Argon2id с индивидуальной солью и сохранёнными параметрами. При успешном входе `NeedsRehash` сравнивает параметры хеша с текущей политикой; устаревший хеш обновляется compare-and-swap запросом, поэтому параллельный login не перезаписывает более новый пароль.
|
||||
|
||||
Параметры `m=65536 KiB`, `t=3`, `p=2` измерены в Linux-контейнере с лимитом 2 CPU и 512 MiB. Пять операций дали около 60,0 мс на hash и 64,8 мс на verify при примерно 64 MiB памяти на операцию. Это сохраняет заметную цену offline-перебора, но ограничивает теоретический последовательный login budget примерно 15 проверками в секунду на одной реплике. Поэтому до дорогого verify применяется общий rate limit: 5 попыток на login и 20 на source address за минуту. Raw summary сохранён в `evidence/lab7-argon2-budget.json`.
|
||||
Параметры `m=65536 KiB`, `t=3`, `p=2` измерены в Linux-контейнере с лимитом 2 CPU и 512 MiB. Пять операций дали около 60,0 мс на hash и 64,8 мс на verify при примерно 64 MiB памяти на операцию. Частотный лимит ограничивает login, а общий semaphore внутри Hasher допускает не более двух `Hash`/`Verify` на API-реплику, включая регистрацию и rehash. Поэтому одновременно занятая Argon2 память ограничена примерно 128 MiB на реплику; лишние операции сразу получают `429 Retry-After: 1`. Лимит задаётся `server.password.max_concurrent_operations`. Raw summary сохранён в `evidence/lab7-argon2-budget.json`.
|
||||
|
||||
`cmd/loginburst` создаёт одновременные волны по 20 регистраций и login-запросов через Nginx, проверяет ответы `429` с положительным `Retry-After`, отсутствие `5xx` и readiness после нагрузки. CI дополнительно проверяет, что API containers не перезапускались. `X-Instance-Id` — случайный alias на время жизни процесса; hostname и IP в него не входят.
|
||||
|
||||
Session token является случайным opaque bearer token. В Valkey сохраняется только его SHA-256 hash с TTL; logout удаляет запись. Login limiter общий для API-реплик: Lua script атомарно увеличивает счётчики по нормализованному login и адресу источника, выставляет TTL и возвращает время до повторной попытки. При превышении лимита API отвечает `429` и положительным `Retry-After`.
|
||||
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type result struct {
|
||||
status int
|
||||
retryAfter string
|
||||
instance string
|
||||
duration time.Duration
|
||||
err error
|
||||
}
|
||||
|
||||
type phase struct {
|
||||
Name string `json:"name"`
|
||||
Requests int `json:"requests"`
|
||||
Statuses map[int]int `json:"statuses"`
|
||||
DurationMS int64 `json:"duration_ms"`
|
||||
P95MS int64 `json:"p95_ms"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
var (
|
||||
baseURL = flag.String("base-url", "https://localhost:8443", "API endpoint")
|
||||
caFile = flag.String("ca-file", ".runtime/security/public-ca/ca.crt", "trusted public CA")
|
||||
count = flag.Int("requests", 20, "concurrent requests per phase")
|
||||
)
|
||||
flag.Parse()
|
||||
if *count < 8 || *count > 100 {
|
||||
return errors.New("requests must be between 8 and 100")
|
||||
}
|
||||
ca, err := os.ReadFile(*caFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
if !roots.AppendCertsFromPEM(ca) {
|
||||
return errors.New("invalid public CA")
|
||||
}
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS13, RootCAs: roots},
|
||||
DisableKeepAlives: true, MaxConnsPerHost: *count,
|
||||
}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &http.Client{Transport: transport, Timeout: 10 * time.Second}
|
||||
username := fmt.Sprintf("burst_%d", time.Now().UnixNano())
|
||||
body, err := json.Marshal(map[string]string{
|
||||
"username": username, "display_name": "Login burst", "password": "T3st-burst-password-123",
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
register, err := burst(client, *count, "registration", func(index int) (*http.Request, error) {
|
||||
request, err := http.NewRequest(http.MethodPost, *baseURL+"/api/v1/users", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
return request, nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
login, err := burst(client, *count, "login", func(index int) (*http.Request, error) {
|
||||
request, err := http.NewRequest(http.MethodPost, *baseURL+"/api/v1/auth/sessions", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.SetBasicAuth(fmt.Sprintf("%s_%d", username, index), "wrong-password")
|
||||
return request, nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
response, err := client.Get(*baseURL + "/health/ready")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = response.Body.Close() }()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("readiness after burst: HTTP %d", response.StatusCode)
|
||||
}
|
||||
return json.NewEncoder(os.Stdout).Encode(struct {
|
||||
Phases []phase `json:"phases"`
|
||||
Ready bool `json:"ready_after_burst"`
|
||||
}{[]phase{register, login}, true})
|
||||
}
|
||||
|
||||
func burst(client *http.Client, count int, name string, request func(int) (*http.Request, error)) (phase, error) {
|
||||
var (
|
||||
start = make(chan struct{})
|
||||
results = make(chan result, count)
|
||||
group sync.WaitGroup
|
||||
instances = make(map[string]struct{})
|
||||
statuses = make(map[int]int)
|
||||
durations = make([]time.Duration, 0, count)
|
||||
started = time.Now()
|
||||
)
|
||||
for index := range count {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
<-start
|
||||
began := time.Now()
|
||||
value, err := request(index)
|
||||
if err != nil {
|
||||
results <- result{err: err}
|
||||
return
|
||||
}
|
||||
response, err := client.Do(value)
|
||||
if err != nil {
|
||||
results <- result{err: err}
|
||||
return
|
||||
}
|
||||
_, copyErr := io.Copy(io.Discard, response.Body)
|
||||
_ = response.Body.Close()
|
||||
results <- result{response.StatusCode, response.Header.Get("Retry-After"), response.Header.Get("X-Instance-Id"), time.Since(began), copyErr}
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
group.Wait()
|
||||
close(results)
|
||||
for value := range results {
|
||||
if value.err != nil {
|
||||
return phase{}, fmt.Errorf("%s burst: %w", name, value.err)
|
||||
}
|
||||
if value.status == http.StatusTooManyRequests {
|
||||
retryAfter, err := strconv.Atoi(value.retryAfter)
|
||||
if err != nil || retryAfter < 1 {
|
||||
return phase{}, errors.New("overload response has no positive Retry-After")
|
||||
}
|
||||
}
|
||||
allowed := value.status == http.StatusTooManyRequests
|
||||
if name == "registration" {
|
||||
allowed = allowed || value.status == http.StatusCreated || value.status == http.StatusConflict
|
||||
} else {
|
||||
allowed = allowed || value.status == http.StatusUnauthorized
|
||||
}
|
||||
if !allowed {
|
||||
return phase{}, fmt.Errorf("%s burst: unexpected HTTP %d", name, value.status)
|
||||
}
|
||||
statuses[value.status]++
|
||||
durations = append(durations, value.duration)
|
||||
if strings.TrimSpace(value.instance) != "" {
|
||||
instances[value.instance] = struct{}{}
|
||||
}
|
||||
}
|
||||
if statuses[http.StatusTooManyRequests] == 0 || len(instances) < 2 {
|
||||
return phase{}, fmt.Errorf("%s burst: expected overload across two replicas, statuses=%v instances=%d", name, statuses, len(instances))
|
||||
}
|
||||
sort.Slice(durations, func(i, j int) bool { return durations[i] < durations[j] })
|
||||
return phase{name, count, statuses, time.Since(started).Milliseconds(), durations[(count*95+99)/100-1].Milliseconds()}, nil
|
||||
}
|
||||
@@ -344,6 +344,7 @@ services:
|
||||
profiles: ["tools"]
|
||||
image: openbao/openbao:2.7.1
|
||||
user: "0:0"
|
||||
entrypoint: ["bao"]
|
||||
environment:
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/security/openbao/ca.crt
|
||||
|
||||
@@ -29,6 +29,7 @@ server:
|
||||
parallelism: 2
|
||||
salt_length: 16
|
||||
key_length: 32
|
||||
max_concurrent_operations: 2
|
||||
|
||||
database:
|
||||
min_connections: 1
|
||||
|
||||
@@ -7,10 +7,11 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/loginlimit"
|
||||
@@ -48,10 +49,11 @@ func RunServer() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
instanceID, err := os.Hostname()
|
||||
instanceUUID, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
instanceID := "api-" + instanceUUID.String()
|
||||
observability, logger, err := startTelemetry("messenger-api", instanceID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -90,7 +92,7 @@ func RunServer() error {
|
||||
MemoryKiB: settings.PasswordMemoryKiB, Iterations: settings.PasswordIterations,
|
||||
Parallelism: settings.PasswordParallelism, SaltLength: settings.PasswordSaltLength,
|
||||
KeyLength: settings.PasswordKeyLength,
|
||||
})
|
||||
}, settings.PasswordMaxConcurrentOperations)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+54
-48
@@ -12,53 +12,54 @@ import (
|
||||
)
|
||||
|
||||
type ServerConfig struct {
|
||||
Address string
|
||||
HealthAddress string
|
||||
MetricsAddress string
|
||||
TLSCAPath string
|
||||
TLSCertificatePath string
|
||||
TLSPrivateKeyPath string
|
||||
TLSAllowedClientURI string
|
||||
TLSAllowedMetricsClientURI string
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
CacheTLS ClientTLSConfig
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
LoginRateLimitAccountAttempts int
|
||||
LoginRateLimitSourceAttempts int
|
||||
LoginRateLimitWindow time.Duration
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
RequestTimeout time.Duration
|
||||
HTTPReadHeaderTimeout time.Duration
|
||||
HTTPReadTimeout time.Duration
|
||||
HTTPWriteTimeout time.Duration
|
||||
HTTPIdleTimeout time.Duration
|
||||
HTTPShutdownTimeout time.Duration
|
||||
PasswordMemoryKiB uint32
|
||||
PasswordIterations uint32
|
||||
PasswordParallelism uint8
|
||||
PasswordSaltLength uint32
|
||||
PasswordKeyLength uint32
|
||||
SwaggerPort string
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3UseTLS bool
|
||||
S3CAPath string
|
||||
S3Timeout time.Duration
|
||||
AttachmentMaxBytes int64
|
||||
AttachmentMaxPixels int64
|
||||
AttachmentBodyMemory int64
|
||||
AttachmentDecodeMemory int64
|
||||
PipelineVersion int
|
||||
Address string
|
||||
HealthAddress string
|
||||
MetricsAddress string
|
||||
TLSCAPath string
|
||||
TLSCertificatePath string
|
||||
TLSPrivateKeyPath string
|
||||
TLSAllowedClientURI string
|
||||
TLSAllowedMetricsClientURI string
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
CacheTLS ClientTLSConfig
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
LoginRateLimitAccountAttempts int
|
||||
LoginRateLimitSourceAttempts int
|
||||
LoginRateLimitWindow time.Duration
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
RequestTimeout time.Duration
|
||||
HTTPReadHeaderTimeout time.Duration
|
||||
HTTPReadTimeout time.Duration
|
||||
HTTPWriteTimeout time.Duration
|
||||
HTTPIdleTimeout time.Duration
|
||||
HTTPShutdownTimeout time.Duration
|
||||
PasswordMemoryKiB uint32
|
||||
PasswordIterations uint32
|
||||
PasswordParallelism uint8
|
||||
PasswordSaltLength uint32
|
||||
PasswordKeyLength uint32
|
||||
PasswordMaxConcurrentOperations int
|
||||
SwaggerPort string
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3UseTLS bool
|
||||
S3CAPath string
|
||||
S3Timeout time.Duration
|
||||
AttachmentMaxBytes int64
|
||||
AttachmentMaxPixels int64
|
||||
AttachmentBodyMemory int64
|
||||
AttachmentDecodeMemory int64
|
||||
PipelineVersion int
|
||||
}
|
||||
|
||||
type MigrationConfig struct {
|
||||
@@ -251,6 +252,10 @@ func LoadServer() (ServerConfig, error) {
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
passwordMaxConcurrentOperations, err := integer(values, "server.password.max_concurrent_operations", 1, 64)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
swaggerPort, err := requiredPort(values, "server.swagger_port")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
@@ -306,7 +311,8 @@ func LoadServer() (ServerConfig, error) {
|
||||
HTTPShutdownTimeout: shutdownTimeout, PasswordMemoryKiB: uint32(passwordMemory),
|
||||
PasswordIterations: uint32(passwordIterations), PasswordParallelism: uint8(passwordParallelism),
|
||||
PasswordSaltLength: uint32(passwordSaltLength), PasswordKeyLength: uint32(passwordKeyLength),
|
||||
SwaggerPort: swaggerPort, S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
|
||||
PasswordMaxConcurrentOperations: passwordMaxConcurrentOperations,
|
||||
SwaggerPort: swaggerPort, S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
|
||||
S3AccessKey: storage.accessKey, S3SecretKey: storage.secretKey,
|
||||
S3UseTLS: storage.useTLS, S3CAPath: storage.caPath, S3Timeout: storage.timeout,
|
||||
AttachmentMaxBytes: int64(attachmentMaxBytes), AttachmentMaxPixels: int64(attachmentMaxPixels),
|
||||
|
||||
@@ -59,6 +59,7 @@ func TestLoadServerLoadsTLSAndHealthSettings(t *testing.T) {
|
||||
require.Equal(t, 5, settings.LoginRateLimitAccountAttempts)
|
||||
require.Equal(t, 20, settings.LoginRateLimitSourceAttempts)
|
||||
require.Equal(t, time.Minute, settings.LoginRateLimitWindow)
|
||||
require.Equal(t, 2, settings.PasswordMaxConcurrentOperations)
|
||||
}
|
||||
|
||||
func TestLoadServerRejectsNonLoopbackHealthAddress(t *testing.T) {
|
||||
@@ -152,6 +153,7 @@ server:
|
||||
parallelism: 2
|
||||
salt_length: 16
|
||||
key_length: 32
|
||||
max_concurrent_operations: 2
|
||||
database:
|
||||
min_connections: 0
|
||||
max_connections: 4
|
||||
|
||||
@@ -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{
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
var (
|
||||
ErrInvalidConfig = errors.New("invalid password configuration")
|
||||
ErrInvalidHash = errors.New("invalid password hash")
|
||||
ErrBusy = errors.New("password operation limit reached")
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
@@ -26,17 +27,24 @@ type Config struct {
|
||||
}
|
||||
|
||||
type Hasher struct {
|
||||
config Config
|
||||
dummyHash string
|
||||
config Config
|
||||
dummyHash string
|
||||
operations chan struct{}
|
||||
}
|
||||
|
||||
func New(config Config) (*Hasher, error) {
|
||||
func New(config Config, maxConcurrentOperations int) (*Hasher, error) {
|
||||
if err := validateConfig(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if maxConcurrentOperations < 1 || maxConcurrentOperations > 64 {
|
||||
return nil, ErrInvalidConfig
|
||||
}
|
||||
salt := make([]byte, config.SaltLength)
|
||||
digest := argon2.IDKey([]byte("invalid-user-password"), salt, config.Iterations, config.MemoryKiB, config.Parallelism, config.KeyLength)
|
||||
return &Hasher{config: config, dummyHash: encode(config, salt, digest)}, nil
|
||||
return &Hasher{
|
||||
config: config, dummyHash: encode(config, salt, digest),
|
||||
operations: make(chan struct{}, maxConcurrentOperations),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func validateConfig(config Config) error {
|
||||
@@ -51,6 +59,10 @@ func validateConfig(config Config) error {
|
||||
}
|
||||
|
||||
func (h *Hasher) Hash(value string) (string, error) {
|
||||
if !h.acquire() {
|
||||
return "", ErrBusy
|
||||
}
|
||||
defer h.release()
|
||||
salt := make([]byte, h.config.SaltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate password salt: %w", err)
|
||||
@@ -60,6 +72,10 @@ func (h *Hasher) Hash(value string) (string, error) {
|
||||
}
|
||||
|
||||
func (h *Hasher) Verify(value, encodedHash string) (bool, error) {
|
||||
if !h.acquire() {
|
||||
return false, ErrBusy
|
||||
}
|
||||
defer h.release()
|
||||
config, salt, digest, err := decode(encodedHash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -68,6 +84,19 @@ func (h *Hasher) Verify(value, encodedHash string) (bool, error) {
|
||||
return subtle.ConstantTimeCompare(actual, digest) == 1, nil
|
||||
}
|
||||
|
||||
func (h *Hasher) acquire() bool {
|
||||
select {
|
||||
case h.operations <- struct{}{}:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hasher) release() {
|
||||
<-h.operations
|
||||
}
|
||||
|
||||
func (h *Hasher) NeedsRehash(encodedHash string) (bool, error) {
|
||||
config, _, _, err := decode(encodedHash)
|
||||
if err != nil {
|
||||
|
||||
@@ -16,7 +16,7 @@ func TestPasswordSuite(t *testing.T) {
|
||||
}
|
||||
|
||||
func (s *PasswordSuite) SetupTest() {
|
||||
hasher, err := New(testConfig())
|
||||
hasher, err := New(testConfig(), 2)
|
||||
s.Require().NoError(err)
|
||||
s.hasher = hasher
|
||||
}
|
||||
@@ -48,7 +48,7 @@ func (s *PasswordSuite) TestNeedsRehashDetectsChangedParameters() {
|
||||
|
||||
legacyConfig := testConfig()
|
||||
legacyConfig.KeyLength = 16
|
||||
legacy, err := New(legacyConfig)
|
||||
legacy, err := New(legacyConfig, 2)
|
||||
s.Require().NoError(err)
|
||||
legacyHash, err := legacy.Hash("T3st-password-123")
|
||||
s.Require().NoError(err)
|
||||
@@ -57,12 +57,34 @@ func (s *PasswordSuite) TestNeedsRehashDetectsChangedParameters() {
|
||||
s.True(needsRehash)
|
||||
}
|
||||
|
||||
func (s *PasswordSuite) TestBusyOperationsRecoverAfterCapacityIsReleased() {
|
||||
s.hasher.operations <- struct{}{}
|
||||
s.hasher.operations <- struct{}{}
|
||||
defer func() { <-s.hasher.operations }()
|
||||
_, err := s.hasher.Hash("T3st-password-123")
|
||||
s.ErrorIs(err, ErrBusy)
|
||||
_, err = s.hasher.Verify("T3st-password-123", s.hasher.DummyHash())
|
||||
s.ErrorIs(err, ErrBusy)
|
||||
|
||||
<-s.hasher.operations
|
||||
hash, err := s.hasher.Hash("T3st-password-123")
|
||||
s.Require().NoError(err)
|
||||
verified, err := s.hasher.Verify("T3st-password-123", hash)
|
||||
s.Require().NoError(err)
|
||||
s.True(verified)
|
||||
}
|
||||
|
||||
func (s *PasswordSuite) TestNewRejectsInvalidOperationLimit() {
|
||||
_, err := New(testConfig(), 0)
|
||||
s.ErrorIs(err, ErrInvalidConfig)
|
||||
}
|
||||
|
||||
func testConfig() Config {
|
||||
return Config{MemoryKiB: 8 * 1024, Iterations: 1, Parallelism: 1, SaltLength: 16, KeyLength: 32}
|
||||
}
|
||||
|
||||
func BenchmarkArgon2idHash(b *testing.B) {
|
||||
hasher, err := New(productionConfig())
|
||||
hasher, err := New(productionConfig(), 2)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
@@ -76,7 +98,7 @@ func BenchmarkArgon2idHash(b *testing.B) {
|
||||
}
|
||||
|
||||
func BenchmarkArgon2idVerify(b *testing.B) {
|
||||
hasher, err := New(productionConfig())
|
||||
hasher, err := New(productionConfig(), 2)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
+2
-1
@@ -5,7 +5,8 @@ set -eu
|
||||
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
|
||||
|
||||
for container in $(docker compose ps -q api); do
|
||||
instance=$(docker inspect --format '{{.Config.Hostname}}' "$container")
|
||||
instance=$(docker exec "$container" wget -S -q -O /dev/null http://127.0.0.1:8082/health/live 2>&1 |
|
||||
sed -n 's/^[[:space:]]*X-Instance-Id:[[:space:]]*//p' | tr -d '\r')
|
||||
if [ "$instance" = "$TARGET_INSTANCE_ID" ]; then
|
||||
docker stop --time 6 "$container" >/dev/null
|
||||
exit 0
|
||||
|
||||
@@ -10,7 +10,20 @@ mode=${1:-sync}
|
||||
|
||||
case "$mode" in
|
||||
sync|--pull-scan) ;;
|
||||
*) echo "usage: $0 [--pull-scan]" >&2; exit 2 ;;
|
||||
--clean)
|
||||
case "$repo_dir" in
|
||||
/tmp/mtusi2026lab7-*) ;;
|
||||
*) echo "cleanup is restricted to temporary CI workspaces" >&2; exit 2 ;;
|
||||
esac
|
||||
run_id=${repo_dir#/tmp/mtusi2026lab7-}
|
||||
case "$run_id" in
|
||||
''|*[!0-9]*) echo "invalid CI workspace name" >&2; exit 2 ;;
|
||||
esac
|
||||
docker run --rm --network none -v "$repo_dir:/workspace" alpine:3.24.2 \
|
||||
find /workspace -mindepth 1 -delete
|
||||
exit 0
|
||||
;;
|
||||
*) echo "usage: $0 [--pull-scan|--clean]" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
[ -f "$repo_dir/compose.yaml" ] || {
|
||||
|
||||
Reference in New Issue
Block a user