lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
@@ -0,0 +1,183 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
attachmentService "mtusi-messenger/internal/service/attachment"
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
func (h *Handler) UploadAttachment(
|
||||
ctx context.Context,
|
||||
req oas.UploadAttachmentReq,
|
||||
params oas.UploadAttachmentParams,
|
||||
) (oas.UploadAttachmentRes, error) {
|
||||
body, declared, err := uploadBody(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
attachment, err := h.attachments.Upload(ctx, attachmentService.UploadInput{
|
||||
ChatID: params.ChatID,
|
||||
OwnerID: caller(ctx),
|
||||
Filename: params.Filename,
|
||||
DeclaredContentType: declared,
|
||||
Body: body,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.AttachmentHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: attachmentResponse(attachment),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) GetAttachment(
|
||||
ctx context.Context,
|
||||
params oas.GetAttachmentParams,
|
||||
) (oas.GetAttachmentRes, error) {
|
||||
attachment, err := h.attachments.Get(ctx, caller(ctx), params.AttachmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.AttachmentHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: attachmentResponse(attachment),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) DownloadAttachment(
|
||||
ctx context.Context,
|
||||
params oas.DownloadAttachmentParams,
|
||||
) (oas.DownloadAttachmentRes, error) {
|
||||
variant := domain.VariantOriginal
|
||||
if requested, ok := params.Variant.Get(); ok {
|
||||
variant = domain.VariantName(requested)
|
||||
}
|
||||
|
||||
attachment, metadata, body, err := h.attachments.OpenVariant(
|
||||
ctx, caller(ctx), params.AttachmentID, variant,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The generated transport copies the body after the handler returns. Close
|
||||
// the S3 stream when the client disconnects; closeOnEOF covers the normal
|
||||
// path.
|
||||
_ = context.AfterFunc(ctx, func() { _ = body.Close() })
|
||||
|
||||
requestID := oas.NewOptString(requestIDFromContext(ctx))
|
||||
reader := closeOnEOF{ReadCloser: body}
|
||||
|
||||
switch metadata.ContentType {
|
||||
case "image/png":
|
||||
return &oas.DownloadAttachmentOKImagePNGHeaders{
|
||||
XRequestID: requestID,
|
||||
Response: oas.DownloadAttachmentOKImagePNG{Data: reader},
|
||||
}, nil
|
||||
case "image/jpeg":
|
||||
return &oas.DownloadAttachmentOKImageJpegHeaders{
|
||||
XRequestID: requestID,
|
||||
Response: oas.DownloadAttachmentOKImageJpeg{Data: reader},
|
||||
}, nil
|
||||
case "image/webp":
|
||||
return &oas.DownloadAttachmentOKImageWEBPHeaders{
|
||||
XRequestID: requestID,
|
||||
Response: oas.DownloadAttachmentOKImageWEBP{Data: reader},
|
||||
}, nil
|
||||
default:
|
||||
_ = body.Close()
|
||||
|
||||
return nil, fmt.Errorf("%w: unexpected content type %q", domain.ErrUnavailable, attachment.ContentType)
|
||||
}
|
||||
}
|
||||
|
||||
func uploadBody(req oas.UploadAttachmentReq) (io.Reader, string, error) {
|
||||
switch typed := req.(type) {
|
||||
case *oas.UploadAttachmentReqImagePNG:
|
||||
return typed.Data, "image/png", nil
|
||||
case *oas.UploadAttachmentReqImageJpeg:
|
||||
return typed.Data, "image/jpeg", nil
|
||||
default:
|
||||
return nil, "", fmt.Errorf("%w: request body must be image/png or image/jpeg", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
}
|
||||
|
||||
func attachmentResponse(attachment domain.Attachment) oas.Attachment {
|
||||
response := oas.Attachment{
|
||||
ID: attachment.ID,
|
||||
ChatID: attachment.ChatID,
|
||||
OwnerID: attachment.OwnerID,
|
||||
Filename: attachment.Filename,
|
||||
SizeBytes: int(attachment.SizeBytes),
|
||||
SHA256: attachment.SHA256,
|
||||
Status: attachmentStatus(attachment.Status),
|
||||
ErrorCode: oas.NilString{Null: true},
|
||||
CreatedAt: attachment.CreatedAt,
|
||||
UpdatedAt: attachment.UpdatedAt,
|
||||
Variants: make([]oas.Variant, 0, len(attachment.Variants)),
|
||||
}
|
||||
|
||||
switch attachment.ContentType {
|
||||
case "image/png":
|
||||
response.ContentType = oas.AttachmentContentTypeImagePNG
|
||||
case "image/jpeg":
|
||||
response.ContentType = oas.AttachmentContentTypeImageJpeg
|
||||
default:
|
||||
response.ContentType = oas.AttachmentContentType(attachment.ContentType)
|
||||
}
|
||||
|
||||
if attachment.ErrorCode != nil {
|
||||
response.ErrorCode = oas.NilString{Value: *attachment.ErrorCode}
|
||||
}
|
||||
|
||||
for _, variant := range attachment.Variants {
|
||||
response.Variants = append(response.Variants, oas.Variant{
|
||||
Name: oas.VariantName(variant.Name),
|
||||
ContentType: oas.VariantContentType(variant.ContentType),
|
||||
SizeBytes: int(variant.SizeBytes),
|
||||
Width: variant.Width,
|
||||
Height: variant.Height,
|
||||
SHA256: variant.SHA256,
|
||||
})
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
func attachmentStatus(status domain.AttachmentStatus) oas.AttachmentStatus {
|
||||
switch status {
|
||||
case domain.AttachmentQueued:
|
||||
return oas.AttachmentStatusQueued
|
||||
case domain.AttachmentProcessing:
|
||||
return oas.AttachmentStatusProcessing
|
||||
case domain.AttachmentReady:
|
||||
return oas.AttachmentStatusReady
|
||||
case domain.AttachmentFailed:
|
||||
return oas.AttachmentStatusFailed
|
||||
default:
|
||||
// Pending is internal and never reaches the transport; map it to the
|
||||
// closest public state rather than inventing a new enum value.
|
||||
return oas.AttachmentStatusQueued
|
||||
}
|
||||
}
|
||||
|
||||
type closeOnEOF struct {
|
||||
io.ReadCloser
|
||||
}
|
||||
|
||||
func (r closeOnEOF) Read(p []byte) (int, error) {
|
||||
n, err := r.ReadCloser.Read(p)
|
||||
if err != nil {
|
||||
_ = r.Close()
|
||||
}
|
||||
|
||||
return n, err
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// attachmentUploadPath matches POST /api/v1/chats/{chat_id}/attachments. The
|
||||
// UUID syntax is not validated here; this middleware only selects a body limit,
|
||||
// and the generated transport rejects malformed identifiers later.
|
||||
var attachmentUploadPath = regexp.MustCompile(`^/api/v1/chats/[^/]+/attachments$`)
|
||||
|
||||
// bodyLimitMiddleware bounds the request body before it reaches the generated
|
||||
// transport. JSON endpoints keep the small default limit; the attachment upload
|
||||
// gets its own larger limit. Without this split the 10 MiB upload would be
|
||||
// rejected before the handler, and raising the global limit would let any
|
||||
// public JSON endpoint read a 10 MiB body.
|
||||
func bodyLimitMiddleware(
|
||||
defaultLimit, uploadLimit int64,
|
||||
log *slog.Logger,
|
||||
next http.Handler,
|
||||
) http.Handler {
|
||||
if defaultLimit <= 0 && uploadLimit <= 0 {
|
||||
return next
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
limit := limitForRequest(r, defaultLimit, uploadLimit)
|
||||
if limit <= 0 {
|
||||
next.ServeHTTP(w, r)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if r.ContentLength > limit {
|
||||
logRejected(r.Context(), log, r, http.StatusRequestEntityTooLarge, nil)
|
||||
writeError(r.Context(), log, w, r, http.StatusRequestEntityTooLarge)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if r.Body != nil {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func limitForRequest(r *http.Request, defaultLimit, uploadLimit int64) int64 {
|
||||
if r.Method == http.MethodPost && attachmentUploadPath.MatchString(r.URL.Path) {
|
||||
return uploadLimit
|
||||
}
|
||||
|
||||
return defaultLimit
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestLimitForRequest(t *testing.T) {
|
||||
const (
|
||||
defaultLimit = 1024
|
||||
uploadLimit = 10 << 20
|
||||
)
|
||||
|
||||
upload, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments", nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(uploadLimit), limitForRequest(upload, defaultLimit, uploadLimit))
|
||||
|
||||
messages, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/messages", nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(defaultLimit), limitForRequest(messages, defaultLimit, uploadLimit))
|
||||
|
||||
presign, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments/presign", nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(defaultLimit), limitForRequest(presign, defaultLimit, uploadLimit))
|
||||
}
|
||||
|
||||
func TestBodyLimitMiddlewareSelectsUploadLimit(t *testing.T) {
|
||||
const (
|
||||
defaultLimit = 16
|
||||
uploadLimit = 64
|
||||
)
|
||||
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(body)
|
||||
})
|
||||
handler := bodyLimitMiddleware(defaultLimit, uploadLimit, nil, next)
|
||||
|
||||
upload := httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodPost,
|
||||
"/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments",
|
||||
strings.NewReader(strings.Repeat("x", 32)),
|
||||
)
|
||||
uploadRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(uploadRecorder, upload)
|
||||
require.Equal(t, http.StatusOK, uploadRecorder.Code)
|
||||
|
||||
jsonRequest := httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodPost,
|
||||
"/api/v1/chats/11111111-1111-4111-8111-111111111111/messages",
|
||||
strings.NewReader(strings.Repeat("x", 32)),
|
||||
)
|
||||
jsonRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(jsonRecorder, jsonRequest)
|
||||
require.Equal(t, http.StatusRequestEntityTooLarge, jsonRecorder.Code)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
var fallbackErrorBody = []byte(`{"error":{"code":"internal_error","message":"Internal error","request_id":""}}`)
|
||||
|
||||
func newErrorHandler(log *slog.Logger) oas.ErrorHandler {
|
||||
return func(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) {
|
||||
status := statusForError(err)
|
||||
|
||||
if preMiddlewareError(err) {
|
||||
logRejected(ctx, log, r, status, err)
|
||||
}
|
||||
|
||||
writeError(ctx, log, w, r, status)
|
||||
}
|
||||
}
|
||||
|
||||
func statusForError(err error) int {
|
||||
var securityErr *ogenerrors.SecurityError
|
||||
|
||||
if errors.As(err, &securityErr) {
|
||||
// A SecurityError only means "the caller did not satisfy a security
|
||||
// requirement". It must not hide a dependency outage behind 401: a
|
||||
// session lookup can fail because PostgreSQL is unavailable.
|
||||
if errors.Is(securityErr.Err, ErrUnauthenticated) ||
|
||||
errors.Is(securityErr.Err, domain.ErrUnauthenticated) ||
|
||||
errors.Is(securityErr.Err, ogenerrors.ErrSecurityRequirementIsNotSatisfied) ||
|
||||
securityErr.Err != nil && securityErr.Err.Error() == "invalid basic auth" {
|
||||
return http.StatusUnauthorized
|
||||
}
|
||||
|
||||
if status := statusForDomainError(securityErr.Err); status != http.StatusInternalServerError {
|
||||
return status
|
||||
}
|
||||
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
|
||||
if status := ogenerrors.ErrorCode(err); status != http.StatusInternalServerError {
|
||||
return status
|
||||
}
|
||||
|
||||
return statusForDomainError(err)
|
||||
}
|
||||
|
||||
func statusForDomainError(err error) int {
|
||||
switch {
|
||||
case errors.Is(err, ErrUnauthenticated), errors.Is(err, domain.ErrUnauthenticated):
|
||||
return http.StatusUnauthorized
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return http.StatusNotFound
|
||||
case errors.Is(err, domain.ErrUsernameTaken),
|
||||
errors.Is(err, domain.ErrConflict),
|
||||
errors.Is(err, domain.ErrIdempotency),
|
||||
errors.Is(err, domain.ErrIncomplete):
|
||||
return http.StatusConflict
|
||||
case errors.Is(err, domain.ErrValidation),
|
||||
errors.Is(err, domain.ErrUnknownMember),
|
||||
errors.Is(err, domain.ErrInvalidCursor):
|
||||
return http.StatusBadRequest
|
||||
case errors.Is(err, domain.ErrRateLimited), errors.Is(err, password.ErrBusy):
|
||||
return http.StatusTooManyRequests
|
||||
case errors.Is(err, domain.ErrTooLarge):
|
||||
return http.StatusRequestEntityTooLarge
|
||||
case errors.Is(err, domain.ErrUnsupportedMedia):
|
||||
return http.StatusUnsupportedMediaType
|
||||
case errors.Is(err, domain.ErrUnavailable):
|
||||
return http.StatusServiceUnavailable
|
||||
default:
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
}
|
||||
|
||||
func newNotFoundHandler(log *slog.Logger) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
logRejected(r.Context(), log, r, http.StatusNotFound, nil)
|
||||
writeError(r.Context(), log, w, r, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func newMethodNotAllowedHandler(log *slog.Logger) func(http.ResponseWriter, *http.Request, string) {
|
||||
return func(w http.ResponseWriter, r *http.Request, allowed string) {
|
||||
w.Header().Set("Allow", allowed)
|
||||
logRejected(r.Context(), log, r, http.StatusMethodNotAllowed, nil)
|
||||
writeError(r.Context(), log, w, r, http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func writeError(ctx context.Context, log *slog.Logger, w http.ResponseWriter, r *http.Request, status int) {
|
||||
requestID := requestIDFromContext(ctx)
|
||||
if requestID == "" {
|
||||
requestID = r.Header.Get(requestIDHeader)
|
||||
}
|
||||
|
||||
body := oas.Error{
|
||||
Error: oas.ErrorError{
|
||||
Code: codeForStatus(status),
|
||||
Message: http.StatusText(status),
|
||||
RequestID: requestID,
|
||||
},
|
||||
}
|
||||
|
||||
payload, marshalErr := json.Marshal(body)
|
||||
if marshalErr != nil {
|
||||
status = http.StatusInternalServerError
|
||||
payload = fallbackErrorBody
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set(requestIDHeader, requestID)
|
||||
if status == http.StatusTooManyRequests && w.Header().Get("Retry-After") == "" {
|
||||
w.Header().Set("Retry-After", "1")
|
||||
}
|
||||
if status == http.StatusUnauthorized {
|
||||
challenge := `Bearer realm="messenger"`
|
||||
if r.URL.Path == "/api/v1/auth/sessions" {
|
||||
challenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", challenge)
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
|
||||
if _, err := w.Write(payload); err != nil && log != nil {
|
||||
log.WarnContext(ctx, "response write failed", slog.String("error", err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
func codeForStatus(status int) oas.ErrorErrorCode {
|
||||
switch status {
|
||||
case http.StatusBadRequest, http.StatusMethodNotAllowed:
|
||||
return oas.ErrorErrorCodeInvalidRequest
|
||||
case http.StatusUnauthorized:
|
||||
return oas.ErrorErrorCodeUnauthorized
|
||||
case http.StatusNotFound:
|
||||
return oas.ErrorErrorCodeNotFound
|
||||
case http.StatusConflict:
|
||||
return oas.ErrorErrorCodeConflict
|
||||
case http.StatusRequestEntityTooLarge:
|
||||
return oas.ErrorErrorCodePayloadTooLarge
|
||||
case http.StatusUnsupportedMediaType:
|
||||
return oas.ErrorErrorCodeUnsupportedMediaType
|
||||
case http.StatusTooManyRequests:
|
||||
return oas.ErrorErrorCodeRateLimited
|
||||
case http.StatusServiceUnavailable:
|
||||
return oas.ErrorErrorCodeUnavailable
|
||||
default:
|
||||
return oas.ErrorErrorCodeInternalError
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
func TestStatusForErrorDoesNotTurnDatabaseOutageInto401(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := &ogenerrors.SecurityError{
|
||||
Security: "BearerAuth",
|
||||
Err: fmt.Errorf("%w: %w", domain.ErrUnavailable, errors.New("57P03")),
|
||||
}
|
||||
if got := statusForError(err); got != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusForErrorKeepsMissingCredentials401(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := &ogenerrors.SecurityError{
|
||||
Security: "BearerAuth",
|
||||
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
||||
}
|
||||
if got := statusForError(err); got != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401", got)
|
||||
}
|
||||
if got := statusForError(&ogenerrors.SecurityError{Err: domain.ErrUnauthenticated}); got != http.StatusUnauthorized {
|
||||
t.Fatalf("domain unauthenticated status = %d, want 401", got)
|
||||
}
|
||||
if got := statusForError(errors.New("unexpected")); got != http.StatusInternalServerError {
|
||||
t.Fatalf("unknown error status = %d, want 500", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
// SessionResolver is implemented by session.Service. Only token resolution is
|
||||
// needed here; the generated security handler keeps its own interface.
|
||||
type SessionResolver interface {
|
||||
Resolve(ctx context.Context, token string) (domain.User, error)
|
||||
}
|
||||
|
||||
// Extensions implements the optional presigned-upload endpoints. They are
|
||||
// mounted outside the ogen server so the mandatory OpenAPI contract remains
|
||||
// untouched.
|
||||
type Extensions struct {
|
||||
attachments AttachmentService
|
||||
sessions SessionResolver
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewExtensions(
|
||||
attachments AttachmentService,
|
||||
sessions SessionResolver,
|
||||
log *slog.Logger,
|
||||
) *Extensions {
|
||||
return &Extensions{attachments: attachments, sessions: sessions, log: log}
|
||||
}
|
||||
|
||||
func (e *Extensions) Presign() http.Handler {
|
||||
return e.route(http.MethodPost, "presign", e.presign)
|
||||
}
|
||||
|
||||
func (e *Extensions) Complete() http.Handler {
|
||||
return e.route(http.MethodPost, "complete", e.complete)
|
||||
}
|
||||
|
||||
type extensionHandler func(http.ResponseWriter, *http.Request, uuid.UUID) error
|
||||
|
||||
func (e *Extensions) route(method, operation string, handler extensionHandler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
started := time.Now()
|
||||
writer := &statusWriter{ResponseWriter: w}
|
||||
|
||||
if r.Method != method {
|
||||
writer.Header().Set("Allow", method)
|
||||
writeError(r.Context(), e.log, writer, r, http.StatusMethodNotAllowed)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := e.authenticate(r)
|
||||
if err != nil {
|
||||
e.fail(writer, r, err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err = handler(writer, r, userID)
|
||||
if err != nil {
|
||||
e.fail(writer, r, err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if e.log != nil {
|
||||
e.log.InfoContext(r.Context(), "extension request handled",
|
||||
slog.String("request_id", requestIDFromContext(r.Context())),
|
||||
slog.String("operation", operation),
|
||||
slog.String("method", r.Method),
|
||||
slog.Int("status", writer.statusCode()),
|
||||
slog.Duration("duration", time.Since(started)),
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Extensions) authenticate(r *http.Request) (uuid.UUID, error) {
|
||||
header := r.Header.Get("Authorization")
|
||||
const prefix = "Bearer "
|
||||
|
||||
if !strings.HasPrefix(header, prefix) {
|
||||
return uuid.Nil, fmt.Errorf("%w: bearer token is required", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
token := strings.TrimSpace(strings.TrimPrefix(header, prefix))
|
||||
if token == "" {
|
||||
return uuid.Nil, fmt.Errorf("%w: bearer token is empty", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
user, err := e.sessions.Resolve(r.Context(), token)
|
||||
if err != nil {
|
||||
// session.Resolve already distinguishes an invalid session (401) from a
|
||||
// database outage (503); do not collapse both into 401 here.
|
||||
return uuid.Nil, err
|
||||
}
|
||||
|
||||
return user.ID, nil
|
||||
}
|
||||
|
||||
func (e *Extensions) presign(w http.ResponseWriter, r *http.Request, userID uuid.UUID) error {
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: chat_id is not a UUID", domain.ErrValidation)
|
||||
}
|
||||
|
||||
var request struct {
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
result, err := e.attachments.Presign(r.Context(), domain.PresignRequest{
|
||||
ChatID: chatID,
|
||||
OwnerID: userID,
|
||||
Filename: request.Filename,
|
||||
ContentType: request.ContentType,
|
||||
SizeBytes: request.SizeBytes,
|
||||
SHA256: request.SHA256,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return writeJSON(w, http.StatusCreated, struct {
|
||||
AttachmentID string `json:"attachment_id"`
|
||||
Method string `json:"method"`
|
||||
UploadURL string `json:"upload_url"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
SHA256 string `json:"sha256"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
}{
|
||||
AttachmentID: result.AttachmentID.String(),
|
||||
Method: http.MethodPut,
|
||||
UploadURL: result.UploadURL,
|
||||
ExpiresAt: result.ExpiresAt.UTC(),
|
||||
SHA256: result.SHA256,
|
||||
SizeBytes: result.SizeBytes,
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Extensions) complete(w http.ResponseWriter, r *http.Request, userID uuid.UUID) error {
|
||||
id, err := uuid.Parse(r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: attachment_id is not a UUID", domain.ErrValidation)
|
||||
}
|
||||
|
||||
var request struct {
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
attachment, err := e.attachments.Complete(r.Context(), userID, id, request.SHA256)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return writeJSON(w, http.StatusAccepted, attachmentResponse(attachment))
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, target any) error {
|
||||
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return fmt.Errorf("%w: Content-Type must be application/json", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return fmt.Errorf("%w: decode JSON: %w", domain.ErrValidation, err)
|
||||
}
|
||||
|
||||
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
return fmt.Errorf("%w: trailing JSON data", domain.ErrValidation)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *Extensions) fail(w http.ResponseWriter, r *http.Request, err error) {
|
||||
status := statusForDomainError(err)
|
||||
if status == http.StatusInternalServerError && e.log != nil {
|
||||
e.log.ErrorContext(r.Context(), "extension request failed",
|
||||
slog.String("request_id", requestIDFromContext(r.Context())),
|
||||
slog.String("method", r.Method),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
}
|
||||
|
||||
writeError(r.Context(), e.log, w, r, status)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, payload any) error {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
if err := json.NewEncoder(w).Encode(payload); err != nil {
|
||||
return fmt.Errorf("write JSON response: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(status int) {
|
||||
if w.status == 0 {
|
||||
w.status = status
|
||||
}
|
||||
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Write(body []byte) (int, error) {
|
||||
if w.status == 0 {
|
||||
w.status = http.StatusOK
|
||||
}
|
||||
|
||||
return w.ResponseWriter.Write(body)
|
||||
}
|
||||
|
||||
func (w *statusWriter) statusCode() int {
|
||||
if w.status == 0 {
|
||||
return http.StatusOK
|
||||
}
|
||||
|
||||
return w.status
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type resolverFunc func(ctx context.Context, token string) (domain.User, error)
|
||||
|
||||
func (f resolverFunc) Resolve(ctx context.Context, token string) (domain.User, error) {
|
||||
return f(ctx, token)
|
||||
}
|
||||
|
||||
func TestExtensionPreservesDependencyErrors(t *testing.T) {
|
||||
extensions := NewExtensions(nil, resolverFunc(func(context.Context, string) (domain.User, error) {
|
||||
return domain.User{}, domain.ErrUnavailable
|
||||
}), nil)
|
||||
|
||||
request := httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments/presign", nil,
|
||||
)
|
||||
request.Header.Set("Authorization", "Bearer token")
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
extensions.Presign().ServeHTTP(recorder, request)
|
||||
|
||||
require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
|
||||
}
|
||||
|
||||
func TestExtensionInvalidSessionIsUnauthorized(t *testing.T) {
|
||||
extensions := NewExtensions(nil, resolverFunc(func(context.Context, string) (domain.User, error) {
|
||||
return domain.User{}, domain.ErrUnauthenticated
|
||||
}), nil)
|
||||
|
||||
request := httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments/presign", nil,
|
||||
)
|
||||
request.Header.Set("Authorization", "Bearer token")
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
extensions.Presign().ServeHTTP(recorder, request)
|
||||
|
||||
require.Equal(t, http.StatusUnauthorized, recorder.Code)
|
||||
}
|
||||
|
||||
func TestExtensionWrongMethodIsNotAllowed(t *testing.T) {
|
||||
extensions := NewExtensions(nil, nil, nil)
|
||||
|
||||
request := httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodGet, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments/presign", nil,
|
||||
)
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
extensions.Presign().ServeHTTP(recorder, request)
|
||||
|
||||
require.Equal(t, http.StatusMethodNotAllowed, recorder.Code)
|
||||
require.Equal(t, http.MethodPost, recorder.Header().Get("Allow"))
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
attachmentService "mtusi-messenger/internal/service/attachment"
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
type UserService interface {
|
||||
Register(ctx context.Context, draft domain.UserDraft) (domain.User, error)
|
||||
GetByID(ctx context.Context, id uuid.UUID) (domain.User, error)
|
||||
}
|
||||
|
||||
type ChatService interface {
|
||||
Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)
|
||||
Get(ctx context.Context, callerID, chatID uuid.UUID) (domain.Chat, error)
|
||||
List(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error)
|
||||
}
|
||||
|
||||
type MessageService interface {
|
||||
Send(ctx context.Context, draft domain.MessageDraft) (domain.Message, error)
|
||||
History(
|
||||
ctx context.Context,
|
||||
callerID, chatID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Message], error)
|
||||
}
|
||||
|
||||
type HealthChecker interface {
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
type SessionService interface {
|
||||
Create(ctx context.Context, user domain.User) (domain.Session, error)
|
||||
Revoke(ctx context.Context, userID uuid.UUID, token string) error
|
||||
}
|
||||
|
||||
type AttachmentService interface {
|
||||
Upload(ctx context.Context, input attachmentService.UploadInput) (domain.Attachment, error)
|
||||
Get(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, error)
|
||||
OpenVariant(
|
||||
ctx context.Context,
|
||||
callerID, id uuid.UUID,
|
||||
name domain.VariantName,
|
||||
) (domain.Attachment, domain.Variant, io.ReadCloser, error)
|
||||
Presign(ctx context.Context, request domain.PresignRequest) (domain.PresignResult, error)
|
||||
Complete(ctx context.Context, ownerID, id uuid.UUID, sha256 string) (domain.Attachment, error)
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
oas.UnimplementedHandler
|
||||
|
||||
users UserService
|
||||
chats ChatService
|
||||
messages MessageService
|
||||
attachments AttachmentService
|
||||
health HealthChecker
|
||||
sessions SessionService
|
||||
}
|
||||
|
||||
var noCursor *domain.Cursor
|
||||
|
||||
func NewHandler(
|
||||
users UserService,
|
||||
chats ChatService,
|
||||
messages MessageService,
|
||||
attachments AttachmentService,
|
||||
health HealthChecker,
|
||||
sessions SessionService,
|
||||
) *Handler {
|
||||
return &Handler{
|
||||
users: users,
|
||||
chats: chats,
|
||||
messages: messages,
|
||||
attachments: attachments,
|
||||
health: health,
|
||||
sessions: sessions,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) CreateSession(ctx context.Context) (oas.CreateSessionRes, error) {
|
||||
user, ok := ctx.Value(credentialsKey{}).(domain.User)
|
||||
if !ok {
|
||||
return nil, domain.ErrUnauthenticated
|
||||
}
|
||||
|
||||
created, err := h.sessions.Create(ctx, user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.SessionHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: oas.Session{
|
||||
Token: created.Token, TokenType: "Bearer", ExpiresAt: created.ExpiresAt, User: userResponse(created.User),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) RevokeSession(ctx context.Context) (oas.RevokeSessionRes, error) {
|
||||
token, ok := ctx.Value(tokenKey{}).(string)
|
||||
if !ok {
|
||||
return nil, domain.ErrUnauthenticated
|
||||
}
|
||||
if err := h.sessions.Revoke(ctx, caller(ctx), token); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &oas.RevokeSessionNoContent{XRequestID: oas.NewOptString(requestIDFromContext(ctx))}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) Liveness(ctx context.Context) (oas.LivenessRes, error) {
|
||||
return &oas.HealthHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: oas.Health{Status: oas.HealthStatusOk},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) Readiness(ctx context.Context) (oas.ReadinessRes, error) {
|
||||
if h.health == nil || h.health.Ping(ctx) == nil {
|
||||
return &oas.HealthHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: oas.Health{Status: oas.HealthStatusOk},
|
||||
}, nil
|
||||
}
|
||||
|
||||
requestID := requestIDFromContext(ctx)
|
||||
|
||||
return &oas.ReadinessServiceUnavailable{
|
||||
XRequestID: oas.NewOptString(requestID),
|
||||
Response: oas.Error{Error: oas.ErrorError{
|
||||
Code: oas.ErrorErrorCodeUnavailable,
|
||||
Message: http.StatusText(http.StatusServiceUnavailable),
|
||||
RequestID: requestID,
|
||||
}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) RegisterUser(ctx context.Context, req *oas.CreateUser) (oas.RegisterUserRes, error) {
|
||||
user, err := h.users.Register(ctx, domain.UserDraft{
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
Password: req.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.UserHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: userResponse(user),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) CurrentUser(ctx context.Context) (oas.CurrentUserRes, error) {
|
||||
callerID := caller(ctx)
|
||||
|
||||
user, err := h.users.GetByID(ctx, callerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.UserHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: userResponse(user),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) CreateChat(ctx context.Context, req *oas.CreateChat) (oas.CreateChatRes, error) {
|
||||
callerID := caller(ctx)
|
||||
|
||||
chat, err := h.chats.Create(ctx, domain.ChatDraft{
|
||||
Title: req.Title,
|
||||
MemberIDs: req.MemberIds,
|
||||
CallerID: callerID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.ChatHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: chatResponse(chat),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) GetChat(ctx context.Context, params oas.GetChatParams) (oas.GetChatRes, error) {
|
||||
callerID := caller(ctx)
|
||||
|
||||
chat, err := h.chats.Get(ctx, callerID, params.ChatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.ChatHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: chatResponse(chat),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) ListChats(ctx context.Context, params oas.ListChatsParams) (oas.ListChatsRes, error) {
|
||||
callerID := caller(ctx)
|
||||
|
||||
after, err := parseCursor(params.Cursor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
page, err := h.chats.List(ctx, callerID, after, limitOrDefault(params.Limit))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items := make([]oas.Chat, 0, len(page.Items))
|
||||
for _, chat := range page.Items {
|
||||
items = append(items, chatResponse(chat))
|
||||
}
|
||||
|
||||
return &oas.ChatPageHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: oas.ChatPage{
|
||||
Items: items,
|
||||
NextCursor: encodeCursor(page.Next),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) CreateMessage(
|
||||
ctx context.Context,
|
||||
req *oas.CreateMessage,
|
||||
params oas.CreateMessageParams,
|
||||
) (oas.CreateMessageRes, error) {
|
||||
callerID := caller(ctx)
|
||||
|
||||
fingerprint, err := messageFingerprint(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
message, err := h.messages.Send(ctx, domain.MessageDraft{
|
||||
ChatID: params.ChatID,
|
||||
SenderID: callerID,
|
||||
Text: req.Text,
|
||||
AttachmentIDs: req.AttachmentIds,
|
||||
Idempotency: domain.MessageIdempotency{
|
||||
Key: params.IdempotencyKey,
|
||||
RequestHash: fingerprint,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.MessageHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: messageResponse(message),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// messageFingerprint canonicalises the create-message payload so that JSON key
|
||||
// order cannot change the fingerprint, while a different payload (including a
|
||||
// different attachment order) with the same Idempotency-Key can. Absent
|
||||
// attachment_ids and [] are equivalent, as required by the contract.
|
||||
func messageFingerprint(req *oas.CreateMessage) ([sha256.Size]byte, error) {
|
||||
ids := req.AttachmentIds
|
||||
if ids == nil {
|
||||
ids = []uuid.UUID{}
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []uuid.UUID `json:"attachment_ids"`
|
||||
}{Text: req.Text, AttachmentIDs: ids})
|
||||
if err != nil {
|
||||
return [sha256.Size]byte{}, fmt.Errorf("encode message payload: %w", err)
|
||||
}
|
||||
|
||||
return sha256.Sum256(payload), nil
|
||||
}
|
||||
|
||||
func (h *Handler) ListMessages(ctx context.Context, params oas.ListMessagesParams) (oas.ListMessagesRes, error) {
|
||||
callerID := caller(ctx)
|
||||
|
||||
after, err := parseCursor(params.Cursor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
page, err := h.messages.History(ctx, callerID, params.ChatID, after, limitOrDefault(params.Limit))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items := make([]oas.Message, 0, len(page.Items))
|
||||
for _, message := range page.Items {
|
||||
items = append(items, messageResponse(message))
|
||||
}
|
||||
|
||||
return &oas.MessagePageHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: oas.MessagePage{
|
||||
Items: items,
|
||||
NextCursor: encodeCursor(page.Next),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseCursor(raw oas.OptString) (*domain.Cursor, error) {
|
||||
encoded, ok := raw.Get()
|
||||
if !ok {
|
||||
return noCursor, nil
|
||||
}
|
||||
|
||||
cursor, err := decodeCursor(encoded)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &cursor, nil
|
||||
}
|
||||
|
||||
func encodeCursor(next *domain.Cursor) oas.NilString {
|
||||
var out oas.NilString
|
||||
|
||||
if next == nil {
|
||||
out.SetToNull()
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
out.SetTo(encodeCursorValue(*next))
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
type cursorWire struct {
|
||||
Scope uuid.UUID `json:"scope"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
}
|
||||
|
||||
func encodeCursorValue(cursor domain.Cursor) string {
|
||||
payload, err := json.Marshal(cursorWire{
|
||||
Scope: cursor.Scope,
|
||||
CreatedAt: cursor.CreatedAt.UTC(),
|
||||
ID: cursor.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return base64.RawURLEncoding.EncodeToString(payload)
|
||||
}
|
||||
|
||||
func decodeCursor(encoded string) (domain.Cursor, error) {
|
||||
payload, err := base64.RawURLEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return domain.Cursor{}, fmt.Errorf("decode cursor: %w", domain.ErrInvalidCursor)
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(payload))
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
var wire cursorWire
|
||||
if err := decoder.Decode(&wire); err != nil {
|
||||
return domain.Cursor{}, fmt.Errorf("parse cursor: %w", domain.ErrInvalidCursor)
|
||||
}
|
||||
|
||||
if wire.ID == uuid.Nil {
|
||||
return domain.Cursor{}, fmt.Errorf("cursor id is empty: %w", domain.ErrInvalidCursor)
|
||||
}
|
||||
|
||||
return domain.Cursor{
|
||||
Scope: wire.Scope,
|
||||
CreatedAt: wire.CreatedAt.UTC(),
|
||||
ID: wire.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func limitOrDefault(limit oas.OptInt) int {
|
||||
if value, ok := limit.Get(); ok {
|
||||
return value
|
||||
}
|
||||
|
||||
return domain.DefaultPageLimit
|
||||
}
|
||||
|
||||
func userResponse(user domain.User) oas.User {
|
||||
return oas.User{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
CreatedAt: user.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func chatResponse(chat domain.Chat) oas.Chat {
|
||||
return oas.Chat{
|
||||
ID: chat.ID,
|
||||
Title: chat.Title,
|
||||
MemberIds: chat.MemberIDs,
|
||||
CreatedAt: chat.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func messageResponse(message domain.Message) oas.Message {
|
||||
ids := make([]uuid.UUID, 0, len(message.AttachmentIDs))
|
||||
ids = append(ids, message.AttachmentIDs...)
|
||||
|
||||
return oas.Message{
|
||||
ID: message.ID,
|
||||
ChatID: message.ChatID,
|
||||
SenderID: message.SenderID,
|
||||
Text: message.Text,
|
||||
AttachmentIds: ids,
|
||||
CreatedAt: message.CreatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
func TestMessageFingerprintPreservesAttachmentOrder(t *testing.T) {
|
||||
first, second := uuid.New(), uuid.New()
|
||||
|
||||
forward, err := messageFingerprint(&oas.CreateMessage{
|
||||
Text: "x",
|
||||
AttachmentIds: []uuid.UUID{first, second},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
reverse, err := messageFingerprint(&oas.CreateMessage{
|
||||
Text: "x",
|
||||
AttachmentIds: []uuid.UUID{second, first},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NotEqual(t, forward, reverse,
|
||||
"reordered attachment_ids are a different payload and must not replay")
|
||||
}
|
||||
|
||||
func TestMessageFingerprintTreatsAbsentAndEmptyAsEqual(t *testing.T) {
|
||||
absent, err := messageFingerprint(&oas.CreateMessage{Text: "x"})
|
||||
require.NoError(t, err)
|
||||
|
||||
empty, err := messageFingerprint(&oas.CreateMessage{Text: "x", AttachmentIds: []uuid.UUID{}})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, absent, empty)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
const (
|
||||
instanceIDEnv = "INSTANCE_ID"
|
||||
instanceIDHeader = "X-Instance-Id"
|
||||
)
|
||||
|
||||
// InstanceID is the alias of this API process reported in the X-Instance-Id
|
||||
// response header (contract 1.3.0). INSTANCE_ID wins when set; otherwise the
|
||||
// hostname is used, which inside a container is the short container id the
|
||||
// stand maps back to the replica that served the request.
|
||||
func InstanceID() string {
|
||||
if id := os.Getenv(instanceIDEnv); id != "" {
|
||||
return id
|
||||
}
|
||||
|
||||
if host, err := os.Hostname(); err == nil && host != "" {
|
||||
return host
|
||||
}
|
||||
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// instanceIDWriter injects the header on the first write of the response, so
|
||||
// every API-generated response carries it — including errors produced by the
|
||||
// router, the security handler and the error handler rather than by a handler.
|
||||
// A value already set by the transport is never overwritten.
|
||||
type instanceIDWriter struct {
|
||||
http.ResponseWriter
|
||||
|
||||
id string
|
||||
sealed bool
|
||||
}
|
||||
|
||||
func (w *instanceIDWriter) inject() {
|
||||
if w.sealed {
|
||||
return
|
||||
}
|
||||
|
||||
w.sealed = true
|
||||
|
||||
if w.Header().Get(instanceIDHeader) == "" {
|
||||
w.Header().Set(instanceIDHeader, w.id)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *instanceIDWriter) WriteHeader(status int) {
|
||||
w.inject()
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *instanceIDWriter) Write(body []byte) (int, error) {
|
||||
w.inject()
|
||||
|
||||
return w.ResponseWriter.Write(body)
|
||||
}
|
||||
|
||||
func instanceIDMiddleware(id string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
next.ServeHTTP(&instanceIDWriter{ResponseWriter: w, id: id}, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestInstanceIDPrefersEnvironment(t *testing.T) {
|
||||
t.Setenv(instanceIDEnv, "api-7")
|
||||
|
||||
assert.Equal(t, "api-7", InstanceID())
|
||||
}
|
||||
|
||||
func TestInstanceIDFallsBackToHostname(t *testing.T) {
|
||||
t.Setenv(instanceIDEnv, "")
|
||||
|
||||
host, err := os.Hostname()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, host, InstanceID())
|
||||
}
|
||||
|
||||
func TestInstanceIDMiddleware(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
handler http.HandlerFunc
|
||||
wantID string
|
||||
wantCode int
|
||||
}{
|
||||
{
|
||||
name: "handler response",
|
||||
handler: func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusCreated) },
|
||||
wantID: "api-1",
|
||||
wantCode: http.StatusCreated,
|
||||
},
|
||||
{
|
||||
name: "response without explicit status",
|
||||
handler: func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) },
|
||||
wantID: "api-1",
|
||||
wantCode: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "error produced outside a handler",
|
||||
handler: func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusMethodNotAllowed) },
|
||||
wantID: "api-1",
|
||||
wantCode: http.StatusMethodNotAllowed,
|
||||
},
|
||||
{
|
||||
name: "header set by the transport is not overwritten",
|
||||
handler: func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set(instanceIDHeader, "explicit")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
},
|
||||
wantID: "explicit",
|
||||
wantCode: http.StatusOK,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
instanceIDMiddleware("api-1", test.handler).ServeHTTP(
|
||||
recorder,
|
||||
httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/v1/users/me", nil),
|
||||
)
|
||||
|
||||
assert.Equal(t, test.wantID, recorder.Header().Get(instanceIDHeader))
|
||||
assert.Equal(t, test.wantCode, recorder.Code)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/ogenregex"
|
||||
)
|
||||
|
||||
var regexMap = map[string]ogenregex.Regexp{
|
||||
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
|
||||
"^[a-f0-9]{64}$": ogenregex.MustCompile("^[a-f0-9]{64}$"),
|
||||
"^[a-z0-9_]{3,32}$": ogenregex.MustCompile("^[a-z0-9_]{3,32}$"),
|
||||
}
|
||||
|
||||
type (
|
||||
optionFunc[C any] func(*C)
|
||||
)
|
||||
|
||||
// ErrorHandler is error handler.
|
||||
type ErrorHandler = ogenerrors.ErrorHandler
|
||||
|
||||
type serverConfig struct {
|
||||
NotFound http.HandlerFunc
|
||||
MethodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)
|
||||
ErrorHandler ErrorHandler
|
||||
Prefix string
|
||||
Middleware Middleware
|
||||
MaxMultipartMemory int64
|
||||
}
|
||||
|
||||
// ServerOption is server config option.
|
||||
type ServerOption interface {
|
||||
applyServer(*serverConfig)
|
||||
}
|
||||
|
||||
var _ ServerOption = (optionFunc[serverConfig])(nil)
|
||||
|
||||
func (o optionFunc[C]) applyServer(c *C) {
|
||||
o(c)
|
||||
}
|
||||
|
||||
func newServerConfig(opts ...ServerOption) serverConfig {
|
||||
cfg := serverConfig{
|
||||
NotFound: http.NotFound,
|
||||
MethodNotAllowed: nil,
|
||||
ErrorHandler: ogenerrors.DefaultErrorHandler,
|
||||
Middleware: nil,
|
||||
MaxMultipartMemory: 32 << 20, // 32 MB
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt.applyServer(&cfg)
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
type baseServer struct {
|
||||
cfg serverConfig
|
||||
}
|
||||
|
||||
func (s baseServer) notFound(w http.ResponseWriter, r *http.Request) {
|
||||
s.cfg.NotFound(w, r)
|
||||
}
|
||||
|
||||
type notAllowedParams struct {
|
||||
allowedMethods string
|
||||
allowedHeaders map[string]string
|
||||
acceptPost string
|
||||
acceptPatch string
|
||||
}
|
||||
|
||||
func (s baseServer) notAllowed(w http.ResponseWriter, r *http.Request, params notAllowedParams) {
|
||||
h := w.Header()
|
||||
isOptions := r.Method == "OPTIONS"
|
||||
if isOptions {
|
||||
h.Set("Access-Control-Allow-Methods", params.allowedMethods)
|
||||
if params.allowedHeaders != nil {
|
||||
m := r.Header.Get("Access-Control-Request-Method")
|
||||
if m != "" {
|
||||
allowedHeaders, ok := params.allowedHeaders[strings.ToUpper(m)]
|
||||
if ok {
|
||||
h.Set("Access-Control-Allow-Headers", allowedHeaders)
|
||||
}
|
||||
}
|
||||
}
|
||||
if params.acceptPost != "" {
|
||||
h.Set("Accept-Post", params.acceptPost)
|
||||
}
|
||||
if params.acceptPatch != "" {
|
||||
h.Set("Accept-Patch", params.acceptPatch)
|
||||
}
|
||||
}
|
||||
if s.cfg.MethodNotAllowed != nil {
|
||||
s.cfg.MethodNotAllowed(w, r, params.allowedMethods)
|
||||
return
|
||||
}
|
||||
status := http.StatusNoContent
|
||||
if !isOptions {
|
||||
h.Set("Allow", params.allowedMethods)
|
||||
status = http.StatusMethodNotAllowed
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (cfg serverConfig) baseServer() (s baseServer, err error) {
|
||||
s = baseServer{cfg: cfg}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Option is config option.
|
||||
type Option interface {
|
||||
ServerOption
|
||||
}
|
||||
|
||||
// WithNotFound specifies Not Found handler to use.
|
||||
func WithNotFound(notFound http.HandlerFunc) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if notFound != nil {
|
||||
cfg.NotFound = notFound
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMethodNotAllowed specifies Method Not Allowed handler to use.
|
||||
func WithMethodNotAllowed(methodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if methodNotAllowed != nil {
|
||||
cfg.MethodNotAllowed = methodNotAllowed
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithErrorHandler specifies error handler to use.
|
||||
func WithErrorHandler(h ErrorHandler) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if h != nil {
|
||||
cfg.ErrorHandler = h
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithPathPrefix specifies server path prefix.
|
||||
func WithPathPrefix(prefix string) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
cfg.Prefix = prefix
|
||||
})
|
||||
}
|
||||
|
||||
// WithMiddleware specifies middlewares to use.
|
||||
func WithMiddleware(m ...Middleware) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
switch len(m) {
|
||||
case 0:
|
||||
cfg.Middleware = nil
|
||||
case 1:
|
||||
cfg.Middleware = m[0]
|
||||
default:
|
||||
cfg.Middleware = middleware.ChainMiddlewares(m...)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMaxMultipartMemory specifies limit of memory for storing file parts.
|
||||
// File parts which can't be stored in memory will be stored on disk in temporary files.
|
||||
func WithMaxMultipartMemory(max int64) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if max > 0 {
|
||||
cfg.MaxMultipartMemory = max
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// setDefaults set default value of fields.
|
||||
func (s *CreateMessage) setDefaults() {
|
||||
{
|
||||
var defaultVal0 []uuid.UUID
|
||||
s.AttachmentIds = defaultVal0
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,62 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
package oas
|
||||
|
||||
type CreateChatRes interface {
|
||||
createChatRes()
|
||||
}
|
||||
|
||||
type CreateMessageRes interface {
|
||||
createMessageRes()
|
||||
}
|
||||
|
||||
type CreateSessionRes interface {
|
||||
createSessionRes()
|
||||
}
|
||||
|
||||
type CurrentUserRes interface {
|
||||
currentUserRes()
|
||||
}
|
||||
|
||||
type DownloadAttachmentRes interface {
|
||||
downloadAttachmentRes()
|
||||
}
|
||||
|
||||
type GetAttachmentRes interface {
|
||||
getAttachmentRes()
|
||||
}
|
||||
|
||||
type GetChatRes interface {
|
||||
getChatRes()
|
||||
}
|
||||
|
||||
type ListChatsRes interface {
|
||||
listChatsRes()
|
||||
}
|
||||
|
||||
type ListMessagesRes interface {
|
||||
listMessagesRes()
|
||||
}
|
||||
|
||||
type LivenessRes interface {
|
||||
livenessRes()
|
||||
}
|
||||
|
||||
type ReadinessRes interface {
|
||||
readinessRes()
|
||||
}
|
||||
|
||||
type RegisterUserRes interface {
|
||||
registerUserRes()
|
||||
}
|
||||
|
||||
type RevokeSessionRes interface {
|
||||
revokeSessionRes()
|
||||
}
|
||||
|
||||
type UploadAttachmentReq interface {
|
||||
uploadAttachmentReq()
|
||||
}
|
||||
|
||||
type UploadAttachmentRes interface {
|
||||
uploadAttachmentRes()
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,10 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
)
|
||||
|
||||
// Middleware is middleware type.
|
||||
type Middleware = middleware.Middleware
|
||||
@@ -0,0 +1,23 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
// OperationName is the ogen operation name
|
||||
type OperationName = string
|
||||
|
||||
const (
|
||||
CreateChatOperation OperationName = "CreateChat"
|
||||
CreateMessageOperation OperationName = "CreateMessage"
|
||||
CreateSessionOperation OperationName = "CreateSession"
|
||||
CurrentUserOperation OperationName = "CurrentUser"
|
||||
DownloadAttachmentOperation OperationName = "DownloadAttachment"
|
||||
GetAttachmentOperation OperationName = "GetAttachment"
|
||||
GetChatOperation OperationName = "GetChat"
|
||||
ListChatsOperation OperationName = "ListChats"
|
||||
ListMessagesOperation OperationName = "ListMessages"
|
||||
LivenessOperation OperationName = "Liveness"
|
||||
ReadinessOperation OperationName = "Readiness"
|
||||
RegisterUserOperation OperationName = "RegisterUser"
|
||||
RevokeSessionOperation OperationName = "RevokeSession"
|
||||
UploadAttachmentOperation OperationName = "UploadAttachment"
|
||||
)
|
||||
@@ -0,0 +1,942 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/google/uuid"
|
||||
"github.com/ogen-go/ogen/conv"
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
// CreateMessageParams is parameters of createMessage operation.
|
||||
type CreateMessageParams struct {
|
||||
ChatID uuid.UUID
|
||||
// Обязателен с lab3. Область: пользователь + метод + путь +
|
||||
// ключ; хранить результат не менее 24 ч. Повтор того же JSON
|
||||
// возвращает исходный 201 и то же сообщение, другой JSON —
|
||||
// 409.
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
func unpackCreateMessageParams(packed middleware.Parameters) (params CreateMessageParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
}
|
||||
params.ChatID = packed[key].(uuid.UUID)
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "Idempotency-Key",
|
||||
In: "header",
|
||||
}
|
||||
params.IdempotencyKey = packed[key].(string)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeCreateMessageParams(args [1]string, argsEscaped bool, r *http.Request) (params CreateMessageParams, _ error) {
|
||||
h := uri.NewHeaderDecoder(r.Header)
|
||||
// Decode path: chat_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "chat_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.ChatID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode header: Idempotency-Key.
|
||||
if err := func() error {
|
||||
cfg := uri.HeaderParameterDecodingConfig{
|
||||
Name: "Idempotency-Key",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.HasParam(cfg); err == nil {
|
||||
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.IdempotencyKey = c
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 128,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[A-Za-z0-9._:-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(params.IdempotencyKey)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "Idempotency-Key",
|
||||
In: "header",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// DownloadAttachmentParams is parameters of downloadAttachment operation.
|
||||
type DownloadAttachmentParams struct {
|
||||
AttachmentID uuid.UUID
|
||||
Variant OptDownloadAttachmentVariant `json:",omitempty,omitzero"`
|
||||
}
|
||||
|
||||
func unpackDownloadAttachmentParams(packed middleware.Parameters) (params DownloadAttachmentParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "attachment_id",
|
||||
In: "path",
|
||||
}
|
||||
params.AttachmentID = packed[key].(uuid.UUID)
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "variant",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Variant = v.(OptDownloadAttachmentVariant)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeDownloadAttachmentParams(args [1]string, argsEscaped bool, r *http.Request) (params DownloadAttachmentParams, _ error) {
|
||||
q := uri.NewQueryDecoder(r.URL.Query())
|
||||
// Decode path: attachment_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "attachment_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.AttachmentID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "attachment_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Set default value for query: variant.
|
||||
{
|
||||
val := DownloadAttachmentVariant("original")
|
||||
params.Variant.SetTo(val)
|
||||
}
|
||||
// Decode query: variant.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "variant",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotVariantVal DownloadAttachmentVariant
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotVariantVal = DownloadAttachmentVariant(c)
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Variant.SetTo(paramsDotVariantVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Variant.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := value.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "variant",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetAttachmentParams is parameters of getAttachment operation.
|
||||
type GetAttachmentParams struct {
|
||||
AttachmentID uuid.UUID
|
||||
}
|
||||
|
||||
func unpackGetAttachmentParams(packed middleware.Parameters) (params GetAttachmentParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "attachment_id",
|
||||
In: "path",
|
||||
}
|
||||
params.AttachmentID = packed[key].(uuid.UUID)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeGetAttachmentParams(args [1]string, argsEscaped bool, r *http.Request) (params GetAttachmentParams, _ error) {
|
||||
// Decode path: attachment_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "attachment_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.AttachmentID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "attachment_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetChatParams is parameters of getChat operation.
|
||||
type GetChatParams struct {
|
||||
ChatID uuid.UUID
|
||||
}
|
||||
|
||||
func unpackGetChatParams(packed middleware.Parameters) (params GetChatParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
}
|
||||
params.ChatID = packed[key].(uuid.UUID)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeGetChatParams(args [1]string, argsEscaped bool, r *http.Request) (params GetChatParams, _ error) {
|
||||
// Decode path: chat_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "chat_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.ChatID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// ListChatsParams is parameters of listChats operation.
|
||||
type ListChatsParams struct {
|
||||
Limit OptInt `json:",omitempty,omitzero"`
|
||||
Cursor OptString `json:",omitempty,omitzero"`
|
||||
}
|
||||
|
||||
func unpackListChatsParams(packed middleware.Parameters) (params ListChatsParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Limit = v.(OptInt)
|
||||
}
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Cursor = v.(OptString)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeListChatsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListChatsParams, _ error) {
|
||||
q := uri.NewQueryDecoder(r.URL.Query())
|
||||
// Set default value for query: limit.
|
||||
{
|
||||
val := int(50)
|
||||
params.Limit.SetTo(val)
|
||||
}
|
||||
// Decode query: limit.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "limit",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotLimitVal int
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotLimitVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Limit.SetTo(paramsDotLimitVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Limit.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 1,
|
||||
MaxSet: true,
|
||||
Max: 100,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(value)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode query: cursor.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "cursor",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotCursorVal string
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotCursorVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Cursor.SetTo(paramsDotCursorVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Cursor.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 0,
|
||||
MaxLengthSet: false,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(value)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// ListMessagesParams is parameters of listMessages operation.
|
||||
type ListMessagesParams struct {
|
||||
ChatID uuid.UUID
|
||||
Limit OptInt `json:",omitempty,omitzero"`
|
||||
Cursor OptString `json:",omitempty,omitzero"`
|
||||
}
|
||||
|
||||
func unpackListMessagesParams(packed middleware.Parameters) (params ListMessagesParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
}
|
||||
params.ChatID = packed[key].(uuid.UUID)
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Limit = v.(OptInt)
|
||||
}
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Cursor = v.(OptString)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeListMessagesParams(args [1]string, argsEscaped bool, r *http.Request) (params ListMessagesParams, _ error) {
|
||||
q := uri.NewQueryDecoder(r.URL.Query())
|
||||
// Decode path: chat_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "chat_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.ChatID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Set default value for query: limit.
|
||||
{
|
||||
val := int(50)
|
||||
params.Limit.SetTo(val)
|
||||
}
|
||||
// Decode query: limit.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "limit",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotLimitVal int
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotLimitVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Limit.SetTo(paramsDotLimitVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Limit.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 1,
|
||||
MaxSet: true,
|
||||
Max: 100,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(value)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode query: cursor.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "cursor",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotCursorVal string
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotCursorVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Cursor.SetTo(paramsDotCursorVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Cursor.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 0,
|
||||
MaxLengthSet: false,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(value)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// UploadAttachmentParams is parameters of uploadAttachment operation.
|
||||
type UploadAttachmentParams struct {
|
||||
ChatID uuid.UUID
|
||||
Filename string
|
||||
}
|
||||
|
||||
func unpackUploadAttachmentParams(packed middleware.Parameters) (params UploadAttachmentParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
}
|
||||
params.ChatID = packed[key].(uuid.UUID)
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "filename",
|
||||
In: "query",
|
||||
}
|
||||
params.Filename = packed[key].(string)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeUploadAttachmentParams(args [1]string, argsEscaped bool, r *http.Request) (params UploadAttachmentParams, _ error) {
|
||||
q := uri.NewQueryDecoder(r.URL.Query())
|
||||
// Decode path: chat_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "chat_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.ChatID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "chat_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode query: filename.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "filename",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.Filename = c
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 255,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(params.Filename)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "filename",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
func (s *Server) decodeCreateChatRequest(r *http.Request) (
|
||||
req *CreateChat,
|
||||
rawBody []byte,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
buf, err := io.ReadAll(r.Body)
|
||||
defer func() {
|
||||
_ = r.Body.Close()
|
||||
}()
|
||||
if err != nil {
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
|
||||
// Reset the body to allow for downstream reading.
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
|
||||
if len(buf) == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
rawBody = append(rawBody, buf...)
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request CreateChat
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, rawBody, close, nil
|
||||
default:
|
||||
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeCreateMessageRequest(r *http.Request) (
|
||||
req *CreateMessage,
|
||||
rawBody []byte,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
buf, err := io.ReadAll(r.Body)
|
||||
defer func() {
|
||||
_ = r.Body.Close()
|
||||
}()
|
||||
if err != nil {
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
|
||||
// Reset the body to allow for downstream reading.
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
|
||||
if len(buf) == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
rawBody = append(rawBody, buf...)
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request CreateMessage
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, rawBody, close, nil
|
||||
default:
|
||||
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeRegisterUserRequest(r *http.Request) (
|
||||
req *CreateUser,
|
||||
rawBody []byte,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
buf, err := io.ReadAll(r.Body)
|
||||
defer func() {
|
||||
_ = r.Body.Close()
|
||||
}()
|
||||
if err != nil {
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
|
||||
// Reset the body to allow for downstream reading.
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
|
||||
if len(buf) == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
rawBody = append(rawBody, buf...)
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request CreateUser
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, rawBody, close, nil
|
||||
default:
|
||||
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeUploadAttachmentRequest(r *http.Request) (
|
||||
req UploadAttachmentReq,
|
||||
rawBody []byte,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "image/jpeg":
|
||||
reader := r.Body
|
||||
request := UploadAttachmentReqImageJpeg{Data: reader}
|
||||
return &request, rawBody, close, nil
|
||||
case ct == "image/png":
|
||||
reader := r.Body
|
||||
request := UploadAttachmentReqImagePNG{Data: reader}
|
||||
return &request, rawBody, close, nil
|
||||
default:
|
||||
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,996 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
)
|
||||
|
||||
var (
|
||||
rn10AllowedHeaders = map[string]string{
|
||||
"GET": "Authorization",
|
||||
}
|
||||
rn11AllowedHeaders = map[string]string{
|
||||
"GET": "Authorization",
|
||||
}
|
||||
rn6AllowedHeaders = map[string]string{
|
||||
"POST": "Authorization",
|
||||
}
|
||||
rn17AllowedHeaders = map[string]string{
|
||||
"DELETE": "Authorization",
|
||||
}
|
||||
rn1AllowedHeaders = map[string]string{
|
||||
"GET": "Authorization",
|
||||
"POST": "Authorization,Content-Type",
|
||||
}
|
||||
rn3AllowedHeaders = map[string]string{
|
||||
"GET": "Authorization",
|
||||
}
|
||||
rn19AllowedHeaders = map[string]string{
|
||||
"POST": "Authorization,Content-Type",
|
||||
}
|
||||
rn4AllowedHeaders = map[string]string{
|
||||
"GET": "Authorization",
|
||||
"POST": "Authorization,Content-Type,Idempotency-Key",
|
||||
}
|
||||
rn16AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn7AllowedHeaders = map[string]string{
|
||||
"GET": "Authorization",
|
||||
}
|
||||
)
|
||||
|
||||
func (s *Server) cutPrefix(path string) (string, bool) {
|
||||
prefix := s.cfg.Prefix
|
||||
if prefix == "" {
|
||||
return path, true
|
||||
}
|
||||
if !strings.HasPrefix(path, prefix) {
|
||||
// Prefix doesn't match.
|
||||
return "", false
|
||||
}
|
||||
// Cut prefix from the path.
|
||||
return strings.TrimPrefix(path, prefix), true
|
||||
}
|
||||
|
||||
// ServeHTTP serves http request as defined by OpenAPI v3 specification,
|
||||
// calling handler that matches the path or returning not found error.
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
elem := r.URL.Path
|
||||
elemIsEscaped := false
|
||||
if rawPath := r.URL.RawPath; rawPath != "" {
|
||||
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
|
||||
elem = normalized
|
||||
elemIsEscaped = strings.ContainsRune(elem, '%')
|
||||
}
|
||||
}
|
||||
|
||||
elem, ok := s.cutPrefix(elem)
|
||||
if !ok || len(elem) == 0 {
|
||||
s.notFound(w, r)
|
||||
return
|
||||
}
|
||||
args := [1]string{}
|
||||
|
||||
// Static code generated router with unwrapped path search.
|
||||
switch {
|
||||
default:
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'a': // Prefix: "api/v1/"
|
||||
|
||||
if l := len("api/v1/"); len(elem) >= l && elem[0:l] == "api/v1/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'a': // Prefix: "a"
|
||||
|
||||
if l := len("a"); len(elem) >= l && elem[0:l] == "a" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 't': // Prefix: "ttachments/"
|
||||
|
||||
if l := len("ttachments/"); len(elem) >= l && elem[0:l] == "ttachments/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "attachment_id"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleGetAttachmentRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: rn10AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/content"
|
||||
|
||||
if l := len("/content"); len(elem) >= l && elem[0:l] == "/content" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleDownloadAttachmentRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: rn11AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "uth/sessions"
|
||||
|
||||
if l := len("uth/sessions"); len(elem) >= l && elem[0:l] == "uth/sessions" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleCreateSessionRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn6AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/current"
|
||||
|
||||
if l := len("/current"); len(elem) >= l && elem[0:l] == "/current" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "DELETE":
|
||||
s.handleRevokeSessionRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE",
|
||||
allowedHeaders: rn17AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'c': // Prefix: "chats"
|
||||
|
||||
if l := len("chats"); len(elem) >= l && elem[0:l] == "chats" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleListChatsRequest([0]string{}, elemIsEscaped, w, r)
|
||||
case "POST":
|
||||
s.handleCreateChatRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,POST",
|
||||
allowedHeaders: rn1AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "chat_id"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleGetChatRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: rn3AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'a': // Prefix: "attachments"
|
||||
|
||||
if l := len("attachments"); len(elem) >= l && elem[0:l] == "attachments" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleUploadAttachmentRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn19AllowedHeaders,
|
||||
acceptPost: "image/jpeg,image/png",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'm': // Prefix: "messages"
|
||||
|
||||
if l := len("messages"); len(elem) >= l && elem[0:l] == "messages" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleListMessagesRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
case "POST":
|
||||
s.handleCreateMessageRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,POST",
|
||||
allowedHeaders: rn4AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "users"
|
||||
|
||||
if l := len("users"); len(elem) >= l && elem[0:l] == "users" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleRegisterUserRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn16AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/me"
|
||||
|
||||
if l := len("/me"); len(elem) >= l && elem[0:l] == "/me" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleCurrentUserRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: rn7AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'h': // Prefix: "health/"
|
||||
|
||||
if l := len("health/"); len(elem) >= l && elem[0:l] == "health/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'l': // Prefix: "live"
|
||||
|
||||
if l := len("live"); len(elem) >= l && elem[0:l] == "live" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleLivenessRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: nil,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'r': // Prefix: "ready"
|
||||
|
||||
if l := len("ready"); len(elem) >= l && elem[0:l] == "ready" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleReadinessRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: nil,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
s.notFound(w, r)
|
||||
}
|
||||
|
||||
// Route is route object.
|
||||
type Route struct {
|
||||
name string
|
||||
summary string
|
||||
operationID string
|
||||
operationGroup string
|
||||
pathPattern string
|
||||
count int
|
||||
args [1]string
|
||||
}
|
||||
|
||||
// Name returns ogen operation name.
|
||||
//
|
||||
// It is guaranteed to be unique and not empty.
|
||||
func (r Route) Name() string {
|
||||
return r.name
|
||||
}
|
||||
|
||||
// Summary returns OpenAPI summary.
|
||||
func (r Route) Summary() string {
|
||||
return r.summary
|
||||
}
|
||||
|
||||
// OperationID returns OpenAPI operationId.
|
||||
func (r Route) OperationID() string {
|
||||
return r.operationID
|
||||
}
|
||||
|
||||
// OperationGroup returns the x-ogen-operation-group value.
|
||||
func (r Route) OperationGroup() string {
|
||||
return r.operationGroup
|
||||
}
|
||||
|
||||
// PathPattern returns OpenAPI path.
|
||||
func (r Route) PathPattern() string {
|
||||
return r.pathPattern
|
||||
}
|
||||
|
||||
// Args returns parsed arguments.
|
||||
func (r Route) Args() []string {
|
||||
return r.args[:r.count]
|
||||
}
|
||||
|
||||
// FindRoute finds Route for given method and path.
|
||||
//
|
||||
// Note: this method does not unescape path or handle reserved characters in path properly. Use FindPath instead.
|
||||
func (s *Server) FindRoute(method, path string) (Route, bool) {
|
||||
return s.FindPath(method, &url.URL{Path: path})
|
||||
}
|
||||
|
||||
// FindPath finds Route for given method and URL.
|
||||
func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
var (
|
||||
elem = u.Path
|
||||
args = r.args
|
||||
)
|
||||
if rawPath := u.RawPath; rawPath != "" {
|
||||
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
|
||||
elem = normalized
|
||||
}
|
||||
defer func() {
|
||||
for i, arg := range r.args[:r.count] {
|
||||
if unescaped, err := url.PathUnescape(arg); err == nil {
|
||||
r.args[i] = unescaped
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
elem, ok := s.cutPrefix(elem)
|
||||
if !ok {
|
||||
return r, false
|
||||
}
|
||||
|
||||
// Static code generated router with unwrapped path search.
|
||||
switch {
|
||||
default:
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'a': // Prefix: "api/v1/"
|
||||
|
||||
if l := len("api/v1/"); len(elem) >= l && elem[0:l] == "api/v1/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'a': // Prefix: "a"
|
||||
|
||||
if l := len("a"); len(elem) >= l && elem[0:l] == "a" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 't': // Prefix: "ttachments/"
|
||||
|
||||
if l := len("ttachments/"); len(elem) >= l && elem[0:l] == "ttachments/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "attachment_id"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = GetAttachmentOperation
|
||||
r.summary = "Метаданные вложения, доступ участникам чата"
|
||||
r.operationID = "getAttachment"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/attachments/{attachment_id}"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/content"
|
||||
|
||||
if l := len("/content"); len(elem) >= l && elem[0:l] == "/content" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = DownloadAttachmentOperation
|
||||
r.summary = "Скачать байты через авторизованный API"
|
||||
r.operationID = "downloadAttachment"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/attachments/{attachment_id}/content"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "uth/sessions"
|
||||
|
||||
if l := len("uth/sessions"); len(elem) >= l && elem[0:l] == "uth/sessions" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = CreateSessionOperation
|
||||
r.summary = "Вход: Basic username:password; выдаёт сессию"
|
||||
r.operationID = "createSession"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/auth/sessions"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/current"
|
||||
|
||||
if l := len("/current"); len(elem) >= l && elem[0:l] == "/current" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "DELETE":
|
||||
r.name = RevokeSessionOperation
|
||||
r.summary = "Отозвать текущую сессию"
|
||||
r.operationID = "revokeSession"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/auth/sessions/current"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'c': // Prefix: "chats"
|
||||
|
||||
if l := len("chats"); len(elem) >= l && elem[0:l] == "chats" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = ListChatsOperation
|
||||
r.summary = "Чаты текущего пользователя"
|
||||
r.operationID = "listChats"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
case "POST":
|
||||
r.name = CreateChatOperation
|
||||
r.summary = "Создать чат; вызывающий должен входить в member_ids"
|
||||
r.operationID = "createChat"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "chat_id"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = GetChatOperation
|
||||
r.summary = "Получить доступный чат"
|
||||
r.operationID = "getChat"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats/{chat_id}"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'a': // Prefix: "attachments"
|
||||
|
||||
if l := len("attachments"); len(elem) >= l && elem[0:l] == "attachments" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = UploadAttachmentOperation
|
||||
r.summary = "Принять один PNG/JPEG, до 10 MiB"
|
||||
r.operationID = "uploadAttachment"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats/{chat_id}/attachments"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'm': // Prefix: "messages"
|
||||
|
||||
if l := len("messages"); len(elem) >= l && elem[0:l] == "messages" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = ListMessagesOperation
|
||||
r.summary = "Сообщения по (created_at, id) по возрастанию"
|
||||
r.operationID = "listMessages"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats/{chat_id}/messages"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
case "POST":
|
||||
r.name = CreateMessageOperation
|
||||
r.summary = "Отправить сообщение"
|
||||
r.operationID = "createMessage"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/chats/{chat_id}/messages"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "users"
|
||||
|
||||
if l := len("users"); len(elem) >= l && elem[0:l] == "users" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = RegisterUserOperation
|
||||
r.summary = "Создать пользователя"
|
||||
r.operationID = "registerUser"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/users"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/me"
|
||||
|
||||
if l := len("/me"); len(elem) >= l && elem[0:l] == "/me" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = CurrentUserOperation
|
||||
r.summary = "Текущий пользователь"
|
||||
r.operationID = "currentUser"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/users/me"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'h': // Prefix: "health/"
|
||||
|
||||
if l := len("health/"); len(elem) >= l && elem[0:l] == "health/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'l': // Prefix: "live"
|
||||
|
||||
if l := len("live"); len(elem) >= l && elem[0:l] == "live" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = LivenessOperation
|
||||
r.summary = "Процесс жив"
|
||||
r.operationID = "liveness"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/health/live"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'r': // Prefix: "ready"
|
||||
|
||||
if l := len("ready"); len(elem) >= l && elem[0:l] == "ready" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = ReadinessOperation
|
||||
r.summary = "Готов принимать трафик"
|
||||
r.operationID = "readiness"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/health/ready"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return r, false
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,134 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
)
|
||||
|
||||
// SecurityHandler is handler for security parameters.
|
||||
type SecurityHandler interface {
|
||||
// HandleBasicAuth handles basicAuth security.
|
||||
HandleBasicAuth(ctx context.Context, operationName OperationName, t BasicAuth) (context.Context, error)
|
||||
// HandleBearerAuth handles bearerAuth security.
|
||||
HandleBearerAuth(ctx context.Context, operationName OperationName, t BearerAuth) (context.Context, error)
|
||||
}
|
||||
|
||||
func findAuthorization(h http.Header, prefix string) (string, bool) {
|
||||
v, ok := h["Authorization"]
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
for _, vv := range v {
|
||||
scheme, value, ok := strings.Cut(vv, " ")
|
||||
if !ok || !strings.EqualFold(scheme, prefix) {
|
||||
continue
|
||||
}
|
||||
return value, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// operationRolesBasicAuth is a private map storing roles per operation.
|
||||
var operationRolesBasicAuth = map[string][]string{
|
||||
CreateSessionOperation: []string{},
|
||||
}
|
||||
|
||||
// GetRolesForBasicAuth returns the required roles for the given operation.
|
||||
//
|
||||
// This is useful for authorization scenarios where you need to know which roles
|
||||
// are required for an operation.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// requiredRoles := GetRolesForBasicAuth(AddPetOperation)
|
||||
//
|
||||
// Returns nil if the operation has no role requirements or if the operation is unknown.
|
||||
func GetRolesForBasicAuth(operation string) []string {
|
||||
roles, ok := operationRolesBasicAuth[operation]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
// Return a copy to prevent external modification
|
||||
result := make([]string, len(roles))
|
||||
copy(result, roles)
|
||||
return result
|
||||
}
|
||||
|
||||
// operationRolesBearerAuth is a private map storing roles per operation.
|
||||
var operationRolesBearerAuth = map[string][]string{
|
||||
CreateChatOperation: []string{},
|
||||
CreateMessageOperation: []string{},
|
||||
CurrentUserOperation: []string{},
|
||||
DownloadAttachmentOperation: []string{},
|
||||
GetAttachmentOperation: []string{},
|
||||
GetChatOperation: []string{},
|
||||
ListChatsOperation: []string{},
|
||||
ListMessagesOperation: []string{},
|
||||
RevokeSessionOperation: []string{},
|
||||
UploadAttachmentOperation: []string{},
|
||||
}
|
||||
|
||||
// GetRolesForBearerAuth returns the required roles for the given operation.
|
||||
//
|
||||
// This is useful for authorization scenarios where you need to know which roles
|
||||
// are required for an operation.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// requiredRoles := GetRolesForBearerAuth(AddPetOperation)
|
||||
//
|
||||
// Returns nil if the operation has no role requirements or if the operation is unknown.
|
||||
func GetRolesForBearerAuth(operation string) []string {
|
||||
roles, ok := operationRolesBearerAuth[operation]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
// Return a copy to prevent external modification
|
||||
result := make([]string, len(roles))
|
||||
copy(result, roles)
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *Server) securityBasicAuth(ctx context.Context, operationName OperationName, req *http.Request) (context.Context, bool, error) {
|
||||
var t BasicAuth
|
||||
if _, ok := findAuthorization(req.Header, "Basic"); !ok {
|
||||
return ctx, false, nil
|
||||
}
|
||||
username, password, ok := req.BasicAuth()
|
||||
if !ok {
|
||||
return nil, false, errors.New("invalid basic auth")
|
||||
}
|
||||
t.Username = username
|
||||
t.Password = password
|
||||
t.Roles = operationRolesBasicAuth[operationName]
|
||||
rctx, err := s.sec.HandleBasicAuth(ctx, operationName, t)
|
||||
if errors.Is(err, ogenerrors.ErrSkipServerSecurity) {
|
||||
return nil, false, nil
|
||||
} else if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return rctx, true, err
|
||||
}
|
||||
|
||||
func (s *Server) securityBearerAuth(ctx context.Context, operationName OperationName, req *http.Request) (context.Context, bool, error) {
|
||||
var t BearerAuth
|
||||
token, ok := findAuthorization(req.Header, "Bearer")
|
||||
if !ok {
|
||||
return ctx, false, nil
|
||||
}
|
||||
t.Token = token
|
||||
t.Roles = operationRolesBearerAuth[operationName]
|
||||
rctx, err := s.sec.HandleBearerAuth(ctx, operationName, t)
|
||||
if errors.Is(err, ogenerrors.ErrSkipServerSecurity) {
|
||||
return nil, false, nil
|
||||
} else if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return rctx, true, err
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// Handler handles operations described by OpenAPI v3 specification.
|
||||
type Handler interface {
|
||||
// CreateChat implements createChat operation.
|
||||
//
|
||||
// Создать чат; вызывающий должен входить в member_ids.
|
||||
//
|
||||
// POST /api/v1/chats
|
||||
CreateChat(ctx context.Context, req *CreateChat) (CreateChatRes, error)
|
||||
// CreateMessage implements createMessage operation.
|
||||
//
|
||||
// Отправить сообщение.
|
||||
//
|
||||
// POST /api/v1/chats/{chat_id}/messages
|
||||
CreateMessage(ctx context.Context, req *CreateMessage, params CreateMessageParams) (CreateMessageRes, error)
|
||||
// CreateSession implements createSession operation.
|
||||
//
|
||||
// Вход: Basic username:password; выдаёт сессию.
|
||||
//
|
||||
// POST /api/v1/auth/sessions
|
||||
CreateSession(ctx context.Context) (CreateSessionRes, error)
|
||||
// CurrentUser implements currentUser operation.
|
||||
//
|
||||
// Текущий пользователь.
|
||||
//
|
||||
// GET /api/v1/users/me
|
||||
CurrentUser(ctx context.Context) (CurrentUserRes, error)
|
||||
// DownloadAttachment implements downloadAttachment operation.
|
||||
//
|
||||
// Скачать байты через авторизованный API.
|
||||
//
|
||||
// GET /api/v1/attachments/{attachment_id}/content
|
||||
DownloadAttachment(ctx context.Context, params DownloadAttachmentParams) (DownloadAttachmentRes, error)
|
||||
// GetAttachment implements getAttachment operation.
|
||||
//
|
||||
// Метаданные вложения, доступ участникам чата.
|
||||
//
|
||||
// GET /api/v1/attachments/{attachment_id}
|
||||
GetAttachment(ctx context.Context, params GetAttachmentParams) (GetAttachmentRes, error)
|
||||
// GetChat implements getChat operation.
|
||||
//
|
||||
// Получить доступный чат.
|
||||
//
|
||||
// GET /api/v1/chats/{chat_id}
|
||||
GetChat(ctx context.Context, params GetChatParams) (GetChatRes, error)
|
||||
// ListChats implements listChats operation.
|
||||
//
|
||||
// Чаты текущего пользователя.
|
||||
//
|
||||
// GET /api/v1/chats
|
||||
ListChats(ctx context.Context, params ListChatsParams) (ListChatsRes, error)
|
||||
// ListMessages implements listMessages operation.
|
||||
//
|
||||
// Сообщения по (created_at, id) по возрастанию.
|
||||
//
|
||||
// GET /api/v1/chats/{chat_id}/messages
|
||||
ListMessages(ctx context.Context, params ListMessagesParams) (ListMessagesRes, error)
|
||||
// Liveness implements liveness operation.
|
||||
//
|
||||
// Процесс жив.
|
||||
//
|
||||
// GET /health/live
|
||||
Liveness(ctx context.Context) (LivenessRes, error)
|
||||
// Readiness implements readiness operation.
|
||||
//
|
||||
// Готов принимать трафик.
|
||||
//
|
||||
// GET /health/ready
|
||||
Readiness(ctx context.Context) (ReadinessRes, error)
|
||||
// RegisterUser implements registerUser operation.
|
||||
//
|
||||
// Создать пользователя.
|
||||
//
|
||||
// POST /api/v1/users
|
||||
RegisterUser(ctx context.Context, req *CreateUser) (RegisterUserRes, error)
|
||||
// RevokeSession implements revokeSession operation.
|
||||
//
|
||||
// Отозвать текущую сессию.
|
||||
//
|
||||
// DELETE /api/v1/auth/sessions/current
|
||||
RevokeSession(ctx context.Context) (RevokeSessionRes, error)
|
||||
// UploadAttachment implements uploadAttachment operation.
|
||||
//
|
||||
// Принять один PNG/JPEG, до 10 MiB.
|
||||
//
|
||||
// POST /api/v1/chats/{chat_id}/attachments
|
||||
UploadAttachment(ctx context.Context, req UploadAttachmentReq, params UploadAttachmentParams) (UploadAttachmentRes, error)
|
||||
}
|
||||
|
||||
// Server implements http server based on OpenAPI v3 specification and
|
||||
// calls Handler to handle requests.
|
||||
type Server struct {
|
||||
h Handler
|
||||
sec SecurityHandler
|
||||
baseServer
|
||||
}
|
||||
|
||||
// NewServer creates new Server.
|
||||
func NewServer(h Handler, sec SecurityHandler, opts ...ServerOption) (*Server, error) {
|
||||
s, err := newServerConfig(opts...).baseServer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Server{
|
||||
h: h,
|
||||
sec: sec,
|
||||
baseServer: s,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package oas
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
)
|
||||
|
||||
// UnimplementedHandler is no-op Handler which returns http.ErrNotImplemented.
|
||||
type UnimplementedHandler struct{}
|
||||
|
||||
var _ Handler = UnimplementedHandler{}
|
||||
|
||||
// CreateChat implements createChat operation.
|
||||
//
|
||||
// Создать чат; вызывающий должен входить в member_ids.
|
||||
//
|
||||
// POST /api/v1/chats
|
||||
func (UnimplementedHandler) CreateChat(ctx context.Context, req *CreateChat) (r CreateChatRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CreateMessage implements createMessage operation.
|
||||
//
|
||||
// Отправить сообщение.
|
||||
//
|
||||
// POST /api/v1/chats/{chat_id}/messages
|
||||
func (UnimplementedHandler) CreateMessage(ctx context.Context, req *CreateMessage, params CreateMessageParams) (r CreateMessageRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CreateSession implements createSession operation.
|
||||
//
|
||||
// Вход: Basic username:password; выдаёт сессию.
|
||||
//
|
||||
// POST /api/v1/auth/sessions
|
||||
func (UnimplementedHandler) CreateSession(ctx context.Context) (r CreateSessionRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CurrentUser implements currentUser operation.
|
||||
//
|
||||
// Текущий пользователь.
|
||||
//
|
||||
// GET /api/v1/users/me
|
||||
func (UnimplementedHandler) CurrentUser(ctx context.Context) (r CurrentUserRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// DownloadAttachment implements downloadAttachment operation.
|
||||
//
|
||||
// Скачать байты через авторизованный API.
|
||||
//
|
||||
// GET /api/v1/attachments/{attachment_id}/content
|
||||
func (UnimplementedHandler) DownloadAttachment(ctx context.Context, params DownloadAttachmentParams) (r DownloadAttachmentRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetAttachment implements getAttachment operation.
|
||||
//
|
||||
// Метаданные вложения, доступ участникам чата.
|
||||
//
|
||||
// GET /api/v1/attachments/{attachment_id}
|
||||
func (UnimplementedHandler) GetAttachment(ctx context.Context, params GetAttachmentParams) (r GetAttachmentRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetChat implements getChat operation.
|
||||
//
|
||||
// Получить доступный чат.
|
||||
//
|
||||
// GET /api/v1/chats/{chat_id}
|
||||
func (UnimplementedHandler) GetChat(ctx context.Context, params GetChatParams) (r GetChatRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListChats implements listChats operation.
|
||||
//
|
||||
// Чаты текущего пользователя.
|
||||
//
|
||||
// GET /api/v1/chats
|
||||
func (UnimplementedHandler) ListChats(ctx context.Context, params ListChatsParams) (r ListChatsRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListMessages implements listMessages operation.
|
||||
//
|
||||
// Сообщения по (created_at, id) по возрастанию.
|
||||
//
|
||||
// GET /api/v1/chats/{chat_id}/messages
|
||||
func (UnimplementedHandler) ListMessages(ctx context.Context, params ListMessagesParams) (r ListMessagesRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// Liveness implements liveness operation.
|
||||
//
|
||||
// Процесс жив.
|
||||
//
|
||||
// GET /health/live
|
||||
func (UnimplementedHandler) Liveness(ctx context.Context) (r LivenessRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// Readiness implements readiness operation.
|
||||
//
|
||||
// Готов принимать трафик.
|
||||
//
|
||||
// GET /health/ready
|
||||
func (UnimplementedHandler) Readiness(ctx context.Context) (r ReadinessRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// RegisterUser implements registerUser operation.
|
||||
//
|
||||
// Создать пользователя.
|
||||
//
|
||||
// POST /api/v1/users
|
||||
func (UnimplementedHandler) RegisterUser(ctx context.Context, req *CreateUser) (r RegisterUserRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// RevokeSession implements revokeSession operation.
|
||||
//
|
||||
// Отозвать текущую сессию.
|
||||
//
|
||||
// DELETE /api/v1/auth/sessions/current
|
||||
func (UnimplementedHandler) RevokeSession(ctx context.Context) (r RevokeSessionRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// UploadAttachment implements uploadAttachment operation.
|
||||
//
|
||||
// Принять один PNG/JPEG, до 10 MiB.
|
||||
//
|
||||
// POST /api/v1/chats/{chat_id}/attachments
|
||||
func (UnimplementedHandler) UploadAttachment(ctx context.Context, req UploadAttachmentReq, params UploadAttachmentParams) (r UploadAttachmentRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,145 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/openapi"
|
||||
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
func loggingMiddleware(log *slog.Logger) oas.Middleware {
|
||||
return func(req middleware.Request, next middleware.Next) (middleware.Response, error) {
|
||||
started := time.Now()
|
||||
|
||||
base := []any{
|
||||
slog.String("request_id", requestIDFromContext(req.Context)),
|
||||
slog.String("operation", req.OperationID),
|
||||
slog.String("method", req.Raw.Method),
|
||||
slog.String("path", req.Raw.URL.Path),
|
||||
}
|
||||
|
||||
accepted := make([]any, 0, len(base)+6)
|
||||
accepted = append(accepted, base...)
|
||||
accepted = append(accepted,
|
||||
slog.String("query", req.Raw.URL.RawQuery),
|
||||
slog.String("remote_addr", req.Raw.RemoteAddr),
|
||||
slog.String("user_agent", req.Raw.UserAgent()),
|
||||
slog.Int64("content_length", req.Raw.ContentLength),
|
||||
slog.Any("params", loggedParams(req.Params)),
|
||||
payloadAttr(req.RawBody),
|
||||
)
|
||||
|
||||
log.InfoContext(req.Context, "request accepted", accepted...)
|
||||
|
||||
resp, err := next(req)
|
||||
|
||||
handled := make([]any, 0, len(base)+4)
|
||||
handled = append(handled, base...)
|
||||
handled = append(handled, slog.Duration("duration", time.Since(started)))
|
||||
|
||||
if err != nil {
|
||||
// Статус в логе должен совпадать с ответом клиенту: ogenerrors.ErrorCode
|
||||
// возвращает 500 для доменных ошибок, поэтому используем ту же функцию,
|
||||
// что и обработчик ошибок транспорта.
|
||||
status := statusForError(err)
|
||||
|
||||
handled = append(handled,
|
||||
slog.Int("status", status),
|
||||
slog.String("error", err.Error()),
|
||||
)
|
||||
log.Log(req.Context, levelForStatus(status), "request failed", handled...)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
handled = append(handled, slog.String("result", resultType(resp)))
|
||||
log.InfoContext(req.Context, "request handled", handled...)
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
func logRejected(ctx context.Context, log *slog.Logger, r *http.Request, status int, err error) {
|
||||
if log == nil {
|
||||
return
|
||||
}
|
||||
|
||||
attrs := []any{
|
||||
slog.String("request_id", requestIDFromContext(ctx)),
|
||||
slog.String("method", r.Method),
|
||||
slog.Int("status", status),
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
attrs = append(attrs, slog.String("error", err.Error()))
|
||||
}
|
||||
|
||||
log.Log(ctx, levelForStatus(status), "request rejected", attrs...)
|
||||
}
|
||||
|
||||
func preMiddlewareError(err error) bool {
|
||||
return errors.As(err, new(*ogenerrors.SecurityError)) ||
|
||||
errors.As(err, new(*ogenerrors.DecodeParamsError)) ||
|
||||
errors.As(err, new(*ogenerrors.DecodeRequestError))
|
||||
}
|
||||
|
||||
func levelForStatus(status int) slog.Level {
|
||||
if status >= http.StatusInternalServerError {
|
||||
return slog.LevelError
|
||||
}
|
||||
|
||||
return slog.LevelWarn
|
||||
}
|
||||
|
||||
func loggedParams(params middleware.Parameters) map[string]any {
|
||||
if len(params) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
out := make(map[string]any, len(params))
|
||||
|
||||
for key, value := range params {
|
||||
name := string(key.In) + "." + key.Name
|
||||
|
||||
if key.In == openapi.LocationHeader {
|
||||
// Значения заголовков не попадают в лог: Idempotency-Key и подобные
|
||||
// параметры — это долгоживущий след конкретного запроса, а для отладки
|
||||
// достаточно факта наличия.
|
||||
out[name] = "redacted"
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
out[name] = value
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func payloadAttr(body []byte) slog.Attr {
|
||||
size := len(body)
|
||||
if size == 0 {
|
||||
return slog.Attr{}
|
||||
}
|
||||
|
||||
return slog.Group("payload",
|
||||
slog.Int("size", size),
|
||||
slog.Bool("content_logged", false),
|
||||
)
|
||||
}
|
||||
|
||||
func resultType(resp middleware.Response) string {
|
||||
if resp.Type == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%T", resp.Type)
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
"github.com/ogen-go/ogen/openapi"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
type LoggingSuite struct {
|
||||
suite.Suite
|
||||
|
||||
sink *strings.Builder
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func TestLoggingSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(LoggingSuite))
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) SetupTest() {
|
||||
s.sink = &strings.Builder{}
|
||||
s.log = logger.New(
|
||||
logger.WithWriter(s.sink),
|
||||
logger.WithLevel(slog.LevelDebug),
|
||||
)
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) records() []map[string]any {
|
||||
var out []map[string]any
|
||||
|
||||
for line := range strings.SplitSeq(strings.TrimSpace(s.sink.String()), "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
var record map[string]any
|
||||
s.Require().NoError(json.Unmarshal([]byte(line), &record))
|
||||
|
||||
out = append(out, record)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) request(method, target, body string) middleware.Request {
|
||||
raw := httptest.NewRequestWithContext(
|
||||
s.T().Context(),
|
||||
method,
|
||||
target,
|
||||
strings.NewReader(body),
|
||||
)
|
||||
raw.RemoteAddr = "192.0.2.10:54321"
|
||||
raw.Header.Set("User-Agent", "smoke/1.0")
|
||||
|
||||
ctx := withRequestID(raw.Context(), "req-42")
|
||||
|
||||
return middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: oas.CreateMessageOperation,
|
||||
OperationID: "createMessage",
|
||||
RawBody: []byte(body),
|
||||
Params: middleware.Parameters{
|
||||
{Name: "chat_id", In: openapi.LocationPath}: "33333333-3333-4333-8333-333333333333",
|
||||
{Name: "limit", In: openapi.LocationQuery}: 50,
|
||||
},
|
||||
Raw: raw,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) TestHeaderParamsAreRedacted() {
|
||||
req := s.request(http.MethodPost, "/api/v1/chats/33333333-3333-4333-8333-333333333333/messages", `{"text":"привет"}`)
|
||||
req.Params = middleware.Parameters{
|
||||
{Name: "chat_id", In: openapi.LocationPath}: "33333333-3333-4333-8333-333333333333",
|
||||
{Name: "Idempotency-Key", In: openapi.LocationHeader}: "secret-key-value",
|
||||
}
|
||||
|
||||
_, err := loggingMiddleware(s.log)(req, func(middleware.Request) (middleware.Response, error) {
|
||||
return middleware.Response{}, nil
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
records := s.records()
|
||||
s.Require().NotEmpty(records)
|
||||
|
||||
params, ok := records[0]["params"].(map[string]any)
|
||||
s.Require().True(ok, "params должны быть объектом")
|
||||
s.Equal("redacted", params["header.Idempotency-Key"], "значение заголовка не логируется")
|
||||
s.Equal("33333333-3333-4333-8333-333333333333", params["path.chat_id"])
|
||||
s.NotContains(s.sink.String(), "secret-key-value")
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) TestLogsAcceptedAndHandled() {
|
||||
req := s.request(http.MethodPost, "/api/v1/chats/33333333-3333-4333-8333-333333333333/messages?limit=50", `{"text":"привет"}`)
|
||||
|
||||
response := middleware.Response{Type: &oas.Message{}}
|
||||
|
||||
got, err := loggingMiddleware(s.log)(req, func(middleware.Request) (middleware.Response, error) {
|
||||
return response, nil
|
||||
})
|
||||
|
||||
s.Require().NoError(err)
|
||||
s.Equal(response, got)
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 2, "ожидаются записи о принятом и обработанном запросе")
|
||||
|
||||
accepted, handled := records[0], records[1]
|
||||
|
||||
s.Equal("request accepted", accepted["msg"])
|
||||
s.Equal("info", accepted["level"])
|
||||
s.Equal("req-42", accepted["request_id"])
|
||||
s.Equal("createMessage", accepted["operation"])
|
||||
s.Equal(http.MethodPost, accepted["method"])
|
||||
s.Equal("/api/v1/chats/33333333-3333-4333-8333-333333333333/messages", accepted["path"])
|
||||
s.Equal("limit=50", accepted["query"])
|
||||
s.Equal("192.0.2.10:54321", accepted["remote_addr"])
|
||||
s.Equal("smoke/1.0", accepted["user_agent"])
|
||||
|
||||
params, ok := accepted["params"].(map[string]any)
|
||||
s.Require().True(ok, "params должны быть объектом")
|
||||
s.Equal("33333333-3333-4333-8333-333333333333", params["path.chat_id"])
|
||||
s.InEpsilon(float64(50), params["query.limit"], 0.0001)
|
||||
|
||||
payload, ok := accepted["payload"].(map[string]any)
|
||||
s.Require().True(ok, "payload должен быть объектом")
|
||||
|
||||
s.False(payload["content_logged"].(bool))
|
||||
s.NotContains(s.sink.String(), "привет")
|
||||
|
||||
s.Equal("request handled", handled["msg"])
|
||||
s.Equal("info", handled["level"])
|
||||
s.Equal("req-42", handled["request_id"])
|
||||
s.Equal("*oas.Message", handled["result"])
|
||||
s.NotEmpty(handled["duration"], "длительность обработки обязательна")
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) TestLogsFailure() {
|
||||
req := s.request(http.MethodGet, "/api/v1/chats", "")
|
||||
|
||||
wantErr := errors.New("storage unavailable")
|
||||
|
||||
_, err := loggingMiddleware(s.log)(req, func(middleware.Request) (middleware.Response, error) {
|
||||
return middleware.Response{}, wantErr
|
||||
})
|
||||
|
||||
s.Require().ErrorIs(err, wantErr)
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 2)
|
||||
|
||||
failed := records[1]
|
||||
s.Equal("request failed", failed["msg"])
|
||||
s.Equal("error", failed["level"])
|
||||
s.Equal("storage unavailable", failed["error"])
|
||||
s.NotEmpty(failed["duration"])
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) TestOmitsPayloadWhenBodyIsEmpty() {
|
||||
req := s.request(http.MethodGet, "/api/v1/chats", "")
|
||||
|
||||
_, err := loggingMiddleware(s.log)(req, func(middleware.Request) (middleware.Response, error) {
|
||||
return middleware.Response{Type: &oas.ChatPage{}}, nil
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
accepted := s.records()[0]
|
||||
s.NotContains(accepted, "payload", "у запроса без тела не должно быть payload")
|
||||
}
|
||||
|
||||
func (s *LoggingSuite) TestPayloadContentIsNeverLogged() {
|
||||
body := strings.Repeat("s", 4096)
|
||||
req := s.request(http.MethodPost, "/api/v1/chats/33333333-3333-4333-8333-333333333333/messages", body)
|
||||
|
||||
_, err := loggingMiddleware(s.log)(req, func(middleware.Request) (middleware.Response, error) {
|
||||
return middleware.Response{Type: &oas.Message{}}, nil
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
payload, ok := s.records()[0]["payload"].(map[string]any)
|
||||
s.Require().True(ok)
|
||||
|
||||
s.InEpsilon(float64(len(body)), payload["size"], 0.0001)
|
||||
s.False(payload["content_logged"].(bool))
|
||||
s.NotContains(s.sink.String(), body)
|
||||
}
|
||||
|
||||
func TestRequestIDMiddlewareSetsHeaderBeforeSecurity(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var seen string
|
||||
|
||||
handler := requestIDMiddleware(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
|
||||
seen = requestIDFromContext(r.Context())
|
||||
}))
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/live", nil))
|
||||
|
||||
require.NotEmpty(t, seen, "идентификатор должен попадать в контекст")
|
||||
require.Equal(t, seen, rec.Header().Get("X-Request-ID"))
|
||||
}
|
||||
|
||||
func TestRequestIDMiddlewarePreservesIncomingID(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
handler := requestIDMiddleware(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/live", nil)
|
||||
req.Header.Set("X-Request-ID", "from-client")
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
require.Equal(t, "from-client", rec.Header().Get("X-Request-ID"))
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/service/attachment"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockAttachmentService creates a new instance of MockAttachmentService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockAttachmentService(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockAttachmentService {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockAttachmentService{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockAttachmentService is an autogenerated mock type for the AttachmentService type
|
||||
type MockAttachmentService struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockAttachmentService_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockAttachmentService) EXPECT() *MockAttachmentService_Expecter {
|
||||
return &MockAttachmentService_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Complete provides a mock function for the type MockAttachmentService
|
||||
func (_mock *MockAttachmentService) Complete(ctx context.Context, ownerID uuid.UUID, id uuid.UUID, sha256 string) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, ownerID, id, sha256)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Complete")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, string) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, ownerID, id, sha256)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, string) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, ownerID, id, sha256)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID, string) error); ok {
|
||||
r1 = returnFunc(ctx, ownerID, id, sha256)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockAttachmentService_Complete_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Complete'
|
||||
type MockAttachmentService_Complete_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Complete is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - ownerID uuid.UUID
|
||||
// - id uuid.UUID
|
||||
// - sha256 string
|
||||
func (_e *MockAttachmentService_Expecter) Complete(ctx any, ownerID any, id any, sha256 any) *MockAttachmentService_Complete_Call {
|
||||
return &MockAttachmentService_Complete_Call{Call: _e.mock.On("Complete", ctx, ownerID, id, sha256)}
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Complete_Call) Run(run func(ctx context.Context, ownerID uuid.UUID, id uuid.UUID, sha256 string)) *MockAttachmentService_Complete_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
var arg3 string
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Complete_Call) Return(attachment domain.Attachment, err error) *MockAttachmentService_Complete_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Complete_Call) RunAndReturn(run func(ctx context.Context, ownerID uuid.UUID, id uuid.UUID, sha256 string) (domain.Attachment, error)) *MockAttachmentService_Complete_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Get provides a mock function for the type MockAttachmentService
|
||||
func (_mock *MockAttachmentService) Get(ctx context.Context, callerID uuid.UUID, id uuid.UUID) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, callerID, id)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Get")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, callerID, id)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, callerID, id)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, callerID, id)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockAttachmentService_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'
|
||||
type MockAttachmentService_Get_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Get is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - callerID uuid.UUID
|
||||
// - id uuid.UUID
|
||||
func (_e *MockAttachmentService_Expecter) Get(ctx any, callerID any, id any) *MockAttachmentService_Get_Call {
|
||||
return &MockAttachmentService_Get_Call{Call: _e.mock.On("Get", ctx, callerID, id)}
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Get_Call) Run(run func(ctx context.Context, callerID uuid.UUID, id uuid.UUID)) *MockAttachmentService_Get_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Get_Call) Return(attachment domain.Attachment, err error) *MockAttachmentService_Get_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Get_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, id uuid.UUID) (domain.Attachment, error)) *MockAttachmentService_Get_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// OpenVariant provides a mock function for the type MockAttachmentService
|
||||
func (_mock *MockAttachmentService) OpenVariant(ctx context.Context, callerID uuid.UUID, id uuid.UUID, name domain.VariantName) (domain.Attachment, domain.Variant, io.ReadCloser, error) {
|
||||
ret := _mock.Called(ctx, callerID, id, name)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for OpenVariant")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 domain.Variant
|
||||
var r2 io.ReadCloser
|
||||
var r3 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, domain.VariantName) (domain.Attachment, domain.Variant, io.ReadCloser, error)); ok {
|
||||
return returnFunc(ctx, callerID, id, name)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, domain.VariantName) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, callerID, id, name)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID, domain.VariantName) domain.Variant); ok {
|
||||
r1 = returnFunc(ctx, callerID, id, name)
|
||||
} else {
|
||||
r1 = ret.Get(1).(domain.Variant)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(2).(func(context.Context, uuid.UUID, uuid.UUID, domain.VariantName) io.ReadCloser); ok {
|
||||
r2 = returnFunc(ctx, callerID, id, name)
|
||||
} else {
|
||||
if ret.Get(2) != nil {
|
||||
r2 = ret.Get(2).(io.ReadCloser)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(3).(func(context.Context, uuid.UUID, uuid.UUID, domain.VariantName) error); ok {
|
||||
r3 = returnFunc(ctx, callerID, id, name)
|
||||
} else {
|
||||
r3 = ret.Error(3)
|
||||
}
|
||||
return r0, r1, r2, r3
|
||||
}
|
||||
|
||||
// MockAttachmentService_OpenVariant_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'OpenVariant'
|
||||
type MockAttachmentService_OpenVariant_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// OpenVariant is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - callerID uuid.UUID
|
||||
// - id uuid.UUID
|
||||
// - name domain.VariantName
|
||||
func (_e *MockAttachmentService_Expecter) OpenVariant(ctx any, callerID any, id any, name any) *MockAttachmentService_OpenVariant_Call {
|
||||
return &MockAttachmentService_OpenVariant_Call{Call: _e.mock.On("OpenVariant", ctx, callerID, id, name)}
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_OpenVariant_Call) Run(run func(ctx context.Context, callerID uuid.UUID, id uuid.UUID, name domain.VariantName)) *MockAttachmentService_OpenVariant_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
var arg3 domain.VariantName
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(domain.VariantName)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_OpenVariant_Call) Return(attachment domain.Attachment, variant domain.Variant, readCloser io.ReadCloser, err error) *MockAttachmentService_OpenVariant_Call {
|
||||
_c.Call.Return(attachment, variant, readCloser, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_OpenVariant_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, id uuid.UUID, name domain.VariantName) (domain.Attachment, domain.Variant, io.ReadCloser, error)) *MockAttachmentService_OpenVariant_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Presign provides a mock function for the type MockAttachmentService
|
||||
func (_mock *MockAttachmentService) Presign(ctx context.Context, request domain.PresignRequest) (domain.PresignResult, error) {
|
||||
ret := _mock.Called(ctx, request)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Presign")
|
||||
}
|
||||
|
||||
var r0 domain.PresignResult
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.PresignRequest) (domain.PresignResult, error)); ok {
|
||||
return returnFunc(ctx, request)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.PresignRequest) domain.PresignResult); ok {
|
||||
r0 = returnFunc(ctx, request)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.PresignResult)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.PresignRequest) error); ok {
|
||||
r1 = returnFunc(ctx, request)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockAttachmentService_Presign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Presign'
|
||||
type MockAttachmentService_Presign_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Presign is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - request domain.PresignRequest
|
||||
func (_e *MockAttachmentService_Expecter) Presign(ctx any, request any) *MockAttachmentService_Presign_Call {
|
||||
return &MockAttachmentService_Presign_Call{Call: _e.mock.On("Presign", ctx, request)}
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Presign_Call) Run(run func(ctx context.Context, request domain.PresignRequest)) *MockAttachmentService_Presign_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.PresignRequest
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.PresignRequest)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Presign_Call) Return(presignResult domain.PresignResult, err error) *MockAttachmentService_Presign_Call {
|
||||
_c.Call.Return(presignResult, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Presign_Call) RunAndReturn(run func(ctx context.Context, request domain.PresignRequest) (domain.PresignResult, error)) *MockAttachmentService_Presign_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Upload provides a mock function for the type MockAttachmentService
|
||||
func (_mock *MockAttachmentService) Upload(ctx context.Context, input attachment.UploadInput) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, input)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Upload")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, attachment.UploadInput) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, input)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, attachment.UploadInput) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, input)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, attachment.UploadInput) error); ok {
|
||||
r1 = returnFunc(ctx, input)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockAttachmentService_Upload_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Upload'
|
||||
type MockAttachmentService_Upload_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Upload is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - input attachment.UploadInput
|
||||
func (_e *MockAttachmentService_Expecter) Upload(ctx any, input any) *MockAttachmentService_Upload_Call {
|
||||
return &MockAttachmentService_Upload_Call{Call: _e.mock.On("Upload", ctx, input)}
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Upload_Call) Run(run func(ctx context.Context, input attachment.UploadInput)) *MockAttachmentService_Upload_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 attachment.UploadInput
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(attachment.UploadInput)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Upload_Call) Return(attachment1 domain.Attachment, err error) *MockAttachmentService_Upload_Call {
|
||||
_c.Call.Return(attachment1, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentService_Upload_Call) RunAndReturn(run func(ctx context.Context, input attachment.UploadInput) (domain.Attachment, error)) *MockAttachmentService_Upload_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockChatService creates a new instance of MockChatService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockChatService(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockChatService {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockChatService{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockChatService is an autogenerated mock type for the ChatService type
|
||||
type MockChatService struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockChatService_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockChatService) EXPECT() *MockChatService_Expecter {
|
||||
return &MockChatService_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockChatService
|
||||
func (_mock *MockChatService) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Chat
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) (domain.Chat, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) domain.Chat); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Chat)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.ChatDraft) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockChatService_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockChatService_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.ChatDraft
|
||||
func (_e *MockChatService_Expecter) Create(ctx any, draft any) *MockChatService_Create_Call {
|
||||
return &MockChatService_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockChatService_Create_Call) Run(run func(ctx context.Context, draft domain.ChatDraft)) *MockChatService_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.ChatDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.ChatDraft)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatService_Create_Call) Return(chat domain.Chat, err error) *MockChatService_Create_Call {
|
||||
_c.Call.Return(chat, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatService_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)) *MockChatService_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Get provides a mock function for the type MockChatService
|
||||
func (_mock *MockChatService) Get(ctx context.Context, callerID uuid.UUID, chatID uuid.UUID) (domain.Chat, error) {
|
||||
ret := _mock.Called(ctx, callerID, chatID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Get")
|
||||
}
|
||||
|
||||
var r0 domain.Chat
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Chat, error)); ok {
|
||||
return returnFunc(ctx, callerID, chatID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Chat); ok {
|
||||
r0 = returnFunc(ctx, callerID, chatID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Chat)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, callerID, chatID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockChatService_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'
|
||||
type MockChatService_Get_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Get is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - callerID uuid.UUID
|
||||
// - chatID uuid.UUID
|
||||
func (_e *MockChatService_Expecter) Get(ctx any, callerID any, chatID any) *MockChatService_Get_Call {
|
||||
return &MockChatService_Get_Call{Call: _e.mock.On("Get", ctx, callerID, chatID)}
|
||||
}
|
||||
|
||||
func (_c *MockChatService_Get_Call) Run(run func(ctx context.Context, callerID uuid.UUID, chatID uuid.UUID)) *MockChatService_Get_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatService_Get_Call) Return(chat domain.Chat, err error) *MockChatService_Get_Call {
|
||||
_c.Call.Return(chat, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatService_Get_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, chatID uuid.UUID) (domain.Chat, error)) *MockChatService_Get_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// List provides a mock function for the type MockChatService
|
||||
func (_mock *MockChatService) List(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
ret := _mock.Called(ctx, callerID, after, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for List")
|
||||
}
|
||||
|
||||
var r0 domain.Page[domain.Chat]
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error)); ok {
|
||||
return returnFunc(ctx, callerID, after, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) domain.Page[domain.Chat]); ok {
|
||||
r0 = returnFunc(ctx, callerID, after, limit)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Page[domain.Chat])
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, *domain.Cursor, int) error); ok {
|
||||
r1 = returnFunc(ctx, callerID, after, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockChatService_List_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'List'
|
||||
type MockChatService_List_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// List is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - callerID uuid.UUID
|
||||
// - after *domain.Cursor
|
||||
// - limit int
|
||||
func (_e *MockChatService_Expecter) List(ctx any, callerID any, after any, limit any) *MockChatService_List_Call {
|
||||
return &MockChatService_List_Call{Call: _e.mock.On("List", ctx, callerID, after, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockChatService_List_Call) Run(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int)) *MockChatService_List_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 *domain.Cursor
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(*domain.Cursor)
|
||||
}
|
||||
var arg3 int
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatService_List_Call) Return(page domain.Page[domain.Chat], err error) *MockChatService_List_Call {
|
||||
_c.Call.Return(page, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatService_List_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error)) *MockChatService_List_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockHealthChecker creates a new instance of MockHealthChecker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockHealthChecker(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockHealthChecker {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockHealthChecker{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockHealthChecker is an autogenerated mock type for the HealthChecker type
|
||||
type MockHealthChecker struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockHealthChecker_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockHealthChecker) EXPECT() *MockHealthChecker_Expecter {
|
||||
return &MockHealthChecker_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Ping provides a mock function for the type MockHealthChecker
|
||||
func (_mock *MockHealthChecker) Ping(ctx context.Context) error {
|
||||
ret := _mock.Called(ctx)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Ping")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context) error); ok {
|
||||
r0 = returnFunc(ctx)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockHealthChecker_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping'
|
||||
type MockHealthChecker_Ping_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Ping is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
func (_e *MockHealthChecker_Expecter) Ping(ctx any) *MockHealthChecker_Ping_Call {
|
||||
return &MockHealthChecker_Ping_Call{Call: _e.mock.On("Ping", ctx)}
|
||||
}
|
||||
|
||||
func (_c *MockHealthChecker_Ping_Call) Run(run func(ctx context.Context)) *MockHealthChecker_Ping_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockHealthChecker_Ping_Call) Return(err error) *MockHealthChecker_Ping_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockHealthChecker_Ping_Call) RunAndReturn(run func(ctx context.Context) error) *MockHealthChecker_Ping_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockMessageService creates a new instance of MockMessageService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockMessageService(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockMessageService {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockMessageService{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockMessageService is an autogenerated mock type for the MessageService type
|
||||
type MockMessageService struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockMessageService_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockMessageService) EXPECT() *MockMessageService_Expecter {
|
||||
return &MockMessageService_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// History provides a mock function for the type MockMessageService
|
||||
func (_mock *MockMessageService) History(ctx context.Context, callerID uuid.UUID, chatID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Message], error) {
|
||||
ret := _mock.Called(ctx, callerID, chatID, after, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for History")
|
||||
}
|
||||
|
||||
var r0 domain.Page[domain.Message]
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Message], error)); ok {
|
||||
return returnFunc(ctx, callerID, chatID, after, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, *domain.Cursor, int) domain.Page[domain.Message]); ok {
|
||||
r0 = returnFunc(ctx, callerID, chatID, after, limit)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Page[domain.Message])
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID, *domain.Cursor, int) error); ok {
|
||||
r1 = returnFunc(ctx, callerID, chatID, after, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockMessageService_History_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'History'
|
||||
type MockMessageService_History_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// History is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - callerID uuid.UUID
|
||||
// - chatID uuid.UUID
|
||||
// - after *domain.Cursor
|
||||
// - limit int
|
||||
func (_e *MockMessageService_Expecter) History(ctx any, callerID any, chatID any, after any, limit any) *MockMessageService_History_Call {
|
||||
return &MockMessageService_History_Call{Call: _e.mock.On("History", ctx, callerID, chatID, after, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockMessageService_History_Call) Run(run func(ctx context.Context, callerID uuid.UUID, chatID uuid.UUID, after *domain.Cursor, limit int)) *MockMessageService_History_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
var arg3 *domain.Cursor
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(*domain.Cursor)
|
||||
}
|
||||
var arg4 int
|
||||
if args[4] != nil {
|
||||
arg4 = args[4].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
arg4,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockMessageService_History_Call) Return(page domain.Page[domain.Message], err error) *MockMessageService_History_Call {
|
||||
_c.Call.Return(page, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockMessageService_History_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, chatID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Message], error)) *MockMessageService_History_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Send provides a mock function for the type MockMessageService
|
||||
func (_mock *MockMessageService) Send(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Send")
|
||||
}
|
||||
|
||||
var r0 domain.Message
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.MessageDraft) (domain.Message, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.MessageDraft) domain.Message); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Message)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.MessageDraft) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockMessageService_Send_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Send'
|
||||
type MockMessageService_Send_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Send is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.MessageDraft
|
||||
func (_e *MockMessageService_Expecter) Send(ctx any, draft any) *MockMessageService_Send_Call {
|
||||
return &MockMessageService_Send_Call{Call: _e.mock.On("Send", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockMessageService_Send_Call) Run(run func(ctx context.Context, draft domain.MessageDraft)) *MockMessageService_Send_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.MessageDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.MessageDraft)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockMessageService_Send_Call) Return(message domain.Message, err error) *MockMessageService_Send_Call {
|
||||
_c.Call.Return(message, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockMessageService_Send_Call) RunAndReturn(run func(ctx context.Context, draft domain.MessageDraft) (domain.Message, error)) *MockMessageService_Send_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockSecSessionService creates a new instance of MockSecSessionService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockSecSessionService(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockSecSessionService {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockSecSessionService{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockSecSessionService is an autogenerated mock type for the SecSessionService type
|
||||
type MockSecSessionService struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockSecSessionService_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockSecSessionService) EXPECT() *MockSecSessionService_Expecter {
|
||||
return &MockSecSessionService_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Authenticate provides a mock function for the type MockSecSessionService
|
||||
func (_mock *MockSecSessionService) Authenticate(ctx context.Context, username string, password string) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, username, password)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Authenticate")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, username, password)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string) domain.User); ok {
|
||||
r0 = returnFunc(ctx, username, password)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string, string) error); ok {
|
||||
r1 = returnFunc(ctx, username, password)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSecSessionService_Authenticate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Authenticate'
|
||||
type MockSecSessionService_Authenticate_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Authenticate is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - username string
|
||||
// - password string
|
||||
func (_e *MockSecSessionService_Expecter) Authenticate(ctx any, username any, password any) *MockSecSessionService_Authenticate_Call {
|
||||
return &MockSecSessionService_Authenticate_Call{Call: _e.mock.On("Authenticate", ctx, username, password)}
|
||||
}
|
||||
|
||||
func (_c *MockSecSessionService_Authenticate_Call) Run(run func(ctx context.Context, username string, password string)) *MockSecSessionService_Authenticate_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
var arg2 string
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSecSessionService_Authenticate_Call) Return(user domain.User, err error) *MockSecSessionService_Authenticate_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSecSessionService_Authenticate_Call) RunAndReturn(run func(ctx context.Context, username string, password string) (domain.User, error)) *MockSecSessionService_Authenticate_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Resolve provides a mock function for the type MockSecSessionService
|
||||
func (_mock *MockSecSessionService) Resolve(ctx context.Context, token string) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, token)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Resolve")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, token)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) domain.User); ok {
|
||||
r0 = returnFunc(ctx, token)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, token)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSecSessionService_Resolve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Resolve'
|
||||
type MockSecSessionService_Resolve_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Resolve is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - token string
|
||||
func (_e *MockSecSessionService_Expecter) Resolve(ctx any, token any) *MockSecSessionService_Resolve_Call {
|
||||
return &MockSecSessionService_Resolve_Call{Call: _e.mock.On("Resolve", ctx, token)}
|
||||
}
|
||||
|
||||
func (_c *MockSecSessionService_Resolve_Call) Run(run func(ctx context.Context, token string)) *MockSecSessionService_Resolve_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSecSessionService_Resolve_Call) Return(user domain.User, err error) *MockSecSessionService_Resolve_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSecSessionService_Resolve_Call) RunAndReturn(run func(ctx context.Context, token string) (domain.User, error)) *MockSecSessionService_Resolve_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockSessionActions creates a new instance of MockSessionActions. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockSessionActions(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockSessionActions {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockSessionActions{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockSessionActions is an autogenerated mock type for the SessionActions type
|
||||
type MockSessionActions struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockSessionActions_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockSessionActions) EXPECT() *MockSessionActions_Expecter {
|
||||
return &MockSessionActions_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Authenticate provides a mock function for the type MockSessionActions
|
||||
func (_mock *MockSessionActions) Authenticate(ctx context.Context, username string, password string) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, username, password)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Authenticate")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, username, password)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string) domain.User); ok {
|
||||
r0 = returnFunc(ctx, username, password)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string, string) error); ok {
|
||||
r1 = returnFunc(ctx, username, password)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSessionActions_Authenticate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Authenticate'
|
||||
type MockSessionActions_Authenticate_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Authenticate is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - username string
|
||||
// - password string
|
||||
func (_e *MockSessionActions_Expecter) Authenticate(ctx any, username any, password any) *MockSessionActions_Authenticate_Call {
|
||||
return &MockSessionActions_Authenticate_Call{Call: _e.mock.On("Authenticate", ctx, username, password)}
|
||||
}
|
||||
|
||||
func (_c *MockSessionActions_Authenticate_Call) Run(run func(ctx context.Context, username string, password string)) *MockSessionActions_Authenticate_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
var arg2 string
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionActions_Authenticate_Call) Return(user domain.User, err error) *MockSessionActions_Authenticate_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionActions_Authenticate_Call) RunAndReturn(run func(ctx context.Context, username string, password string) (domain.User, error)) *MockSessionActions_Authenticate_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockSessionActions
|
||||
func (_mock *MockSessionActions) Create(ctx context.Context, user domain.User) (domain.Session, error) {
|
||||
ret := _mock.Called(ctx, user)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Session
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.User) (domain.Session, error)); ok {
|
||||
return returnFunc(ctx, user)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.User) domain.Session); ok {
|
||||
r0 = returnFunc(ctx, user)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.User) error); ok {
|
||||
r1 = returnFunc(ctx, user)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSessionActions_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockSessionActions_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - user domain.User
|
||||
func (_e *MockSessionActions_Expecter) Create(ctx any, user any) *MockSessionActions_Create_Call {
|
||||
return &MockSessionActions_Create_Call{Call: _e.mock.On("Create", ctx, user)}
|
||||
}
|
||||
|
||||
func (_c *MockSessionActions_Create_Call) Run(run func(ctx context.Context, user domain.User)) *MockSessionActions_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.User
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.User)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionActions_Create_Call) Return(session domain.Session, err error) *MockSessionActions_Create_Call {
|
||||
_c.Call.Return(session, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionActions_Create_Call) RunAndReturn(run func(ctx context.Context, user domain.User) (domain.Session, error)) *MockSessionActions_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Resolve provides a mock function for the type MockSessionActions
|
||||
func (_mock *MockSessionActions) Resolve(ctx context.Context, token string) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, token)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Resolve")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, token)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) domain.User); ok {
|
||||
r0 = returnFunc(ctx, token)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, token)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSessionActions_Resolve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Resolve'
|
||||
type MockSessionActions_Resolve_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Resolve is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - token string
|
||||
func (_e *MockSessionActions_Expecter) Resolve(ctx any, token any) *MockSessionActions_Resolve_Call {
|
||||
return &MockSessionActions_Resolve_Call{Call: _e.mock.On("Resolve", ctx, token)}
|
||||
}
|
||||
|
||||
func (_c *MockSessionActions_Resolve_Call) Run(run func(ctx context.Context, token string)) *MockSessionActions_Resolve_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionActions_Resolve_Call) Return(user domain.User, err error) *MockSessionActions_Resolve_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionActions_Resolve_Call) RunAndReturn(run func(ctx context.Context, token string) (domain.User, error)) *MockSessionActions_Resolve_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Revoke provides a mock function for the type MockSessionActions
|
||||
func (_mock *MockSessionActions) Revoke(ctx context.Context, userID uuid.UUID, token string) error {
|
||||
ret := _mock.Called(ctx, userID, token)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Revoke")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string) error); ok {
|
||||
r0 = returnFunc(ctx, userID, token)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockSessionActions_Revoke_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Revoke'
|
||||
type MockSessionActions_Revoke_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Revoke is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - userID uuid.UUID
|
||||
// - token string
|
||||
func (_e *MockSessionActions_Expecter) Revoke(ctx any, userID any, token any) *MockSessionActions_Revoke_Call {
|
||||
return &MockSessionActions_Revoke_Call{Call: _e.mock.On("Revoke", ctx, userID, token)}
|
||||
}
|
||||
|
||||
func (_c *MockSessionActions_Revoke_Call) Run(run func(ctx context.Context, userID uuid.UUID, token string)) *MockSessionActions_Revoke_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 string
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionActions_Revoke_Call) Return(err error) *MockSessionActions_Revoke_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionActions_Revoke_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, token string) error) *MockSessionActions_Revoke_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockSessionResolver creates a new instance of MockSessionResolver. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockSessionResolver(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockSessionResolver {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockSessionResolver{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockSessionResolver is an autogenerated mock type for the SessionResolver type
|
||||
type MockSessionResolver struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockSessionResolver_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockSessionResolver) EXPECT() *MockSessionResolver_Expecter {
|
||||
return &MockSessionResolver_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Resolve provides a mock function for the type MockSessionResolver
|
||||
func (_mock *MockSessionResolver) Resolve(ctx context.Context, token string) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, token)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Resolve")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, token)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) domain.User); ok {
|
||||
r0 = returnFunc(ctx, token)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, token)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSessionResolver_Resolve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Resolve'
|
||||
type MockSessionResolver_Resolve_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Resolve is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - token string
|
||||
func (_e *MockSessionResolver_Expecter) Resolve(ctx any, token any) *MockSessionResolver_Resolve_Call {
|
||||
return &MockSessionResolver_Resolve_Call{Call: _e.mock.On("Resolve", ctx, token)}
|
||||
}
|
||||
|
||||
func (_c *MockSessionResolver_Resolve_Call) Run(run func(ctx context.Context, token string)) *MockSessionResolver_Resolve_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionResolver_Resolve_Call) Return(user domain.User, err error) *MockSessionResolver_Resolve_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionResolver_Resolve_Call) RunAndReturn(run func(ctx context.Context, token string) (domain.User, error)) *MockSessionResolver_Resolve_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockSessionService creates a new instance of MockSessionService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockSessionService(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockSessionService {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockSessionService{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockSessionService is an autogenerated mock type for the SessionService type
|
||||
type MockSessionService struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockSessionService_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockSessionService) EXPECT() *MockSessionService_Expecter {
|
||||
return &MockSessionService_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockSessionService
|
||||
func (_mock *MockSessionService) Create(ctx context.Context, user domain.User) (domain.Session, error) {
|
||||
ret := _mock.Called(ctx, user)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Session
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.User) (domain.Session, error)); ok {
|
||||
return returnFunc(ctx, user)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.User) domain.Session); ok {
|
||||
r0 = returnFunc(ctx, user)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.User) error); ok {
|
||||
r1 = returnFunc(ctx, user)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSessionService_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockSessionService_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - user domain.User
|
||||
func (_e *MockSessionService_Expecter) Create(ctx any, user any) *MockSessionService_Create_Call {
|
||||
return &MockSessionService_Create_Call{Call: _e.mock.On("Create", ctx, user)}
|
||||
}
|
||||
|
||||
func (_c *MockSessionService_Create_Call) Run(run func(ctx context.Context, user domain.User)) *MockSessionService_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.User
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.User)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionService_Create_Call) Return(session domain.Session, err error) *MockSessionService_Create_Call {
|
||||
_c.Call.Return(session, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionService_Create_Call) RunAndReturn(run func(ctx context.Context, user domain.User) (domain.Session, error)) *MockSessionService_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Revoke provides a mock function for the type MockSessionService
|
||||
func (_mock *MockSessionService) Revoke(ctx context.Context, userID uuid.UUID, token string) error {
|
||||
ret := _mock.Called(ctx, userID, token)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Revoke")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string) error); ok {
|
||||
r0 = returnFunc(ctx, userID, token)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockSessionService_Revoke_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Revoke'
|
||||
type MockSessionService_Revoke_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Revoke is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - userID uuid.UUID
|
||||
// - token string
|
||||
func (_e *MockSessionService_Expecter) Revoke(ctx any, userID any, token any) *MockSessionService_Revoke_Call {
|
||||
return &MockSessionService_Revoke_Call{Call: _e.mock.On("Revoke", ctx, userID, token)}
|
||||
}
|
||||
|
||||
func (_c *MockSessionService_Revoke_Call) Run(run func(ctx context.Context, userID uuid.UUID, token string)) *MockSessionService_Revoke_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 string
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionService_Revoke_Call) Return(err error) *MockSessionService_Revoke_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSessionService_Revoke_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, token string) error) *MockSessionService_Revoke_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockUserLookup creates a new instance of MockUserLookup. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockUserLookup(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockUserLookup {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockUserLookup{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockUserLookup is an autogenerated mock type for the UserLookup type
|
||||
type MockUserLookup struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockUserLookup_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockUserLookup) EXPECT() *MockUserLookup_Expecter {
|
||||
return &MockUserLookup_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// GetByID provides a mock function for the type MockUserLookup
|
||||
func (_mock *MockUserLookup) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, id)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetByID")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, id)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) domain.User); ok {
|
||||
r0 = returnFunc(ctx, id)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, id)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockUserLookup_GetByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetByID'
|
||||
type MockUserLookup_GetByID_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetByID is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - id uuid.UUID
|
||||
func (_e *MockUserLookup_Expecter) GetByID(ctx any, id any) *MockUserLookup_GetByID_Call {
|
||||
return &MockUserLookup_GetByID_Call{Call: _e.mock.On("GetByID", ctx, id)}
|
||||
}
|
||||
|
||||
func (_c *MockUserLookup_GetByID_Call) Run(run func(ctx context.Context, id uuid.UUID)) *MockUserLookup_GetByID_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockUserLookup_GetByID_Call) Return(user domain.User, err error) *MockUserLookup_GetByID_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockUserLookup_GetByID_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID) (domain.User, error)) *MockUserLookup_GetByID_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockUserService creates a new instance of MockUserService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockUserService(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockUserService {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockUserService{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockUserService is an autogenerated mock type for the UserService type
|
||||
type MockUserService struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockUserService_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockUserService) EXPECT() *MockUserService_Expecter {
|
||||
return &MockUserService_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// GetByID provides a mock function for the type MockUserService
|
||||
func (_mock *MockUserService) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, id)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetByID")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, id)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) domain.User); ok {
|
||||
r0 = returnFunc(ctx, id)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, id)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockUserService_GetByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetByID'
|
||||
type MockUserService_GetByID_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetByID is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - id uuid.UUID
|
||||
func (_e *MockUserService_Expecter) GetByID(ctx any, id any) *MockUserService_GetByID_Call {
|
||||
return &MockUserService_GetByID_Call{Call: _e.mock.On("GetByID", ctx, id)}
|
||||
}
|
||||
|
||||
func (_c *MockUserService_GetByID_Call) Run(run func(ctx context.Context, id uuid.UUID)) *MockUserService_GetByID_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockUserService_GetByID_Call) Return(user domain.User, err error) *MockUserService_GetByID_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockUserService_GetByID_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID) (domain.User, error)) *MockUserService_GetByID_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Register provides a mock function for the type MockUserService
|
||||
func (_mock *MockUserService) Register(ctx context.Context, draft domain.UserDraft) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Register")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.UserDraft) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.UserDraft) domain.User); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.UserDraft) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockUserService_Register_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Register'
|
||||
type MockUserService_Register_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Register is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.UserDraft
|
||||
func (_e *MockUserService_Expecter) Register(ctx any, draft any) *MockUserService_Register_Call {
|
||||
return &MockUserService_Register_Call{Call: _e.mock.On("Register", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockUserService_Register_Call) Run(run func(ctx context.Context, draft domain.UserDraft)) *MockUserService_Register_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.UserDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.UserDraft)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockUserService_Register_Call) Return(user domain.User, err error) *MockUserService_Register_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockUserService_Register_Call) RunAndReturn(run func(ctx context.Context, draft domain.UserDraft) (domain.User, error)) *MockUserService_Register_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/ratelimit"
|
||||
)
|
||||
|
||||
type LoginLimits struct {
|
||||
Account ratelimit.Limit
|
||||
Source ratelimit.Limit
|
||||
Global ratelimit.Limit
|
||||
}
|
||||
|
||||
func DefaultLoginLimits() LoginLimits {
|
||||
return LoginLimits{
|
||||
Account: ratelimit.Limit{Count: 8, Window: time.Minute},
|
||||
Source: ratelimit.Limit{Count: 120, Window: time.Minute},
|
||||
Global: ratelimit.Limit{Count: 16, Window: time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
// WithLoginLimits must wrap the router so admission precedes generated Basic
|
||||
// authentication. Registration shares the source and global derivation budgets.
|
||||
func WithLoginLimits(
|
||||
next http.Handler, limiter ratelimit.Limiter, limits LoginLimits, log *slog.Logger,
|
||||
) http.Handler {
|
||||
id := InstanceID()
|
||||
return requestIDMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
isLogin := r.Method == http.MethodPost && r.URL.Path == "/api/v1/auth/sessions"
|
||||
isRegister := r.Method == http.MethodPost && r.URL.Path == "/api/v1/users"
|
||||
if !isLogin && !isRegister {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set(instanceIDHeader, id)
|
||||
if limiter == nil {
|
||||
logRejected(r.Context(), log, r, http.StatusServiceUnavailable, domain.ErrUnavailable)
|
||||
writeError(r.Context(), log, w, r, http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
reservations := make([]ratelimit.Limit, 0, 3)
|
||||
source, global := limits.Source, limits.Global
|
||||
source.Key = loginLimitKey("source", loginSourceIP(r))
|
||||
global.Key = loginLimitKey("global", "login-register")
|
||||
reservations = append(reservations, source, global)
|
||||
if isLogin {
|
||||
username, _, _ := r.BasicAuth()
|
||||
account := limits.Account
|
||||
account.Key = loginLimitKey("account", username)
|
||||
reservations = append(reservations, account)
|
||||
}
|
||||
retryAfter, err := limiter.Reserve(r.Context(), reservations)
|
||||
if err != nil {
|
||||
logRejected(r.Context(), log, r, http.StatusServiceUnavailable, domain.ErrUnavailable)
|
||||
writeError(r.Context(), log, w, r, http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if retryAfter > 0 {
|
||||
w.Header().Set("Retry-After", retryAfterSeconds(retryAfter))
|
||||
logRejected(r.Context(), log, r, http.StatusTooManyRequests, domain.ErrRateLimited)
|
||||
writeError(r.Context(), log, w, r, http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
}))
|
||||
}
|
||||
|
||||
func loginLimitKey(scope, value string) string {
|
||||
digest := sha256.Sum256([]byte(scope + "\x00" + value))
|
||||
return hex.EncodeToString(digest[:])
|
||||
}
|
||||
|
||||
func loginSourceIP(r *http.Request) string {
|
||||
if authenticatedLB(r) {
|
||||
values := r.Header.Values("X-Forwarded-For")
|
||||
if len(values) == 1 {
|
||||
if ip, err := netip.ParseAddr(strings.TrimSpace(values[0])); err == nil {
|
||||
return ip.Unmap().String()
|
||||
}
|
||||
}
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
host = r.RemoteAddr
|
||||
}
|
||||
if ip, err := netip.ParseAddr(host); err == nil {
|
||||
return ip.Unmap().String()
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
func authenticatedLB(r *http.Request) bool {
|
||||
if r.TLS == nil {
|
||||
return false
|
||||
}
|
||||
for _, chain := range r.TLS.VerifiedChains {
|
||||
if len(chain) == 0 {
|
||||
continue
|
||||
}
|
||||
for _, uri := range chain[0].URIs {
|
||||
if uri.String() == "spiffe://mtusi/lb" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func retryAfterSeconds(duration time.Duration) string {
|
||||
seconds := duration / time.Second
|
||||
if duration%time.Second != 0 {
|
||||
seconds++
|
||||
}
|
||||
return strconv.FormatInt(max(1, int64(seconds)), 10)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
"mtusi-messenger/internal/platform/ratelimit"
|
||||
)
|
||||
|
||||
type limiterFunc func(context.Context, []ratelimit.Limit) (time.Duration, error)
|
||||
|
||||
func (f limiterFunc) Reserve(ctx context.Context, limits []ratelimit.Limit) (time.Duration, error) {
|
||||
return f(ctx, limits)
|
||||
}
|
||||
|
||||
func TestLoginLimitsReserveBeforeAuthenticationAndFailClosed(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
retry time.Duration
|
||||
err error
|
||||
status int
|
||||
wantRetry string
|
||||
}{
|
||||
{name: "accepted", status: http.StatusNoContent},
|
||||
{name: "limited", retry: 1500 * time.Millisecond, status: http.StatusTooManyRequests, wantRetry: "2"},
|
||||
{name: "dependency failure", err: errors.New("sensitive dependency failure"), status: http.StatusServiceUnavailable},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Setenv(instanceIDEnv, "admission-replica")
|
||||
reserved, authenticated, authenticatedBeforeReservation := false, false, false
|
||||
limiter := limiterFunc(func(_ context.Context, _ []ratelimit.Limit) (time.Duration, error) {
|
||||
require.False(t, authenticated)
|
||||
reserved = true
|
||||
return test.retry, test.err
|
||||
})
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
authenticatedBeforeReservation = !reserved
|
||||
authenticated = true
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("private-account", "private-password")
|
||||
request.Header.Set(requestIDHeader, "invalid\r\nrequest-id")
|
||||
recorder := httptest.NewRecorder()
|
||||
WithLoginLimits(next, limiter, DefaultLoginLimits(), nil).ServeHTTP(recorder, request)
|
||||
require.True(t, reserved)
|
||||
require.Equal(t, test.status, recorder.Code)
|
||||
require.Equal(t, test.wantRetry, recorder.Header().Get("Retry-After"))
|
||||
require.Equal(t, test.status == http.StatusNoContent, authenticated)
|
||||
require.False(t, authenticatedBeforeReservation)
|
||||
require.True(t, requestIDPattern.MatchString(recorder.Header().Get(requestIDHeader)))
|
||||
require.Equal(t, "admission-replica", recorder.Header().Get(instanceIDHeader))
|
||||
require.NotContains(t, recorder.Body.String(), "sensitive")
|
||||
require.NotContains(t, recorder.Body.String(), "private")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginSourceIPRejectsForwardedSpoofing(t *testing.T) {
|
||||
lbURI, err := url.Parse("spiffe://mtusi/lb")
|
||||
require.NoError(t, err)
|
||||
rogueURI, err := url.Parse("spiffe://mtusi/rogue")
|
||||
require.NoError(t, err)
|
||||
lb := &x509.Certificate{URIs: []*url.URL{lbURI}}
|
||||
rogue := &x509.Certificate{URIs: []*url.URL{rogueURI}}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
tls *tls.ConnectionState
|
||||
header string
|
||||
want string
|
||||
}{
|
||||
{name: "plaintext spoof", header: "198.51.100.1", want: "192.0.2.1"},
|
||||
{
|
||||
name: "unverified lb", tls: &tls.ConnectionState{PeerCertificates: []*x509.Certificate{lb}},
|
||||
header: "198.51.100.1", want: "192.0.2.1",
|
||||
},
|
||||
{
|
||||
name: "verified rogue", tls: &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{rogue}}},
|
||||
header: "198.51.100.1", want: "192.0.2.1",
|
||||
},
|
||||
{
|
||||
name: "authenticated lb", tls: &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{lb}}},
|
||||
header: "198.51.100.1", want: "198.51.100.1",
|
||||
},
|
||||
{
|
||||
name: "forwarded chain rejected", tls: &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{lb}}},
|
||||
header: "198.51.100.1, 203.0.113.2", want: "192.0.2.1",
|
||||
},
|
||||
{
|
||||
name: "malformed forwarded rejected", tls: &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{lb}}},
|
||||
header: "not-an-ip", want: "192.0.2.1",
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.RemoteAddr, request.TLS = "192.0.2.1:1234", test.tls
|
||||
request.Header.Set("X-Forwarded-For", test.header)
|
||||
require.Equal(t, test.want, loginSourceIP(request))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBusyDerivationProduces429Not401(t *testing.T) {
|
||||
for _, err := range []error{
|
||||
fmt.Errorf("hash password: %w", password.ErrBusy),
|
||||
&ogenerrors.SecurityError{Security: "BasicAuth", Err: fmt.Errorf("verify password: %w", password.ErrBusy)},
|
||||
} {
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
newErrorHandler(nil)(request.Context(), recorder, request, err)
|
||||
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
|
||||
require.Equal(t, "1", recorder.Header().Get("Retry-After"))
|
||||
require.Empty(t, recorder.Header().Get("WWW-Authenticate"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginLimitsDoNotAdmitWhenLimiterMissing(t *testing.T) {
|
||||
called := false
|
||||
next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true })
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/users", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
WithLoginLimits(next, nil, DefaultLoginLimits(), nil).ServeHTTP(recorder, request)
|
||||
require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
|
||||
require.False(t, called)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const requestIDHeader = "X-Request-ID"
|
||||
|
||||
var requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
|
||||
|
||||
type requestIDKey struct{}
|
||||
|
||||
func requestIDFromContext(ctx context.Context) string {
|
||||
id, _ := ctx.Value(requestIDKey{}).(string)
|
||||
|
||||
return id
|
||||
}
|
||||
|
||||
func withRequestID(ctx context.Context, id string) context.Context {
|
||||
return context.WithValue(ctx, requestIDKey{}, id)
|
||||
}
|
||||
|
||||
func requestIDMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get(requestIDHeader)
|
||||
if !requestIDPattern.MatchString(id) {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
|
||||
w.Header().Set(requestIDHeader, id)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(withRequestID(r.Context(), id)))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
func NewRouter(
|
||||
handler oas.Handler,
|
||||
security oas.SecurityHandler,
|
||||
extensions *Extensions,
|
||||
log *slog.Logger,
|
||||
maxBodyBytes, maxUploadBytes int64,
|
||||
) (http.Handler, error) {
|
||||
server, err := oas.NewServer(
|
||||
handler,
|
||||
security,
|
||||
oas.WithErrorHandler(newErrorHandler(log)),
|
||||
oas.WithNotFound(newNotFoundHandler(log)),
|
||||
oas.WithMethodNotAllowed(newMethodNotAllowedHandler(log)),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
if extensions != nil {
|
||||
// These routes are an optional contract extension (presigned uploads).
|
||||
// They live outside the generated server so contracts/openapi.json stays
|
||||
// byte-identical to the mandatory contract.
|
||||
mux.Handle("/api/v1/chats/{chat_id}/attachments/presign", extensions.Presign())
|
||||
mux.Handle("/api/v1/attachments/{attachment_id}/complete", extensions.Complete())
|
||||
}
|
||||
|
||||
mux.Handle("/", server)
|
||||
|
||||
limited := bodyLimitMiddleware(maxBodyBytes, maxUploadBytes, log, mux)
|
||||
|
||||
return requestIDMiddleware(
|
||||
instanceIDMiddleware(InstanceID(), telemetryMiddleware(log, server, mux, limited)),
|
||||
), nil
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
package rest_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/logger"
|
||||
"mtusi-messenger/internal/transport/rest"
|
||||
"mtusi-messenger/internal/transport/rest/mocks"
|
||||
)
|
||||
|
||||
const (
|
||||
requestIDHeader = "X-Request-ID"
|
||||
instanceIDHeader = "X-Instance-Id"
|
||||
)
|
||||
|
||||
func basic(username, password string) string {
|
||||
return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
|
||||
}
|
||||
|
||||
func assertError(message string) error {
|
||||
return errors.New(message)
|
||||
}
|
||||
|
||||
type httpResult struct {
|
||||
status int
|
||||
header http.Header
|
||||
body []byte
|
||||
}
|
||||
|
||||
type routerFixture struct {
|
||||
users *mocks.MockUserService
|
||||
chats *mocks.MockChatService
|
||||
messages *mocks.MockMessageService
|
||||
attachments *mocks.MockAttachmentService
|
||||
health *mocks.MockHealthChecker
|
||||
sessions *mocks.MockSessionActions
|
||||
|
||||
server *httptest.Server
|
||||
}
|
||||
|
||||
// testMaxBodyBytes is small on purpose: the limit test does not need a 256 KiB body.
|
||||
const testMaxBodyBytes = 64 << 10
|
||||
|
||||
func newRouterFixture(t *testing.T) *routerFixture {
|
||||
t.Helper()
|
||||
|
||||
fixture := &routerFixture{
|
||||
users: mocks.NewMockUserService(t),
|
||||
chats: mocks.NewMockChatService(t),
|
||||
messages: mocks.NewMockMessageService(t),
|
||||
attachments: mocks.NewMockAttachmentService(t),
|
||||
health: mocks.NewMockHealthChecker(t),
|
||||
sessions: mocks.NewMockSessionActions(t),
|
||||
}
|
||||
|
||||
router, err := rest.NewRouter(
|
||||
rest.NewHandler(
|
||||
fixture.users,
|
||||
fixture.chats,
|
||||
fixture.messages,
|
||||
fixture.attachments,
|
||||
fixture.health,
|
||||
fixture.sessions,
|
||||
),
|
||||
rest.NewSecurityHandler(fixture.sessions),
|
||||
nil,
|
||||
logger.New(logger.WithLevel(slog.LevelError)),
|
||||
testMaxBodyBytes,
|
||||
testMaxBodyBytes,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
fixture.server = httptest.NewServer(router)
|
||||
t.Cleanup(fixture.server.Close)
|
||||
|
||||
return fixture
|
||||
}
|
||||
|
||||
func (f *routerFixture) do(t *testing.T, method, path string, body []byte, headers map[string]string) httpResult {
|
||||
t.Helper()
|
||||
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
reader = bytes.NewReader(body)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(t.Context(), method, f.server.URL+path, reader)
|
||||
require.NoError(t, err)
|
||||
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
for key, value := range headers {
|
||||
req.Header.Set(key, value)
|
||||
}
|
||||
|
||||
resp, err := f.server.Client().Do(req)
|
||||
require.NoError(t, err)
|
||||
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
payload, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
return httpResult{status: resp.StatusCode, header: resp.Header, body: payload}
|
||||
}
|
||||
|
||||
func TestHealthEndpoints(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
fixture.health.EXPECT().Ping(mock.Anything).Return(nil).Maybe()
|
||||
|
||||
result := fixture.do(t, http.MethodGet, "/health/live", nil, nil)
|
||||
require.Equal(t, http.StatusOK, result.status)
|
||||
require.NotEmpty(t, result.header.Get(requestIDHeader))
|
||||
require.JSONEq(t, `{"status":"ok"}`, string(result.body))
|
||||
|
||||
result = fixture.do(t, http.MethodGet, "/health/ready", nil, nil)
|
||||
require.Equal(t, http.StatusOK, result.status)
|
||||
}
|
||||
|
||||
func TestReadinessReturns503WhenDependencyDown(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
fixture.health.EXPECT().Ping(mock.Anything).Return(assertError("down")).Maybe()
|
||||
|
||||
result := fixture.do(t, http.MethodGet, "/health/ready", nil, nil)
|
||||
require.Equal(t, http.StatusServiceUnavailable, result.status)
|
||||
|
||||
var body struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(result.body, &body))
|
||||
require.Equal(t, "unavailable", body.Error.Code)
|
||||
}
|
||||
|
||||
func TestRequestIDEchoedFromClient(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
result := fixture.do(t, http.MethodGet, "/health/live", nil, map[string]string{requestIDHeader: "from-client"})
|
||||
require.Equal(t, "from-client", result.header.Get(requestIDHeader))
|
||||
}
|
||||
|
||||
func TestProtectedEndpointRequiresBearer(t *testing.T) {
|
||||
tests := map[string]map[string]string{
|
||||
"без заголовка": nil,
|
||||
"только X-User-Id": {"X-User-Id": uuid.NewString()},
|
||||
"basic вместо bearer": {"Authorization": "Basic dXNlcjpwYXNz"},
|
||||
}
|
||||
|
||||
for name, headers := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
result := fixture.do(t, http.MethodGet, "/api/v1/users/me", nil, headers)
|
||||
require.Equal(t, http.StatusUnauthorized, result.status)
|
||||
require.Contains(t, result.header.Get("WWW-Authenticate"), "Bearer")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBearerSessionIsResolvedToCaller(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Once()
|
||||
fixture.users.EXPECT().GetByID(mock.Anything, user.ID).Return(user, nil).Once()
|
||||
|
||||
result := fixture.do(t, http.MethodGet, "/api/v1/users/me", nil, map[string]string{"Authorization": "Bearer opaque-token"})
|
||||
require.Equal(t, http.StatusOK, result.status)
|
||||
|
||||
var body map[string]any
|
||||
require.NoError(t, json.Unmarshal(result.body, &body))
|
||||
require.Equal(t, user.ID.String(), body["id"])
|
||||
}
|
||||
|
||||
func TestUnknownBearerIsRejected(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
fixture.sessions.EXPECT().Resolve(mock.Anything, "unknown").Return(domain.User{}, domain.ErrUnauthenticated).Once()
|
||||
|
||||
result := fixture.do(t, http.MethodGet, "/api/v1/chats", nil, map[string]string{"Authorization": "Bearer unknown"})
|
||||
require.Equal(t, http.StatusUnauthorized, result.status)
|
||||
require.Contains(t, result.header.Get("WWW-Authenticate"), "Bearer")
|
||||
}
|
||||
|
||||
func TestRegisterUserReturnsContractShape(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
|
||||
fixture.users.EXPECT().Register(mock.Anything, draft).Return(user, nil).Once()
|
||||
|
||||
body, err := json.Marshal(map[string]string{"username": "alice", "display_name": "Алиса", "password": draft.Password})
|
||||
require.NoError(t, err)
|
||||
|
||||
result := fixture.do(t, http.MethodPost, "/api/v1/users", body, nil)
|
||||
require.Equal(t, http.StatusCreated, result.status)
|
||||
require.NotContains(t, string(result.body), "password")
|
||||
|
||||
var decoded map[string]any
|
||||
require.NoError(t, json.Unmarshal(result.body, &decoded))
|
||||
require.Equal(t, user.ID.String(), decoded["id"])
|
||||
require.Len(t, decoded, 4)
|
||||
}
|
||||
|
||||
func TestRegisterDuplicateUsernameConflicts(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
fixture.users.EXPECT().Register(mock.Anything, mock.Anything).Return(domain.User{}, domain.ErrUsernameTaken).Once()
|
||||
|
||||
body, err := json.Marshal(map[string]string{"username": "alice", "display_name": "Алиса", "password": "very-secret-password"})
|
||||
require.NoError(t, err)
|
||||
|
||||
result := fixture.do(t, http.MethodPost, "/api/v1/users", body, nil)
|
||||
require.Equal(t, http.StatusConflict, result.status)
|
||||
}
|
||||
|
||||
func TestCreateSessionFromBasicAuth(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
session := domain.Session{Token: "opaque-token", ExpiresAt: time.Now().UTC().Add(time.Hour), User: user}
|
||||
|
||||
fixture.sessions.EXPECT().Authenticate(mock.Anything, "alice", "very-secret-password").Return(user, nil).Once()
|
||||
fixture.sessions.EXPECT().Create(mock.Anything, user).Return(session, nil).Once()
|
||||
|
||||
result := fixture.do(t, http.MethodPost, "/api/v1/auth/sessions", nil, map[string]string{
|
||||
"Authorization": "Basic " + basic("alice", "very-secret-password"),
|
||||
})
|
||||
require.Equal(t, http.StatusCreated, result.status)
|
||||
|
||||
var body struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(result.body, &body))
|
||||
require.Equal(t, "opaque-token", body.Token)
|
||||
require.Equal(t, "Bearer", body.TokenType)
|
||||
}
|
||||
|
||||
func TestCreateSessionRejectsBadCredentials(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
fixture.sessions.EXPECT().Authenticate(mock.Anything, mock.Anything, mock.Anything).Return(domain.User{}, domain.ErrUnauthenticated).Once()
|
||||
|
||||
result := fixture.do(t, http.MethodPost, "/api/v1/auth/sessions", nil, map[string]string{
|
||||
"Authorization": "Basic " + basic("alice", "wrong-password-value"),
|
||||
})
|
||||
require.Equal(t, http.StatusUnauthorized, result.status)
|
||||
require.Contains(t, result.header.Get("WWW-Authenticate"), "Basic")
|
||||
}
|
||||
|
||||
func TestRevokeSession(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Once()
|
||||
fixture.sessions.EXPECT().Revoke(mock.Anything, user.ID, "opaque-token").Return(nil).Once()
|
||||
|
||||
result := fixture.do(t, http.MethodDelete, "/api/v1/auth/sessions/current", nil, map[string]string{"Authorization": "Bearer opaque-token"})
|
||||
require.Equal(t, http.StatusNoContent, result.status)
|
||||
require.Empty(t, result.body)
|
||||
}
|
||||
|
||||
func TestCursorRoundTrip(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
chatID := uuid.New()
|
||||
message := domain.Message{ID: uuid.New(), ChatID: chatID, SenderID: user.ID, Text: "первое", CreatedAt: time.Now().UTC()}
|
||||
|
||||
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
|
||||
fixture.messages.EXPECT().
|
||||
History(mock.Anything, user.ID, chatID, (*domain.Cursor)(nil), 1).
|
||||
Return(domain.Page[domain.Message]{
|
||||
Items: []domain.Message{message},
|
||||
Next: &domain.Cursor{Scope: chatID, CreatedAt: message.CreatedAt, ID: message.ID},
|
||||
}, nil).
|
||||
Once()
|
||||
|
||||
result := fixture.do(t, http.MethodGet, "/api/v1/chats/"+chatID.String()+"/messages?limit=1", nil, map[string]string{"Authorization": "Bearer opaque-token"})
|
||||
require.Equal(t, http.StatusOK, result.status)
|
||||
|
||||
var body struct {
|
||||
Items []json.RawMessage `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(result.body, &body))
|
||||
require.Len(t, body.Items, 1)
|
||||
require.NotNil(t, body.NextCursor)
|
||||
|
||||
fixture.messages.EXPECT().
|
||||
History(mock.Anything, user.ID, chatID, mock.Anything, 1).
|
||||
Return(domain.Page[domain.Message]{Items: []domain.Message{}}, nil).
|
||||
Once()
|
||||
|
||||
result = fixture.do(
|
||||
t,
|
||||
http.MethodGet,
|
||||
"/api/v1/chats/"+chatID.String()+"/messages?limit=1&cursor="+*body.NextCursor,
|
||||
nil,
|
||||
map[string]string{"Authorization": "Bearer opaque-token"},
|
||||
)
|
||||
require.Equal(t, http.StatusOK, result.status)
|
||||
}
|
||||
|
||||
func TestInvalidCursorIsRejected(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
fixture.sessions.EXPECT().Resolve(mock.Anything, mock.Anything).Return(user, nil).Maybe()
|
||||
|
||||
result := fixture.do(
|
||||
t,
|
||||
http.MethodGet,
|
||||
"/api/v1/chats/"+uuid.NewString()+"/messages?cursor=not-a-cursor",
|
||||
nil,
|
||||
map[string]string{"Authorization": "Bearer opaque-token"},
|
||||
)
|
||||
require.Equal(t, http.StatusBadRequest, result.status)
|
||||
}
|
||||
|
||||
func TestNotFoundAndMethodNotAllowed(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
result := fixture.do(t, http.MethodGet, "/nope", nil, nil)
|
||||
require.Equal(t, http.StatusNotFound, result.status)
|
||||
|
||||
result = fixture.do(t, http.MethodDelete, "/health/live", nil, nil)
|
||||
require.Equal(t, http.StatusMethodNotAllowed, result.status)
|
||||
}
|
||||
|
||||
func TestOversizedBodyIsRejectedWithPayloadTooLarge(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
// Тело больше лимита не читается и не декодируется: отказ приходит сразу,
|
||||
// до обращения к сервисам.
|
||||
body, err := json.Marshal(map[string]string{
|
||||
"username": "alice",
|
||||
"display_name": "Алиса",
|
||||
"password": strings.Repeat("x", testMaxBodyBytes+1),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
result := fixture.do(t, http.MethodPost, "/api/v1/users", body, nil)
|
||||
require.Equal(t, http.StatusRequestEntityTooLarge, result.status)
|
||||
require.NotEmpty(t, result.header.Get(instanceIDHeader), "ответ об ошибке тоже помечен репликой")
|
||||
require.NotEmpty(t, result.header.Get(requestIDHeader))
|
||||
|
||||
var decoded struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(result.body, &decoded))
|
||||
require.Equal(t, "payload_too_large", decoded.Error.Code)
|
||||
}
|
||||
|
||||
func TestCreateMessageRequiresIdempotencyKey(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
|
||||
|
||||
result := fixture.do(
|
||||
t,
|
||||
http.MethodPost,
|
||||
"/api/v1/chats/"+uuid.NewString()+"/messages",
|
||||
[]byte(`{"text":"привет"}`),
|
||||
map[string]string{"Authorization": "Bearer opaque-token"},
|
||||
)
|
||||
require.Equal(t, http.StatusBadRequest, result.status)
|
||||
require.NotEmpty(t, result.header.Get(instanceIDHeader), "ответ об ошибке тоже помечен репликой")
|
||||
}
|
||||
|
||||
func TestCreateMessageFingerprintIgnoresJSONFormatting(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
chatID := uuid.New()
|
||||
message := domain.Message{ID: uuid.New(), ChatID: chatID, SenderID: user.ID, Text: "привет", CreatedAt: time.Now().UTC()}
|
||||
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
|
||||
|
||||
var fingerprints [][sha256.Size]byte
|
||||
|
||||
fixture.messages.EXPECT().
|
||||
Send(mock.Anything, mock.MatchedBy(func(draft domain.MessageDraft) bool {
|
||||
if draft.ChatID != chatID || draft.SenderID != user.ID || draft.Idempotency.Key != "key-1" {
|
||||
return false
|
||||
}
|
||||
|
||||
fingerprints = append(fingerprints, draft.Idempotency.RequestHash)
|
||||
|
||||
return true
|
||||
})).
|
||||
Return(message, nil)
|
||||
|
||||
headers := map[string]string{"Authorization": "Bearer opaque-token", "Idempotency-Key": "key-1"}
|
||||
path := "/api/v1/chats/" + chatID.String() + "/messages"
|
||||
|
||||
first := fixture.do(t, http.MethodPost, path, []byte(`{"text":"привет"}`), headers)
|
||||
replay := fixture.do(t, http.MethodPost, path, []byte(`{ "text" : "привет" }`), headers)
|
||||
other := fixture.do(t, http.MethodPost, path, []byte(`{"text":"другое"}`), headers)
|
||||
|
||||
require.Equal(t, http.StatusCreated, first.status)
|
||||
require.Equal(t, http.StatusCreated, replay.status)
|
||||
require.Equal(t, http.StatusCreated, other.status)
|
||||
require.NotEmpty(t, first.header.Get(instanceIDHeader))
|
||||
require.Len(t, fingerprints, 3)
|
||||
require.Equal(t, fingerprints[0], fingerprints[1],
|
||||
"порядок ключей и пробелы в JSON не меняют отпечаток payload")
|
||||
require.NotEqual(t, fingerprints[0], fingerprints[2],
|
||||
"другой payload с тем же ключом — это конфликт, отпечатки обязаны различаться")
|
||||
}
|
||||
|
||||
func TestCreateMessageReplayConflictIsReportedAsConflict(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
|
||||
fixture.messages.EXPECT().
|
||||
Send(mock.Anything, mock.Anything).
|
||||
Return(domain.Message{}, domain.ErrIdempotency).
|
||||
Once()
|
||||
|
||||
result := fixture.do(
|
||||
t,
|
||||
http.MethodPost,
|
||||
"/api/v1/chats/"+uuid.NewString()+"/messages",
|
||||
[]byte(`{"text":"другой"}`),
|
||||
map[string]string{"Authorization": "Bearer opaque-token", "Idempotency-Key": "key-1"},
|
||||
)
|
||||
require.Equal(t, http.StatusConflict, result.status)
|
||||
|
||||
var body struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(result.body, &body))
|
||||
require.Equal(t, "conflict", body.Error.Code)
|
||||
}
|
||||
|
||||
func TestEveryResponseCarriesInstanceID(t *testing.T) {
|
||||
fixture := newRouterFixture(t)
|
||||
|
||||
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
|
||||
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
|
||||
|
||||
tests := map[string]httpResult{
|
||||
"успешный ответ": fixture.do(t, http.MethodGet, "/health/live", nil, nil),
|
||||
"неизвестный маршрут": fixture.do(t, http.MethodGet, "/nope", nil, nil),
|
||||
"неподдерживаемый метод": fixture.do(t, http.MethodDelete, "/health/live", nil, nil),
|
||||
"ошибка валидации схемы": fixture.do(
|
||||
t,
|
||||
http.MethodPost,
|
||||
"/api/v1/chats/"+uuid.NewString()+"/messages",
|
||||
[]byte(`{"text":"привет"}`),
|
||||
map[string]string{"Authorization": "Bearer opaque-token"},
|
||||
),
|
||||
}
|
||||
|
||||
for name, result := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
require.NotEmpty(t, result.header.Get(instanceIDHeader))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
var ErrUnauthenticated = errors.New("caller is not identified")
|
||||
|
||||
type (
|
||||
callerKey struct{}
|
||||
tokenKey struct{}
|
||||
credentialsKey struct{}
|
||||
)
|
||||
|
||||
func CallerFromContext(ctx context.Context) (uuid.UUID, bool) {
|
||||
id, ok := ctx.Value(callerKey{}).(uuid.UUID)
|
||||
return id, ok
|
||||
}
|
||||
|
||||
func caller(ctx context.Context) uuid.UUID {
|
||||
id, _ := CallerFromContext(ctx)
|
||||
return id
|
||||
}
|
||||
|
||||
type SecSessionService interface {
|
||||
Authenticate(ctx context.Context, username, password string) (domain.User, error)
|
||||
Resolve(ctx context.Context, token string) (domain.User, error)
|
||||
}
|
||||
|
||||
type SecurityHandler struct {
|
||||
sessions SecSessionService
|
||||
}
|
||||
|
||||
func NewSecurityHandler(sessions SecSessionService) *SecurityHandler {
|
||||
return &SecurityHandler{sessions: sessions}
|
||||
}
|
||||
|
||||
func (h *SecurityHandler) HandleBasicAuth(ctx context.Context, _ oas.OperationName, auth oas.BasicAuth) (context.Context, error) {
|
||||
user, err := h.sessions.Authenticate(ctx, auth.Username, auth.Password)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
ctx = context.WithValue(ctx, callerKey{}, user.ID)
|
||||
return context.WithValue(ctx, credentialsKey{}, user), nil
|
||||
}
|
||||
|
||||
func (h *SecurityHandler) HandleBearerAuth(ctx context.Context, _ oas.OperationName, auth oas.BearerAuth) (context.Context, error) {
|
||||
user, err := h.sessions.Resolve(ctx, auth.Token)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
ctx = context.WithValue(ctx, callerKey{}, user.ID)
|
||||
return context.WithValue(ctx, tokenKey{}, auth.Token), nil
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi-messenger/internal/telemetry"
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
// telemetryMiddleware is the single source of HTTP spans, metrics and access
|
||||
// logs. It resolves the OpenAPI template before the span is started: the
|
||||
// generated ogen router does not set http.Request.Pattern for its routes.
|
||||
func telemetryMiddleware(log *slog.Logger, server *oas.Server, mux *http.ServeMux, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
route, operation := resolveRoute(server, mux, r)
|
||||
if strings.HasPrefix(route, "/health/") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
||||
method := normalizeMethod(r.Method)
|
||||
started := time.Now()
|
||||
ctx, span := otel.Tracer("messenger/http").Start(ctx, method+" "+route,
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("http.request.method", method),
|
||||
attribute.String("http.route", route),
|
||||
),
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
writer := &statusWriter{ResponseWriter: w}
|
||||
next.ServeHTTP(writer, r.WithContext(ctx))
|
||||
|
||||
status := writer.statusCode()
|
||||
span.SetAttributes(attribute.Int("http.response.status_code", status))
|
||||
if status >= http.StatusInternalServerError {
|
||||
span.SetStatus(codes.Error, http.StatusText(status))
|
||||
}
|
||||
telemetry.RecordHTTP(ctx, method, route, status, time.Since(started))
|
||||
|
||||
attrs := []any{
|
||||
slog.String("event", "http.request.completed"),
|
||||
slog.String("operation", operation),
|
||||
slog.String("route", route),
|
||||
slog.String("method", method),
|
||||
slog.Int("status", status),
|
||||
slog.Duration("duration", time.Since(started)),
|
||||
slog.String("request_id", requestIDFromContext(ctx)),
|
||||
}
|
||||
level := slog.LevelInfo
|
||||
if status >= http.StatusInternalServerError {
|
||||
level = slog.LevelError
|
||||
} else if status >= http.StatusBadRequest {
|
||||
level = slog.LevelWarn
|
||||
}
|
||||
log.Log(ctx, level, "http.request.completed", attrs...)
|
||||
})
|
||||
}
|
||||
|
||||
// normalizeMethod keeps the metric/span label set low-cardinality. Any method
|
||||
// outside the standard set is deliberately collapsed to OTHER.
|
||||
func normalizeMethod(method string) string {
|
||||
switch method {
|
||||
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead, http.MethodOptions:
|
||||
return method
|
||||
default:
|
||||
return "OTHER"
|
||||
}
|
||||
}
|
||||
|
||||
func resolveRoute(server *oas.Server, mux *http.ServeMux, r *http.Request) (route, operation string) {
|
||||
if route, ok := server.FindPath(r.Method, r.URL); ok {
|
||||
return route.PathPattern(), route.OperationID()
|
||||
}
|
||||
if _, pattern := mux.Handler(r); pattern != "" && pattern != "/" {
|
||||
return pattern, ""
|
||||
}
|
||||
return "unmatched", ""
|
||||
}
|
||||
Reference in New Issue
Block a user