chore: finalize lab7 security verification
CI / verify (pull_request) Successful in 14m53s

This commit is contained in:
2026-11-06 22:00:42 +03:00
parent 5ac64f51fa
commit a8edaf058d
53 changed files with 1130 additions and 224 deletions
+175
View File
@@ -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
}
+5 -6
View File
@@ -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)