4 Commits
Author SHA1 Message Date
dizi ba7aabede2 ci: verify lab7 over HTTPS 2026-11-04 23:05:11 +03:00
dizi 58c9bb027b ops: add PKI and HTTPS ingress 2026-11-04 23:05:11 +03:00
dizi 951e554e06 feat: enforce TLS service identities 2026-11-04 23:05:11 +03:00
dizi cb51354889 Merge lab6 baseline into lab7 2026-11-01 17:59:40 +03:00
75 changed files with 1294 additions and 260 deletions
+1
View File
@@ -3,6 +3,7 @@
.env .env
.env.* .env.*
!.env.example !.env.example
.runtime
secrets secrets
certs certs
volumes volumes
+12 -12
View File
@@ -16,7 +16,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 45 timeout-minutes: 45
env: env:
COMPOSE_PROJECT_NAME: mtusi2026lab6-${{ github.run_id }} COMPOSE_PROJECT_NAME: mtusi2026lab7-${{ github.run_id }}
API_BIND_ADDRESS: 127.0.0.1:0 API_BIND_ADDRESS: 127.0.0.1:0
SWAGGER_BIND_ADDRESS: 127.0.0.1:0 SWAGGER_BIND_ADDRESS: 127.0.0.1:0
PROMETHEUS_BIND_ADDRESS: 127.0.0.1:0 PROMETHEUS_BIND_ADDRESS: 127.0.0.1:0
@@ -48,7 +48,7 @@ jobs:
- name: Check formatting and shell scripts - name: Check formatting and shell scripts
run: | run: |
test -z "$(gofmt -l cmd internal migrations)" test -z "$(gofmt -l cmd internal migrations)"
sh -n infra/minio/bootstrap.sh scripts/restart.sh scripts/rolling-update.sh scripts/stop-one.sh scripts/test-lab5.sh scripts/test-lab5-acceptance.sh scripts/test-lab6.sh scripts/incident-worker.sh scripts/incident-database.sh scripts/incident-telemetry.sh sh -n infra/minio/bootstrap.sh infra/pki/bootstrap.sh infra/pki/install.sh scripts/restart.sh scripts/rolling-update.sh scripts/stop-one.sh scripts/test-lab5.sh scripts/test-lab5-acceptance.sh scripts/test-lab6.sh scripts/test-tls-matrix.sh scripts/incident-worker.sh scripts/incident-database.sh scripts/incident-telemetry.sh
python3 -m py_compile scripts/lab6-traffic.py scripts/lab6-observe.py scripts/lab6-alert.py scripts/lab6-correlation.py scripts/validate-lab6-evidence.py python3 -m py_compile scripts/lab6-traffic.py scripts/lab6-observe.py scripts/lab6-alert.py scripts/lab6-correlation.py scripts/validate-lab6-evidence.py
- name: Lint - name: Lint
@@ -65,7 +65,8 @@ jobs:
- name: Prepare local stack - name: Prepare local stack
run: | run: |
cp lab6.env.example .env cp lab7.env.example .env
./infra/pki/bootstrap.sh
docker compose config --quiet docker compose config --quiet
docker compose up -d --build --scale api=2 --wait --wait-timeout 150 docker compose up -d --build --scale api=2 --wait --wait-timeout 150
docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME" docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME"
@@ -74,19 +75,18 @@ jobs:
- name: Integration checks - name: Integration checks
run: | run: |
set -a test "$(curl --noproxy '*' -s -o /dev/null -w '%{http_code}' "http://s3:9000/messenger-attachments")" = "403"
. ./.env make test BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
set +a make test-security BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
test "$(curl --noproxy '*' -s -o /dev/null -w '%{http_code}' "http://s3:9000/$S3_BUCKET")" = "403" make test-tls-matrix
make test BASE_URL=http://nginx:8080
docker compose --profile tests run --rm --build tests docker compose --profile tests run --rm --build tests
go run ./cmd/dependencycheck -base-url=http://nginx:8080 go run ./cmd/dependencycheck -base-url=https://nginx:8443 -ca-file=.runtime/security/public-ca/ca.crt
make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://nginx:8080 make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://nginx:8080 make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
docker compose up -d --scale api=2 --wait --wait-timeout 90 docker compose up -d --scale api=2 --wait --wait-timeout 90
make test-lab5-acceptance make test-lab5-acceptance
make test-lab5 make test-lab5
ENV_FILE=.env PROMETHEUS_URL=http://prometheus:9090 TEMPO_URL=http://tempo:3200 LOKI_URL=http://loki:3100 make test-lab6-smoke BASE_URL=http://nginx:8080 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: Container logs - name: Container logs
if: failure() if: failure()
+22 -22
View File
@@ -22,7 +22,7 @@ jobs:
s3_image: ${{ steps.publish.outputs.s3_image }} s3_image: ${{ steps.publish.outputs.s3_image }}
s3_bootstrap_image: ${{ steps.publish.outputs.s3_bootstrap_image }} s3_bootstrap_image: ${{ steps.publish.outputs.s3_bootstrap_image }}
env: env:
COMPOSE_PROJECT_NAME: mtusi2026lab6-deploy-${{ github.run_id }} COMPOSE_PROJECT_NAME: mtusi2026lab7-deploy-${{ github.run_id }}
COMPOSE_FILE: compose.yaml:deploy/compose.images.yaml COMPOSE_FILE: compose.yaml:deploy/compose.images.yaml
API_BIND_ADDRESS: 127.0.0.1:0 API_BIND_ADDRESS: 127.0.0.1:0
SWAGGER_BIND_ADDRESS: 127.0.0.1:0 SWAGGER_BIND_ADDRESS: 127.0.0.1:0
@@ -30,13 +30,13 @@ jobs:
GRAFANA_BIND_ADDRESS: 127.0.0.1:0 GRAFANA_BIND_ADDRESS: 127.0.0.1:0
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
API_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab6-api:${{ github.sha }} API_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab7-api:${{ github.sha }}
NGINX_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab6-nginx:${{ github.sha }} NGINX_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab7-nginx:${{ github.sha }}
SWAGGER_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab6-swagger:${{ github.sha }} SWAGGER_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab7-swagger:${{ github.sha }}
PROMETHEUS_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab6-prometheus:${{ github.sha }} PROMETHEUS_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab7-prometheus:${{ github.sha }}
GRAFANA_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab6-grafana:${{ github.sha }} GRAFANA_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab7-grafana:${{ github.sha }}
S3_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab6-minio:${{ github.sha }} S3_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab7-minio:${{ github.sha }}
S3_BOOTSTRAP_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab6-minio-client:${{ github.sha }} S3_BOOTSTRAP_IMAGE: gitea.privcloud.tech/${{ github.repository_owner }}/mtusi2026lab7-minio-client:${{ github.sha }}
steps: steps:
- name: Checkout exact commit - name: Checkout exact commit
run: | run: |
@@ -62,7 +62,7 @@ jobs:
- name: Check formatting and shell scripts - name: Check formatting and shell scripts
run: | run: |
test -z "$(gofmt -l cmd internal migrations)" test -z "$(gofmt -l cmd internal migrations)"
sh -n infra/minio/bootstrap.sh scripts/restart.sh scripts/rolling-update.sh scripts/stop-one.sh scripts/test-lab5.sh scripts/test-lab5-acceptance.sh scripts/test-lab6.sh scripts/incident-worker.sh scripts/incident-database.sh scripts/incident-telemetry.sh sh -n infra/minio/bootstrap.sh infra/pki/bootstrap.sh infra/pki/install.sh scripts/restart.sh scripts/rolling-update.sh scripts/stop-one.sh scripts/test-lab5.sh scripts/test-lab5-acceptance.sh scripts/test-lab6.sh scripts/test-tls-matrix.sh scripts/incident-worker.sh scripts/incident-database.sh scripts/incident-telemetry.sh
python3 -m py_compile scripts/lab6-traffic.py scripts/lab6-observe.py scripts/lab6-alert.py scripts/lab6-correlation.py scripts/validate-lab6-evidence.py python3 -m py_compile scripts/lab6-traffic.py scripts/lab6-observe.py scripts/lab6-alert.py scripts/lab6-correlation.py scripts/validate-lab6-evidence.py
- name: Lint - name: Lint
@@ -79,7 +79,8 @@ jobs:
- name: Prepare local stack - name: Prepare local stack
run: | run: |
cp lab6.env.example .env cp lab7.env.example .env
./infra/pki/bootstrap.sh
docker compose config --quiet docker compose config --quiet
docker compose up -d --build --scale api=2 --wait --wait-timeout 150 docker compose up -d --build --scale api=2 --wait --wait-timeout 150
docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME" docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME"
@@ -88,18 +89,17 @@ jobs:
- name: Integration checks - name: Integration checks
run: | run: |
set -a test "$(curl --noproxy '*' -s -o /dev/null -w '%{http_code}' "http://s3:9000/messenger-attachments")" = "403"
. ./.env make test BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
set +a make test-security BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
test "$(curl --noproxy '*' -s -o /dev/null -w '%{http_code}' "http://s3:9000/$S3_BUCKET")" = "403" make test-tls-matrix
make test BASE_URL=http://nginx:8080
docker compose --profile tests run --rm --build tests docker compose --profile tests run --rm --build tests
go run ./cmd/dependencycheck -base-url=http://nginx:8080 go run ./cmd/dependencycheck -base-url=https://nginx:8443 -ca-file=.runtime/security/public-ca/ca.crt
make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://nginx:8080 make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://nginx:8080 make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=https://nginx:8443 CA_FILE=.runtime/security/public-ca/ca.crt
make test-lab5-acceptance make test-lab5-acceptance
make test-lab5 make test-lab5
ENV_FILE=.env PROMETHEUS_URL=http://prometheus:9090 TEMPO_URL=http://tempo:3200 LOKI_URL=http://loki:3100 make test-lab6-smoke BASE_URL=http://nginx:8080 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: Publish verified images - name: Publish verified images
id: publish id: publish
@@ -177,17 +177,17 @@ jobs:
run: printf '%s' "$REGISTRY_PASSWORD" | ssh "$DEPLOY_USER@$DEPLOY_HOST" "docker login gitea.privcloud.tech --username '$REGISTRY_USERNAME' --password-stdin" run: printf '%s' "$REGISTRY_PASSWORD" | ssh "$DEPLOY_USER@$DEPLOY_HOST" "docker login gitea.privcloud.tech --username '$REGISTRY_USERNAME' --password-stdin"
- name: Upload image manifest - name: Upload image manifest
run: scp deploy-images.env "$DEPLOY_USER@$DEPLOY_HOST:/tmp/mtusi2026lab6-${{ github.run_id }}.env" run: scp deploy-images.env "$DEPLOY_USER@$DEPLOY_HOST:/tmp/mtusi2026lab7-${{ github.run_id }}.env"
- name: Deploy and verify - name: Deploy and verify
run: | run: |
ssh "$DEPLOY_USER@$DEPLOY_HOST" " ssh "$DEPLOY_USER@$DEPLOY_HOST" "
set -eu set -eu
cd ~/mtusi2026lab6 cd ~/mtusi2026lab7
git fetch origin main git fetch origin main
git cat-file -e '$DEPLOY_SHA^{commit}' git cat-file -e '$DEPLOY_SHA^{commit}'
git reset --hard '$DEPLOY_SHA' git reset --hard '$DEPLOY_SHA'
manifest='/tmp/mtusi2026lab6-${{ github.run_id }}.env' manifest='/tmp/mtusi2026lab7-${{ github.run_id }}.env'
if DEPLOY_GENERATION='${{ github.run_id }}' scripts/rolling-update.sh \"\$manifest\"; then if DEPLOY_GENERATION='${{ github.run_id }}' scripts/rolling-update.sh \"\$manifest\"; then
rm -f \"\$manifest\" rm -f \"\$manifest\"
else else
+7 -5
View File
@@ -1,10 +1,10 @@
name: Lab 6 incidents name: Lab 7 inherited incidents
on: on:
workflow_dispatch: workflow_dispatch:
concurrency: concurrency:
group: lab6-incidents-${{ github.repository }}-${{ github.ref }} group: lab7-incidents-${{ github.repository }}-${{ github.ref }}
cancel-in-progress: false cancel-in-progress: false
jobs: jobs:
@@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 35 timeout-minutes: 35
env: env:
COMPOSE_PROJECT_NAME: mtusi2026lab6-incidents-${{ github.run_id }} COMPOSE_PROJECT_NAME: mtusi2026lab7-incidents-${{ github.run_id }}
API_BIND_ADDRESS: 127.0.0.1:0 API_BIND_ADDRESS: 127.0.0.1:0
SWAGGER_BIND_ADDRESS: 127.0.0.1:0 SWAGGER_BIND_ADDRESS: 127.0.0.1:0
PROMETHEUS_BIND_ADDRESS: 127.0.0.1:0 PROMETHEUS_BIND_ADDRESS: 127.0.0.1:0
@@ -34,7 +34,8 @@ jobs:
- name: Prepare stack - name: Prepare stack
run: | run: |
cp lab6.env.example .env cp lab7.env.example .env
./infra/pki/bootstrap.sh
docker compose config --quiet docker compose config --quiet
docker compose up -d --build --scale api=2 --wait --wait-timeout 180 docker compose up -d --build --scale api=2 --wait --wait-timeout 180
docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME" docker network connect "${COMPOSE_PROJECT_NAME}_application" "$HOSTNAME"
@@ -44,7 +45,8 @@ jobs:
- name: Reproduce SLO incidents - name: Reproduce SLO incidents
run: | run: |
ENV_FILE=.env \ ENV_FILE=.env \
BASE_URL=http://nginx:8080 \ BASE_URL=https://nginx:8443 \
CA_FILE=.runtime/security/public-ca/ca.crt \
PROMETHEUS_URL=http://prometheus:9090 \ PROMETHEUS_URL=http://prometheus:9090 \
TEMPO_URL=http://tempo:3200 \ TEMPO_URL=http://tempo:3200 \
LOKI_URL=http://loki:3100 \ LOKI_URL=http://loki:3100 \
+2
View File
@@ -2,6 +2,7 @@
.env .env
.env.* .env.*
!.env.example !.env.example
.runtime/
secrets/ secrets/
certs/private/ certs/private/
*.key *.key
@@ -32,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/
+12 -2
View File
@@ -1,9 +1,19 @@
FROM alpine:3.24.2 AS security-test
RUN apk add --no-cache curl openssl
WORKDIR /src
COPY scripts/test-tls-matrix.sh /src/scripts/test-tls-matrix.sh
CMD ["/bin/sh", "/src/scripts/test-tls-matrix.sh"]
FROM golang:1.26.5-alpine3.24 AS build FROM golang:1.26.5-alpine3.24 AS build
ARG GOPROXY=https://proxy.golang.org
WORKDIR /src WORKDIR /src
ENV GOMAXPROCS=2 GOMEMLIMIT=1GiB ENV GOMAXPROCS=2 GOMEMLIMIT=1GiB
RUN apk add --no-cache git
COPY go.mod go.sum ./ COPY go.mod go.sum ./
RUN go mod download RUN GOPROXY="$GOPROXY" go mod download
COPY . . COPY . .
RUN go build -p=1 -o /out/messenger ./cmd/messenger RUN go build -p=1 -o /out/messenger ./cmd/messenger
RUN go build -p=1 -o /out/lab5experiment ./cmd/lab5experiment RUN go build -p=1 -o /out/lab5experiment ./cmd/lab5experiment
@@ -41,5 +51,5 @@ COPY --from=build --chown=app:app /out/lab5experiment /app/lab5experiment
USER app USER app
WORKDIR /app WORKDIR /app
HEALTHCHECK --interval=10s --timeout=2s --start-period=5s --retries=3 \ HEALTHCHECK --interval=10s --timeout=2s --start-period=5s --retries=3 \
CMD wget -q -O /dev/null "http://127.0.0.1:${APP_PORT}/health/ready" || exit 1 CMD wget -q -O /dev/null "http://127.0.0.1:8082/health/ready" || exit 1
CMD ["/app/messenger"] CMD ["/app/messenger"]
+20 -1
View File
@@ -2,9 +2,10 @@ PYTHON ?= python3
BASE_URL ?= https://localhost:8443 BASE_URL ?= https://localhost:8443
CA_FILE ?= CA_FILE ?=
ACTION_SCRIPT ?= ACTION_SCRIPT ?=
ENV_FILE ?= $(if $(wildcard .env),.env,lab7.env.example)
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
.PHONY: help check validate test load test-persistence test-failover test-security .PHONY: help check validate test load test-persistence test-failover test-security test-tls-matrix test-lab5 test-lab5-acceptance lab6-load test-lab6-smoke test-lab6
help: help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@@ -31,3 +32,21 @@ test-failover:
test-security: test-security:
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-tls-matrix:
docker compose --env-file "$(ENV_FILE)" --profile security run --rm security-tests
test-lab5:
./scripts/test-lab5.sh
test-lab5-acceptance:
./scripts/test-lab5-acceptance.sh
lab6-load:
$(PYTHON) scripts/lab6-traffic.py --base-url "$(BASE_URL)" $(TLS_ARGS) --mode mixed --duration 60 --concurrency 4 --wait-ready
test-lab6-smoke:
ENV_FILE="$(ENV_FILE)" BASE_URL="$(BASE_URL)" CA_FILE="$(CA_FILE)" ./scripts/test-lab6.sh smoke
test-lab6:
ENV_FILE="$(ENV_FILE)" BASE_URL="$(BASE_URL)" CA_FILE="$(CA_FILE)" ./scripts/test-lab6.sh full
+26 -7
View File
@@ -2,6 +2,8 @@ package main
import ( import (
"bytes" "bytes"
"crypto/tls"
"crypto/x509"
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
@@ -17,10 +19,11 @@ import (
) )
type apiClient struct { type apiClient struct {
baseURL string baseURL string
client *http.Client client *http.Client
token string transport *http.Transport
userID string token string
userID string
} }
func main() { func main() {
@@ -32,9 +35,23 @@ func main() {
} }
func run() error { func run() error {
baseURL := flag.String("base-url", "http://localhost:8080", "API base URL") baseURL := flag.String("base-url", "https://localhost:8443", "API base URL")
caFile := flag.String("ca-file", ".runtime/security/public-ca/ca.crt", "trusted CA certificate")
flag.Parse() flag.Parse()
client := &apiClient{baseURL: *baseURL, client: &http.Client{Timeout: 10 * time.Second}} caPEM, err := os.ReadFile(*caFile)
if err != nil {
return fmt.Errorf("read trusted CA: %w", err)
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(caPEM) {
return fmt.Errorf("trusted CA does not contain a certificate")
}
transport := &http.Transport{TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}}
defer transport.CloseIdleConnections()
client := &apiClient{
baseURL: *baseURL, client: &http.Client{Transport: transport, Timeout: 10 * time.Second},
transport: transport,
}
if err := client.registerAndLogin(); err != nil { if err := client.registerAndLogin(); err != nil {
return err return err
} }
@@ -130,7 +147,9 @@ func (c *apiClient) verifyConcurrentIdempotency() error {
instances = make(map[string]struct{}) instances = make(map[string]struct{})
messageID string messageID string
) )
transport := &http.Transport{DisableKeepAlives: true, MaxConnsPerHost: workers} transport := c.transport.Clone()
transport.DisableKeepAlives = true
transport.MaxConnsPerHost = workers
client := &http.Client{Transport: transport, Timeout: 10 * time.Second} client := &http.Client{Transport: transport, Timeout: 10 * time.Second}
defer transport.CloseIdleConnections() defer transport.CloseIdleConnections()
+32 -6
View File
@@ -3,6 +3,8 @@ package main
import ( import (
"bytes" "bytes"
"context" "context"
"crypto/tls"
"crypto/x509"
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"errors" "errors"
@@ -12,16 +14,18 @@ import (
_ "image/jpeg" _ "image/jpeg"
"io" "io"
"net/http" "net/http"
"os"
"strings" "strings"
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
type apiState struct { type apiState struct {
BaseURL string `json:"base_url"` BaseURL string `json:"base_url"`
CAFile string `json:"ca_file"`
Token string `json:"token"` Token string `json:"token"`
AttachmentID string `json:"attachment_id"` AttachmentID string `json:"attachment_id"`
} }
@@ -41,11 +45,15 @@ type apiChat struct {
func runAPIProduce(arguments []string, output io.Writer) error { func runAPIProduce(arguments []string, output io.Writer) error {
flags := flag.NewFlagSet("api-produce", flag.ContinueOnError) flags := flag.NewFlagSet("api-produce", flag.ContinueOnError)
flags.SetOutput(io.Discard) flags.SetOutput(io.Discard)
baseURL := flags.String("base-url", "http://nginx:8080", "messenger base URL") baseURL := flags.String("base-url", "https://nginx:8443", "messenger base URL")
caFile := flags.String("ca-file", "/run/security/public-ca/ca.crt", "trusted CA certificate")
if err := flags.Parse(arguments); err != nil || flags.NArg() != 0 { if err := flags.Parse(arguments); err != nil || flags.NArg() != 0 {
return errors.New("usage: lab5experiment api-produce [-base-url URL]") return errors.New("usage: lab5experiment api-produce [-base-url URL] [-ca-file PATH]")
}
client, err := newAPIClient(*caFile)
if err != nil {
return err
} }
client := &http.Client{Timeout: 10 * time.Second}
suffix := strings.ReplaceAll(uuid.NewString(), "-", "")[:12] suffix := strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
password := "Lab5-" + uuid.NewString() password := "Lab5-" + uuid.NewString()
owner, err := registerAPIUser(client, *baseURL, "qa_"+suffix, password) owner, err := registerAPIUser(client, *baseURL, "qa_"+suffix, password)
@@ -102,7 +110,9 @@ func runAPIProduce(arguments []string, output io.Writer) error {
if response.StatusCode != http.StatusConflict { if response.StatusCode != http.StatusConflict {
return fmt.Errorf("queued content returned %d, expected 409", response.StatusCode) return fmt.Errorf("queued content returned %d, expected 409", response.StatusCode)
} }
return json.NewEncoder(output).Encode(apiState{BaseURL: *baseURL, Token: token, AttachmentID: attachment.ID}) return json.NewEncoder(output).Encode(apiState{
BaseURL: *baseURL, CAFile: *caFile, Token: token, AttachmentID: attachment.ID,
})
} }
func runAPIVerify(arguments []string, input io.Reader, output io.Writer) error { func runAPIVerify(arguments []string, input io.Reader, output io.Writer) error {
@@ -116,7 +126,10 @@ func runAPIVerify(arguments []string, input io.Reader, output io.Writer) error {
if err := json.NewDecoder(input).Decode(&state); err != nil { if err := json.NewDecoder(input).Decode(&state); err != nil {
return fmt.Errorf("decode API scenario state: %w", err) return fmt.Errorf("decode API scenario state: %w", err)
} }
client := &http.Client{Timeout: 10 * time.Second} client, err := newAPIClient(state.CAFile)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), *waitTimeout) ctx, cancel := context.WithTimeout(context.Background(), *waitTimeout)
defer cancel() defer cancel()
var attachment model.Attachment var attachment model.Attachment
@@ -176,6 +189,19 @@ func runAPIVerify(arguments []string, input io.Reader, output io.Writer) error {
}) })
} }
func newAPIClient(caFile string) (*http.Client, error) {
caPEM, err := os.ReadFile(caFile)
if err != nil {
return nil, fmt.Errorf("read trusted CA: %w", err)
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(caPEM) {
return nil, errors.New("trusted CA does not contain a certificate")
}
transport := &http.Transport{TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}}
return &http.Client{Transport: transport, Timeout: 10 * time.Second}, nil
}
func registerAPIUser(client *http.Client, baseURL, username, password string) (apiUser, error) { func registerAPIUser(client *http.Client, baseURL, username, password string) (apiUser, error) {
body, err := json.Marshal(map[string]string{ body, err := json.Marshal(map[string]string{
"username": username, "display_name": username, "password": password, "username": username, "display_name": username, "password": password,
+9 -9
View File
@@ -21,15 +21,15 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/broker/redisstream" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/broker/redisstream"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/transform"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/worker" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/worker"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/outbox" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/outbox"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres"
) )
const ( const (
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"log/slog" "log/slog"
"os" "os"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/bootstrap" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/bootstrap"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/logger" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/logger"
) )
func main() { func main() {
+84 -24
View File
@@ -10,6 +10,20 @@ x-telemetry-environment: &telemetry-environment
OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=${DEPLOYMENT_ENVIRONMENT},service.version=${SERVICE_VERSION} OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=${DEPLOYMENT_ENVIRONMENT},service.version=${SERVICE_VERSION}
services: services:
security-bootstrap:
image: alpine:3.24.2
entrypoint: ["/bin/sh", "/install.sh"]
volumes:
- ./.runtime/security:/source:ro
- ./infra/pki/install.sh:/install.sh:ro
- api_security:/target/api
- nginx_security:/target/nginx
- prometheus_security:/target/prometheus
- client_security:/target/client
healthcheck:
disable: true
restart: "no"
postgres: postgres:
image: postgres:17.6-alpine3.22 image: postgres:17.6-alpine3.22
environment: environment:
@@ -123,7 +137,7 @@ services:
networks: [data] networks: [data]
migrate: migrate:
image: ${API_IMAGE:-mtusi-messenger:lab6} image: ${API_IMAGE:-mtusi-messenger:lab7}
command: ["/app/messenger", "migrate"] command: ["/app/messenger", "migrate"]
environment: environment:
MESSENGER_CONFIG_PATH: /etc/messenger/messenger.yaml MESSENGER_CONFIG_PATH: /etc/messenger/messenger.yaml
@@ -142,13 +156,14 @@ services:
api: api:
build: . build: .
image: ${API_IMAGE:-mtusi-messenger:lab6} image: ${API_IMAGE:-mtusi-messenger:lab7}
environment: environment:
<<: *telemetry-environment <<: *telemetry-environment
OTEL_SERVICE_NAME: messenger-api OTEL_SERVICE_NAME: messenger-api
MESSENGER_CONFIG_PATH: /etc/messenger/messenger.yaml MESSENGER_CONFIG_PATH: /etc/messenger/messenger.yaml
APP_HOST: ${APP_HOST} APP_HOST: ${APP_HOST}
APP_PORT: ${APP_PORT} APP_PORT: ${APP_PORT}
APP_HEALTH_ADDRESS: ${APP_HEALTH_ADDRESS}
DATABASE_URL: ${DATABASE_URL} DATABASE_URL: ${DATABASE_URL}
CACHE_URL: ${CACHE_URL} CACHE_URL: ${CACHE_URL}
SWAGGER_PORT: ${SWAGGER_PORT} SWAGGER_PORT: ${SWAGGER_PORT}
@@ -159,9 +174,13 @@ services:
S3_SECRET_KEY: ${S3_SECRET_KEY} S3_SECRET_KEY: ${S3_SECRET_KEY}
volumes: volumes:
- *messenger-config-volume - *messenger-config-volume
- api_security:/run/security:ro
expose: expose:
- "8080" - "8443"
- "9091"
depends_on: depends_on:
security-bootstrap:
condition: service_completed_successfully
migrate: migrate:
condition: service_completed_successfully condition: service_completed_successfully
valkey: valkey:
@@ -169,7 +188,7 @@ services:
s3-bootstrap: s3-bootstrap:
condition: service_completed_successfully condition: service_completed_successfully
healthcheck: healthcheck:
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:${APP_PORT}/health/ready || exit 1"] test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8082/health/ready || exit 1"]
interval: 2s interval: 2s
timeout: 1s timeout: 1s
start_period: 5s start_period: 5s
@@ -180,10 +199,10 @@ services:
mem_limit: ${API_MEMORY} mem_limit: ${API_MEMORY}
stop_grace_period: 8s stop_grace_period: 8s
restart: unless-stopped restart: unless-stopped
networks: [application, data] networks: [application, data, monitoring]
dispatcher: dispatcher:
image: ${API_IMAGE:-mtusi-messenger:lab6} image: ${API_IMAGE:-mtusi-messenger:lab7}
command: ["/app/messenger", "dispatch"] command: ["/app/messenger", "dispatch"]
environment: environment:
<<: *telemetry-environment <<: *telemetry-environment
@@ -211,7 +230,7 @@ services:
networks: [data, monitoring] networks: [data, monitoring]
worker: worker:
image: ${API_IMAGE:-mtusi-messenger:lab6} image: ${API_IMAGE:-mtusi-messenger:lab7}
command: ["/app/messenger", "worker"] command: ["/app/messenger", "worker"]
environment: environment:
<<: *telemetry-environment <<: *telemetry-environment
@@ -250,10 +269,14 @@ services:
build: build:
context: . context: .
target: loadbalancer target: loadbalancer
image: ${NGINX_IMAGE:-mtusi-nginx:lab6} image: ${NGINX_IMAGE:-mtusi-nginx:lab7}
ports: ports:
- "${API_BIND_ADDRESS}:8080" - "${API_BIND_ADDRESS}:8443"
volumes:
- nginx_security:/run/security:ro
depends_on: depends_on:
security-bootstrap:
condition: service_completed_successfully
api: api:
condition: service_healthy condition: service_healthy
healthcheck: healthcheck:
@@ -266,11 +289,29 @@ services:
restart: unless-stopped restart: unless-stopped
networks: [edge, application, monitoring] networks: [edge, application, monitoring]
security-tests:
profiles: ["security"]
build:
context: .
target: security-test
environment:
PUBLIC_TLS_HOST: nginx
PUBLIC_TLS_PORT: "8443"
API_TLS_ADDRESS: api:8443
METRICS_TLS_ADDRESS: api:9091
SECURITY_DIR: /src/.runtime/security
volumes:
- ./.runtime/security:/src/.runtime/security:ro
depends_on:
nginx:
condition: service_healthy
networks: [edge, application]
swagger: swagger:
build: build:
context: . context: .
target: swagger target: swagger
image: ${SWAGGER_IMAGE:-mtusi-swagger:lab6} image: ${SWAGGER_IMAGE:-mtusi-swagger:lab7}
ports: ports:
- "${SWAGGER_BIND_ADDRESS}:8080" - "${SWAGGER_BIND_ADDRESS}:8080"
depends_on: depends_on:
@@ -300,7 +341,7 @@ services:
lab5-experiment: lab5-experiment:
profiles: ["experiments"] profiles: ["experiments"]
image: ${API_IMAGE:-mtusi-messenger:lab6} image: ${API_IMAGE:-mtusi-messenger:lab7}
command: ["/app/lab5experiment"] command: ["/app/lab5experiment"]
environment: environment:
MESSENGER_CONFIG_PATH: /etc/messenger/messenger.yaml MESSENGER_CONFIG_PATH: /etc/messenger/messenger.yaml
@@ -313,6 +354,7 @@ services:
BROKER_URL: ${BROKER_URL} BROKER_URL: ${BROKER_URL}
volumes: volumes:
- *messenger-config-volume - *messenger-config-volume
- client_security:/run/security:ro
depends_on: depends_on:
migrate: migrate:
condition: service_completed_successfully condition: service_completed_successfully
@@ -386,7 +428,7 @@ services:
build: build:
context: . context: .
target: prometheus target: prometheus
image: ${PROMETHEUS_IMAGE:-mtusi-prometheus:lab6} image: ${PROMETHEUS_IMAGE:-mtusi-prometheus:lab7}
command: command:
- --config.file=/etc/prometheus/prometheus.yml - --config.file=/etc/prometheus/prometheus.yml
- --storage.tsdb.path=/prometheus - --storage.tsdb.path=/prometheus
@@ -394,6 +436,7 @@ services:
- --web.enable-remote-write-receiver - --web.enable-remote-write-receiver
volumes: volumes:
- prometheus_data:/prometheus - prometheus_data:/prometheus
- prometheus_security:/run/security:ro
ports: ports:
- "${PROMETHEUS_BIND_ADDRESS}:9090" - "${PROMETHEUS_BIND_ADDRESS}:9090"
healthcheck: healthcheck:
@@ -402,17 +445,30 @@ services:
timeout: 3s timeout: 3s
retries: 20 retries: 20
depends_on: depends_on:
- api security-bootstrap:
- nginx-exporter condition: service_completed_successfully
- postgres-exporter api:
- valkey-exporter condition: service_healthy
- redis-broker-exporter nginx-exporter:
- dispatcher condition: service_started
- worker postgres-exporter:
- s3 condition: service_started
- otel-collector valkey-exporter:
- loki condition: service_started
- tempo redis-broker-exporter:
condition: service_started
dispatcher:
condition: service_healthy
worker:
condition: service_healthy
s3:
condition: service_healthy
otel-collector:
condition: service_healthy
loki:
condition: service_healthy
tempo:
condition: service_healthy
cpus: ${PROMETHEUS_CPUS} cpus: ${PROMETHEUS_CPUS}
mem_limit: ${PROMETHEUS_MEMORY} mem_limit: ${PROMETHEUS_MEMORY}
restart: unless-stopped restart: unless-stopped
@@ -422,7 +478,7 @@ services:
build: build:
context: . context: .
target: grafana target: grafana
image: ${GRAFANA_IMAGE:-mtusi-grafana:lab6} image: ${GRAFANA_IMAGE:-mtusi-grafana:lab7}
environment: environment:
GF_SECURITY_ADMIN_USER: admin GF_SECURITY_ADMIN_USER: admin
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD} GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD}
@@ -507,6 +563,10 @@ services:
networks: [application, data, monitoring] networks: [application, data, monitoring]
volumes: volumes:
api_security:
nginx_security:
prometheus_security:
client_security:
postgres_data: postgres_data:
valkey_data: valkey_data:
redis_broker_data: redis_broker_data:
+8
View File
@@ -1,6 +1,14 @@
version: 1 version: 1
server: server:
health_address: 127.0.0.1:8082
metrics_address: 0.0.0.0:9091
tls:
ca_path: /run/security/internal-ca/ca.crt
certificate_path: /run/security/api/tls.crt
private_key_path: /run/security/api/tls.key
allowed_client_uri: spiffe://mtusi/lab7/load-balancer
allowed_metrics_client_uri: spiffe://mtusi/lab7/prometheus
session_store: valkey session_store: valkey
session_ttl: 1h session_ttl: 1h
idempotency_ttl: 24h idempotency_ttl: 24h
+1 -1
View File
@@ -1,4 +1,4 @@
module gitea.privcloud.tech/dizi/mtusi2026lab6 module gitea.privcloud.tech/dizi/mtusi2026lab7
go 1.26.0 go 1.26.0
+7
View File
@@ -58,6 +58,13 @@ service:
telemetry: telemetry:
logs: logs:
level: info level: info
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
pipelines: pipelines:
metrics: metrics:
receivers: [otlp] receivers: [otlp]
+107
View File
@@ -0,0 +1,107 @@
#!/bin/sh
set -eu
umask 077
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
repo_dir=$(CDPATH= cd -- "$script_dir/../.." && pwd)
security_dir="$repo_dir/.runtime/security"
staging_dir="$security_dir/.bootstrap.$$"
cleanup() {
rm -rf "$staging_dir"
}
trap cleanup EXIT HUP INT TERM
if [ "${1:-}" = "--force" ]; then
force=1
elif [ "$#" -eq 0 ]; then
force=0
else
echo "usage: $0 [--force]" >&2
exit 2
fi
if [ -d "$security_dir/public-ca" ] || [ -d "$security_dir/internal-ca" ]; then
if [ "$force" -ne 1 ]; then
echo "security material already exists; use --force to replace it" >&2
exit 1
fi
fi
mkdir -p "$security_dir" "$staging_dir"
chmod 0700 "$security_dir" "$staging_dir"
create_ca() {
name=$1
common_name=$2
directory="$staging_dir/$name"
mkdir -p "$directory"
openssl genpkey -quiet -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out "$directory/ca.key"
openssl req -new -x509 -sha256 -days 3650 \
-key "$directory/ca.key" \
-out "$directory/ca.crt" \
-subj "/CN=$common_name" \
-config "$script_dir/templates/ca.cnf" \
-extensions v3_ca
}
create_leaf() {
name=$1
common_name=$2
issuer=$3
template=$4
directory="$staging_dir/$name"
issuer_directory="$staging_dir/$issuer"
mkdir -p "$directory"
openssl genpkey -quiet -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out "$directory/tls.key"
openssl req -new -sha256 \
-key "$directory/tls.key" \
-out "$directory/tls.csr" \
-subj "/CN=$common_name"
openssl x509 -req -sha256 -days 30 \
-in "$directory/tls.csr" \
-CA "$issuer_directory/ca.crt" \
-CAkey "$issuer_directory/ca.key" \
-CAcreateserial \
-out "$directory/tls.crt" \
-extfile "$script_dir/templates/$template"
rm "$directory/tls.csr"
}
create_ca public-ca "MTUSI Lab 7 Public CA"
create_ca internal-ca "MTUSI Lab 7 Internal CA"
create_ca foreign-ca "MTUSI Lab 7 Foreign CA"
create_leaf ingress localhost public-ca ingress.cnf
create_leaf api api internal-ca api.cnf
create_leaf load-balancer load-balancer internal-ca load-balancer.cnf
create_leaf prometheus prometheus internal-ca prometheus.cnf
create_leaf forbidden-client worker internal-ca forbidden-client.cnf
create_leaf foreign-client load-balancer foreign-ca load-balancer.cnf
openssl verify -purpose sslserver -verify_hostname localhost \
-CAfile "$staging_dir/public-ca/ca.crt" "$staging_dir/ingress/tls.crt" >/dev/null
openssl verify -purpose sslserver -verify_hostname api \
-CAfile "$staging_dir/internal-ca/ca.crt" "$staging_dir/api/tls.crt" >/dev/null
openssl verify -purpose sslclient \
-CAfile "$staging_dir/internal-ca/ca.crt" \
"$staging_dir/load-balancer/tls.crt" \
"$staging_dir/prometheus/tls.crt" \
"$staging_dir/forbidden-client/tls.crt" >/dev/null
openssl verify -purpose sslclient \
-CAfile "$staging_dir/foreign-ca/ca.crt" "$staging_dir/foreign-client/tls.crt" >/dev/null
find "$staging_dir" -type d -exec chmod 0700 {} \;
find "$staging_dir" -type f -exec chmod 0600 {} \;
for directory in public-ca internal-ca foreign-ca ingress api load-balancer prometheus forbidden-client foreign-client; do
rm -rf "$security_dir/$directory"
mv "$staging_dir/$directory" "$security_dir/$directory"
done
echo "local PKI created in .runtime/security"
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
set -eu
umask 077
rm -rf /target/api/internal-ca /target/api/api
mkdir -p /target/api/internal-ca /target/api/api
cp /source/internal-ca/ca.crt /target/api/internal-ca/ca.crt
cp /source/api/tls.crt /target/api/api/tls.crt
cp /source/api/tls.key /target/api/api/tls.key
chown -R 10001:10001 /target/api
find /target/api -type d -exec chmod 0700 {} \;
find /target/api -type f -exec chmod 0600 {} \;
rm -rf /target/nginx/ingress /target/nginx/public-ca /target/nginx/internal-ca /target/nginx/load-balancer
mkdir -p /target/nginx/ingress /target/nginx/public-ca /target/nginx/internal-ca /target/nginx/load-balancer
cp /source/ingress/tls.crt /target/nginx/ingress/tls.crt
cp /source/ingress/tls.key /target/nginx/ingress/tls.key
cp /source/public-ca/ca.crt /target/nginx/public-ca/ca.crt
cp /source/internal-ca/ca.crt /target/nginx/internal-ca/ca.crt
cp /source/load-balancer/tls.crt /target/nginx/load-balancer/tls.crt
cp /source/load-balancer/tls.key /target/nginx/load-balancer/tls.key
chown -R 0:0 /target/nginx
find /target/nginx -type d -exec chmod 0700 {} \;
find /target/nginx -type f -exec chmod 0600 {} \;
rm -rf /target/prometheus/internal-ca /target/prometheus/prometheus
mkdir -p /target/prometheus/internal-ca /target/prometheus/prometheus
cp /source/internal-ca/ca.crt /target/prometheus/internal-ca/ca.crt
cp /source/prometheus/tls.crt /target/prometheus/prometheus/tls.crt
cp /source/prometheus/tls.key /target/prometheus/prometheus/tls.key
chown -R 65534:65534 /target/prometheus
find /target/prometheus -type d -exec chmod 0700 {} \;
find /target/prometheus -type f -exec chmod 0600 {} \;
rm -rf /target/client/public-ca
mkdir -p /target/client/public-ca
cp /source/public-ca/ca.crt /target/client/public-ca/ca.crt
chown -R 10001:10001 /target/client
find /target/client -type d -exec chmod 0700 {} \;
find /target/client -type f -exec chmod 0600 {} \;
+10
View File
@@ -0,0 +1,10 @@
basicConstraints = critical,CA:FALSE
keyUsage = critical,digitalSignature,keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @subject_alt_names
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
[subject_alt_names]
DNS.1 = api
URI.1 = spiffe://mtusi/lab7/api
+12
View File
@@ -0,0 +1,12 @@
[req]
distinguished_name = distinguished_name
prompt = no
[distinguished_name]
CN = local-ca
[v3_ca]
basicConstraints = critical,CA:TRUE,pathlen:0
keyUsage = critical,keyCertSign,cRLSign
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always
+9
View File
@@ -0,0 +1,9 @@
basicConstraints = critical,CA:FALSE
keyUsage = critical,digitalSignature
extendedKeyUsage = clientAuth
subjectAltName = @subject_alt_names
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
[subject_alt_names]
URI.1 = spiffe://mtusi/lab7/worker
+11
View File
@@ -0,0 +1,11 @@
basicConstraints = critical,CA:FALSE
keyUsage = critical,digitalSignature,keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @subject_alt_names
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
[subject_alt_names]
DNS.1 = localhost
DNS.2 = nginx
IP.1 = 127.0.0.1
+9
View File
@@ -0,0 +1,9 @@
basicConstraints = critical,CA:FALSE
keyUsage = critical,digitalSignature
extendedKeyUsage = clientAuth
subjectAltName = @subject_alt_names
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
[subject_alt_names]
URI.1 = spiffe://mtusi/lab7/load-balancer
+4
View File
@@ -0,0 +1,4 @@
basicConstraints = critical,CA:FALSE
keyUsage = critical,digitalSignature
extendedKeyUsage = clientAuth
subjectAltName = URI:spiffe://mtusi/lab7/prometheus
+2 -2
View File
@@ -3,8 +3,8 @@ package bootstrap
import ( import (
"context" "context"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
) )
func RunMigrations() error { func RunMigrations() error {
+10 -10
View File
@@ -14,16 +14,16 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/broker/redisstream" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/broker/redisstream"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/pipeline" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/pipeline"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/transform"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/worker" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/worker"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/outbox" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/outbox"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
func RunDispatcher(logger *slog.Logger) error { func RunDispatcher(logger *slog.Logger) error {
+5 -5
View File
@@ -10,11 +10,11 @@ import (
"syscall" "syscall"
"time" "time"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/reconcile" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/reconcile"
) )
type reconciliationOutput struct { type reconciliationOutput struct {
+3 -3
View File
@@ -6,9 +6,9 @@ import (
"fmt" "fmt"
"io" "io"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres"
) )
func RunAttachmentReplay(arguments []string, output io.Writer) error { func RunAttachmentReplay(arguments []string, output io.Writer) error {
+91 -24
View File
@@ -2,6 +2,9 @@ package bootstrap
import ( import (
"context" "context"
"crypto/tls"
"errors"
"fmt"
"log/slog" "log/slog"
"net" "net"
"net/http" "net/http"
@@ -9,22 +12,42 @@ import (
"os/signal" "os/signal"
"syscall" "syscall"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/httpapi" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/httpapi"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/password" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/password"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/session" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/security/tlsconfig"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/session"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
type serverResult struct {
name string
err error
}
func RunServer(logger *slog.Logger) 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
} }
apiTLSConfiguration, err := tlsconfig.LoadServer(tlsconfig.ServerConfig{
CAPath: settings.TLSCAPath, CertificatePath: settings.TLSCertificatePath,
PrivateKeyPath: settings.TLSPrivateKeyPath, AllowedClientURI: settings.TLSAllowedClientURI,
})
if err != nil {
return err
}
metricsTLSConfiguration, err := tlsconfig.LoadServer(tlsconfig.ServerConfig{
CAPath: settings.TLSCAPath, CertificatePath: settings.TLSCertificatePath,
PrivateKeyPath: settings.TLSPrivateKeyPath, AllowedClientURI: settings.TLSAllowedMetricsClientURI,
})
if err != nil {
return err
}
instanceID, err := os.Hostname() instanceID, err := os.Hostname()
if err != nil { if err != nil {
return err return err
@@ -76,34 +99,78 @@ func RunServer(logger *slog.Logger) error {
SessionTTL: settings.SessionTTL, IdempotencyTTL: settings.IdempotencyTTL, SessionTTL: settings.SessionTTL, IdempotencyTTL: settings.IdempotencyTTL,
RequestTTL: settings.RequestTimeout, InstanceID: instanceID, SwaggerPort: settings.SwaggerPort, RequestTTL: settings.RequestTimeout, InstanceID: instanceID, SwaggerPort: settings.SwaggerPort,
}) })
server := &http.Server{ apiServer := &http.Server{
Addr: settings.Address, Handler: app.Handler(), ReadHeaderTimeout: settings.HTTPReadHeaderTimeout, Addr: settings.Address, Handler: app.Handler(), ReadHeaderTimeout: settings.HTTPReadHeaderTimeout,
ReadTimeout: settings.HTTPReadTimeout, WriteTimeout: settings.HTTPWriteTimeout, ReadTimeout: settings.HTTPReadTimeout, WriteTimeout: settings.HTTPWriteTimeout,
IdleTimeout: settings.HTTPIdleTimeout, IdleTimeout: settings.HTTPIdleTimeout, TLSConfig: apiTLSConfiguration,
} }
listener, err := net.Listen("tcp", server.Addr) healthServer := &http.Server{
Addr: settings.HealthAddress, Handler: app.HealthHandler(),
ReadHeaderTimeout: settings.HTTPReadHeaderTimeout, ReadTimeout: settings.HTTPReadTimeout,
WriteTimeout: settings.HTTPWriteTimeout, IdleTimeout: settings.HTTPIdleTimeout,
}
metricsServer := &http.Server{
Addr: settings.MetricsAddress, Handler: app.MetricsHandler(),
ReadHeaderTimeout: settings.HTTPReadHeaderTimeout, ReadTimeout: settings.HTTPReadTimeout,
WriteTimeout: settings.HTTPWriteTimeout, IdleTimeout: settings.HTTPIdleTimeout,
TLSConfig: metricsTLSConfiguration,
}
apiListener, err := net.Listen("tcp", apiServer.Addr)
if err != nil { if err != nil {
return err return err
} }
serveResult := make(chan error, 1) healthListener, err := net.Listen("tcp", healthServer.Addr)
go func() { serveResult <- server.Serve(listener) }() if err != nil {
logger.Info("server started", "address", server.Addr) _ = apiListener.Close()
return err
}
metricsListener, err := net.Listen("tcp", metricsServer.Addr)
if err != nil {
_ = apiListener.Close()
_ = healthListener.Close()
return err
}
serveResults := make(chan serverResult, 3)
go serveHTTP(serveResults, "api", apiServer, tls.NewListener(apiListener, apiTLSConfiguration))
go serveHTTP(serveResults, "health", healthServer, healthListener)
go serveHTTP(serveResults, "metrics", metricsServer, tls.NewListener(metricsListener, metricsTLSConfiguration))
logger.Info("servers started", "api_address", apiServer.Addr, "health_address", healthServer.Addr, "metrics_address", metricsServer.Addr)
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop() defer stop()
var serveErr error
select { select {
case err := <-serveResult: case result := <-serveResults:
return err serveErr = fmt.Errorf("%s server stopped: %w", result.name, result.err)
case <-ctx.Done(): case <-ctx.Done():
logger.Info("shutdown requested") logger.Info("shutdown requested")
app.SetReady(false) }
shutdownCtx, cancel := context.WithTimeout(context.Background(), settings.HTTPShutdownTimeout) app.SetReady(false)
defer cancel() shutdownCtx, cancel := context.WithTimeout(context.Background(), settings.HTTPShutdownTimeout)
if err := server.Shutdown(shutdownCtx); err != nil { defer cancel()
_ = server.Close() shutdownErr := shutdownServers(shutdownCtx, apiServer, healthServer, metricsServer)
return err return errors.Join(serveErr, shutdownErr)
} }
func serveHTTP(results chan<- serverResult, name string, server *http.Server, listener net.Listener) {
results <- serverResult{name: name, err: server.Serve(listener)}
}
func shutdownServers(ctx context.Context, servers ...*http.Server) error {
results := make(chan error, len(servers))
for _, server := range servers {
go func() { results <- server.Shutdown(ctx) }()
}
var shutdownErr error
for range servers {
shutdownErr = errors.Join(shutdownErr, <-results)
}
if shutdownErr == nil {
return nil return nil
} }
for _, server := range servers {
_ = server.Close()
}
return shutdownErr
} }
func databaseConfig(settings config.ServerConfig) database.Config { func databaseConfig(settings config.ServerConfig) database.Config {
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"log/slog" "log/slog"
"time" "time"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
func startTelemetry(serviceName, instanceID string) (*telemetry.Runtime, *slog.Logger, error) { func startTelemetry(serviceName, instanceID string) (*telemetry.Runtime, *slog.Logger, error) {
+1 -1
View File
@@ -16,7 +16,7 @@ import (
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/outbox" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/outbox"
) )
const ( const (
+108 -36
View File
@@ -12,41 +12,48 @@ import (
) )
type ServerConfig struct { type ServerConfig struct {
Address string Address string
DatabaseURL string HealthAddress string
CacheURL string MetricsAddress string
SessionTTL time.Duration TLSCAPath string
IdempotencyTTL time.Duration TLSCertificatePath string
DBMaxConns int32 TLSPrivateKeyPath string
DBMinConns int32 TLSAllowedClientURI string
DBMaxConnectionAge time.Duration TLSAllowedMetricsClientURI string
DBMaxConnectionIdle time.Duration DatabaseURL string
DBHealthCheckPeriod time.Duration CacheURL string
DependencyTimeout time.Duration SessionTTL time.Duration
RequestTimeout time.Duration IdempotencyTTL time.Duration
HTTPReadHeaderTimeout time.Duration DBMaxConns int32
HTTPReadTimeout time.Duration DBMinConns int32
HTTPWriteTimeout time.Duration DBMaxConnectionAge time.Duration
HTTPIdleTimeout time.Duration DBMaxConnectionIdle time.Duration
HTTPShutdownTimeout time.Duration DBHealthCheckPeriod time.Duration
PasswordMemoryKiB uint32 DependencyTimeout time.Duration
PasswordIterations uint32 RequestTimeout time.Duration
PasswordParallelism uint8 HTTPReadHeaderTimeout time.Duration
PasswordSaltLength uint32 HTTPReadTimeout time.Duration
PasswordKeyLength uint32 HTTPWriteTimeout time.Duration
SwaggerPort string HTTPIdleTimeout time.Duration
S3Endpoint string HTTPShutdownTimeout time.Duration
S3Region string PasswordMemoryKiB uint32
S3Bucket string PasswordIterations uint32
S3AccessKey string PasswordParallelism uint8
S3SecretKey string PasswordSaltLength uint32
S3UseTLS bool PasswordKeyLength uint32
S3Timeout time.Duration SwaggerPort string
AttachmentMaxBytes int64 S3Endpoint string
AttachmentMaxPixels int64 S3Region string
AttachmentBodyMemory int64 S3Bucket string
AttachmentDecodeMemory int64 S3AccessKey string
PipelineVersion int S3SecretKey string
S3UseTLS bool
S3Timeout time.Duration
AttachmentMaxBytes int64
AttachmentMaxPixels int64
AttachmentBodyMemory int64
AttachmentDecodeMemory int64
PipelineVersion int
} }
type MigrationConfig struct { type MigrationConfig struct {
@@ -111,6 +118,34 @@ func LoadServer() (ServerConfig, error) {
if err != nil { if err != nil {
return ServerConfig{}, err return ServerConfig{}, err
} }
healthAddress, err := loopbackAddress(values, "server.health_address")
if err != nil {
return ServerConfig{}, err
}
metricsAddress, err := nonLoopbackAddress(values, "server.metrics_address")
if err != nil {
return ServerConfig{}, err
}
tlsCAPath, err := requiredString(values, "server.tls.ca_path")
if err != nil {
return ServerConfig{}, err
}
tlsCertificatePath, err := requiredString(values, "server.tls.certificate_path")
if err != nil {
return ServerConfig{}, err
}
tlsPrivateKeyPath, err := requiredString(values, "server.tls.private_key_path")
if err != nil {
return ServerConfig{}, err
}
tlsAllowedClientURI, err := requiredString(values, "server.tls.allowed_client_uri")
if err != nil {
return ServerConfig{}, err
}
tlsAllowedMetricsClientURI, err := requiredString(values, "server.tls.allowed_metrics_client_uri")
if err != nil {
return ServerConfig{}, err
}
database, err := loadDatabaseConfig(values) database, err := loadDatabaseConfig(values)
if err != nil { if err != nil {
return ServerConfig{}, err return ServerConfig{}, err
@@ -216,7 +251,11 @@ func LoadServer() (ServerConfig, error) {
} }
return ServerConfig{ return ServerConfig{
Address: net.JoinHostPort(host, port), DatabaseURL: database.url, CacheURL: cacheURL, Address: net.JoinHostPort(host, port), HealthAddress: healthAddress, MetricsAddress: metricsAddress,
TLSCAPath: tlsCAPath, TLSCertificatePath: tlsCertificatePath,
TLSPrivateKeyPath: tlsPrivateKeyPath, TLSAllowedClientURI: tlsAllowedClientURI,
TLSAllowedMetricsClientURI: tlsAllowedMetricsClientURI,
DatabaseURL: database.url, CacheURL: cacheURL,
SessionTTL: sessionTTL, IdempotencyTTL: idempotencyTTL, SessionTTL: sessionTTL, IdempotencyTTL: idempotencyTTL,
DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns), DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle, DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
@@ -371,6 +410,39 @@ func requiredPort(values *viper.Viper, name string) (string, error) {
return value, nil return value, nil
} }
func loopbackAddress(values *viper.Viper, name string) (string, error) {
value, err := requiredString(values, name)
if err != nil {
return "", err
}
host, port, err := net.SplitHostPort(value)
if err != nil || host != "127.0.0.1" {
return "", fmt.Errorf("%s: must use 127.0.0.1 with an explicit port", name)
}
if _, err := integerValue(port, 1, 65535); err != nil {
return "", fmt.Errorf("%s: %w", name, err)
}
return net.JoinHostPort(host, port), nil
}
func nonLoopbackAddress(values *viper.Viper, name string) (string, error) {
value, err := requiredString(values, name)
if err != nil {
return "", err
}
host, port, err := net.SplitHostPort(value)
if err != nil || host == "" || strings.EqualFold(host, "localhost") {
return "", fmt.Errorf("%s: must use a non-loopback host with an explicit port", name)
}
if address := net.ParseIP(host); address != nil && address.IsLoopback() {
return "", fmt.Errorf("%s: must use a non-loopback host with an explicit port", name)
}
if _, err := integerValue(port, 1, 65535); err != nil {
return "", fmt.Errorf("%s: %w", name, err)
}
return net.JoinHostPort(host, port), nil
}
func duration(values *viper.Viper, name string, minimum, maximum time.Duration) (time.Duration, error) { func duration(values *viper.Viper, name string, minimum, maximum time.Duration) (time.Duration, error) {
value, err := requiredString(values, name) value, err := requiredString(values, name)
if err != nil { if err != nil {
+36
View File
@@ -46,6 +46,34 @@ func TestLoadValuesRejectsUnknownVersion(t *testing.T) {
require.ErrorContains(t, err, "version: must be 1") require.ErrorContains(t, err, "version: must be 1")
} }
func TestLoadServerLoadsTLSAndHealthSettings(t *testing.T) {
setConfigEnvironment(t, validTestConfig)
settings, err := LoadServer()
require.NoError(t, err)
require.Equal(t, "127.0.0.1:8082", settings.HealthAddress)
require.Equal(t, "0.0.0.0:9091", settings.MetricsAddress)
require.Equal(t, "/run/security/internal-ca/ca.crt", settings.TLSCAPath)
require.Equal(t, "spiffe://mtusi/lab7/load-balancer", settings.TLSAllowedClientURI)
require.Equal(t, "spiffe://mtusi/lab7/prometheus", settings.TLSAllowedMetricsClientURI)
}
func TestLoadServerRejectsNonLoopbackHealthAddress(t *testing.T) {
content := strings.Replace(validTestConfig, "health_address: 127.0.0.1:8082", "health_address: 0.0.0.0:8082", 1)
setConfigEnvironment(t, content)
_, err := LoadServer()
require.ErrorContains(t, err, "server.health_address: must use 127.0.0.1")
}
func TestLoadServerRejectsLoopbackMetricsAddress(t *testing.T) {
content := strings.Replace(validTestConfig, "metrics_address: 0.0.0.0:9091", "metrics_address: 127.0.0.1:9091", 1)
setConfigEnvironment(t, content)
_, err := LoadServer()
require.ErrorContains(t, err, "server.metrics_address: must use a non-loopback host")
}
func setConfigEnvironment(t *testing.T, content string) { func setConfigEnvironment(t *testing.T, content string) {
t.Helper() t.Helper()
path := filepath.Join(t.TempDir(), "messenger.yaml") path := filepath.Join(t.TempDir(), "messenger.yaml")
@@ -64,6 +92,14 @@ func setConfigEnvironment(t *testing.T, content string) {
const validTestConfig = `version: 1 const validTestConfig = `version: 1
server: server:
health_address: 127.0.0.1:8082
metrics_address: 0.0.0.0:9091
tls:
ca_path: /run/security/internal-ca/ca.crt
certificate_path: /run/security/api/tls.crt
private_key_path: /run/security/api/tls.key
allowed_client_uri: spiffe://mtusi/lab7/load-balancer
allowed_metrics_client_uri: spiffe://mtusi/lab7/prometheus
session_store: valkey session_store: valkey
session_ttl: 1h session_ttl: 1h
idempotency_ttl: 24h idempotency_ttl: 24h
+18 -11
View File
@@ -12,17 +12,24 @@ import (
const supportedConfigVersion = 1 const supportedConfigVersion = 1
var environmentKeys = map[string]string{ var environmentKeys = map[string]string{
"server.host": "APP_HOST", "server.host": "APP_HOST",
"server.port": "APP_PORT", "server.port": "APP_PORT",
"server.swagger_port": "SWAGGER_PORT", "server.health_address": "APP_HEALTH_ADDRESS",
"database.url": "DATABASE_URL", "server.metrics_address": "APP_METRICS_ADDRESS",
"cache.url": "CACHE_URL", "server.tls.ca_path": "APP_TLS_CA_PATH",
"object_storage.endpoint": "S3_ENDPOINT", "server.tls.certificate_path": "APP_TLS_CERTIFICATE_PATH",
"object_storage.region": "S3_REGION", "server.tls.private_key_path": "APP_TLS_PRIVATE_KEY_PATH",
"object_storage.bucket": "S3_BUCKET", "server.tls.allowed_client_uri": "APP_TLS_ALLOWED_CLIENT_URI",
"object_storage.access_key": "S3_ACCESS_KEY", "server.tls.allowed_metrics_client_uri": "APP_TLS_ALLOWED_METRICS_CLIENT_URI",
"object_storage.secret_key": "S3_SECRET_KEY", "server.swagger_port": "SWAGGER_PORT",
"broker.url": "BROKER_URL", "database.url": "DATABASE_URL",
"cache.url": "CACHE_URL",
"object_storage.endpoint": "S3_ENDPOINT",
"object_storage.region": "S3_REGION",
"object_storage.bucket": "S3_BUCKET",
"object_storage.access_key": "S3_ACCESS_KEY",
"object_storage.secret_key": "S3_SECRET_KEY",
"broker.url": "BROKER_URL",
} }
func loadValues() (*viper.Viper, error) { func loadValues() (*viper.Viper, error) {
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/dizi/mtusi2026lab6/migrations" "gitea.privcloud.tech/dizi/mtusi2026lab7/migrations"
) )
var ( var (
+2 -2
View File
@@ -19,8 +19,8 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"golang.org/x/sync/semaphore" "golang.org/x/sync/semaphore"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
type Repository interface { type Repository interface {
@@ -15,7 +15,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
func TestUploadLifecycle(t *testing.T) { func TestUploadLifecycle(t *testing.T) {
@@ -23,11 +23,11 @@ import (
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/broker/redisstream" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/broker/redisstream"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/transform"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
type Repository interface { type Repository interface {
@@ -9,9 +9,9 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/transform"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore"
) )
func TestConfigRequiresEnoughMemoryForMaximumImage(t *testing.T) { func TestConfigRequiresEnoughMemoryForMaximumImage(t *testing.T) {
+3 -3
View File
@@ -16,9 +16,9 @@ import (
"go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/metric"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError { func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError {
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"net/http" "net/http"
"strings" "strings"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError { func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"time" "time"
"unicode/utf8" "unicode/utf8"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
@@ -4,8 +4,8 @@ import (
"context" "context"
"time" "time"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
type UserRepository interface { type UserRepository interface {
+1 -1
View File
@@ -1,7 +1,7 @@
package httpapi package httpapi
import ( import (
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"github.com/google/uuid" "github.com/google/uuid"
) )
-3
View File
@@ -14,9 +14,6 @@ func (s *Server) route(w http.ResponseWriter, r *http.Request) *apiError {
handler = s.live handler = s.live
case "/health/ready": case "/health/ready":
handler = s.readiness handler = s.readiness
case "/metrics":
s.metrics.handler.ServeHTTP(w, r)
return nil
case "/api/v1/users": case "/api/v1/users":
handler = s.users handler = s.users
case "/api/v1/users/me": case "/api/v1/users/me":
+24 -1
View File
@@ -15,7 +15,7 @@ import (
semconv "go.opentelemetry.io/otel/semconv/v1.34.0" semconv "go.opentelemetry.io/otel/semconv/v1.34.0"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
type Dependencies struct { type Dependencies struct {
@@ -94,6 +94,29 @@ func (s *Server) Handler() http.Handler {
return http.HandlerFunc(s.serve) return http.HandlerFunc(s.serve)
} }
func (s *Server) HealthHandler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/health/live", func(w http.ResponseWriter, r *http.Request) {
s.serveHealth(w, r, s.live)
})
mux.HandleFunc("/health/ready", func(w http.ResponseWriter, r *http.Request) {
s.serveHealth(w, r, s.readiness)
})
return mux
}
func (s *Server) MetricsHandler() http.Handler {
mux := http.NewServeMux()
mux.Handle("/metrics", s.metrics.handler)
return mux
}
func (s *Server) serveHealth(w http.ResponseWriter, r *http.Request, handler requestHandler) {
if err := handler(w, r); err != nil {
writeError(w, "", err)
}
}
func (s *Server) serve(w http.ResponseWriter, r *http.Request) { func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
requestContext := telemetry.Extract(r.Context(), propagation.HeaderCarrier(r.Header)) requestContext := telemetry.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
tracer := otel.Tracer("messenger-api/http") tracer := otel.Tracer("messenger-api/http")
+33 -3
View File
@@ -14,8 +14,8 @@ import (
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
var errDependency = errors.New("dependency unavailable") var errDependency = errors.New("dependency unavailable")
@@ -135,7 +135,7 @@ func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
server := s.server(tt.store, tt.sessions, passwordsStub{}, tt.objects, attachmentServiceStub{}) server := s.server(tt.store, tt.sessions, passwordsStub{}, tt.objects, attachmentServiceStub{})
response := serveRequest(server, http.MethodGet, "/health/ready", "") response := serveHealthRequest(server, http.MethodGet, "/health/ready")
if response.Code != http.StatusServiceUnavailable { if response.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable) t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
} }
@@ -143,6 +143,29 @@ func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
} }
} }
func (s *MessengerSuite) TestHealthHandlerDoesNotExposeBusinessAPI() {
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
response := serveHealthRequest(server, http.MethodGet, "/api/v1/users/me")
s.Equal(http.StatusNotFound, response.Code)
}
func (s *MessengerSuite) TestMetricsHandlerOnlyExposesMetrics() {
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
server.metrics.handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
metrics := httptest.NewRecorder()
server.MetricsHandler().ServeHTTP(metrics, httptest.NewRequest(http.MethodGet, "/metrics", nil))
s.Equal(http.StatusNoContent, metrics.Code)
for _, path := range []string{"/health/ready", "/api/v1/users/me"} {
response := httptest.NewRecorder()
server.MetricsHandler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil))
s.Equal(http.StatusNotFound, response.Code, path)
}
s.Equal(http.StatusNotFound, serveRequest(server, http.MethodGet, "/metrics", "").Code)
}
func (s *MessengerSuite) TestBusinessRequestReturnsUnavailableForDependencyFailure() { func (s *MessengerSuite) TestBusinessRequestReturnsUnavailableForDependencyFailure() {
t := s.T() t := s.T()
tests := []struct { tests := []struct {
@@ -376,3 +399,10 @@ func serveRequest(server *Server, method, path, body string) *httptest.ResponseR
server.Handler().ServeHTTP(response, request) server.Handler().ServeHTTP(response, request)
return response return response
} }
func serveHealthRequest(server *Server, method, path string) *httptest.ResponseRecorder {
request := httptest.NewRequest(method, path, nil)
response := httptest.NewRecorder()
server.HealthHandler().ServeHTTP(response, request)
return response
}
+1 -1
View File
@@ -18,7 +18,7 @@ import (
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
var ErrNotFound = errors.New("object not found") var ErrNotFound = errors.New("object not found")
+2 -2
View File
@@ -11,8 +11,8 @@ import (
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
var errLeaseLost = errors.New("outbox lease lost") var errLeaseLost = errors.New("outbox lease lost")
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"testing" "testing"
"time" "time"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
const attachmentJobTopic = "attachment.jobs" const attachmentJobTopic = "attachment.jobs"
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"fmt" "fmt"
"time" "time"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
func (s *Store) RenewAttachmentJobLease( func (s *Store) RenewAttachmentJobLease(
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
func (s *Store) RecoverExpiredAttachmentJobs( func (s *Store) RecoverExpiredAttachmentJobs(
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
const attachmentColumns = ` const attachmentColumns = `
+1 -1
View File
@@ -1,6 +1,6 @@
package postgres package postgres
import "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" import "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
var ( var (
ErrConflict = model.ErrConflict ErrConflict = model.ErrConflict
+1 -1
View File
@@ -12,7 +12,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
const expiredIdempotencyCleanupBatch = 100 const expiredIdempotencyCleanupBatch = 100
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
func (s *Store) ClaimOutboxEvents( func (s *Store) ClaimOutboxEvents(
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
type Store struct { type Store struct {
+4 -4
View File
@@ -15,10 +15,10 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/reconcile" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/reconcile"
) )
type PostgresSuite struct { type PostgresSuite struct {
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"fmt" "fmt"
"time" "time"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
type MetadataStore interface { type MetadataStore interface {
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
func TestReconcilerLifecycleAndRepeat(t *testing.T) { func TestReconcilerLifecycleAndRepeat(t *testing.T) {
+54
View File
@@ -0,0 +1,54 @@
package tlsconfig
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net/url"
"os"
)
type ServerConfig struct {
CAPath string
CertificatePath string
PrivateKeyPath string
AllowedClientURI string
}
func LoadServer(config ServerConfig) (*tls.Config, error) {
allowedURI, err := url.Parse(config.AllowedClientURI)
if err != nil || allowedURI.Scheme == "" || allowedURI.Host == "" || allowedURI.String() != config.AllowedClientURI {
return nil, errors.New("allowed client URI must be an absolute canonical URI")
}
caPEM, err := os.ReadFile(config.CAPath)
if err != nil {
return nil, fmt.Errorf("read client CA: %w", err)
}
clientCAs := x509.NewCertPool()
if !clientCAs.AppendCertsFromPEM(caPEM) {
return nil, errors.New("client CA does not contain a certificate")
}
certificate, err := tls.LoadX509KeyPair(config.CertificatePath, config.PrivateKeyPath)
if err != nil {
return nil, fmt.Errorf("load server certificate: %w", err)
}
return &tls.Config{
MinVersion: tls.VersionTLS13,
Certificates: []tls.Certificate{certificate},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: clientCAs,
VerifyConnection: func(state tls.ConnectionState) error {
if len(state.PeerCertificates) == 0 {
return errors.New("client certificate is required")
}
for _, identity := range state.PeerCertificates[0].URIs {
if identity.String() == config.AllowedClientURI {
return nil
}
}
return fmt.Errorf("client certificate URI SAN is not allowed: want %s", config.AllowedClientURI)
},
}, nil
}
+185
View File
@@ -0,0 +1,185 @@
package tlsconfig
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"net"
"net/url"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
)
const allowedClientURI = "spiffe://mtusi/lab7/load-balancer"
func TestServerRequiresAllowedClientIdentity(t *testing.T) {
files := issueTestCertificates(t)
serverConfig, err := LoadServer(ServerConfig{
CAPath: files.caPath, CertificatePath: files.serverCertificatePath,
PrivateKeyPath: files.serverPrivateKeyPath, AllowedClientURI: allowedClientURI,
})
require.NoError(t, err)
tests := []struct {
name string
certificatePath string
privateKeyPath string
wantServerError bool
}{
{name: "allowed identity", certificatePath: files.allowedCertificatePath, privateKeyPath: files.allowedPrivateKeyPath},
{name: "other identity from trusted CA", certificatePath: files.otherCertificatePath, privateKeyPath: files.otherPrivateKeyPath, wantServerError: true},
{name: "missing certificate", wantServerError: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
clientConfig := &tls.Config{RootCAs: files.caPool, ServerName: "api.internal", MinVersion: tls.VersionTLS13}
if tt.certificatePath != "" {
certificate, loadErr := tls.LoadX509KeyPair(tt.certificatePath, tt.privateKeyPath)
require.NoError(t, loadErr)
clientConfig.Certificates = []tls.Certificate{certificate}
}
serverErr, clientErr := handshake(serverConfig, clientConfig)
if tt.wantServerError {
require.Error(t, serverErr)
return
}
require.NoError(t, serverErr)
require.NoError(t, clientErr)
})
}
}
func TestLoadServerRejectsInvalidClientCA(t *testing.T) {
directory := t.TempDir()
caPath := filepath.Join(directory, "ca.pem")
require.NoError(t, os.WriteFile(caPath, []byte("not a certificate"), 0o600))
_, err := LoadServer(ServerConfig{CAPath: caPath, AllowedClientURI: allowedClientURI})
require.ErrorContains(t, err, "client CA does not contain a certificate")
}
func handshake(serverConfig, clientConfig *tls.Config) (error, error) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return err, err
}
defer listener.Close()
serverResult := make(chan error, 1)
go func() {
connection, acceptErr := listener.Accept()
if acceptErr != nil {
serverResult <- acceptErr
return
}
server := tls.Server(connection, serverConfig)
serverResult <- server.Handshake()
_ = server.Close()
}()
client, clientErr := tls.Dial("tcp", listener.Addr().String(), clientConfig)
if client != nil {
_ = client.Close()
}
serverErr := <-serverResult
return serverErr, clientErr
}
type testCertificateFiles struct {
caPath string
serverCertificatePath string
serverPrivateKeyPath string
allowedCertificatePath string
allowedPrivateKeyPath string
otherCertificatePath string
otherPrivateKeyPath string
caPool *x509.CertPool
}
func issueTestCertificates(t *testing.T) testCertificateFiles {
t.Helper()
directory := t.TempDir()
caCertificate, caKey := issueCA(t)
caPath := filepath.Join(directory, "ca.pem")
writeCertificate(t, caPath, caCertificate.Raw)
caPool := x509.NewCertPool()
caPool.AddCert(caCertificate)
serverCertificatePath, serverPrivateKeyPath := issueLeaf(t, directory, caCertificate, caKey, "server", nil, []string{"api.internal"}, x509.ExtKeyUsageServerAuth)
allowed := mustParseURI(t, allowedClientURI)
allowedCertificatePath, allowedPrivateKeyPath := issueLeaf(t, directory, caCertificate, caKey, "allowed", []*url.URL{allowed}, nil, x509.ExtKeyUsageClientAuth)
other := mustParseURI(t, "spiffe://mtusi/lab7/worker")
otherCertificatePath, otherPrivateKeyPath := issueLeaf(t, directory, caCertificate, caKey, "other", []*url.URL{other}, nil, x509.ExtKeyUsageClientAuth)
return testCertificateFiles{
caPath: caPath, serverCertificatePath: serverCertificatePath, serverPrivateKeyPath: serverPrivateKeyPath,
allowedCertificatePath: allowedCertificatePath, allowedPrivateKeyPath: allowedPrivateKeyPath,
otherCertificatePath: otherCertificatePath, otherPrivateKeyPath: otherPrivateKeyPath, caPool: caPool,
}
}
func issueCA(t *testing.T) (*x509.Certificate, *ecdsa.PrivateKey) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
template := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test CA"},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign,
}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
require.NoError(t, err)
certificate, err := x509.ParseCertificate(der)
require.NoError(t, err)
return certificate, key
}
func issueLeaf(
t *testing.T,
directory string,
ca *x509.Certificate,
caKey *ecdsa.PrivateKey,
name string,
identities []*url.URL,
dnsNames []string,
usage x509.ExtKeyUsage,
) (string, string) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
template := &x509.Certificate{
SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: name},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{usage},
URIs: identities, DNSNames: dnsNames,
}
der, err := x509.CreateCertificate(rand.Reader, template, ca, &key.PublicKey, caKey)
require.NoError(t, err)
certificatePath := filepath.Join(directory, name+".crt")
privateKeyPath := filepath.Join(directory, name+".key")
writeCertificate(t, certificatePath, der)
keyDER, err := x509.MarshalPKCS8PrivateKey(key)
require.NoError(t, err)
require.NoError(t, os.WriteFile(privateKeyPath, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}), 0o600))
return certificatePath, privateKeyPath
}
func writeCertificate(t *testing.T, path string, der []byte) {
t.Helper()
require.NoError(t, os.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600))
}
func mustParseURI(t *testing.T, value string) *url.URL {
t.Helper()
identity, err := url.Parse(value)
require.NoError(t, err)
return identity
}
+1 -1
View File
@@ -14,7 +14,7 @@ import (
"github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
const ( const (
+1 -1
View File
@@ -11,7 +11,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/session" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/session"
) )
type SessionSuite struct { type SessionSuite struct {
+6 -5
View File
@@ -1,13 +1,14 @@
# Изолированное имя Compose-проекта и его volumes/networks. # Изолированное имя Compose-проекта и его volumes/networks.
COMPOSE_PROJECT_NAME=mtusi2026lab6 COMPOSE_PROJECT_NAME=mtusi2026lab7
# Адрес и внутренний порт HTTP-сервера. # Адреса HTTPS API и локального health-only listener.
APP_HOST=0.0.0.0 APP_HOST=0.0.0.0
APP_PORT=8080 APP_PORT=8443
APP_HEALTH_ADDRESS=127.0.0.1:8082
MESSENGER_CONFIG_PATH=config/messenger.yaml MESSENGER_CONFIG_PATH=config/messenger.yaml
# Адреса публикации сервисов на локальной машине. # Адреса публикации сервисов на локальной машине.
API_BIND_ADDRESS=127.0.0.1:8080 API_BIND_ADDRESS=127.0.0.1:8443
SWAGGER_BIND_ADDRESS=127.0.0.1:8081 SWAGGER_BIND_ADDRESS=127.0.0.1:8081
PROMETHEUS_BIND_ADDRESS=127.0.0.1:9090 PROMETHEUS_BIND_ADDRESS=127.0.0.1:9090
GRAFANA_BIND_ADDRESS=127.0.0.1:3000 GRAFANA_BIND_ADDRESS=127.0.0.1:3000
@@ -16,7 +17,7 @@ TEMPO_BIND_ADDRESS=127.0.0.1:3200
# Ресурсные атрибуты и внутренний OTLP endpoint приложений. # Ресурсные атрибуты и внутренний OTLP endpoint приложений.
DEPLOYMENT_ENVIRONMENT=lab DEPLOYMENT_ENVIRONMENT=lab
SERVICE_VERSION=lab6 SERVICE_VERSION=lab7
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
OTEL_EXPORTER_OTLP_PROTOCOL=grpc OTEL_EXPORTER_OTLP_PROTOCOL=grpc
+8 -1
View File
@@ -12,8 +12,15 @@ scrape_configs:
dns_sd_configs: dns_sd_configs:
- names: ["api"] - names: ["api"]
type: A type: A
port: 8080 port: 9091
refresh_interval: 2s refresh_interval: 2s
scheme: https
tls_config:
ca_file: /run/security/internal-ca/ca.crt
cert_file: /run/security/prometheus/tls.crt
key_file: /run/security/prometheus/tls.key
server_name: api
min_version: TLS13
relabel_configs: relabel_configs:
- target_label: service_name - target_label: service_name
replacement: messenger-api replacement: messenger-api
+17 -3
View File
@@ -25,18 +25,32 @@ http {
} }
server { server {
listen 8080; listen 8443 ssl;
client_max_body_size 11m; client_max_body_size 11m;
ssl_certificate /run/security/ingress/tls.crt;
ssl_certificate_key /run/security/ingress/tls.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_tickets off;
location / { location / {
proxy_pass http://messenger; proxy_pass https://messenger;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Connection ""; proxy_set_header Connection "";
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto https;
proxy_request_buffering off; proxy_request_buffering off;
proxy_ssl_server_name on;
proxy_ssl_name api;
proxy_ssl_trusted_certificate /run/security/internal-ca/ca.crt;
proxy_ssl_verify on;
proxy_ssl_verify_depth 1;
proxy_ssl_certificate /run/security/load-balancer/tls.crt;
proxy_ssl_certificate_key /run/security/load-balancer/tls.key;
proxy_ssl_session_reuse off;
proxy_connect_timeout 1s; proxy_connect_timeout 1s;
proxy_send_timeout 10s; proxy_send_timeout 10s;
proxy_read_timeout 10s; proxy_read_timeout 10s;
+1 -1
View File
@@ -1 +1 @@
server api:8080 resolve max_fails=1 fail_timeout=3s; server api:8443 resolve max_fails=1 fail_timeout=3s;
+4 -2
View File
@@ -2,8 +2,9 @@
set -eu set -eu
env_file=${ENV_FILE:-lab6.env.example} env_file=${ENV_FILE:-lab7.env.example}
base_url=${BASE_URL:-http://127.0.0.1:8080} base_url=${BASE_URL:-https://localhost:8443}
ca_file=${CA_FILE:-.runtime/security/public-ca/ca.crt}
prometheus_url=${PROMETHEUS_URL:-http://127.0.0.1:9090} prometheus_url=${PROMETHEUS_URL:-http://127.0.0.1:9090}
tempo_url=${TEMPO_URL:-http://127.0.0.1:3200} tempo_url=${TEMPO_URL:-http://127.0.0.1:3200}
loki_url=${LOKI_URL:-http://127.0.0.1:3100} loki_url=${LOKI_URL:-http://127.0.0.1:3100}
@@ -33,6 +34,7 @@ trap restore EXIT INT TERM
python3 scripts/lab6-observe.py --prometheus-url "$prometheus_url" --phase baseline --output "$output_dir/baseline.json" >/dev/null python3 scripts/lab6-observe.py --prometheus-url "$prometheus_url" --phase baseline --output "$output_dir/baseline.json" >/dev/null
python3 scripts/lab6-traffic.py \ python3 scripts/lab6-traffic.py \
--base-url "$base_url" \ --base-url "$base_url" \
--ca-file "$ca_file" \
--mode messages \ --mode messages \
--duration "$((outage_seconds + 20))" \ --duration "$((outage_seconds + 20))" \
--concurrency 4 \ --concurrency 4 \
+5 -3
View File
@@ -2,8 +2,9 @@
set -eu set -eu
env_file=${ENV_FILE:-lab6.env.example} env_file=${ENV_FILE:-lab7.env.example}
base_url=${BASE_URL:-http://127.0.0.1:8080} base_url=${BASE_URL:-https://localhost:8443}
ca_file=${CA_FILE:-.runtime/security/public-ca/ca.crt}
prometheus_url=${PROMETHEUS_URL:-http://127.0.0.1:9090} prometheus_url=${PROMETHEUS_URL:-http://127.0.0.1:9090}
evidence_root=${EVIDENCE_DIR:-evidence/runtime} evidence_root=${EVIDENCE_DIR:-evidence/runtime}
outage_seconds=${TELEMETRY_OUTAGE_SECONDS:-30} outage_seconds=${TELEMETRY_OUTAGE_SECONDS:-30}
@@ -30,6 +31,7 @@ started_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
compose stop tempo loki >/dev/null compose stop tempo loki >/dev/null
python3 scripts/lab6-traffic.py \ python3 scripts/lab6-traffic.py \
--base-url "$base_url" \ --base-url "$base_url" \
--ca-file "$ca_file" \
--mode mixed \ --mode mixed \
--duration "$outage_seconds" \ --duration "$outage_seconds" \
--concurrency 4 \ --concurrency 4 \
@@ -41,7 +43,7 @@ load_pid=$!
sleep "$outage_seconds" sleep "$outage_seconds"
wait "$load_pid" wait "$load_pid"
load_pid= load_pid=
health_code=$(curl --silent --output /dev/null --write-out '%{http_code}' "$base_url/health/ready") health_code=$(curl --silent --output /dev/null --write-out '%{http_code}' --cacert "$ca_file" "$base_url/health/ready")
python3 scripts/lab6-observe.py --prometheus-url "$prometheus_url" --phase degraded --output "$output_dir/degraded.json" >/dev/null python3 scripts/lab6-observe.py --prometheus-url "$prometheus_url" --phase degraded --output "$output_dir/degraded.json" >/dev/null
recovery_started_at=$(date -u +%Y-%m-%dT%H:%M:%SZ) recovery_started_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
compose up -d --wait --wait-timeout 90 tempo loki >/dev/null compose up -d --wait --wait-timeout 90 tempo loki >/dev/null
+4 -2
View File
@@ -3,8 +3,9 @@
set -eu set -eu
mode=${1:-short} mode=${1:-short}
env_file=${ENV_FILE:-lab6.env.example} env_file=${ENV_FILE:-lab7.env.example}
base_url=${BASE_URL:-http://127.0.0.1:8080} base_url=${BASE_URL:-https://localhost:8443}
ca_file=${CA_FILE:-.runtime/security/public-ca/ca.crt}
prometheus_url=${PROMETHEUS_URL:-http://127.0.0.1:9090} prometheus_url=${PROMETHEUS_URL:-http://127.0.0.1:9090}
evidence_root=${EVIDENCE_DIR:-evidence/runtime} evidence_root=${EVIDENCE_DIR:-evidence/runtime}
require_alerts=${REQUIRE_ALERT_TRANSITIONS:-1} require_alerts=${REQUIRE_ALERT_TRANSITIONS:-1}
@@ -51,6 +52,7 @@ started_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
compose stop worker >/dev/null compose stop worker >/dev/null
python3 scripts/lab6-traffic.py \ python3 scripts/lab6-traffic.py \
--base-url "$base_url" \ --base-url "$base_url" \
--ca-file "$ca_file" \
--mode attachments \ --mode attachments \
--duration "$load_seconds" \ --duration "$load_seconds" \
--requests "$requests" \ --requests "$requests" \
+9 -2
View File
@@ -7,6 +7,7 @@ import json
import math import math
from pathlib import Path from pathlib import Path
import secrets import secrets
import ssl
import struct import struct
import threading import threading
import time import time
@@ -16,6 +17,7 @@ import urllib.request
import zlib import zlib
MAX_RESPONSE_BYTES = 1 << 20 MAX_RESPONSE_BYTES = 1 << 20
TLS_CONTEXT = None
def png_fixture(width=96, height=64): def png_fixture(width=96, height=64):
@@ -37,7 +39,7 @@ def png_fixture(width=96, height=64):
def request(method, url, body=None, headers=None, timeout=10): def request(method, url, body=None, headers=None, timeout=10):
req = urllib.request.Request(url, data=body, method=method, headers=headers or {}) req = urllib.request.Request(url, data=body, method=method, headers=headers or {})
try: try:
with urllib.request.urlopen(req, timeout=timeout) as response: with urllib.request.urlopen(req, timeout=timeout, context=TLS_CONTEXT) as response:
payload = response.read(MAX_RESPONSE_BYTES) payload = response.read(MAX_RESPONSE_BYTES)
return response.status, payload return response.status, payload
except urllib.error.HTTPError as error: except urllib.error.HTTPError as error:
@@ -167,7 +169,8 @@ def wait_for_attachments(base_url, token, attachment_ids, timeout):
def main(): def main():
parser = argparse.ArgumentParser(description="Bounded synthetic load for Lab 6 telemetry and incidents") parser = argparse.ArgumentParser(description="Bounded synthetic load for Lab 6 telemetry and incidents")
parser.add_argument("--base-url", default="http://127.0.0.1:8080") parser.add_argument("--base-url", default="https://localhost:8443")
parser.add_argument("--ca-file", default=".runtime/security/public-ca/ca.crt")
parser.add_argument("--mode", choices=("messages", "attachments", "mixed"), default="mixed") parser.add_argument("--mode", choices=("messages", "attachments", "mixed"), default="mixed")
parser.add_argument("--duration", type=float, default=30) parser.add_argument("--duration", type=float, default=30)
parser.add_argument("--requests", type=int, default=0, help="Maximum requests; zero means duration only") parser.add_argument("--requests", type=int, default=0, help="Maximum requests; zero means duration only")
@@ -179,6 +182,10 @@ def main():
parser.add_argument("--started-file", help="Touch after synthetic session and chat are ready") parser.add_argument("--started-file", help="Touch after synthetic session and chat are ready")
args = parser.parse_args() args = parser.parse_args()
global TLS_CONTEXT
if args.base_url.startswith("https://"):
TLS_CONTEXT = ssl.create_default_context(cafile=args.ca_file)
if args.duration <= 0 or args.duration > 1800: if args.duration <= 0 or args.duration > 1800:
parser.error("duration must be in (0, 1800]") parser.error("duration must be in (0, 1800]")
if args.requests < 0: if args.requests < 0:
+9 -4
View File
@@ -8,7 +8,7 @@ if [ "$#" -ne 1 ] || [ ! -f "$1" ]; then
fi fi
manifest=$1 manifest=$1
deploy_dir=${DEPLOY_STATE_DIR:-"$HOME/.local/state/mtusi2026lab5"} deploy_dir=${DEPLOY_STATE_DIR:-"$HOME/.local/state/mtusi2026lab7"}
current_manifest=$deploy_dir/current-images.env current_manifest=$deploy_dir/current-images.env
active_containers=$deploy_dir/active-api-containers active_containers=$deploy_dir/active-api-containers
previous_containers=$deploy_dir/previous-api-containers previous_containers=$deploy_dir/previous-api-containers
@@ -16,7 +16,9 @@ upstream_file=$deploy_dir/upstream.conf
upstream_backup=$deploy_dir/upstream.previous.conf upstream_backup=$deploy_dir/upstream.previous.conf
candidate_file=$deploy_dir/candidate-api-containers candidate_file=$deploy_dir/candidate-api-containers
replicas=${API_REPLICAS:-2} replicas=${API_REPLICAS:-2}
project=${COMPOSE_PROJECT_NAME:-mtusi2026lab5} project=${COMPOSE_PROJECT_NAME:-mtusi2026lab7}
public_base_url=${PUBLIC_BASE_URL:-https://localhost:8443}
public_ca_file=${PUBLIC_CA_FILE:-.runtime/security/public-ca/ca.crt}
switched=false switched=false
nginx_created=false nginx_created=false
upstream_changed=false upstream_changed=false
@@ -52,7 +54,7 @@ write_upstream() {
: > "$output" : > "$output"
for container in $containers; do for container in $containers; do
name=$(container_name "$container") name=$(container_name "$container")
printf 'server %s:8080 resolve max_fails=1 fail_timeout=3s;\n' "$name" >> "$output" printf 'server %s:8443 resolve max_fails=1 fail_timeout=3s;\n' "$name" >> "$output"
done done
} }
@@ -81,7 +83,8 @@ wait_for_containers() {
} }
smoke_check() { smoke_check() {
compose exec -T nginx wget -q -O /dev/null http://127.0.0.1:8080/health/ready curl --fail --silent --show-error --noproxy '*' \
--cacert "$public_ca_file" "$public_base_url/health/ready" >/dev/null
} }
remove_containers() { remove_containers() {
@@ -123,6 +126,7 @@ trap 'exit 143' TERM
load_manifest "$manifest" load_manifest "$manifest"
new_api_image=$API_IMAGE new_api_image=$API_IMAGE
test -r "$public_ca_file"
if [ -f "$previous_containers" ]; then if [ -f "$previous_containers" ]; then
remove_containers "$(cat "$previous_containers")" remove_containers "$(cat "$previous_containers")"
@@ -151,6 +155,7 @@ cp "$upstream_file" "$upstream_backup"
compose pull api nginx swagger prometheus grafana s3 s3-bootstrap compose pull api nginx swagger prometheus grafana s3 s3-bootstrap
compose up -d --no-build --wait --wait-timeout 120 postgres valkey redis-broker s3 compose up -d --no-build --wait --wait-timeout 120 postgres valkey redis-broker s3
compose run --rm security-bootstrap
compose run --rm --no-deps s3-bootstrap compose run --rm --no-deps s3-bootstrap
compose run --rm --no-deps migrate compose run --rm --no-deps migrate
+8 -6
View File
@@ -11,8 +11,9 @@ case "$profile" in
;; ;;
esac esac
env_file=${ENV_FILE:-lab6.env.example} env_file=${ENV_FILE:-lab7.env.example}
base_url=${BASE_URL:-http://127.0.0.1:8080} base_url=${BASE_URL:-https://localhost:8443}
ca_file=${CA_FILE:-.runtime/security/public-ca/ca.crt}
prometheus_url=${PROMETHEUS_URL:-http://127.0.0.1:9090} prometheus_url=${PROMETHEUS_URL:-http://127.0.0.1:9090}
tempo_url=${TEMPO_URL:-http://127.0.0.1:3200} tempo_url=${TEMPO_URL:-http://127.0.0.1:3200}
loki_url=${LOKI_URL:-http://127.0.0.1:3100} loki_url=${LOKI_URL:-http://127.0.0.1:3100}
@@ -35,6 +36,7 @@ compose config --quiet
compose up -d --build --wait --wait-timeout 180 compose up -d --build --wait --wait-timeout 180
python3 scripts/lab6-traffic.py \ python3 scripts/lab6-traffic.py \
--base-url "$base_url" \ --base-url "$base_url" \
--ca-file "$ca_file" \
--mode mixed \ --mode mixed \
--duration "${BASELINE_LOAD_SECONDS:-15}" \ --duration "${BASELINE_LOAD_SECONDS:-15}" \
--requests "${BASELINE_REQUESTS:-120}" \ --requests "${BASELINE_REQUESTS:-120}" \
@@ -54,10 +56,10 @@ python3 scripts/lab6-correlation.py \
--require >/dev/null --require >/dev/null
if [ "$profile" = "full" ]; then if [ "$profile" = "full" ]; then
ENV_FILE="$env_file" BASE_URL="$base_url" PROMETHEUS_URL="$prometheus_url" TEMPO_URL="$tempo_url" LOKI_URL="$loki_url" EVIDENCE_DIR="$output_dir/incidents" scripts/incident-database.sh ENV_FILE="$env_file" BASE_URL="$base_url" CA_FILE="$ca_file" PROMETHEUS_URL="$prometheus_url" TEMPO_URL="$tempo_url" LOKI_URL="$loki_url" EVIDENCE_DIR="$output_dir/incidents" scripts/incident-database.sh
ENV_FILE="$env_file" BASE_URL="$base_url" PROMETHEUS_URL="$prometheus_url" EVIDENCE_DIR="$output_dir/incidents" scripts/incident-worker.sh long ENV_FILE="$env_file" BASE_URL="$base_url" CA_FILE="$ca_file" PROMETHEUS_URL="$prometheus_url" EVIDENCE_DIR="$output_dir/incidents" scripts/incident-worker.sh long
ENV_FILE="$env_file" BASE_URL="$base_url" PROMETHEUS_URL="$prometheus_url" EVIDENCE_DIR="$output_dir/incidents" scripts/incident-worker.sh short ENV_FILE="$env_file" BASE_URL="$base_url" CA_FILE="$ca_file" PROMETHEUS_URL="$prometheus_url" EVIDENCE_DIR="$output_dir/incidents" scripts/incident-worker.sh short
ENV_FILE="$env_file" BASE_URL="$base_url" PROMETHEUS_URL="$prometheus_url" EVIDENCE_DIR="$output_dir/incidents" scripts/incident-telemetry.sh ENV_FILE="$env_file" BASE_URL="$base_url" CA_FILE="$ca_file" PROMETHEUS_URL="$prometheus_url" EVIDENCE_DIR="$output_dir/incidents" scripts/incident-telemetry.sh
fi fi
arguments= arguments=
+163
View File
@@ -0,0 +1,163 @@
#!/bin/sh
set -eu
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
repo_dir=$(CDPATH= cd -- "$script_dir/.." && pwd)
security_dir=${SECURITY_DIR:-$repo_dir/.runtime/security}
public_port=${PUBLIC_TLS_PORT:-8443}
public_host=${PUBLIC_TLS_HOST:-localhost}
api_address=${API_TLS_ADDRESS:-api:8443}
metrics_address=${METRICS_TLS_ADDRESS:-api:9091}
empty_ca="${TMPDIR:-/tmp}/lab7-empty-ca.$$"
cleanup() {
rm -f "$empty_ca"
}
trap cleanup EXIT HUP INT TERM
require_file() {
if [ ! -r "$1" ]; then
echo "missing security material: $1" >&2
exit 1
fi
}
expect_failure() {
name=$1
shift
if "$@" >/dev/null 2>&1; then
echo "FAIL: $name unexpectedly succeeded" >&2
exit 1
fi
echo "PASS: $name"
}
expect_tls_success() {
name=$1
certificate=$2
key=$3
if curl --fail --silent --show-error --noproxy '*' \
--connect-timeout 5 --max-time 10 \
--cacert "$security_dir/internal-ca/ca.crt" \
--cert "$certificate" --key "$key" \
"https://$api_address/health/ready" >/dev/null 2>&1; then
echo "PASS: $name"
return
fi
echo "FAIL: $name" >&2
exit 1
}
expect_tls_failure() {
name=$1
shift
if curl --fail --silent --show-error --noproxy '*' \
--connect-timeout 5 --max-time 10 \
--cacert "$security_dir/internal-ca/ca.crt" \
"$@" "https://$api_address/health/ready" >/dev/null 2>&1; then
echo "FAIL: $name unexpectedly succeeded" >&2
exit 1
fi
echo "PASS: $name"
}
expect_public_hostname_failure() {
if openssl s_client \
-connect "$public_host:$public_port" \
-servername wrong.local \
-verify_hostname wrong.local \
-verify_return_error \
-CAfile "$security_dir/public-ca/ca.crt" </dev/null >/dev/null 2>&1; then
echo "FAIL: public TLS with wrong hostname unexpectedly succeeded" >&2
exit 1
fi
echo "PASS: public TLS with wrong hostname"
}
for file in \
"$security_dir/public-ca/ca.crt" \
"$security_dir/internal-ca/ca.crt" \
"$security_dir/foreign-ca/ca.crt" \
"$security_dir/load-balancer/tls.crt" \
"$security_dir/load-balancer/tls.key" \
"$security_dir/prometheus/tls.crt" \
"$security_dir/prometheus/tls.key" \
"$security_dir/forbidden-client/tls.crt" \
"$security_dir/forbidden-client/tls.key" \
"$security_dir/foreign-client/tls.crt" \
"$security_dir/foreign-client/tls.key"; do
require_file "$file"
done
: >"$empty_ca"
chmod 0600 "$empty_ca"
curl --fail --silent --show-error --noproxy '*' \
--connect-timeout 5 --max-time 10 \
--cacert "$security_dir/public-ca/ca.crt" \
"https://$public_host:$public_port/health/ready" >/dev/null
echo "PASS: public TLS with trusted CA and hostname"
expect_failure "public TLS with empty CA" \
curl --fail --silent --show-error --noproxy '*' \
--connect-timeout 5 --max-time 10 \
--cacert "$empty_ca" \
"https://$public_host:$public_port/health/ready"
expect_failure "public TLS with foreign CA" \
curl --fail --silent --show-error --noproxy '*' \
--connect-timeout 5 --max-time 10 \
--cacert "$security_dir/foreign-ca/ca.crt" \
"https://$public_host:$public_port/health/ready"
expect_public_hostname_failure
expect_tls_failure "API mTLS without client certificate"
expect_tls_failure "API mTLS with forbidden trusted identity" \
--cert "$security_dir/forbidden-client/tls.crt" \
--key "$security_dir/forbidden-client/tls.key"
expect_tls_failure "API mTLS with client certificate from foreign CA" \
--cert "$security_dir/foreign-client/tls.crt" \
--key "$security_dir/foreign-client/tls.key"
expect_tls_success "API mTLS with load-balancer identity" \
"$security_dir/load-balancer/tls.crt" \
"$security_dir/load-balancer/tls.key"
expect_tls_failure "business API with Prometheus identity" \
--cert "$security_dir/prometheus/tls.crt" \
--key "$security_dir/prometheus/tls.key"
expect_failure "metrics mTLS without client certificate" \
curl --fail --silent --show-error --noproxy '*' \
--connect-timeout 5 --max-time 10 \
--cacert "$security_dir/internal-ca/ca.crt" \
"https://$metrics_address/metrics"
expect_failure "metrics mTLS with load-balancer identity" \
curl --fail --silent --show-error --noproxy '*' \
--connect-timeout 5 --max-time 10 \
--cacert "$security_dir/internal-ca/ca.crt" \
--cert "$security_dir/load-balancer/tls.crt" \
--key "$security_dir/load-balancer/tls.key" \
"https://$metrics_address/metrics"
expect_failure "metrics mTLS with client certificate from foreign CA" \
curl --fail --silent --show-error --noproxy '*' \
--connect-timeout 5 --max-time 10 \
--cacert "$security_dir/internal-ca/ca.crt" \
--cert "$security_dir/foreign-client/tls.crt" \
--key "$security_dir/foreign-client/tls.key" \
"https://$metrics_address/metrics"
curl --fail --silent --show-error --noproxy '*' \
--connect-timeout 5 --max-time 10 \
--cacert "$security_dir/internal-ca/ca.crt" \
--cert "$security_dir/prometheus/tls.crt" \
--key "$security_dir/prometheus/tls.key" \
"https://$metrics_address/metrics" >/dev/null
echo "PASS: metrics mTLS with Prometheus identity"