1 Commits
Author SHA1 Message Date
dizi fc290d4338 docs: record threat model and security evidence 2026-11-06 21:19:10 +03:00
34 changed files with 142 additions and 504 deletions
+11 -33
View File
@@ -24,9 +24,6 @@ jobs:
LOKI_BIND_ADDRESS: 127.0.0.1:0 LOKI_BIND_ADDRESS: 127.0.0.1:0
TEMPO_BIND_ADDRESS: 127.0.0.1:0 TEMPO_BIND_ADDRESS: 127.0.0.1:0
OPENBAO_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: steps:
- name: Checkout exact commit - name: Checkout exact commit
run: | run: |
@@ -37,7 +34,7 @@ jobs:
- uses: actions/setup-go@v5 - uses: actions/setup-go@v5
with: with:
go-version: "1.26.10" go-version-file: go.mod
cache: false cache: false
- name: Check contract - name: Check contract
@@ -69,16 +66,8 @@ jobs:
- name: Prepare local stack - name: Prepare local stack
run: | run: |
mkdir -p "$CI_WORKSPACE"
git archive HEAD | tar -x -C "$CI_WORKSPACE"
cd "$CI_WORKSPACE"
cp lab7.env.example .env cp lab7.env.example .env
docker compose config --quiet 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 ./scripts/bootstrap-local.sh .env
docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME" docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME"
docker network connect "${COMPOSE_PROJECT_NAME}_data" "$HOSTNAME" docker network connect "${COMPOSE_PROJECT_NAME}_data" "$HOSTNAME"
@@ -89,15 +78,15 @@ jobs:
- name: Integration checks - name: Integration checks
run: | 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" 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 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-security BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
make test-tls-matrix ENV_FILE=.env make test-tls-matrix ENV_FILE=.env
ENV_FILE=.env BASE_URL=https://nginx:8443 ./scripts/test-leaf-rotation.sh ENV_FILE=.env BASE_URL=https://nginx:8443 ./scripts/test-leaf-rotation.sh
docker compose --profile security run --rm dependency-tests docker compose --profile security run --rm dependency-tests
ENV_FILE=.env BAO_ADDR=https://openbao:8200 BAO_CACERT="$PWD/.runtime/security/openbao/ca.crt" ./scripts/openbao-test-policy.sh OPENBAO_ADDRESS=$(docker compose port openbao 8200)
ENV_FILE=.env BAO_ADDR=https://openbao:8200 BAO_CACERT="$PWD/.runtime/security/openbao/ca.crt" ./scripts/test-openbao-lifecycle.sh 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
make test-login-rate-limit BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt 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 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 go run ./cmd/dependencycheck -base-url=https://nginx:8443 -ca-file=.runtime/security/public-ca/ca.crt
@@ -108,36 +97,25 @@ jobs:
make test-worker-compromise ENV_FILE=.env make test-worker-compromise ENV_FILE=.env
make scan-security 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 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()
run: if [ -f "$CI_WORKSPACE/.env" ]; then cd "$CI_WORKSPACE"; docker compose logs --no-color --tail=200; fi
- name: Upload security evidence - name: Upload security evidence
if: always() if: always()
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v4
env:
ACTIONS_RUNTIME_URL: https://gitea.privcloud.tech/api/actions_pipeline/
with: with:
name: lab7-security-${{ github.sha }} name: lab7-security-${{ github.sha }}
path: | path: |
${{ env.CI_WORKSPACE }}/evidence/lab7-*.json evidence/lab7-*.json
${{ env.CI_WORKSPACE }}/evidence/runtime/security-scan evidence/runtime/security-scan
${{ env.CI_WORKSPACE }}/evidence/runtime/login-burst.json
if-no-files-found: warn if-no-files-found: warn
retention-days: 14 retention-days: 14
- name: Container logs
if: failure()
run: if [ -f .env ]; then docker compose logs --no-color --tail=200; fi
- name: Stop local stack - name: Stop local stack
if: always() if: always()
run: | 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}_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" "$HOSTNAME" 2>/dev/null || true
docker network disconnect "${COMPOSE_PROJECT_NAME}_data_backend" "$HOSTNAME" 2>/dev/null || true docker network disconnect "${COMPOSE_PROJECT_NAME}_data_backend" "$HOSTNAME" 2>/dev/null || true
+5 -24
View File
@@ -31,9 +31,6 @@ jobs:
LOKI_BIND_ADDRESS: 127.0.0.1:0 LOKI_BIND_ADDRESS: 127.0.0.1:0
TEMPO_BIND_ADDRESS: 127.0.0.1:0 TEMPO_BIND_ADDRESS: 127.0.0.1:0
OPENBAO_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 }} API_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab7-api:${{ github.sha }}
NGINX_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab7-nginx:${{ 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 }} SWAGGER_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab7-swagger:${{ github.sha }}
@@ -51,7 +48,7 @@ jobs:
- uses: actions/setup-go@v5 - uses: actions/setup-go@v5
with: with:
go-version: "1.26.10" go-version-file: go.mod
cache: false cache: false
- name: Check contract - name: Check contract
@@ -83,16 +80,8 @@ jobs:
- name: Prepare local stack - name: Prepare local stack
run: | run: |
mkdir -p "$CI_WORKSPACE"
git archive HEAD | tar -x -C "$CI_WORKSPACE"
cd "$CI_WORKSPACE"
cp lab7.env.example .env cp lab7.env.example .env
docker compose config --quiet 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 ./scripts/bootstrap-local.sh .env
docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME" docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME"
docker network connect "${COMPOSE_PROJECT_NAME}_data" "$HOSTNAME" docker network connect "${COMPOSE_PROJECT_NAME}_data" "$HOSTNAME"
@@ -103,15 +92,15 @@ jobs:
- name: Integration checks - name: Integration checks
run: | 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" 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 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-security BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
make test-tls-matrix ENV_FILE=.env make test-tls-matrix ENV_FILE=.env
ENV_FILE=.env BASE_URL=https://nginx:8443 ./scripts/test-leaf-rotation.sh ENV_FILE=.env BASE_URL=https://nginx:8443 ./scripts/test-leaf-rotation.sh
docker compose --profile security run --rm dependency-tests docker compose --profile security run --rm dependency-tests
ENV_FILE=.env BAO_ADDR=https://openbao:8200 BAO_CACERT="$PWD/.runtime/security/openbao/ca.crt" ./scripts/openbao-test-policy.sh OPENBAO_ADDRESS=$(docker compose port openbao 8200)
ENV_FILE=.env BAO_ADDR=https://openbao:8200 BAO_CACERT="$PWD/.runtime/security/openbao/ca.crt" ./scripts/test-openbao-lifecycle.sh 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
make test-login-rate-limit BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt 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 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 go run ./cmd/dependencycheck -base-url=https://nginx:8443 -ca-file=.runtime/security/public-ca/ca.crt
@@ -120,10 +109,6 @@ jobs:
make test-lab5-acceptance make test-lab5-acceptance
make test-worker-compromise ENV_FILE=.env 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 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 - name: Publish verified images
id: publish id: publish
@@ -154,15 +139,11 @@ jobs:
- name: Container logs - name: Container logs
if: failure() if: failure()
run: if [ -f "$CI_WORKSPACE/.env" ]; then cd "$CI_WORKSPACE"; docker compose logs --no-color --tail=200; fi run: if [ -f .env ]; then docker compose logs --no-color --tail=200; fi
- name: Stop local stack - name: Stop local stack
if: always() if: always()
run: | 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}_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" "$HOSTNAME" 2>/dev/null || true
docker network disconnect "${COMPOSE_PROJECT_NAME}_data_backend" "$HOSTNAME" 2>/dev/null || true docker network disconnect "${COMPOSE_PROJECT_NAME}_data_backend" "$HOSTNAME" 2>/dev/null || true
+4 -22
View File
@@ -20,9 +20,6 @@ jobs:
LOKI_BIND_ADDRESS: 127.0.0.1:0 LOKI_BIND_ADDRESS: 127.0.0.1:0
TEMPO_BIND_ADDRESS: 127.0.0.1:0 TEMPO_BIND_ADDRESS: 127.0.0.1:0
OPENBAO_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: steps:
- name: Checkout exact commit - name: Checkout exact commit
run: | run: |
@@ -33,21 +30,13 @@ jobs:
- uses: actions/setup-go@v5 - uses: actions/setup-go@v5
with: with:
go-version: "1.26.10" go-version-file: go.mod
cache: false cache: false
- name: Prepare stack - name: Prepare stack
run: | run: |
mkdir -p "$CI_WORKSPACE"
git archive HEAD | tar -x -C "$CI_WORKSPACE"
cd "$CI_WORKSPACE"
cp lab7.env.example .env cp lab7.env.example .env
docker compose config --quiet 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 ./scripts/bootstrap-local.sh .env
docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME" docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME"
docker network connect "${COMPOSE_PROJECT_NAME}_data" "$HOSTNAME" docker network connect "${COMPOSE_PROJECT_NAME}_data" "$HOSTNAME"
@@ -58,7 +47,6 @@ jobs:
- name: Reproduce SLO incidents - name: Reproduce SLO incidents
run: | run: |
cd "$CI_WORKSPACE"
ENV_FILE=.env \ ENV_FILE=.env \
BASE_URL=https://nginx:8443 \ BASE_URL=https://nginx:8443 \
CA_FILE=.runtime/security/public-ca/ca.crt \ CA_FILE=.runtime/security/public-ca/ca.crt \
@@ -70,26 +58,20 @@ jobs:
- name: Upload sanitized evidence - name: Upload sanitized evidence
if: always() if: always()
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v4
env:
ACTIONS_RUNTIME_URL: https://gitea.privcloud.tech/api/actions_pipeline/
with: with:
name: lab6-incidents-${{ github.sha }} name: lab6-incidents-${{ github.sha }}
path: ${{ env.CI_WORKSPACE }}/evidence/runtime/ci path: evidence/runtime/ci
if-no-files-found: warn if-no-files-found: warn
retention-days: 14 retention-days: 14
- name: Container logs - name: Container logs
if: failure() if: failure()
run: if [ -f "$CI_WORKSPACE/.env" ]; then cd "$CI_WORKSPACE"; docker compose logs --no-color --tail=200; fi run: docker compose logs --no-color --tail=200
- name: Stop local stack - name: Stop local stack
if: always() if: always()
run: | 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}_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" "$HOSTNAME" 2>/dev/null || true
docker network disconnect "${COMPOSE_PROJECT_NAME}_data_backend" "$HOSTNAME" 2>/dev/null || true docker network disconnect "${COMPOSE_PROJECT_NAME}_data_backend" "$HOSTNAME" 2>/dev/null || true
+1
View File
@@ -33,3 +33,4 @@ coverage/
# Inspect git diff --cached: ignore rules are not a secret scanner. # Inspect git diff --cached: ignore rules are not a secret scanner.
evidence/runtime/ evidence/runtime/
.runtime/
+1 -3
View File
@@ -82,9 +82,7 @@ PostgreSQL использует `verify-full` и отдельные роли API
Пароли хешируются Argon2id с индивидуальной солью и сохранёнными параметрами. При успешном входе `NeedsRehash` сравнивает параметры хеша с текущей политикой; устаревший хеш обновляется compare-and-swap запросом, поэтому параллельный login не перезаписывает более новый пароль. Пароли хешируются 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 памяти на операцию. Частотный лимит ограничивает 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`. Параметры `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`.
`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`. Session token является случайным opaque bearer token. В Valkey сохраняется только его SHA-256 hash с TTL; logout удаляет запись. Login limiter общий для API-реплик: Lua script атомарно увеличивает счётчики по нормализованному login и адресу источника, выставляет TTL и возвращает время до повторной попытки. При превышении лимита API отвечает `429` и положительным `Retry-After`.
-175
View File
@@ -1,175 +0,0 @@
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
}
+6 -5
View File
@@ -2,6 +2,7 @@ package main
import ( import (
"errors" "errors"
"log/slog"
"os" "os"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/bootstrap" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/bootstrap"
@@ -10,24 +11,24 @@ import (
func main() { func main() {
appLogger := logger.New() appLogger := logger.New()
if err := run(os.Args[1:]); err != nil { if err := run(appLogger, os.Args[1:]); err != nil {
appLogger.Error("application stopped", "error", err) appLogger.Error("application stopped", "error", err)
os.Exit(1) os.Exit(1)
} }
} }
func run(arguments []string) error { func run(logger *slog.Logger, arguments []string) error {
if len(arguments) == 0 { if len(arguments) == 0 {
return bootstrap.RunServer() return bootstrap.RunServer(logger)
} }
if len(arguments) == 1 && arguments[0] == "migrate" { if len(arguments) == 1 && arguments[0] == "migrate" {
return bootstrap.RunMigrations() return bootstrap.RunMigrations()
} }
if len(arguments) == 1 && arguments[0] == "dispatch" { if len(arguments) == 1 && arguments[0] == "dispatch" {
return bootstrap.RunDispatcher() return bootstrap.RunDispatcher(logger)
} }
if len(arguments) == 1 && arguments[0] == "worker" { if len(arguments) == 1 && arguments[0] == "worker" {
return bootstrap.RunWorker() return bootstrap.RunWorker(logger)
} }
if arguments[0] == "reconcile-attachments" { if arguments[0] == "reconcile-attachments" {
return bootstrap.RunReconciliation(arguments[1:], os.Stdout) return bootstrap.RunReconciliation(arguments[1:], os.Stdout)
-2
View File
@@ -343,8 +343,6 @@ services:
openbao-cli: openbao-cli:
profiles: ["tools"] profiles: ["tools"]
image: openbao/openbao:2.7.1 image: openbao/openbao:2.7.1
user: "0:0"
entrypoint: ["bao"]
environment: environment:
BAO_ADDR: https://openbao:8200 BAO_ADDR: https://openbao:8200
BAO_CACERT: /run/security/openbao/ca.crt BAO_CACERT: /run/security/openbao/ca.crt
-1
View File
@@ -29,7 +29,6 @@ server:
parallelism: 2 parallelism: 2
salt_length: 16 salt_length: 16
key_length: 32 key_length: 32
max_concurrent_operations: 2
database: database:
min_connections: 1 min_connections: 1
+2 -2
View File
@@ -28,7 +28,7 @@ import (
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
func RunDispatcher() error { func RunDispatcher(logger *slog.Logger) error {
settings, err := config.LoadDispatcher() settings, err := config.LoadDispatcher()
if err != nil { if err != nil {
return err return err
@@ -87,7 +87,7 @@ func RunDispatcher() error {
) )
} }
func RunWorker() error { func RunWorker(logger *slog.Logger) error {
settings, err := config.LoadWorker() settings, err := config.LoadWorker()
if err != nil { if err != nil {
return err return err
+5 -6
View File
@@ -5,13 +5,13 @@ import (
"crypto/tls" "crypto/tls"
"errors" "errors"
"fmt" "fmt"
"log/slog"
"net" "net"
"net/http" "net/http"
"os"
"os/signal" "os/signal"
"syscall" "syscall"
"github.com/google/uuid"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/loginlimit" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/loginlimit"
@@ -30,7 +30,7 @@ type serverResult struct {
err error err error
} }
func RunServer() error { func RunServer(logger *slog.Logger) error {
settings, err := config.LoadServer() settings, err := config.LoadServer()
if err != nil { if err != nil {
return err return err
@@ -49,11 +49,10 @@ func RunServer() error {
if err != nil { if err != nil {
return err return err
} }
instanceUUID, err := uuid.NewRandom() instanceID, err := os.Hostname()
if err != nil { if err != nil {
return err return err
} }
instanceID := "api-" + instanceUUID.String()
observability, logger, err := startTelemetry("messenger-api", instanceID) observability, logger, err := startTelemetry("messenger-api", instanceID)
if err != nil { if err != nil {
return err return err
@@ -92,7 +91,7 @@ func RunServer() error {
MemoryKiB: settings.PasswordMemoryKiB, Iterations: settings.PasswordIterations, MemoryKiB: settings.PasswordMemoryKiB, Iterations: settings.PasswordIterations,
Parallelism: settings.PasswordParallelism, SaltLength: settings.PasswordSaltLength, Parallelism: settings.PasswordParallelism, SaltLength: settings.PasswordSaltLength,
KeyLength: settings.PasswordKeyLength, KeyLength: settings.PasswordKeyLength,
}, settings.PasswordMaxConcurrentOperations) })
if err != nil { if err != nil {
return err return err
} }
+48 -54
View File
@@ -12,54 +12,53 @@ import (
) )
type ServerConfig struct { type ServerConfig struct {
Address string Address string
HealthAddress string HealthAddress string
MetricsAddress string MetricsAddress string
TLSCAPath string TLSCAPath string
TLSCertificatePath string TLSCertificatePath string
TLSPrivateKeyPath string TLSPrivateKeyPath string
TLSAllowedClientURI string TLSAllowedClientURI string
TLSAllowedMetricsClientURI string TLSAllowedMetricsClientURI string
DatabaseURL string DatabaseURL string
CacheURL string CacheURL string
CacheTLS ClientTLSConfig CacheTLS ClientTLSConfig
SessionTTL time.Duration SessionTTL time.Duration
IdempotencyTTL time.Duration IdempotencyTTL time.Duration
LoginRateLimitAccountAttempts int LoginRateLimitAccountAttempts int
LoginRateLimitSourceAttempts int LoginRateLimitSourceAttempts int
LoginRateLimitWindow time.Duration LoginRateLimitWindow time.Duration
DBMaxConns int32 DBMaxConns int32
DBMinConns int32 DBMinConns int32
DBMaxConnectionAge time.Duration DBMaxConnectionAge time.Duration
DBMaxConnectionIdle time.Duration DBMaxConnectionIdle time.Duration
DBHealthCheckPeriod time.Duration DBHealthCheckPeriod time.Duration
DependencyTimeout time.Duration DependencyTimeout time.Duration
RequestTimeout time.Duration RequestTimeout time.Duration
HTTPReadHeaderTimeout time.Duration HTTPReadHeaderTimeout time.Duration
HTTPReadTimeout time.Duration HTTPReadTimeout time.Duration
HTTPWriteTimeout time.Duration HTTPWriteTimeout time.Duration
HTTPIdleTimeout time.Duration HTTPIdleTimeout time.Duration
HTTPShutdownTimeout time.Duration HTTPShutdownTimeout time.Duration
PasswordMemoryKiB uint32 PasswordMemoryKiB uint32
PasswordIterations uint32 PasswordIterations uint32
PasswordParallelism uint8 PasswordParallelism uint8
PasswordSaltLength uint32 PasswordSaltLength uint32
PasswordKeyLength uint32 PasswordKeyLength uint32
PasswordMaxConcurrentOperations int SwaggerPort string
SwaggerPort string S3Endpoint string
S3Endpoint string S3Region string
S3Region string S3Bucket string
S3Bucket string S3AccessKey string
S3AccessKey string S3SecretKey string
S3SecretKey string S3UseTLS bool
S3UseTLS bool S3CAPath string
S3CAPath string S3Timeout time.Duration
S3Timeout time.Duration AttachmentMaxBytes int64
AttachmentMaxBytes int64 AttachmentMaxPixels int64
AttachmentMaxPixels int64 AttachmentBodyMemory int64
AttachmentBodyMemory int64 AttachmentDecodeMemory int64
AttachmentDecodeMemory int64 PipelineVersion int
PipelineVersion int
} }
type MigrationConfig struct { type MigrationConfig struct {
@@ -252,10 +251,6 @@ func LoadServer() (ServerConfig, error) {
if err != nil { if err != nil {
return ServerConfig{}, err 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") swaggerPort, err := requiredPort(values, "server.swagger_port")
if err != nil { if err != nil {
return ServerConfig{}, err return ServerConfig{}, err
@@ -311,8 +306,7 @@ func LoadServer() (ServerConfig, error) {
HTTPShutdownTimeout: shutdownTimeout, PasswordMemoryKiB: uint32(passwordMemory), HTTPShutdownTimeout: shutdownTimeout, PasswordMemoryKiB: uint32(passwordMemory),
PasswordIterations: uint32(passwordIterations), PasswordParallelism: uint8(passwordParallelism), PasswordIterations: uint32(passwordIterations), PasswordParallelism: uint8(passwordParallelism),
PasswordSaltLength: uint32(passwordSaltLength), PasswordKeyLength: uint32(passwordKeyLength), PasswordSaltLength: uint32(passwordSaltLength), PasswordKeyLength: uint32(passwordKeyLength),
PasswordMaxConcurrentOperations: passwordMaxConcurrentOperations, SwaggerPort: swaggerPort, S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
SwaggerPort: swaggerPort, S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
S3AccessKey: storage.accessKey, S3SecretKey: storage.secretKey, S3AccessKey: storage.accessKey, S3SecretKey: storage.secretKey,
S3UseTLS: storage.useTLS, S3CAPath: storage.caPath, S3Timeout: storage.timeout, S3UseTLS: storage.useTLS, S3CAPath: storage.caPath, S3Timeout: storage.timeout,
AttachmentMaxBytes: int64(attachmentMaxBytes), AttachmentMaxPixels: int64(attachmentMaxPixels), AttachmentMaxBytes: int64(attachmentMaxBytes), AttachmentMaxPixels: int64(attachmentMaxPixels),
-2
View File
@@ -59,7 +59,6 @@ func TestLoadServerLoadsTLSAndHealthSettings(t *testing.T) {
require.Equal(t, 5, settings.LoginRateLimitAccountAttempts) require.Equal(t, 5, settings.LoginRateLimitAccountAttempts)
require.Equal(t, 20, settings.LoginRateLimitSourceAttempts) require.Equal(t, 20, settings.LoginRateLimitSourceAttempts)
require.Equal(t, time.Minute, settings.LoginRateLimitWindow) require.Equal(t, time.Minute, settings.LoginRateLimitWindow)
require.Equal(t, 2, settings.PasswordMaxConcurrentOperations)
} }
func TestLoadServerRejectsNonLoopbackHealthAddress(t *testing.T) { func TestLoadServerRejectsNonLoopbackHealthAddress(t *testing.T) {
@@ -153,7 +152,6 @@ server:
parallelism: 2 parallelism: 2
salt_length: 16 salt_length: 16
key_length: 32 key_length: 32
max_concurrent_operations: 2
database: database:
min_connections: 0 min_connections: 0
max_connections: 4 max_connections: 4
+1 -1
View File
@@ -74,7 +74,7 @@ func loadSecretFile(values *viper.Viper, path string) error {
if err != nil { if err != nil {
return fmt.Errorf("open messenger secrets: %w", err) return fmt.Errorf("open messenger secrets: %w", err)
} }
defer func() { _ = file.Close() }() defer file.Close()
decoder := json.NewDecoder(io.LimitReader(file, 64<<10)) decoder := json.NewDecoder(io.LimitReader(file, 64<<10))
var secrets map[string]string var secrets map[string]string
if err := decoder.Decode(&secrets); err != nil { if err := decoder.Decode(&secrets); err != nil {
+17
View File
@@ -6,6 +6,7 @@ import (
"mime" "mime"
"net/http" "net/http"
"net/url" "net/url"
"regexp"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -152,6 +153,22 @@ 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) { func attachmentIDFromRequest(r *http.Request) (string, *apiError) {
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/") parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
attachmentID, valid := canonicalID(parts[3]) attachmentID, valid := canonicalID(parts[3])
+5 -5
View File
@@ -37,7 +37,7 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
credentials, err := s.userRepository.UserByUsername(r.Context(), username) credentials, err := s.userRepository.UserByUsername(r.Context(), username)
if errors.Is(err, model.ErrNotFound) { if errors.Is(err, model.ErrNotFound) {
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil { if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
return passwordOperationError(verifyErr) return internalError()
} }
return unauthorized() 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) verified, err := s.passwords.Verify(passwordValue, credentials.PasswordHash)
if err != nil { if err != nil {
return passwordOperationError(err) return internalError()
} }
if !verified { if !verified {
return unauthorized() 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 { func (s *Server) rehashPassword(ctx context.Context, credentials model.UserCredentials, passwordValue string) *apiError {
needsRehash, err := s.passwords.NeedsRehash(credentials.PasswordHash) needsRehash, err := s.passwords.NeedsRehash(credentials.PasswordHash)
if err != nil { if err != nil {
return passwordOperationError(err) return internalError()
} }
if !needsRehash { if !needsRehash {
return nil return nil
} }
passwordHash, err := s.passwords.Hash(passwordValue) passwordHash, err := s.passwords.Hash(passwordValue)
if err != nil { if err != nil {
return passwordOperationError(err) return internalError()
} }
updated, err := s.userRepository.UpdatePasswordHash(ctx, credentials.ID, credentials.PasswordHash, passwordHash) updated, err := s.userRepository.UpdatePasswordHash(ctx, credentials.ID, credentials.PasswordHash, passwordHash)
if err != nil { 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) verified, err := s.passwords.Verify(passwordValue, current.PasswordHash)
if err != nil { if err != nil {
return passwordOperationError(err) return internalError()
} }
if !verified { if !verified {
return unauthorized() return unauthorized()
-10
View File
@@ -2,10 +2,7 @@ package httpapi
import ( import (
"encoding/json" "encoding/json"
"errors"
"net/http" "net/http"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/password"
) )
const ( const (
@@ -43,13 +40,6 @@ func rateLimited() *apiError {
return &apiError{http.StatusTooManyRequests, errorCodeRateLimited, "too many requests"} 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 { func notFound() *apiError {
return &apiError{http.StatusNotFound, errorCodeNotFound, "resource not found"} return &apiError{http.StatusNotFound, errorCodeNotFound, "resource not found"}
} }
+1 -1
View File
@@ -64,7 +64,7 @@ func (s *Server) users(w http.ResponseWriter, r *http.Request) *apiError {
} }
passwordHash, err := s.passwords.Hash(input.Password) passwordHash, err := s.passwords.Hash(input.Password)
if err != nil { if err != nil {
return passwordOperationError(err) return internalError()
} }
user, err := s.userRepository.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash) user, err := s.userRepository.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
if errors.Is(err, model.ErrConflict) { if errors.Is(err, model.ErrConflict) {
-4
View File
@@ -115,7 +115,6 @@ func (s *Server) MetricsHandler() http.Handler {
} }
func (s *Server) serveHealth(w http.ResponseWriter, r *http.Request, handler requestHandler) { 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 { if err := handler(w, r); err != nil {
writeError(w, "", err) writeError(w, "", err)
} }
@@ -169,9 +168,6 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
if apiErr.status == http.StatusUnauthorized { if apiErr.status == http.StatusUnauthorized {
wrapped.Header().Set("WWW-Authenticate", authenticationChallenge(r)) 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) writeError(wrapped, requestID, apiErr)
} }
} }
-17
View File
@@ -16,7 +16,6 @@ import (
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/password"
) )
var errDependency = errors.New("dependency unavailable") var errDependency = errors.New("dependency unavailable")
@@ -255,22 +254,6 @@ func (s *MessengerSuite) TestSessionCreationReturnsRateLimitWithRetryAfter() {
s.Contains(response.Body.String(), `"code":"rate_limited"`) 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() { func (s *MessengerSuite) TestSessionCreationRehashesPasswordWithCompareAndSwap() {
var updated []string var updated []string
store := messengerStoreStub{ store := messengerStoreStub{
+4 -33
View File
@@ -15,7 +15,6 @@ import (
var ( var (
ErrInvalidConfig = errors.New("invalid password configuration") ErrInvalidConfig = errors.New("invalid password configuration")
ErrInvalidHash = errors.New("invalid password hash") ErrInvalidHash = errors.New("invalid password hash")
ErrBusy = errors.New("password operation limit reached")
) )
type Config struct { type Config struct {
@@ -27,24 +26,17 @@ type Config struct {
} }
type Hasher struct { type Hasher struct {
config Config config Config
dummyHash string dummyHash string
operations chan struct{}
} }
func New(config Config, maxConcurrentOperations int) (*Hasher, error) { func New(config Config) (*Hasher, error) {
if err := validateConfig(config); err != nil { if err := validateConfig(config); err != nil {
return nil, err return nil, err
} }
if maxConcurrentOperations < 1 || maxConcurrentOperations > 64 {
return nil, ErrInvalidConfig
}
salt := make([]byte, config.SaltLength) salt := make([]byte, config.SaltLength)
digest := argon2.IDKey([]byte("invalid-user-password"), salt, config.Iterations, config.MemoryKiB, config.Parallelism, config.KeyLength) digest := argon2.IDKey([]byte("invalid-user-password"), salt, config.Iterations, config.MemoryKiB, config.Parallelism, config.KeyLength)
return &Hasher{ return &Hasher{config: config, dummyHash: encode(config, salt, digest)}, nil
config: config, dummyHash: encode(config, salt, digest),
operations: make(chan struct{}, maxConcurrentOperations),
}, nil
} }
func validateConfig(config Config) error { func validateConfig(config Config) error {
@@ -59,10 +51,6 @@ func validateConfig(config Config) error {
} }
func (h *Hasher) Hash(value string) (string, error) { func (h *Hasher) Hash(value string) (string, error) {
if !h.acquire() {
return "", ErrBusy
}
defer h.release()
salt := make([]byte, h.config.SaltLength) salt := make([]byte, h.config.SaltLength)
if _, err := rand.Read(salt); err != nil { if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate password salt: %w", err) return "", fmt.Errorf("generate password salt: %w", err)
@@ -72,10 +60,6 @@ func (h *Hasher) Hash(value string) (string, error) {
} }
func (h *Hasher) Verify(value, encodedHash string) (bool, 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) config, salt, digest, err := decode(encodedHash)
if err != nil { if err != nil {
return false, err return false, err
@@ -84,19 +68,6 @@ func (h *Hasher) Verify(value, encodedHash string) (bool, error) {
return subtle.ConstantTimeCompare(actual, digest) == 1, nil 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) { func (h *Hasher) NeedsRehash(encodedHash string) (bool, error) {
config, _, _, err := decode(encodedHash) config, _, _, err := decode(encodedHash)
if err != nil { if err != nil {
+4 -26
View File
@@ -16,7 +16,7 @@ func TestPasswordSuite(t *testing.T) {
} }
func (s *PasswordSuite) SetupTest() { func (s *PasswordSuite) SetupTest() {
hasher, err := New(testConfig(), 2) hasher, err := New(testConfig())
s.Require().NoError(err) s.Require().NoError(err)
s.hasher = hasher s.hasher = hasher
} }
@@ -48,7 +48,7 @@ func (s *PasswordSuite) TestNeedsRehashDetectsChangedParameters() {
legacyConfig := testConfig() legacyConfig := testConfig()
legacyConfig.KeyLength = 16 legacyConfig.KeyLength = 16
legacy, err := New(legacyConfig, 2) legacy, err := New(legacyConfig)
s.Require().NoError(err) s.Require().NoError(err)
legacyHash, err := legacy.Hash("T3st-password-123") legacyHash, err := legacy.Hash("T3st-password-123")
s.Require().NoError(err) s.Require().NoError(err)
@@ -57,34 +57,12 @@ func (s *PasswordSuite) TestNeedsRehashDetectsChangedParameters() {
s.True(needsRehash) 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 { func testConfig() Config {
return Config{MemoryKiB: 8 * 1024, Iterations: 1, Parallelism: 1, SaltLength: 16, KeyLength: 32} return Config{MemoryKiB: 8 * 1024, Iterations: 1, Parallelism: 1, SaltLength: 16, KeyLength: 32}
} }
func BenchmarkArgon2idHash(b *testing.B) { func BenchmarkArgon2idHash(b *testing.B) {
hasher, err := New(productionConfig(), 2) hasher, err := New(productionConfig())
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
@@ -98,7 +76,7 @@ func BenchmarkArgon2idHash(b *testing.B) {
} }
func BenchmarkArgon2idVerify(b *testing.B) { func BenchmarkArgon2idVerify(b *testing.B) {
hasher, err := New(productionConfig(), 2) hasher, err := New(productionConfig())
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
+15
View File
@@ -263,6 +263,21 @@ func scanAttachmentWithReferenceAndObjectKey(
return err 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) { func (s *Store) AttachmentReferenced(ctx context.Context, attachmentID string) (bool, error) {
const query = `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1)` const query = `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1)`
var referenced bool var referenced bool
+3 -3
View File
@@ -40,7 +40,7 @@ func Run(ctx context.Context, config Config) error {
if err != nil { if err != nil {
return fmt.Errorf("listen: %w", err) return fmt.Errorf("listen: %w", err)
} }
defer func() { _ = listener.Close() }() defer listener.Close()
go func() { go func() {
<-ctx.Done() <-ctx.Done()
_ = listener.Close() _ = 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) { func serve(ctx context.Context, connection net.Conn, config Config, tlsConfiguration *tls.Config) {
client := tls.Server(connection, tlsConfiguration) client := tls.Server(connection, tlsConfiguration)
defer func() { _ = client.Close() }() defer client.Close()
handshakeCtx, cancel := context.WithTimeout(ctx, config.DialTimeout) handshakeCtx, cancel := context.WithTimeout(ctx, config.DialTimeout)
defer cancel() defer cancel()
if err := client.HandshakeContext(handshakeCtx); err != nil { 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 { if err != nil {
return return
} }
defer func() { _ = target.Close() }() defer target.Close()
result := make(chan struct{}, 2) result := make(chan struct{}, 2)
copyConnection := func(destination, source net.Conn) { copyConnection := func(destination, source net.Conn) {
+1 -1
View File
@@ -73,7 +73,7 @@ func handshake(serverConfig, clientConfig *tls.Config) (error, error) {
if err != nil { if err != nil {
return err, err return err, err
} }
defer func() { _ = listener.Close() }() defer listener.Close()
serverResult := make(chan error, 1) serverResult := make(chan error, 1)
go func() { go func() {
connection, acceptErr := listener.Accept() connection, acceptErr := listener.Accept()
-2
View File
@@ -6,7 +6,5 @@ script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
repo_dir=$(CDPATH= cd -- "$script_dir/.." && pwd) repo_dir=$(CDPATH= cd -- "$script_dir/.." && pwd)
env_file=${ENV_FILE:-$repo_dir/lab7.env.example} 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 \ exec docker compose --project-directory "$repo_dir" --env-file "$env_file" run --rm --no-deps -T \
-v "$repo_dir:$repo_dir:ro" openbao-cli "$@" -v "$repo_dir:$repo_dir:ro" openbao-cli "$@"
+4 -7
View File
@@ -20,17 +20,14 @@ if [ ! -f "$repo_dir/.runtime/security/openbao/tls.crt" ]; then
fi fi
"$script_dir/openbao-seed.sh" "$env_file" "$script_dir/openbao-seed.sh" "$env_file"
"$script_dir/sync-docker-workspace.sh"
compose up -d security-bootstrap openbao-permissions openbao compose up -d security-bootstrap openbao-permissions openbao
if [ -z "${BAO_ADDR:-}" ]; then openbao_address=$(compose port openbao 8200)
openbao_address=$(compose port openbao 8200) BAO_ADDR="https://$openbao_address"
BAO_ADDR="https://$openbao_address"
fi
BAO_CACERT="$repo_dir/.runtime/security/openbao/ca.crt" BAO_CACERT="$repo_dir/.runtime/security/openbao/ca.crt"
export BAO_ADDR BAO_CACERT ENV_FILE="$env_file" export BAO_ADDR BAO_CACERT ENV_FILE="$env_file"
remaining=60 remaining=60
until curl --silent --show-error --connect-timeout 2 --max-time 3 --cacert "$BAO_CACERT" \ until curl --silent --show-error --cacert "$BAO_CACERT" \
--output /dev/null "$BAO_ADDR/v1/sys/health"; do --output /dev/null "$BAO_ADDR/v1/sys/health"; do
remaining=$((remaining - 1)) remaining=$((remaining - 1))
[ "$remaining" -gt 0 ] || { [ "$remaining" -gt 0 ] || {
@@ -43,7 +40,7 @@ done
ENV_FILE="$env_file" "$script_dir/openbao-init.sh" ENV_FILE="$env_file" "$script_dir/openbao-init.sh"
ENV_FILE="$env_file" "$script_dir/openbao-unseal.sh" ENV_FILE="$env_file" "$script_dir/openbao-unseal.sh"
remaining=60 remaining=60
until curl --fail --silent --show-error --connect-timeout 2 --max-time 3 --cacert "$BAO_CACERT" \ until curl --fail --silent --show-error --cacert "$BAO_CACERT" \
--output /dev/null "$BAO_ADDR/v1/sys/health"; do --output /dev/null "$BAO_ADDR/v1/sys/health"; do
remaining=$((remaining - 1)) remaining=$((remaining - 1))
[ "$remaining" -gt 0 ] || { [ "$remaining" -gt 0 ] || {
+2 -4
View File
@@ -56,10 +56,8 @@ mkdir -p "$runtime_dir"
chmod 0700 "$repo_dir/.runtime/evidence" "$runtime_dir" chmod 0700 "$repo_dir/.runtime/evidence" "$runtime_dir"
trap restore EXIT HUP INT TERM trap restore EXIT HUP INT TERM
if [ -z "${BAO_ADDR:-}" ]; then openbao_address=$(compose port openbao 8200)
openbao_address=$(compose port openbao 8200) BAO_ADDR="https://$openbao_address"
BAO_ADDR="https://$openbao_address"
fi
BAO_CACERT="$repo_dir/.runtime/security/openbao/ca.crt" BAO_CACERT="$repo_dir/.runtime/security/openbao/ca.crt"
export BAO_ADDR BAO_CACERT export BAO_ADDR BAO_CACERT
+1 -3
View File
@@ -30,9 +30,7 @@ require_file() {
require_private_file() { require_private_file() {
require_file "$1" require_file "$1"
if ! permissions=$(stat -c '%a' "$1" 2>/dev/null); then permissions=$(stat -f '%Lp' "$1" 2>/dev/null || stat -c '%a' "$1")
permissions=$(stat -f '%Lp' "$1")
fi
case "$permissions" in case "$permissions" in
600|400) ;; 600|400) ;;
*) fail "file must have permissions 0600 or 0400: $1" ;; *) fail "file must have permissions 0600 or 0400: $1" ;;
-1
View File
@@ -79,7 +79,6 @@ if [ -n "$old_accessor" ]; then
fi fi
if [ "$output_dir" = "$openbao_runtime_dir/approle/$service" ]; then 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}" \ 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 run --rm --no-deps -e SERVICE="$service" openbao-identity-install
fi fi
-3
View File
@@ -17,7 +17,6 @@ if [ -z "$image_list" ]; then
fi fi
mkdir -p "$runtime_dir" "$cache_dir" mkdir -p "$runtime_dir" "$cache_dir"
"$script_dir/sync-docker-workspace.sh"
docker run --rm \ docker run --rm \
-v "$repo_dir:/src:ro" \ -v "$repo_dir:/src:ro" \
@@ -51,8 +50,6 @@ for image in $image_list; do
image_reports="$image_reports $image=$report" image_reports="$image_reports $image=$report"
done done
"$script_dir/sync-docker-workspace.sh" --pull-scan
python3 - "$raw_file" "$summary_file" $image_reports <<'PY' python3 - "$raw_file" "$summary_file" $image_reports <<'PY'
import datetime import datetime
import json import json
+1 -2
View File
@@ -5,8 +5,7 @@ set -eu
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}" : "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
for container in $(docker compose ps -q api); do for container in $(docker compose ps -q api); do
instance=$(docker exec "$container" wget -S -q -O /dev/null http://127.0.0.1:8082/health/live 2>&1 | instance=$(docker inspect --format '{{.Config.Hostname}}' "$container")
sed -n 's/^[[:space:]]*X-Instance-Id:[[:space:]]*//p' | tr -d '\r')
if [ "$instance" = "$TARGET_INSTANCE_ID" ]; then if [ "$instance" = "$TARGET_INSTANCE_ID" ]; then
docker stop --time 6 "$container" >/dev/null docker stop --time 6 "$container" >/dev/null
exit 0 exit 0
-51
View File
@@ -1,51 +0,0 @@
#!/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"
-1
View File
@@ -25,7 +25,6 @@ compose_rotated() {
} }
install_security_material() { install_security_material() {
"$script_dir/sync-docker-workspace.sh"
compose run --rm --no-deps security-bootstrap >/dev/null compose run --rm --no-deps security-bootstrap >/dev/null
} }