Files
mtusi2026lab7/student-tests/helpers_test.go
T
sxdees 2f2047909f
Skeleton contracts / contracts (pull_request) Blocked by required conditions
ЛР7 на 4: HTTPS, mTLS, OpenBao AppRole и ротация leaf.
Smoke/security/grade4/persistence/failover пройдены; REPORT и DEFENSE.
2026-12-02 23:08:27 +03:00

281 lines
5.3 KiB
Go

package studenttests_test
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"flag"
"image"
"image/color"
"image/png"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/google/uuid"
"gavrilenko-sxdees/lab7/internal/dto"
)
var baseURL = flag.String("base-url", "https://127.0.0.1:8443", "base URL of the running server")
func secretPath(name string) string {
const repoRoot = ".."
if name == "ca.crt" {
if p := os.Getenv("CA_FILE"); p != "" {
if filepath.IsAbs(p) {
return p
}
return filepath.Join(repoRoot, filepath.Clean(p))
}
}
return filepath.Join(repoRoot, "secrets", name)
}
var httpClient = &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 200,
IdleConnTimeout: 30 * time.Second,
MaxIdleConnsPerHost: 200,
MaxConnsPerHost: 200,
},
}
func configureHTTPClientTLS() {
if !strings.HasPrefix(*baseURL, "https:") {
return
}
caPEM, err := os.ReadFile(secretPath("ca.crt"))
if err != nil {
return
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(caPEM) {
return
}
httpClient.Transport = &http.Transport{
MaxIdleConns: 200,
IdleConnTimeout: 30 * time.Second,
MaxIdleConnsPerHost: 200,
MaxConnsPerHost: 200,
TLSClientConfig: &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12},
}
}
type testUser struct {
dto.UserResponse
Token string
}
const testPassword = "correct-horse-battery"
func doRequest(t *testing.T, method, path, token string, body []byte) *http.Response {
t.Helper()
req, err := http.NewRequest(method, *baseURL+path, bytes.NewReader(body))
if err != nil {
t.Fatalf("build request: %v", err)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("%s %s: request failed: %v", method, path, err)
}
return resp
}
func mustDecode(t *testing.T, resp *http.Response, dst any) {
t.Helper()
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
if err := json.Unmarshal(data, dst); err != nil {
t.Fatalf("decode body %q: %v", data, err)
}
}
func requireStatus(t *testing.T, resp *http.Response, expected int) {
t.Helper()
if resp.StatusCode != expected {
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf(
"expected status %d, got %d, body: %s",
expected,
resp.StatusCode,
data,
)
}
if resp.Header.Get("X-Request-Id") == "" {
t.Errorf("missing X-Request-Id header")
}
}
func createUser(t *testing.T) testUser {
t.Helper()
username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
body, err := json.Marshal(map[string]string{
"username": username,
"display_name": "Test " + username,
"password": testPassword,
})
if err != nil {
t.Fatalf("marshal user: %v", err)
}
resp := doRequest(t, http.MethodPost, "/api/v1/users", "", body)
requireStatus(t, resp, http.StatusCreated)
var u dto.UserResponse
mustDecode(t, resp, &u)
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/auth/sessions",
nil,
)
if err != nil {
t.Fatalf("build login request: %v", err)
}
req.SetBasicAuth(username, testPassword)
resp, err = httpClient.Do(req)
if err != nil {
t.Fatalf("login request failed: %v", err)
}
requireStatus(t, resp, http.StatusCreated)
var session dto.SessionResponse
mustDecode(t, resp, &session)
return testUser{UserResponse: u, Token: session.Token}
}
func createChat(
t *testing.T,
creator testUser,
memberIDs ...uuid.UUID,
) dto.ChatResponse {
t.Helper()
body, err := json.Marshal(map[string]any{
"title": "Test chat " + uuid.NewString()[:8],
"member_ids": memberIDs,
})
if err != nil {
t.Fatalf("marshal chat: %v", err)
}
resp := doRequest(
t,
http.MethodPost,
"/api/v1/chats",
creator.Token,
body,
)
requireStatus(t, resp, http.StatusCreated)
var c dto.ChatResponse
mustDecode(t, resp, &c)
return c
}
func sendMessage(
t *testing.T,
actor testUser,
chatID uuid.UUID,
text string,
) *http.Response {
t.Helper()
resp, err := sendLoadMessage(actor, chatID, text)
if err != nil {
t.Fatalf("send message: %v", err)
}
return resp
}
func sendLoadMessage(
actor testUser,
chatID uuid.UUID,
text string,
) (*http.Response, error) {
body, err := json.Marshal(map[string]string{
"text": text,
})
if err != nil {
return nil, err
}
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/messages",
bytes.NewReader(body),
)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+actor.Token)
req.Header.Set("Idempotency-Key", uuid.NewString())
return httpClient.Do(req)
}
func makePNG(t *testing.T, width, height int) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, width, height))
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
img.Set(x, y, color.RGBA{
R: uint8((x * 7) % 256),
G: uint8((y * 13) % 256),
B: uint8((x + y) % 256),
A: 255,
})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatalf("encode png: %v", err)
}
return buf.Bytes()
}
func TestMain(m *testing.M) {
flag.Parse()
configureHTTPClientTLS()
os.Exit(m.Run())
}