Реализация на 5

This commit is contained in:
Grbisba
2026-11-17 13:08:13 +03:00
parent 470d9d6f1e
commit 60f48c0337
229 changed files with 74928 additions and 47 deletions
@@ -0,0 +1,257 @@
package framework
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"mime"
"net/http"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
v10 "github.com/go-playground/validator/v10"
"github.com/google/uuid"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/headers"
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
)
func validate(ctx context.Context, v *validator.ValidatorImpl, value any) error {
err := v.ValidateCtx(ctx, value)
if err == nil {
return nil
}
var fieldErrors v10.ValidationErrors
if errors.As(err, &fieldErrors) {
return apperr.Wrap(err, apperr.CodeValidation, "invalid request fields")
}
return apperr.Wrap(err, apperr.CodeInternal, "validation failed")
}
func Validate(w http.ResponseWriter, r *http.Request, v *validator.ValidatorImpl, value any) bool {
if err := validate(r.Context(), v, value); err != nil {
JSONError(r.Context(), w, err)
return false
}
return true
}
func JSONResponse(w http.ResponseWriter, status int, body any) {
w.Header().Set(headers.HeaderContentType, "application/json")
w.WriteHeader(status)
if status == http.StatusNoContent {
return
}
if err := json.NewEncoder(w).Encode(body); err != nil {
wrapped := apperr.Wrap(err, apperr.CodeInternal, "failed json encode")
slog.Error("response", "error", wrapped)
}
}
func JSONError(ctx context.Context, w http.ResponseWriter, err error) {
if err == nil {
return
}
requestId, ok := ctx.Value(headers.HeaderRequestID).(uuid.UUID)
if !ok {
requestId = uuid.New()
}
w.Header().Set(headers.HeaderRequestID, requestId.String())
if errors.Is(err, context.DeadlineExceeded) {
err = apperr.Wrap(err, apperr.CodeServiceUnavailable, "request deadline exceeded")
}
appErr := apperr.As(err)
if appErr == nil {
appErr = apperr.As(apperr.New(apperr.CodeInternal, "internal server error"))
}
if appErr.Code().HTTPStatus() == http.StatusUnauthorized && w.Header().Get("WWW-Authenticate") == "" {
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
}
slog.ErrorContext(ctx, "http_error", "error_code", appErr.Code().String(), "status", appErr.Code().HTTPStatus(), "request_id", requestId.String())
var code contracts.ErrorErrorCode
switch appErr.Code() {
case apperr.CodeBadRequest, apperr.CodeValidation:
code = contracts.InvalidRequest
case apperr.CodeUnauthorized:
code = contracts.Unauthorized
case apperr.CodeNotFound:
code = contracts.NotFound
case apperr.CodeAlreadyExists, apperr.CodeConflict:
code = contracts.Conflict
case apperr.CodePayloadTooLarge:
code = contracts.PayloadTooLarge
case apperr.CodeTooManyRequests:
code = contracts.RateLimited
case apperr.CodeServiceUnavailable, apperr.CodeUnavailable:
code = contracts.Unavailable
case apperr.CodeUnsupportedMediaType:
code = contracts.UnsupportedMediaType
default:
code = contracts.InternalError
}
JSONResponse(w, appErr.Code().HTTPStatus(), contracts.Error{
Error: struct {
Code contracts.ErrorErrorCode `json:"code"`
Message string `json:"message"`
RequestId string `json:"request_id"`
}{
Code: code,
Message: appErr.Message(),
RequestId: requestId.String(),
},
})
}
func Decode(w http.ResponseWriter, r *http.Request, object any) bool {
mediaType, params, err := mime.ParseMediaType(r.Header.Get(headers.HeaderContentType))
if err != nil || mediaType != "application/json" ||
(params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
JSONError(r.Context(), w, apperr.New(apperr.CodeUnsupportedMediaType, "expected application/json"))
return false
}
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(object); err != nil {
JSONError(r.Context(), w, apperr.Wrap(err, apperr.CodeBadRequest, "failed decode"))
return false
}
var trailing any
if err := decoder.Decode(&trailing); err != io.EOF {
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "expected one JSON object"))
return false
}
return true
}
func PathParam(r *http.Request, key string) string {
return chi.URLParam(r, key)
}
func QueryParam(r *http.Request, key string) string {
return r.URL.Query().Get(key)
}
func HeaderParam(r *http.Request, key string) string {
return r.Header.Get(key)
}
func ParseIDFromPathParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
rawID := PathParam(r, key)
id, err := uuid.Parse(rawID)
if err != nil {
JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
return uuid.Nil, err
}
return id, nil
}
func ParseIDFromQueryParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
rawID := QueryParam(r, key)
id, err := uuid.Parse(rawID)
if err != nil {
JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
return uuid.Nil, err
}
return id, nil
}
func ParseIDFromHeaderParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
rawID := HeaderParam(r, key)
id, err := uuid.Parse(rawID)
if err != nil {
JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing or invalid user ID"))
return uuid.Nil, err
}
return id, nil
}
func Header(r *http.Request, header string) (string, bool) {
return r.Header.Get(header), r.Header.Get(header) != ""
}
func Token(r *http.Request) (string, bool) {
foundHeader := r.Header.Get(headers.HeaderAuthorization)
if foundHeader == "" {
return "", false
}
token, found := strings.CutPrefix(foundHeader, "Bearer ")
if !found {
return "", false
}
return token, true
}
type sessionContextKey struct{}
func WithVerifiedSession(r *http.Request, data *dto.UserDataInToken) *http.Request {
return r.WithContext(context.WithValue(r.Context(), sessionContextKey{}, *data))
}
func ParseToken(r *http.Request, provider jwtprovider.Provider) (*dto.UserDataInToken, error) {
if data, ok := r.Context().Value(sessionContextKey{}).(dto.UserDataInToken); ok {
return &data, nil
}
foundHeader := r.Header.Get(headers.HeaderAuthorization)
if foundHeader == "" {
return nil, apperr.New(apperr.CodeUnauthorized, "missing authorization header")
}
token, found := strings.CutPrefix(foundHeader, "Bearer ")
if !found {
return nil, apperr.New(apperr.CodeUnauthorized, "invalid authorization header")
}
userData, err := provider.ParseVerified(&dto.Token{Payload: token})
if err != nil {
return nil, apperr.Wrap(err, apperr.CodeUnauthorized, "invalid token")
}
return userData, nil
}
func PageParams(w http.ResponseWriter, r *http.Request) (*int, *uuid.UUID, bool) {
query := r.URL.Query()
var limit *int
if values, exists := query["limit"]; exists {
if len(values) != 1 {
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid limit"))
return nil, nil, false
}
value, err := strconv.Atoi(values[0])
if err != nil || value < 1 || value > 100 {
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid limit"))
return nil, nil, false
}
limit = &value
}
var afterID *uuid.UUID
if values, exists := query["cursor"]; exists {
if len(values) != 1 {
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid cursor"))
return nil, nil, false
}
id, err := uuid.Parse(values[0])
if err != nil || id == uuid.Nil {
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid cursor"))
return nil, nil, false
}
afterID = &id
}
return limit, afterID, true
}
@@ -0,0 +1,8 @@
package headers
const (
HeaderContentType = "Content-Type"
HeaderRequestID = "X-Request-Id"
HeaderUserID = "X-User-Id"
HeaderAuthorization = "Authorization"
)
@@ -0,0 +1,75 @@
package middleware
import (
"context"
"net/http"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
)
var _ AuthMiddleware = (*authMiddleware)(nil)
type AuthMiddleware interface {
WithPrivateAccess(next http.Handler) http.Handler
WithAdminAccess(next http.Handler) http.Handler
}
type SessionVerifier interface {
VerifySession(ctx context.Context, token dto.Token) (*dto.UserDataInToken, error)
}
type authMiddleware struct {
verifier SessionVerifier
}
func NewAuthMiddleware(verifier SessionVerifier) AuthMiddleware {
return &authMiddleware{verifier: verifier}
}
func (a *authMiddleware) WithPrivateAccess(next http.Handler) http.Handler {
return a.privateAccessCheckCallback(next)
}
func (a *authMiddleware) WithAdminAccess(next http.Handler) http.Handler {
return a.operatorAccessCheckCallback(role.Admin, next)
}
func (a *authMiddleware) privateAccessCheckCallback(next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data, err := a.verifySession(r)
if err != nil {
framework.JSONError(r.Context(), w, err)
return
}
next.ServeHTTP(w, framework.WithVerifiedSession(r, data))
}
}
func (a *authMiddleware) operatorAccessCheckCallback(expectedRole role.Role, next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
u, err := a.verifySession(r)
if err != nil {
framework.JSONError(r.Context(), w, err)
return
}
if u.Role != role.Admin && u.Role != expectedRole {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeForbidden, "insufficient permissions"))
return
}
next.ServeHTTP(w, framework.WithVerifiedSession(r, u))
}
}
func (a *authMiddleware) verifySession(r *http.Request) (*dto.UserDataInToken, error) {
token, found := framework.Token(r)
if !found || token == "" {
return nil, apperr.New(apperr.CodeUnauthorized, "missing or invalid bearer token")
}
return a.verifier.VerifySession(r.Context(), dto.Token{Payload: token})
}
@@ -0,0 +1,73 @@
package middleware
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
"github.com/google/uuid"
)
type sessionVerifier struct {
calls int
data dto.UserDataInToken
err error
}
func (v *sessionVerifier) VerifySession(context.Context, dto.Token) (*dto.UserDataInToken, error) {
v.calls++
return &v.data, v.err
}
func TestVerifiedSessionIsRequestScoped(t *testing.T) {
verifier := &sessionVerifier{data: dto.UserDataInToken{UserID: uuid.New()}}
middleware := NewAuthMiddleware(verifier)
handled := 0
handler := middleware.WithPrivateAccess(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// A nil provider is intentional: the handler must use the verified request identity.
data, err := framework.ParseToken(r, nil)
if err != nil {
t.Fatal(err)
}
if data.UserID != verifier.data.UserID {
t.Fatal("verified identity changed")
}
handled++
w.WriteHeader(http.StatusNoContent)
}))
for range 2 {
request := httptest.NewRequest("GET", "/private", nil)
request.Header.Set("Authorization", "Bearer synthetic-token")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != 204 {
t.Fatal(recorder.Code)
}
}
if verifier.calls != 2 || handled != 2 {
t.Fatal("session verification must run for every request")
}
verifier.err = apperr.New(apperr.CodeUnauthorized, "revoked session")
request := httptest.NewRequest("GET", "/private", nil)
request.Header.Set("Authorization", "Bearer synthetic-token")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != 401 || handled != 2 {
t.Fatal("revocation was bypassed by cached request identity")
}
}
func TestMissingTokenDoesNotCallSessionStore(t *testing.T) {
verifier := &sessionVerifier{err: errors.New("must not be called")}
handler := NewAuthMiddleware(verifier).WithPrivateAccess(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Fatal("handler called without a token") }))
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest("GET", "/private", nil))
if recorder.Code != 401 || verifier.calls != 0 {
t.Fatal("missing token was accepted")
}
}
@@ -0,0 +1,12 @@
package middleware
import "net/http"
func Instance(id string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Instance-Id", id)
next.ServeHTTP(w, r)
})
}
}
@@ -0,0 +1,34 @@
package middleware
import (
"log/slog"
"net/http"
"time"
"github.com/go-chi/chi/v5/middleware"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/headers"
)
func LoggingMiddleware() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started := time.Now()
wrapped := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(wrapped, r)
status := wrapped.Status()
if status == 0 {
status = http.StatusOK
}
slog.InfoContext(r.Context(), "http request",
"method", r.Method,
"path", r.URL.Path,
"status", status,
"duration", time.Since(started),
"bytes", wrapped.BytesWritten(),
"request_id", w.Header().Get(headers.HeaderRequestID),
)
})
}
}
@@ -0,0 +1,5 @@
package middleware
import "net/http"
type Middleware = func(http.Handler) http.Handler
@@ -0,0 +1,22 @@
package middleware
import (
"context"
"net/http"
"github.com/google/uuid"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/headers"
)
func RequestIDMiddleware() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
requestID := uuid.New()
w.Header().Set(headers.HeaderRequestID, requestID.String())
ctx = context.WithValue(ctx, headers.HeaderRequestID, requestID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
@@ -0,0 +1,23 @@
package middleware
import (
"context"
"net/http"
"strings"
"time"
)
// RequestTimeout bounds database work and waiting for a pooled connection.
func RequestTimeout(timeout time.Duration, attachmentTimeout ...time.Duration) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestTimeout := timeout
if len(attachmentTimeout) > 0 && strings.Contains(r.URL.Path, "/attachments") {
requestTimeout = attachmentTimeout[0]
}
ctx, cancel := context.WithTimeout(r.Context(), requestTimeout)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
+135
View File
@@ -0,0 +1,135 @@
package router
import (
"gitea.privcloud.tech/mtusi2026/internal/pkg/telemetry"
"net/http"
"github.com/go-chi/chi/v5"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/middleware"
)
type Router interface {
Private(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler)
Public(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler)
Admin(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler)
ServeHTTP(w http.ResponseWriter, r *http.Request)
With(mw ...func(http.Handler) http.Handler) Router
Use(mw ...func(http.Handler) http.Handler) Router
Handle(pattern string, handler http.Handler)
Get(pattern string, handler http.HandlerFunc)
Head(pattern string, handler http.HandlerFunc)
Options(pattern string, handler http.HandlerFunc)
Post(pattern string, handler http.HandlerFunc)
Put(pattern string, handler http.HandlerFunc)
Patch(pattern string, handler http.HandlerFunc)
Delete(pattern string, handler http.HandlerFunc)
Connect(pattern string, handler http.HandlerFunc)
Trace(pattern string, handler http.HandlerFunc)
}
type router struct {
r chi.Router
jwtMw middleware.AuthMiddleware
}
func New(jwtMw middleware.AuthMiddleware, mw ...middleware.Middleware) Router {
r := chi.NewRouter()
r.Use(mw...)
return &router{
r: r,
jwtMw: jwtMw,
}
}
func (c *router) Group(pattern string) Router {
sub := &router{
r: chi.NewRouter(),
jwtMw: c.jwtMw,
}
c.r.Mount(pattern, sub.r)
return sub
}
func (c *router) Public(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
telemetry.RegisterRoute(method, pattern)
next := c.applyMiddlewares(handler, mw...)
c.r.MethodFunc(method, pattern, next.ServeHTTP)
}
func (c *router) Private(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
telemetry.RegisterRoute(method, pattern)
next := c.applyMiddlewares(handler, mw...)
c.r.MethodFunc(method, pattern, (c.jwtMw.WithPrivateAccess(next)).ServeHTTP)
}
func (c *router) Admin(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
telemetry.RegisterRoute(method, pattern)
next := c.applyMiddlewares(handler, mw...)
c.r.MethodFunc(method, pattern, (c.jwtMw.WithAdminAccess(next)).ServeHTTP)
}
func (c *router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c.r.ServeHTTP(w, r)
}
func (c *router) With(mw ...func(http.Handler) http.Handler) Router {
sub := &router{
r: c.r.With(mw...),
jwtMw: c.jwtMw,
}
return sub
}
func (c *router) Use(mw ...func(http.Handler) http.Handler) Router {
c.r.Use(mw...)
return c
}
func (c *router) Handle(pattern string, handler http.Handler) {
c.r.Handle(pattern, handler)
}
func (c *router) Get(pattern string, handler http.HandlerFunc) {
c.r.Get(pattern, handler)
}
func (c *router) Head(pattern string, handler http.HandlerFunc) {
c.r.Head(pattern, handler)
}
func (c *router) Options(pattern string, handler http.HandlerFunc) {
c.r.Options(pattern, handler)
}
func (c *router) Post(pattern string, handler http.HandlerFunc) {
c.r.Post(pattern, handler)
}
func (c *router) Put(pattern string, handler http.HandlerFunc) {
c.r.Put(pattern, handler)
}
func (c *router) Patch(pattern string, handler http.HandlerFunc) {
c.r.Patch(pattern, handler)
}
func (c *router) Delete(pattern string, handler http.HandlerFunc) {
c.r.Delete(pattern, handler)
}
func (c *router) Connect(pattern string, handler http.HandlerFunc) {
c.r.Connect(pattern, handler)
}
func (c *router) Trace(pattern string, handler http.HandlerFunc) {
c.r.Trace(pattern, handler)
}
func (c *router) applyMiddlewares(handler http.HandlerFunc, mw ...func(http.Handler) http.Handler) http.Handler {
next := http.Handler(handler)
for _, mwFunc := range mw {
next = mwFunc(next)
}
return next
}