lab7: безопасность, mTLS, OpenBao и PKI lifecycle
Application / Go invariants and static checks (pull_request) Canceled after 0s
Application / Lab7 verified TLS and retained features (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Vladislav Kunetskiy
2026-11-10 14:39:57 +03:00
parent 20afc2c790
commit 1b6e96ccc0
570 changed files with 298308 additions and 137 deletions
+171
View File
@@ -0,0 +1,171 @@
package domain
import (
"time"
"github.com/google/uuid"
)
// AttachmentStatus is the public lifecycle of an attachment. Pending is an
// internal presign state and is never exposed by the API.
type AttachmentStatus string
const (
AttachmentPending AttachmentStatus = "pending"
AttachmentQueued AttachmentStatus = "queued"
AttachmentProcessing AttachmentStatus = "processing"
AttachmentReady AttachmentStatus = "ready"
AttachmentFailed AttachmentStatus = "failed"
)
func (s AttachmentStatus) Valid() bool {
switch s {
case AttachmentPending, AttachmentQueued, AttachmentProcessing, AttachmentReady, AttachmentFailed:
return true
default:
return false
}
}
// Public reports whether the status is part of the API enum.
func (s AttachmentStatus) Public() bool {
switch s {
case AttachmentQueued, AttachmentProcessing, AttachmentReady, AttachmentFailed:
return true
default:
return false
}
}
// VariantName is the contract variant identifier.
type VariantName string
const (
VariantOriginal VariantName = "original"
VariantThumbnail VariantName = "thumbnail"
VariantCrop VariantName = "crop"
VariantOptimized VariantName = "optimized"
)
func (n VariantName) Valid() bool {
switch n {
case VariantThumbnail, VariantCrop, VariantOptimized:
return true
default:
return false
}
}
// ContentType returns the contract media type of the variant.
func (n VariantName) ContentType() string {
if n == VariantOptimized {
return "image/webp"
}
return "image/jpeg"
}
// ObjectName returns the object suffix for the variant.
func (n VariantName) ObjectName() string {
if n == VariantOptimized {
return string(n) + ".webp"
}
return string(n) + ".jpg"
}
// Variant is one derived image. ObjectKey is internal and never leaves the
// service.
type Variant struct {
Name VariantName
ContentType string
SizeBytes int64
Width int
Height int
SHA256 string
ObjectKey string
}
// Attachment describes the original object and the current pipeline result.
type Attachment struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
ContentType string
SizeBytes int64
SHA256 string
Status AttachmentStatus
ErrorCode *string
ObjectKey string
StagingKey string
PipelineVersion int
Variants []Variant
CreatedAt time.Time
UpdatedAt time.Time
ReadyAt *time.Time
FailedAt *time.Time
}
// AdmissionLimits bounds accepted-but-unfinished work. Zero means unlimited.
type AdmissionLimits struct {
PerUser int
Total int
Bytes int64
}
// AttachmentDraft is a fully validated attachment awaiting persistence.
type AttachmentDraft struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
ObjectKey string
StagingKey string
Filename string
ContentType string
SizeBytes int64
SHA256 string
Status AttachmentStatus
PipelineVersion int
}
// AttachmentState is the minimal projection used while validating message
// attachments in a transaction.
type AttachmentState struct {
ID uuid.UUID
Status AttachmentStatus
}
// AttachmentKey is the minimal projection used by the orphan sweeper.
type AttachmentKey struct {
ID uuid.UUID
ObjectKey string
Status AttachmentStatus
CreatedAt time.Time
}
// StaleStaging is one staging object whose owner row is already terminal.
type StaleStaging struct {
AttachmentID uuid.UUID
StagingKey string
Status AttachmentStatus
}
// PresignRequest is the validated client intent for a direct upload.
type PresignRequest struct {
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
ContentType string
SizeBytes int64
SHA256 string
}
// PresignResult is returned by the server and never contains credentials.
type PresignResult struct {
AttachmentID uuid.UUID
UploadURL string
ExpiresAt time.Time
SizeBytes int64
SHA256 string
}
+51
View File
@@ -0,0 +1,51 @@
package domain
import (
"fmt"
"slices"
"time"
"github.com/google/uuid"
)
type Chat struct {
ID uuid.UUID
Title string
MemberIDs []uuid.UUID
CreatedAt time.Time
}
func (c Chat) HasMember(userID uuid.UUID) bool {
return slices.Contains(c.MemberIDs, userID)
}
type ChatDraft struct {
Title string
MemberIDs []uuid.UUID
CallerID uuid.UUID
}
func (d ChatDraft) Validate() error {
if err := validateNotBlank("title", d.Title); err != nil {
return err
}
if len(d.MemberIDs) == 0 {
return fmt.Errorf("member_ids must not be empty: %w", ErrValidation)
}
seen := make(map[uuid.UUID]struct{}, len(d.MemberIDs))
for _, id := range d.MemberIDs {
if _, ok := seen[id]; ok {
return fmt.Errorf("member_ids contains duplicates: %w", ErrValidation)
}
seen[id] = struct{}{}
}
if _, ok := seen[d.CallerID]; !ok {
return fmt.Errorf("member_ids must contain the caller: %w", ErrValidation)
}
return nil
}
+17
View File
@@ -0,0 +1,17 @@
package domain
import (
"time"
"github.com/google/uuid"
)
type Cursor struct {
Scope uuid.UUID
CreatedAt time.Time
ID uuid.UUID
}
func (c Cursor) BelongsTo(scope uuid.UUID) bool {
return c.Scope == scope
}
+19
View File
@@ -0,0 +1,19 @@
package domain
import "errors"
var (
ErrNotFound = errors.New("not found")
ErrUsernameTaken = errors.New("username already taken")
ErrUnknownMember = errors.New("member does not exist")
ErrValidation = errors.New("validation failed")
ErrInvalidCursor = errors.New("invalid cursor")
ErrConflict = errors.New("conflict")
ErrIdempotency = errors.New("idempotency key already used with another payload")
ErrUnauthenticated = errors.New("unauthenticated")
ErrUnavailable = errors.New("temporarily unavailable")
ErrTooLarge = errors.New("payload is too large")
ErrUnsupportedMedia = errors.New("unsupported media type")
ErrIncomplete = errors.New("object is not fully uploaded")
ErrRateLimited = errors.New("too many unfinished uploads")
)
+192
View File
@@ -0,0 +1,192 @@
package domain
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"time"
"github.com/google/uuid"
)
// JobType is the fixed contract type from contracts/jobs.schema.json.
const JobType = "attachment.process.v1"
// JobStatus is the durable state of one logical processing job. Superseded is
// internal: a newer pipeline version replaced the job before it completed.
type JobStatus string
const (
JobQueued JobStatus = "queued"
JobProcessing JobStatus = "processing"
JobReady JobStatus = "ready"
JobFailed JobStatus = "failed"
JobSuperseded JobStatus = "superseded"
)
func (s JobStatus) Valid() bool {
switch s {
case JobQueued, JobProcessing, JobReady, JobFailed, JobSuperseded:
return true
default:
return false
}
}
// Job is the durable processing intent. SourceKey is the trusted object the
// worker reads: staging for a fresh upload, the original object for reprocess.
type Job struct {
ID uuid.UUID
AttachmentID uuid.UUID
PipelineVersion int
SourceKey string
Attempt int
MaxAttempts int
Status JobStatus
AvailableAt time.Time
LeaseOwner string
LeaseExpiresAt *time.Time
LastErrorCode *string
ReplayCount int
CreatedAt time.Time
UpdatedAt time.Time
CompletedAt *time.Time
Traceparent string
Tracestate string
}
// OutboxMessage is one pending broker publication. Payload is the exact
// jobs.schema.json document; no binary data or credentials are stored.
type OutboxMessage struct {
ID int64
JobID uuid.UUID
Attempt int
Kind string
RoutingKey string
Payload []byte
AvailableAt time.Time
PublishedAt *time.Time
ClaimedBy string
ClaimedUntil *time.Time
PublishAttempts int
LastError *string
CreatedAt time.Time
}
// JobMessage is the broker carrier defined by contracts/jobs.schema.json.
type JobMessage struct {
SchemaVersion int `json:"schema_version"`
JobID uuid.UUID `json:"job_id"`
Type string `json:"type"`
AttachmentID uuid.UUID `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Attempt int `json:"attempt"`
CreatedAt time.Time `json:"created_at"`
Traceparent string `json:"traceparent,omitempty"`
Tracestate string `json:"tracestate,omitempty"`
}
// NewJobMessage builds the only message the application is allowed to publish.
func NewJobMessage(job Job) JobMessage {
return JobMessage{
SchemaVersion: 1,
JobID: job.ID,
Type: JobType,
AttachmentID: job.AttachmentID,
PipelineVersion: job.PipelineVersion,
Attempt: job.Attempt,
CreatedAt: job.CreatedAt.UTC(),
}
}
// Validate enforces the closed schema. The worker must never trust paths or
// storage metadata from this message.
func (m JobMessage) Validate() error {
if m.SchemaVersion != 1 {
return errors.New("unsupported schema_version")
}
if m.Type != JobType {
return fmt.Errorf("unsupported type %q", m.Type)
}
if m.JobID == uuid.Nil || m.AttachmentID == uuid.Nil {
return errors.New("job_id and attachment_id are required")
}
if m.PipelineVersion < 1 || m.Attempt < 1 {
return errors.New("pipeline_version and attempt must be >= 1")
}
if m.CreatedAt.IsZero() {
return errors.New("created_at is required")
}
if m.Traceparent != "" && !traceparentPattern.MatchString(m.Traceparent) {
return errors.New("traceparent does not match W3C format")
}
if len(m.Tracestate) > 512 {
return errors.New("tracestate is too long")
}
return nil
}
var traceparentPattern = regexp.MustCompile(`^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$`)
func (m JobMessage) MarshalPayload() ([]byte, error) {
return json.Marshal(m)
}
func ParseJobMessage(payload []byte) (JobMessage, error) {
var message JobMessage
if err := json.Unmarshal(payload, &message); err != nil {
return JobMessage{}, fmt.Errorf("decode job message: %w", err)
}
if err := message.Validate(); err != nil {
return JobMessage{}, err
}
return message, nil
}
// ClaimOutcome explains why a delivery did or did not become the active
// processing attempt. The worker maps it to ack/nack without guessing.
type ClaimOutcome string
const (
ClaimAcquired ClaimOutcome = "acquired"
ClaimAlreadyReady ClaimOutcome = "already_ready"
ClaimAlreadyFailed ClaimOutcome = "already_failed"
ClaimSuperseded ClaimOutcome = "superseded"
ClaimStaleAttempt ClaimOutcome = "stale_attempt"
ClaimFutureAttempt ClaimOutcome = "future_attempt"
ClaimBusyLease ClaimOutcome = "busy_lease"
ClaimNotDue ClaimOutcome = "not_due"
ClaimVersionStale ClaimOutcome = "version_stale"
ClaimJobNotFound ClaimOutcome = "job_not_found"
ClaimSourceMissing ClaimOutcome = "source_missing"
ClaimPayloadInvalid ClaimOutcome = "payload_invalid"
)
type ClaimResult struct {
Outcome ClaimOutcome
Job Job
Attachment Attachment
}
// Job event names used by the operator audit trail.
const (
EventEnqueued = "enqueued"
EventClaimed = "claimed"
EventRetried = "retried"
EventReady = "ready"
EventFailed = "failed"
EventLeaseExpired = "lease_expired"
EventReplayed = "replayed"
EventReprocessed = "reprocessed"
EventSuperseded = "superseded"
)
+31
View File
@@ -0,0 +1,31 @@
package domain
import (
"strconv"
"github.com/google/uuid"
)
const (
StagingUploadPrefix = "staging/uploads/"
StagingVerifiedPrefix = "staging/verified/"
StagingPresignPrefix = "staging/presign/"
AttachmentsPrefix = "attachments/"
)
func StagingUploadKey(chatID, attachmentID uuid.UUID) string {
return StagingUploadPrefix + chatID.String() + "/" + attachmentID.String()
}
func StagingVerifiedKey(chatID, attachmentID uuid.UUID) string {
return StagingVerifiedPrefix + chatID.String() + "/" + attachmentID.String()
}
func OriginalObjectKey(chatID, attachmentID uuid.UUID) string {
return AttachmentsPrefix + chatID.String() + "/" + attachmentID.String() + "/original"
}
func VariantObjectKey(chatID, attachmentID uuid.UUID, pipelineVersion int, name VariantName) string {
return AttachmentsPrefix + chatID.String() + "/" + attachmentID.String() +
"/variants/v" + strconv.Itoa(pipelineVersion) + "/" + name.ObjectName()
}
+70
View File
@@ -0,0 +1,70 @@
package domain
import (
"crypto/sha256"
"fmt"
"strings"
"time"
"github.com/google/uuid"
)
// MaxMessageAttachments is the contract limit for attachment_ids on a message.
const MaxMessageAttachments = 10
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
AttachmentIDs []uuid.UUID
CreatedAt time.Time
}
// MessageIdempotency is the client Idempotency-Key together with the fingerprint
// of the payload it was first used with. The same key and fingerprint replay the
// stored message; the same key with another payload is a conflict.
type MessageIdempotency struct {
Key string
RequestHash [sha256.Size]byte
}
type MessageDraft struct {
ChatID uuid.UUID
SenderID uuid.UUID
Text string
AttachmentIDs []uuid.UUID
Idempotency MessageIdempotency
}
// Validate enforces the contract rule that a message carries either non-blank
// text or at least one attachment, never neither.
func (d MessageDraft) Validate() error {
if strings.TrimSpace(d.Text) == "" && len(d.AttachmentIDs) == 0 {
return fmt.Errorf("message has neither text nor attachments: %w", ErrValidation)
}
if len(d.AttachmentIDs) > MaxMessageAttachments {
return fmt.Errorf("too many attachments: %w", ErrValidation)
}
seen := make(map[uuid.UUID]struct{}, len(d.AttachmentIDs))
for _, id := range d.AttachmentIDs {
if id == uuid.Nil {
return fmt.Errorf("attachment id is empty: %w", ErrValidation)
}
if _, ok := seen[id]; ok {
return fmt.Errorf("duplicate attachment id %s: %w", id, ErrValidation)
}
seen[id] = struct{}{}
}
if d.Idempotency.Key == "" {
return fmt.Errorf("idempotency key is missing: %w", ErrValidation)
}
return nil
}
+8
View File
@@ -0,0 +1,8 @@
package domain
const DefaultPageLimit = 50
type Page[T any] struct {
Items []T
Next *Cursor
}
+19
View File
@@ -0,0 +1,19 @@
package domain
import (
"time"
"github.com/google/uuid"
)
type Session struct {
Token string
ExpiresAt time.Time
User User
}
type NewSession struct {
TokenHash []byte
UserID uuid.UUID
ExpiresAt time.Time
}
+14
View File
@@ -0,0 +1,14 @@
package domain
import (
"fmt"
"strings"
)
func validateNotBlank(field, value string) error {
if strings.TrimSpace(value) == "" {
return fmt.Errorf("%s consists of whitespace only: %w", field, ErrValidation)
}
return nil
}
+44
View File
@@ -0,0 +1,44 @@
package domain
import (
"fmt"
"time"
"github.com/google/uuid"
)
type User struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
}
type UserDraft struct {
Username string
DisplayName string
Password string
}
func (d UserDraft) Validate() error {
if err := validateNotBlank("display_name", d.DisplayName); err != nil {
return err
}
if length := len([]rune(d.Password)); length < 12 || length > 128 {
return fmt.Errorf("password length must be between 12 and 128 code points: %w", ErrValidation)
}
return nil
}
type NewUser struct {
Username string
DisplayName string
PasswordHash string
}
type UserCredentials struct {
User User
PasswordHash string
}
+121
View File
@@ -0,0 +1,121 @@
package domain_test
import (
"strings"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
)
// Длины, regex и uniqueItems проверяет сгенерированный слой по contracts/openapi.json.
// Домен закрывает только то, что схема выразить не может.
func TestUserDraftRejectsBlankDisplayName(t *testing.T) {
t.Parallel()
for _, blank := range []string{" ", " ", "\t", "\n", "\u00a0"} {
draft := domain.UserDraft{Username: "alice", DisplayName: blank}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
}
func TestUserDraftAcceptsVisibleName(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
assert.NoError(t, draft.Validate())
}
func TestUserDraftRejectsShortPassword(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "too-short"}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
func TestUserDraftRejectsTooLongPassword(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: strings.Repeat("a", 129)}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
func TestUserDraftAcceptsMinimalPassword(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: strings.Repeat("a", 12)}
assert.NoError(t, draft.Validate())
}
func TestChatDraftRequiresCallerAmongMembers(t *testing.T) {
t.Parallel()
caller := uuid.New()
outside := domain.ChatDraft{
Title: "Проект",
MemberIDs: []uuid.UUID{uuid.New(), uuid.New()},
CallerID: caller,
}
require.ErrorIs(t, outside.Validate(), domain.ErrValidation)
inside := domain.ChatDraft{
Title: "Проект",
MemberIDs: []uuid.UUID{uuid.New(), caller},
CallerID: caller,
}
assert.NoError(t, inside.Validate())
}
func TestChatDraftRejectsBlankTitle(t *testing.T) {
t.Parallel()
caller := uuid.New()
draft := domain.ChatDraft{
Title: " ",
MemberIDs: []uuid.UUID{caller},
CallerID: caller,
}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
func TestMessageDraftRejectsBlankText(t *testing.T) {
t.Parallel()
draft := domain.MessageDraft{
ChatID: uuid.New(),
SenderID: uuid.New(),
Text: strings.Repeat(" ", 10),
Idempotency: domain.MessageIdempotency{Key: "key-1"},
}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
func TestMessageDraftRejectsMissingIdempotencyKey(t *testing.T) {
t.Parallel()
draft := domain.MessageDraft{
ChatID: uuid.New(),
SenderID: uuid.New(),
Text: "привет",
}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation,
"с lab3 отправка сообщения невозможна без Idempotency-Key")
}
func TestMessageDraftAcceptsTextWithSurroundingSpaces(t *testing.T) {
t.Parallel()
draft := domain.MessageDraft{
ChatID: uuid.New(),
SenderID: uuid.New(),
Text: " привет ",
Idempotency: domain.MessageIdempotency{Key: "key-1"},
}
assert.NoError(t, draft.Validate(), "контракт запрещает только полностью пробельный текст")
}