forked from mtusi2026/mtusi2026lab7
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8edaf058d |
+38
-16
@@ -24,6 +24,9 @@ jobs:
|
||||
LOKI_BIND_ADDRESS: 127.0.0.1:0
|
||||
TEMPO_BIND_ADDRESS: 127.0.0.1:0
|
||||
OPENBAO_BIND_ADDRESS: 127.0.0.1:0
|
||||
BAO_ADDR: https://openbao:8200
|
||||
DOCKER_WORKSPACE_MIRROR: "1"
|
||||
CI_WORKSPACE: /tmp/mtusi2026lab7-${{ github.run_id }}
|
||||
steps:
|
||||
- name: Checkout exact commit
|
||||
run: |
|
||||
@@ -34,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
|
||||
@@ -66,8 +69,16 @@ jobs:
|
||||
|
||||
- name: Prepare local stack
|
||||
run: |
|
||||
mkdir -p "$CI_WORKSPACE"
|
||||
git archive HEAD | tar -x -C "$CI_WORKSPACE"
|
||||
cd "$CI_WORKSPACE"
|
||||
cp lab7.env.example .env
|
||||
docker compose config --quiet
|
||||
./infra/pki/bootstrap.sh
|
||||
./scripts/openbao-seed.sh .env
|
||||
./scripts/sync-docker-workspace.sh
|
||||
docker compose up -d security-bootstrap openbao-permissions openbao
|
||||
docker network connect "${COMPOSE_PROJECT_NAME}_secrets" "$HOSTNAME"
|
||||
./scripts/bootstrap-local.sh .env
|
||||
docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME"
|
||||
docker network connect "${COMPOSE_PROJECT_NAME}_data" "$HOSTNAME"
|
||||
@@ -78,15 +89,15 @@ jobs:
|
||||
|
||||
- name: Integration checks
|
||||
run: |
|
||||
cd "$CI_WORKSPACE"
|
||||
test "$(curl --noproxy '*' --cacert .runtime/security/internal-ca/ca.crt -s -o /dev/null -w '%{http_code}' "https://s3:9000/messenger-attachments")" = "403"
|
||||
make test BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
|
||||
make test-security BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
|
||||
make test-tls-matrix ENV_FILE=.env
|
||||
ENV_FILE=.env BASE_URL=https://nginx:8443 ./scripts/test-leaf-rotation.sh
|
||||
docker compose --profile security run --rm dependency-tests
|
||||
OPENBAO_ADDRESS=$(docker compose port openbao 8200)
|
||||
ENV_FILE=.env BAO_ADDR="https://$OPENBAO_ADDRESS" BAO_CACERT="$PWD/.runtime/security/openbao/ca.crt" ./scripts/openbao-test-policy.sh
|
||||
ENV_FILE=.env BAO_ADDR="https://$OPENBAO_ADDRESS" BAO_CACERT="$PWD/.runtime/security/openbao/ca.crt" ./scripts/test-openbao-lifecycle.sh
|
||||
ENV_FILE=.env BAO_ADDR=https://openbao:8200 BAO_CACERT="$PWD/.runtime/security/openbao/ca.crt" ./scripts/openbao-test-policy.sh
|
||||
ENV_FILE=.env BAO_ADDR=https://openbao:8200 BAO_CACERT="$PWD/.runtime/security/openbao/ca.crt" ./scripts/test-openbao-lifecycle.sh
|
||||
make test-login-rate-limit BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
|
||||
docker compose --profile tests run --rm --build tests
|
||||
go run ./cmd/dependencycheck -base-url=https://nginx:8443 -ca-file=.runtime/security/public-ca/ca.crt
|
||||
@@ -97,25 +108,36 @@ 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
|
||||
|
||||
- name: Upload security evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: lab7-security-${{ github.sha }}
|
||||
path: |
|
||||
evidence/lab7-*.json
|
||||
evidence/runtime/security-scan
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
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()
|
||||
run: if [ -f .env ]; then docker compose logs --no-color --tail=200; fi
|
||||
run: if [ -f "$CI_WORKSPACE/.env" ]; then cd "$CI_WORKSPACE"; docker compose logs --no-color --tail=200; fi
|
||||
|
||||
- name: Upload security evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v3
|
||||
env:
|
||||
ACTIONS_RUNTIME_URL: https://gitea.privcloud.tech/api/actions_pipeline/
|
||||
with:
|
||||
name: lab7-security-${{ github.sha }}
|
||||
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
|
||||
|
||||
- name: Stop local stack
|
||||
if: always()
|
||||
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
|
||||
docker network disconnect "${COMPOSE_PROJECT_NAME}_data_backend" "$HOSTNAME" 2>/dev/null || true
|
||||
|
||||
@@ -31,6 +31,9 @@ jobs:
|
||||
LOKI_BIND_ADDRESS: 127.0.0.1:0
|
||||
TEMPO_BIND_ADDRESS: 127.0.0.1:0
|
||||
OPENBAO_BIND_ADDRESS: 127.0.0.1:0
|
||||
BAO_ADDR: https://openbao:8200
|
||||
DOCKER_WORKSPACE_MIRROR: "1"
|
||||
CI_WORKSPACE: /tmp/mtusi2026lab7-${{ github.run_id }}
|
||||
API_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab7-api:${{ github.sha }}
|
||||
NGINX_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab7-nginx:${{ github.sha }}
|
||||
SWAGGER_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab7-swagger:${{ github.sha }}
|
||||
@@ -48,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
|
||||
@@ -80,8 +83,16 @@ jobs:
|
||||
|
||||
- name: Prepare local stack
|
||||
run: |
|
||||
mkdir -p "$CI_WORKSPACE"
|
||||
git archive HEAD | tar -x -C "$CI_WORKSPACE"
|
||||
cd "$CI_WORKSPACE"
|
||||
cp lab7.env.example .env
|
||||
docker compose config --quiet
|
||||
./infra/pki/bootstrap.sh
|
||||
./scripts/openbao-seed.sh .env
|
||||
./scripts/sync-docker-workspace.sh
|
||||
docker compose up -d security-bootstrap openbao-permissions openbao
|
||||
docker network connect "${COMPOSE_PROJECT_NAME}_secrets" "$HOSTNAME"
|
||||
./scripts/bootstrap-local.sh .env
|
||||
docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME"
|
||||
docker network connect "${COMPOSE_PROJECT_NAME}_data" "$HOSTNAME"
|
||||
@@ -92,15 +103,15 @@ jobs:
|
||||
|
||||
- name: Integration checks
|
||||
run: |
|
||||
cd "$CI_WORKSPACE"
|
||||
test "$(curl --noproxy '*' --cacert .runtime/security/internal-ca/ca.crt -s -o /dev/null -w '%{http_code}' "https://s3:9000/messenger-attachments")" = "403"
|
||||
make test BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
|
||||
make test-security BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
|
||||
make test-tls-matrix ENV_FILE=.env
|
||||
ENV_FILE=.env BASE_URL=https://nginx:8443 ./scripts/test-leaf-rotation.sh
|
||||
docker compose --profile security run --rm dependency-tests
|
||||
OPENBAO_ADDRESS=$(docker compose port openbao 8200)
|
||||
ENV_FILE=.env BAO_ADDR="https://$OPENBAO_ADDRESS" BAO_CACERT="$PWD/.runtime/security/openbao/ca.crt" ./scripts/openbao-test-policy.sh
|
||||
ENV_FILE=.env BAO_ADDR="https://$OPENBAO_ADDRESS" BAO_CACERT="$PWD/.runtime/security/openbao/ca.crt" ./scripts/test-openbao-lifecycle.sh
|
||||
ENV_FILE=.env BAO_ADDR=https://openbao:8200 BAO_CACERT="$PWD/.runtime/security/openbao/ca.crt" ./scripts/openbao-test-policy.sh
|
||||
ENV_FILE=.env BAO_ADDR=https://openbao:8200 BAO_CACERT="$PWD/.runtime/security/openbao/ca.crt" ./scripts/test-openbao-lifecycle.sh
|
||||
make test-login-rate-limit BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
|
||||
docker compose --profile tests run --rm --build tests
|
||||
go run ./cmd/dependencycheck -base-url=https://nginx:8443 -ca-file=.runtime/security/public-ca/ca.crt
|
||||
@@ -109,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
|
||||
@@ -139,11 +154,15 @@ jobs:
|
||||
|
||||
- name: Container logs
|
||||
if: failure()
|
||||
run: if [ -f .env ]; then docker compose logs --no-color --tail=200; fi
|
||||
run: if [ -f "$CI_WORKSPACE/.env" ]; then cd "$CI_WORKSPACE"; docker compose logs --no-color --tail=200; fi
|
||||
|
||||
- name: Stop local stack
|
||||
if: always()
|
||||
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
|
||||
docker network disconnect "${COMPOSE_PROJECT_NAME}_data_backend" "$HOSTNAME" 2>/dev/null || true
|
||||
|
||||
@@ -20,6 +20,9 @@ jobs:
|
||||
LOKI_BIND_ADDRESS: 127.0.0.1:0
|
||||
TEMPO_BIND_ADDRESS: 127.0.0.1:0
|
||||
OPENBAO_BIND_ADDRESS: 127.0.0.1:0
|
||||
BAO_ADDR: https://openbao:8200
|
||||
DOCKER_WORKSPACE_MIRROR: "1"
|
||||
CI_WORKSPACE: /tmp/mtusi2026lab7-${{ github.run_id }}
|
||||
steps:
|
||||
- name: Checkout exact commit
|
||||
run: |
|
||||
@@ -30,13 +33,21 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
go-version: "1.26.10"
|
||||
cache: false
|
||||
|
||||
- name: Prepare stack
|
||||
run: |
|
||||
mkdir -p "$CI_WORKSPACE"
|
||||
git archive HEAD | tar -x -C "$CI_WORKSPACE"
|
||||
cd "$CI_WORKSPACE"
|
||||
cp lab7.env.example .env
|
||||
docker compose config --quiet
|
||||
./infra/pki/bootstrap.sh
|
||||
./scripts/openbao-seed.sh .env
|
||||
./scripts/sync-docker-workspace.sh
|
||||
docker compose up -d security-bootstrap openbao-permissions openbao
|
||||
docker network connect "${COMPOSE_PROJECT_NAME}_secrets" "$HOSTNAME"
|
||||
./scripts/bootstrap-local.sh .env
|
||||
docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME"
|
||||
docker network connect "${COMPOSE_PROJECT_NAME}_data" "$HOSTNAME"
|
||||
@@ -47,6 +58,7 @@ jobs:
|
||||
|
||||
- name: Reproduce SLO incidents
|
||||
run: |
|
||||
cd "$CI_WORKSPACE"
|
||||
ENV_FILE=.env \
|
||||
BASE_URL=https://nginx:8443 \
|
||||
CA_FILE=.runtime/security/public-ca/ca.crt \
|
||||
@@ -58,20 +70,26 @@ jobs:
|
||||
|
||||
- name: Upload sanitized evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v3
|
||||
env:
|
||||
ACTIONS_RUNTIME_URL: https://gitea.privcloud.tech/api/actions_pipeline/
|
||||
with:
|
||||
name: lab6-incidents-${{ github.sha }}
|
||||
path: evidence/runtime/ci
|
||||
path: ${{ env.CI_WORKSPACE }}/evidence/runtime/ci
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
- name: Container logs
|
||||
if: failure()
|
||||
run: docker compose logs --no-color --tail=200
|
||||
run: if [ -f "$CI_WORKSPACE/.env" ]; then cd "$CI_WORKSPACE"; docker compose logs --no-color --tail=200; fi
|
||||
|
||||
- name: Stop local stack
|
||||
if: always()
|
||||
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
|
||||
docker network disconnect "${COMPOSE_PROJECT_NAME}_data_backend" "$HOSTNAME" 2>/dev/null || true
|
||||
|
||||
@@ -33,4 +33,3 @@ coverage/
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
|
||||
evidence/runtime/
|
||||
.runtime/
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/bootstrap"
|
||||
@@ -11,24 +10,24 @@ import (
|
||||
|
||||
func main() {
|
||||
appLogger := logger.New()
|
||||
if err := run(appLogger, os.Args[1:]); err != nil {
|
||||
if err := run(os.Args[1:]); err != nil {
|
||||
appLogger.Error("application stopped", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(logger *slog.Logger, arguments []string) error {
|
||||
func run(arguments []string) error {
|
||||
if len(arguments) == 0 {
|
||||
return bootstrap.RunServer(logger)
|
||||
return bootstrap.RunServer()
|
||||
}
|
||||
if len(arguments) == 1 && arguments[0] == "migrate" {
|
||||
return bootstrap.RunMigrations()
|
||||
}
|
||||
if len(arguments) == 1 && arguments[0] == "dispatch" {
|
||||
return bootstrap.RunDispatcher(logger)
|
||||
return bootstrap.RunDispatcher()
|
||||
}
|
||||
if len(arguments) == 1 && arguments[0] == "worker" {
|
||||
return bootstrap.RunWorker(logger)
|
||||
return bootstrap.RunWorker()
|
||||
}
|
||||
if arguments[0] == "reconcile-attachments" {
|
||||
return bootstrap.RunReconciliation(arguments[1:], os.Stdout)
|
||||
|
||||
@@ -343,6 +343,8 @@ services:
|
||||
openbao-cli:
|
||||
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
|
||||
|
||||
@@ -28,7 +28,7 @@ import (
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
|
||||
)
|
||||
|
||||
func RunDispatcher(logger *slog.Logger) error {
|
||||
func RunDispatcher() error {
|
||||
settings, err := config.LoadDispatcher()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -87,7 +87,7 @@ func RunDispatcher(logger *slog.Logger) error {
|
||||
)
|
||||
}
|
||||
|
||||
func RunWorker(logger *slog.Logger) error {
|
||||
func RunWorker() error {
|
||||
settings, err := config.LoadWorker()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -5,13 +5,13 @@ import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"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"
|
||||
@@ -30,7 +30,7 @@ type serverResult struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func RunServer(logger *slog.Logger) error {
|
||||
func RunServer() error {
|
||||
settings, err := config.LoadServer()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -49,10 +49,11 @@ func RunServer(logger *slog.Logger) 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
|
||||
@@ -91,7 +92,7 @@ func RunServer(logger *slog.Logger) 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
|
||||
|
||||
@@ -74,7 +74,7 @@ func loadSecretFile(values *viper.Viper, path string) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("open messenger secrets: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
defer func() { _ = file.Close() }()
|
||||
decoder := json.NewDecoder(io.LimitReader(file, 64<<10))
|
||||
var secrets map[string]string
|
||||
if err := decoder.Decode(&secrets); err != nil {
|
||||
|
||||
@@ -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{
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -263,21 +263,6 @@ func scanAttachmentWithReferenceAndObjectKey(
|
||||
return err
|
||||
}
|
||||
|
||||
func scanAttachmentWithReference(row rowScanner, attachment *model.Attachment) error {
|
||||
var stagingKey *string
|
||||
err := row.Scan(
|
||||
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
|
||||
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
|
||||
&attachment.Status, &attachment.CreatedAt, &attachment.UpdatedAt, &attachment.ReadyAt,
|
||||
&attachment.PipelineVersion, &attachment.ErrorCode, &stagingKey,
|
||||
&attachment.Referenced,
|
||||
)
|
||||
if stagingKey != nil {
|
||||
attachment.StagingKey = *stagingKey
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) AttachmentReferenced(ctx context.Context, attachmentID string) (bool, error) {
|
||||
const query = `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1)`
|
||||
var referenced bool
|
||||
|
||||
@@ -40,7 +40,7 @@ func Run(ctx context.Context, config Config) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("listen: %w", err)
|
||||
}
|
||||
defer listener.Close()
|
||||
defer func() { _ = listener.Close() }()
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
_ = listener.Close()
|
||||
@@ -66,7 +66,7 @@ func Run(ctx context.Context, config Config) error {
|
||||
|
||||
func serve(ctx context.Context, connection net.Conn, config Config, tlsConfiguration *tls.Config) {
|
||||
client := tls.Server(connection, tlsConfiguration)
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
handshakeCtx, cancel := context.WithTimeout(ctx, config.DialTimeout)
|
||||
defer cancel()
|
||||
if err := client.HandshakeContext(handshakeCtx); err != nil {
|
||||
@@ -76,7 +76,7 @@ func serve(ctx context.Context, connection net.Conn, config Config, tlsConfigura
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer target.Close()
|
||||
defer func() { _ = target.Close() }()
|
||||
|
||||
result := make(chan struct{}, 2)
|
||||
copyConnection := func(destination, source net.Conn) {
|
||||
|
||||
@@ -73,7 +73,7 @@ func handshake(serverConfig, clientConfig *tls.Config) (error, error) {
|
||||
if err != nil {
|
||||
return err, err
|
||||
}
|
||||
defer listener.Close()
|
||||
defer func() { _ = listener.Close() }()
|
||||
serverResult := make(chan error, 1)
|
||||
go func() {
|
||||
connection, acceptErr := listener.Accept()
|
||||
|
||||
@@ -6,5 +6,7 @@ script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
repo_dir=$(CDPATH= cd -- "$script_dir/.." && pwd)
|
||||
env_file=${ENV_FILE:-$repo_dir/lab7.env.example}
|
||||
|
||||
"$script_dir/sync-docker-workspace.sh"
|
||||
|
||||
exec docker compose --project-directory "$repo_dir" --env-file "$env_file" run --rm --no-deps -T \
|
||||
-v "$repo_dir:$repo_dir:ro" openbao-cli "$@"
|
||||
|
||||
@@ -20,14 +20,17 @@ if [ ! -f "$repo_dir/.runtime/security/openbao/tls.crt" ]; then
|
||||
fi
|
||||
|
||||
"$script_dir/openbao-seed.sh" "$env_file"
|
||||
"$script_dir/sync-docker-workspace.sh"
|
||||
compose up -d security-bootstrap openbao-permissions openbao
|
||||
openbao_address=$(compose port openbao 8200)
|
||||
BAO_ADDR="https://$openbao_address"
|
||||
if [ -z "${BAO_ADDR:-}" ]; then
|
||||
openbao_address=$(compose port openbao 8200)
|
||||
BAO_ADDR="https://$openbao_address"
|
||||
fi
|
||||
BAO_CACERT="$repo_dir/.runtime/security/openbao/ca.crt"
|
||||
export BAO_ADDR BAO_CACERT ENV_FILE="$env_file"
|
||||
|
||||
remaining=60
|
||||
until curl --silent --show-error --cacert "$BAO_CACERT" \
|
||||
until curl --silent --show-error --connect-timeout 2 --max-time 3 --cacert "$BAO_CACERT" \
|
||||
--output /dev/null "$BAO_ADDR/v1/sys/health"; do
|
||||
remaining=$((remaining - 1))
|
||||
[ "$remaining" -gt 0 ] || {
|
||||
@@ -40,7 +43,7 @@ done
|
||||
ENV_FILE="$env_file" "$script_dir/openbao-init.sh"
|
||||
ENV_FILE="$env_file" "$script_dir/openbao-unseal.sh"
|
||||
remaining=60
|
||||
until curl --fail --silent --show-error --cacert "$BAO_CACERT" \
|
||||
until curl --fail --silent --show-error --connect-timeout 2 --max-time 3 --cacert "$BAO_CACERT" \
|
||||
--output /dev/null "$BAO_ADDR/v1/sys/health"; do
|
||||
remaining=$((remaining - 1))
|
||||
[ "$remaining" -gt 0 ] || {
|
||||
|
||||
@@ -56,8 +56,10 @@ mkdir -p "$runtime_dir"
|
||||
chmod 0700 "$repo_dir/.runtime/evidence" "$runtime_dir"
|
||||
trap restore EXIT HUP INT TERM
|
||||
|
||||
openbao_address=$(compose port openbao 8200)
|
||||
BAO_ADDR="https://$openbao_address"
|
||||
if [ -z "${BAO_ADDR:-}" ]; then
|
||||
openbao_address=$(compose port openbao 8200)
|
||||
BAO_ADDR="https://$openbao_address"
|
||||
fi
|
||||
BAO_CACERT="$repo_dir/.runtime/security/openbao/ca.crt"
|
||||
export BAO_ADDR BAO_CACERT
|
||||
|
||||
|
||||
@@ -30,7 +30,9 @@ require_file() {
|
||||
|
||||
require_private_file() {
|
||||
require_file "$1"
|
||||
permissions=$(stat -f '%Lp' "$1" 2>/dev/null || stat -c '%a' "$1")
|
||||
if ! permissions=$(stat -c '%a' "$1" 2>/dev/null); then
|
||||
permissions=$(stat -f '%Lp' "$1")
|
||||
fi
|
||||
case "$permissions" in
|
||||
600|400) ;;
|
||||
*) fail "file must have permissions 0600 or 0400: $1" ;;
|
||||
|
||||
@@ -79,6 +79,7 @@ if [ -n "$old_accessor" ]; then
|
||||
fi
|
||||
|
||||
if [ "$output_dir" = "$openbao_runtime_dir/approle/$service" ]; then
|
||||
"$script_dir/sync-docker-workspace.sh"
|
||||
docker compose --project-directory "$repo_dir" --env-file "${ENV_FILE:-$repo_dir/lab7.env.example}" \
|
||||
run --rm --no-deps -e SERVICE="$service" openbao-identity-install
|
||||
fi
|
||||
|
||||
@@ -17,6 +17,7 @@ if [ -z "$image_list" ]; then
|
||||
fi
|
||||
|
||||
mkdir -p "$runtime_dir" "$cache_dir"
|
||||
"$script_dir/sync-docker-workspace.sh"
|
||||
|
||||
docker run --rm \
|
||||
-v "$repo_dir:/src:ro" \
|
||||
@@ -50,6 +51,8 @@ for image in $image_list; do
|
||||
image_reports="$image_reports $image=$report"
|
||||
done
|
||||
|
||||
"$script_dir/sync-docker-workspace.sh" --pull-scan
|
||||
|
||||
python3 - "$raw_file" "$summary_file" $image_reports <<'PY'
|
||||
import datetime
|
||||
import json
|
||||
|
||||
+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
|
||||
|
||||
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -eu
|
||||
|
||||
[ "${DOCKER_WORKSPACE_MIRROR:-0}" = "1" ] || exit 0
|
||||
|
||||
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
repo_dir=$(CDPATH= cd -- "$script_dir/.." && pwd)
|
||||
mode=${1:-sync}
|
||||
|
||||
case "$mode" in
|
||||
sync|--pull-scan) ;;
|
||||
--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" ] || {
|
||||
echo "repository checkout is incomplete" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
container=$(docker create --network none \
|
||||
-v "$repo_dir:/workspace" \
|
||||
alpine:3.24.2 /bin/true)
|
||||
|
||||
cleanup() {
|
||||
docker rm -f "$container" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
trap cleanup EXIT HUP INT TERM
|
||||
|
||||
if [ "$mode" = "--pull-scan" ]; then
|
||||
destination=$repo_dir/evidence/runtime/security-scan
|
||||
mkdir -p "$destination"
|
||||
docker cp "$container:/workspace/evidence/runtime/security-scan/." "$destination"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
docker cp "$repo_dir/." "$container:/workspace"
|
||||
@@ -25,6 +25,7 @@ compose_rotated() {
|
||||
}
|
||||
|
||||
install_security_material() {
|
||||
"$script_dir/sync-docker-workspace.sh"
|
||||
compose run --rm --no-deps security-bootstrap >/dev/null
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user