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

This commit is contained in:
Grbisba
2026-11-05 14:24:40 +03:00
parent 20f2f00a60
commit 8d44c74535
85 changed files with 3601 additions and 1109 deletions
+274
View File
@@ -0,0 +1,274 @@
package apperr
import (
"errors"
"net/http"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
grpcCodes "google.golang.org/grpc/codes"
)
//go:generate stringer -type=Code -linecomment
type Code uint16
const (
// CodeBadRequest = {AppError: BAD_REQUEST, HTTP:400}
CodeBadRequest Code = iota
// CodePayloadTooLarge = {AppError: REQUEST_ENTITY_TOO_LARGE, HTTP:413}
CodePayloadTooLarge
// CodeValidation = {AppError: VALIDATION, HTTP:422}
CodeValidation
// CodeUnauthorized = {AppError: UNAUTHORIZED, HTTP:401}
CodeUnauthorized
// CodeForbidden = {AppError: FORBIDDEN, HTTP:403}
CodeForbidden
// CodeNotFound = {AppError: NOT_FOUND, HTTP:404}
CodeNotFound
// CodeAlreadyExists = {AppError: ALREADY_EXISTS, HTTP:409}
CodeAlreadyExists
// CodeConflict = {AppError: CONFLICT, HTTP:409}
CodeConflict
// CodeTooManyRequests = {AppError: TOO_MANY_REQUESTS, HTTP:429}
CodeTooManyRequests
// CodeTimeout = {AppError: TIMEOUT, HTTP:504}
CodeTimeout
// CodeInternal = {AppError: INTERNAL, HTTP:500}
CodeInternal
// CodeServiceUnavailable = {AppError: SERVICE_UNAVAILABLE, HTTP:503}
CodeServiceUnavailable
// CodeOK = {AppError: OK, HTTP:200}
CodeOK
// CodeLocked = {AppError: LOCKED, HTTP:423}
CodeLocked
// CodeUnsupportedMediaType = {AppError: UNSUPPORTED_MEDIA_TYPE, HTTP:415}
CodeUnsupportedMediaType
// CodeUnavailable = {AppError: SERVICE_UNAVAILABLE, HTTP: 503}
CodeUnavailable
)
func (c Code) HTTPStatus() int {
if status, ok := httpStatusByCode[c]; ok {
return status
}
return http.StatusInternalServerError
}
func (c Code) GRPCCode() grpcCodes.Code {
if code, ok := grpcCodeByCode[c]; ok {
return code
}
return grpcCodes.Internal
}
func (c Code) PostgresCodes() []string {
codes := postgresCodesByCode[c]
if len(codes) == 0 {
return nil
}
cp := make([]string, len(codes))
copy(cp, codes)
return cp
}
func (c Code) PostgresCode() string {
codes := c.PostgresCodes()
if len(codes) == 0 {
return ""
}
return codes[0]
}
func CodeFromError(err error) Code {
if err == nil {
return CodeInternal
}
var coded interface {
Code() Code
}
if errors.As(err, &coded) {
return coded.Code()
}
if code, ok := codeFromRedisError(err, false, false); ok {
return code
}
return CodeFromPostgresError(err)
}
func HTTPStatusFromError(err error) int {
return CodeFromError(err).HTTPStatus()
}
func GRPCCodeFromError(err error) grpcCodes.Code {
return CodeFromError(err).GRPCCode()
}
func CodeFromHTTPStatus(status int) Code {
if code, ok := codeByHTTPStatus[status]; ok {
return code
}
return CodeInternal
}
func CodeFromGRPC(code grpcCodes.Code) Code {
if appCode, ok := codeByGRPCCode[code]; ok {
return appCode
}
return CodeInternal
}
func CodeFromPostgres(pgCode string) Code {
if code, ok := codeByPostgresCode[pgCode]; ok {
return code
}
return CodeInternal
}
func CodeFromPostgresError(err error) Code {
if err == nil {
return CodeInternal
}
if code, ok := codeByPgxError[err]; ok {
return code
}
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
return CodeFromPostgres(pgErr.Code)
}
return CodeInternal
}
var (
httpStatusByCode = map[Code]int{
CodeBadRequest: http.StatusBadRequest,
CodeUnauthorized: http.StatusUnauthorized,
CodeForbidden: http.StatusForbidden,
CodeNotFound: http.StatusNotFound,
CodeAlreadyExists: http.StatusConflict,
CodeConflict: http.StatusConflict,
CodePayloadTooLarge: http.StatusRequestEntityTooLarge,
CodeTooManyRequests: http.StatusTooManyRequests,
CodeValidation: http.StatusUnprocessableEntity,
CodeTimeout: http.StatusGatewayTimeout,
CodeInternal: http.StatusInternalServerError,
CodeServiceUnavailable: http.StatusServiceUnavailable,
CodeUnsupportedMediaType: http.StatusUnsupportedMediaType,
CodeUnavailable: http.StatusServiceUnavailable,
CodeOK: http.StatusOK,
CodeLocked: http.StatusLocked,
}
codeByHTTPStatus = map[int]Code{
http.StatusBadRequest: CodeBadRequest,
http.StatusUnauthorized: CodeUnauthorized,
http.StatusForbidden: CodeForbidden,
http.StatusNotFound: CodeNotFound,
http.StatusConflict: CodeConflict,
http.StatusRequestEntityTooLarge: CodePayloadTooLarge,
http.StatusTooManyRequests: CodeTooManyRequests,
http.StatusUnprocessableEntity: CodeValidation,
http.StatusGatewayTimeout: CodeTimeout,
http.StatusInternalServerError: CodeInternal,
http.StatusServiceUnavailable: CodeServiceUnavailable,
http.StatusOK: CodeOK,
http.StatusLocked: CodeLocked,
http.StatusUnsupportedMediaType: CodeUnavailable,
}
grpcCodeByCode = map[Code]grpcCodes.Code{
CodeBadRequest: grpcCodes.InvalidArgument,
CodePayloadTooLarge: grpcCodes.ResourceExhausted,
CodeValidation: grpcCodes.InvalidArgument,
CodeUnauthorized: grpcCodes.Unauthenticated,
CodeForbidden: grpcCodes.PermissionDenied,
CodeNotFound: grpcCodes.NotFound,
CodeAlreadyExists: grpcCodes.AlreadyExists,
CodeConflict: grpcCodes.Aborted,
CodeTooManyRequests: grpcCodes.ResourceExhausted,
CodeTimeout: grpcCodes.DeadlineExceeded,
CodeInternal: grpcCodes.Internal,
CodeServiceUnavailable: grpcCodes.Unavailable,
CodeOK: grpcCodes.OK,
CodeLocked: grpcCodes.FailedPrecondition,
}
codeByGRPCCode = map[grpcCodes.Code]Code{
grpcCodes.InvalidArgument: CodeBadRequest,
grpcCodes.ResourceExhausted: CodeTooManyRequests,
grpcCodes.Unauthenticated: CodeUnauthorized,
grpcCodes.PermissionDenied: CodeForbidden,
grpcCodes.NotFound: CodeNotFound,
grpcCodes.AlreadyExists: CodeAlreadyExists,
grpcCodes.Aborted: CodeConflict,
grpcCodes.FailedPrecondition: CodeLocked,
grpcCodes.DeadlineExceeded: CodeTimeout,
grpcCodes.Internal: CodeInternal,
grpcCodes.Unimplemented: CodeInternal,
grpcCodes.Unavailable: CodeServiceUnavailable,
grpcCodes.OK: CodeOK,
}
postgresCodesByCode = map[Code][]string{
CodeBadRequest: {
pgerrcode.InvalidTextRepresentation,
pgerrcode.InvalidParameterValue,
},
CodeValidation: {
pgerrcode.NotNullViolation,
pgerrcode.CheckViolation,
pgerrcode.StringDataRightTruncationDataException,
pgerrcode.NumericValueOutOfRange,
},
CodeNotFound: {
pgerrcode.ForeignKeyViolation,
},
CodeAlreadyExists: {
pgerrcode.UniqueViolation,
},
CodeConflict: {
pgerrcode.ExclusionViolation,
pgerrcode.SerializationFailure,
pgerrcode.DeadlockDetected,
},
CodeLocked: {
pgerrcode.LockNotAvailable,
pgerrcode.ObjectInUse,
},
CodeTooManyRequests: {
pgerrcode.TooManyConnections,
},
CodeTimeout: {
pgerrcode.QueryCanceled,
},
CodeInternal: {
pgerrcode.ConnectionException,
pgerrcode.ConnectionFailure,
pgerrcode.SQLClientUnableToEstablishSQLConnection,
pgerrcode.SQLServerRejectedEstablishmentOfSQLConnection,
pgerrcode.TransactionResolutionUnknown,
},
CodeServiceUnavailable: {
pgerrcode.CannotConnectNow,
},
}
codeByPostgresCode = buildCodeByPostgresCode(postgresCodesByCode)
codeByPgxError = map[error]Code{
pgx.ErrNoRows: CodeNotFound,
pgx.ErrTxClosed: CodeInternal,
pgx.ErrTxCommitRollback: CodeConflict,
pgx.ErrTooManyRows: CodeInternal,
}
)
func buildCodeByPostgresCode(src map[Code][]string) map[string]Code {
dst := make(map[string]Code, len(src))
for code, pgCodes := range src {
for _, pgCode := range pgCodes {
dst[pgCode] = code
}
}
return dst
}
@@ -0,0 +1,37 @@
// Code generated by "stringer -type=Code -linecomment"; DO NOT EDIT.
package apperr
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[CodeBadRequest-0]
_ = x[CodePayloadTooLarge-1]
_ = x[CodeValidation-2]
_ = x[CodeUnauthorized-3]
_ = x[CodeForbidden-4]
_ = x[CodeNotFound-5]
_ = x[CodeAlreadyExists-6]
_ = x[CodeConflict-7]
_ = x[CodeTooManyRequests-8]
_ = x[CodeTimeout-9]
_ = x[CodeInternal-10]
_ = x[CodeServiceUnavailable-11]
_ = x[CodeOK-12]
_ = x[CodeLocked-13]
}
const _Code_name = "CodeBadRequestCodePayloadTooLargeCodeValidationCodeUnauthorizedCodeForbiddenCodeNotFoundCodeAlreadyExistsCodeConflictCodeTooManyRequestsCodeTimeoutCodeInternalCodeServiceUnavailableCodeOKCodeLocked"
var _Code_index = [...]uint8{0, 14, 33, 47, 63, 76, 88, 105, 117, 136, 147, 159, 181, 187, 197}
func (i Code) String() string {
idx := int(i) - 0
if i < 0 || idx >= len(_Code_index)-1 {
return "Code(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Code_name[_Code_index[idx]:_Code_index[idx+1]]
}
+81 -80
View File
@@ -2,90 +2,96 @@ package apperr
import (
"errors"
"net/http"
"fmt"
grpcCodes "google.golang.org/grpc/codes"
)
// Code is the machine-readable error code used by the API contract.
type Code string
const (
CodeInvalidRequest Code = "invalid_request"
CodeUnauthorized Code = "unauthorized"
CodeNotFound Code = "not_found"
CodeConflict Code = "conflict"
CodePayloadTooLarge Code = "payload_too_large"
CodeUnsupportedMediaType Code = "unsupported_media_type"
CodeRateLimited Code = "rate_limited"
CodeUnavailable Code = "unavailable"
CodeInternalError Code = "internal_error"
CodeValidation Code = CodeInvalidRequest
CodeBadRequest Code = CodeInvalidRequest
CodeInternal Code = CodeInternalError
)
func (c Code) HTTPStatus() int {
switch c {
case CodeInvalidRequest:
return http.StatusBadRequest
case CodeUnauthorized:
return http.StatusUnauthorized
case CodeNotFound:
return http.StatusNotFound
case CodeConflict:
return http.StatusConflict
case CodePayloadTooLarge:
return http.StatusRequestEntityTooLarge
case CodeUnsupportedMediaType:
return http.StatusUnsupportedMediaType
case CodeRateLimited:
return http.StatusTooManyRequests
case CodeUnavailable:
return http.StatusServiceUnavailable
default:
return http.StatusInternalServerError
}
}
// AppError adds a public message and API code to an optional underlying error.
type AppError struct {
code Code
message string
cause error
err error
msg string
code Code
meta metadata
}
func New(code Code, message string) *AppError {
return &AppError{code: code, message: message}
}
// Wrap returns nil for a nil cause.
func Wrap(err error, code Code, message string) error {
if err == nil {
return nil
func New(code Code, msg string) error {
return &AppError{
msg: msg,
code: code,
meta: metadata{},
}
return &AppError{code: code, message: message, cause: err}
}
func Wrap(err error, code Code, msg string) error {
m := AppError{
err: err,
msg: msg,
code: code,
meta: metadata{},
}
return &m
}
func WrapAppError(err error, msg string) error {
m := AppError{
err: err,
msg: msg,
code: CodeInternal,
meta: metadata{},
}
if mistake := As(err); mistake != nil {
m.err = mistake
m.code = mistake.code
m.meta = mistake.meta
}
return &m
}
func As(err error) *AppError {
if mistakeErr, ok := errors.AsType[*AppError](err); ok {
return mistakeErr
}
return nil
}
func CodeIs(err error, code Code) bool {
if appErr := As(err); appErr != nil && appErr.Code() == code {
return true
}
return false
}
func (e *AppError) Error() string {
if e == nil {
return "<nil>"
return ""
}
if e.cause != nil {
return e.message + ": " + e.cause.Error()
if e.err == nil {
if e.msg != "" {
return e.msg
}
return e.code.String()
}
return e.message
if e.msg == "" {
return e.err.Error()
}
return fmt.Sprintf("%s: %s", e.msg, e.err.Error())
}
func (e *AppError) Unwrap() error {
if e == nil {
return nil
}
return e.cause
return e.err
}
func (e *AppError) Code() Code {
if e == nil {
return CodeInternalError
return CodeInternal
}
return e.code
}
@@ -94,29 +100,24 @@ func (e *AppError) Message() string {
if e == nil {
return ""
}
return e.message
return e.msg
}
// As finds an AppError even when it is wrapped with fmt.Errorf("...: %w", err).
func As(err error) (*AppError, bool) {
var appErr *AppError
if !errors.As(err, &appErr) || appErr == nil {
return nil, false
func (e *AppError) Cause() error {
if e == nil {
return nil
}
return appErr, true
return e.err
}
// Root is retained for existing HTTP handler call sites.
func Root(err error) *AppError {
appErr, _ := As(err)
return appErr
func (e *AppError) Metadata() Metadata {
return e.meta
}
// PublicMessage never exposes an unknown error or the cause of a server error.
func PublicMessage(err error) string {
appErr, ok := As(err)
if !ok || appErr.Code().HTTPStatus() >= http.StatusInternalServerError {
return "internal server error"
}
return appErr.Message()
func (e *AppError) HTTPStatus() int {
return e.Code().HTTPStatus()
}
func (e *AppError) GRPCCode() grpcCodes.Code {
return e.Code().GRPCCode()
}
+42
View File
@@ -0,0 +1,42 @@
package apperr
import (
"fmt"
"maps"
"strings"
)
var _ Metadata = (*metadata)(nil)
type Metadata interface {
Get(key metakey) string
Clone() map[metakey]string
CloneToAnyMap() map[string]any
String() string
}
type metadata map[metakey]string
func (m metadata) Get(key metakey) string {
return m[key]
}
func (m metadata) Clone() map[metakey]string {
return maps.Clone(m)
}
func (m metadata) CloneToAnyMap() map[string]any {
newM := make(map[string]any, len(m))
for k, v := range m {
newM[k.String()] = v
}
return newM
}
func (m metadata) String() string {
var b strings.Builder
for k, v := range m {
b.WriteString(fmt.Sprintf("%s: %s, ", k, v))
}
return b.String()
}
+19
View File
@@ -0,0 +1,19 @@
package apperr
type metakey uint16
const (
PgErrorCode metakey = iota
RedisErrorCode
)
func (m metakey) String() string {
switch m {
case PgErrorCode:
return "pg_err_code"
case RedisErrorCode:
return "redis_err_code"
default:
return "unknown"
}
}
+63
View File
@@ -0,0 +1,63 @@
package apperr
import (
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
func WrapPostgres(err error, msg string) error {
m := AppError{
err: err,
msg: msg,
code: CodeInternal,
meta: metadata{},
}
m.handlePostgres()
return &m
}
func (e *AppError) handlePostgres() {
if e.err == nil {
e.code = CodeOK
return
}
if pgErr, ok := errors.AsType[*pgconn.PgError](e.err); ok {
e.meta[PgErrorCode] = pgErr.Code
e.code = CodeFromPostgres(pgErr.Code)
return
}
switch {
case errors.Is(e.err, pgx.ErrNoRows):
e.msg = fmt.Sprintf("not found: %s", e.msg)
e.code = CodeNotFound
return
case errors.Is(e.err, pgx.ErrTooManyRows):
e.msg = fmt.Sprintf("got too many rows: %s", e.msg)
e.code = CodeInternal
return
case errors.Is(e.err, pgx.ErrTxClosed):
e.msg = fmt.Sprintf("transaction is closed: %s", e.msg)
e.code = CodeInternal
return
case errors.Is(e.err, pgx.ErrTxCommitRollback):
e.msg = fmt.Sprintf("transaction commit resulted in rollback: %s", e.msg)
e.code = CodeInternal
return
}
}
func (e *AppError) PgCode() string {
if e == nil {
return ""
}
if e.meta == nil {
return ""
}
return e.meta.Get(PgErrorCode)
}
+170
View File
@@ -0,0 +1,170 @@
package apperr
import (
"context"
"errors"
"fmt"
"net"
"strings"
"github.com/redis/go-redis/v9"
)
func WrapRedis(err error, msg string) error {
m := AppError{
err: err,
msg: msg,
meta: metadata{},
}
m.handleRedis()
return &m
}
func CodeFromRedisError(err error) Code {
code, ok := codeFromRedisError(err, true, true)
if !ok {
return CodeInternal
}
return code
}
func (e *AppError) handleRedis() {
if e.err == nil {
e.code = CodeOK
return
}
if code := redisErrorCode(e.err); code != "" {
e.meta[RedisErrorCode] = code
}
if errors.Is(e.err, redis.Nil) {
e.msg = fmt.Sprintf("not found: %s", e.msg)
}
e.code = CodeFromRedisError(e.err)
}
func (e *AppError) RedisCode() string {
if e == nil {
return ""
}
if e.meta == nil {
return ""
}
return e.meta.Get(RedisErrorCode)
}
func codeFromRedisError(err error, includeTransport bool, includeProtocolString bool) (Code, bool) {
if err == nil {
return CodeInternal, false
}
switch {
case errors.Is(err, redis.Nil):
return CodeNotFound, true
case errors.Is(err, redis.TxFailedErr):
return CodeConflict, true
case errors.Is(err, redis.ErrCrossSlot):
return CodeBadRequest, true
case errors.Is(err, redis.ErrPoolTimeout):
return CodeTimeout, true
case errors.Is(err, redis.ErrPoolExhausted):
return CodeTooManyRequests, true
case errors.Is(err, redis.ErrClosed):
return CodeServiceUnavailable, true
}
if includeTransport {
if errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded) {
return CodeTimeout, true
}
if netErr, ok := errors.AsType[net.Error](err); ok {
if netErr.Timeout() {
return CodeTimeout, true
}
return CodeServiceUnavailable, true
}
}
hasRedisError := isRedisError(err)
if !hasRedisError && !includeProtocolString {
return CodeInternal, false
}
switch {
case redis.IsExecAbortError(err):
return CodeConflict, true
case redis.IsMaxClientsError(err):
return CodeTooManyRequests, true
case redis.IsLoadingError(err),
redis.IsReadOnlyError(err),
redis.IsClusterDownError(err),
redis.IsTryAgainError(err),
redis.IsMasterDownError(err),
redis.IsNoReplicasError(err),
redis.IsOOMError(err):
return CodeServiceUnavailable, true
case redis.IsAuthError(err),
redis.IsPermissionError(err):
return CodeInternal, true
}
if _, ok := redis.IsMovedError(err); ok {
return CodeServiceUnavailable, true
}
if _, ok := redis.IsAskError(err); ok {
return CodeServiceUnavailable, true
}
if hasRedisError {
return CodeInternal, true
}
return CodeInternal, false
}
func isRedisError(err error) bool {
if err == nil {
return false
}
var redisErr redis.Error
return errors.As(err, &redisErr)
}
func redisErrorCode(err error) string {
switch {
case err == nil:
return ""
case errors.Is(err, redis.Nil):
return "nil"
case errors.Is(err, redis.TxFailedErr):
return "tx_failed"
case errors.Is(err, redis.ErrCrossSlot):
return "CROSSSLOT"
case errors.Is(err, redis.ErrPoolTimeout):
return "pool_timeout"
case errors.Is(err, redis.ErrPoolExhausted):
return "pool_exhausted"
case errors.Is(err, redis.ErrClosed):
return "closed"
}
var redisErr redis.Error
if !errors.As(err, &redisErr) {
return ""
}
msg := strings.TrimSpace(redisErr.Error())
msg = strings.TrimPrefix(msg, "ERR ")
parts := strings.Fields(msg)
if len(parts) == 0 {
return ""
}
return parts[0]
}
@@ -1,4 +1,4 @@
package provider
package jwtprovider
import (
"fmt"
@@ -9,7 +9,7 @@ import (
"github.com/google/uuid"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/role"
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
)
var _ Claims = (*jwtClaims)(nil)
@@ -110,14 +110,15 @@ func (p *provider) parseClaimsFromProtectedJWT(token *dto.Token) (*jwtClaims, er
token.Payload,
claims,
p.readKeyFunc,
jwt.WithValidMethods([]string{jwt.SigningMethodRS256.Alg()}),
jwt.WithExpirationRequired(),
jwt.WithIssuedAt(),
)
if err != nil {
slog.Error("failed to parse token with claims", "error", err)
return nil, ErrInvalidToken
}
// todo ADD VALIDATION
if !parsed.Valid {
slog.Error("failed to parse token: provided invalid token", "valid", parsed.Valid)
return nil, ErrInvalidToken
@@ -1,4 +1,4 @@
package provider
package jwtprovider
import (
"net/http"
@@ -1,4 +1,4 @@
package provider
package jwtprovider
import (
"errors"
@@ -1,4 +1,4 @@
package provider
package jwtprovider
import (
"net/http"
@@ -6,7 +6,7 @@ import (
"github.com/google/uuid"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/role"
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
)
type Provider interface {
@@ -1,4 +1,4 @@
package provider
package jwtprovider
import (
"fmt"
@@ -18,13 +18,13 @@ type manager struct {
func NewCookieManager(cfg *config.Config, provider Provider) Cookie {
m := &manager{
enabled: cfg.Cookies.Enabled,
cookieFabric: newCookieBuilder(
cfg.Cookies.Domain,
cfg.Cookies.Path,
cfg.Cookies.Secure,
cfg.Cookies.SameSite,
),
//enabled: cfg.Cookies.Enabled,
//cookieFabric: newCookieBuilder(
// cfg.Cookies.Domain,
// cfg.Cookies.Path,
// cfg.Cookies.Secure,
// cfg.Cookies.SameSite,
//),
prv: provider,
}
@@ -1,4 +1,4 @@
package provider
package jwtprovider
import (
"crypto/rsa"
@@ -11,8 +11,8 @@ import (
"gitea.privcloud.tech/mtusi2026/internal/config"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/environment"
"gitea.privcloud.tech/mtusi2026/internal/pkg/role"
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/environment"
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
)
var (
@@ -76,7 +76,7 @@ func (p *provider) ParseVerified(t *dto.Token) (*dto.UserDataInToken, error) {
if t == nil {
return nil, ErrTokenIsMissing
}
claims, err := p.parseFunc(t)
claims, err := p.parseClaimsFromProtectedJWT(t)
if err != nil {
return nil, fmt.Errorf("failed to parse token: %w", err)
}
@@ -173,10 +173,8 @@ func (p *provider) ValidateUserDataInToken(u *dto.UserDataInToken) error {
}
func (p *provider) readKeyFunc(token *jwt.Token) (interface{}, error) {
switch token.Method.(type) {
case *jwt.SigningMethodRSA:
return p.publicKey, nil
default:
if token.Method != jwt.SigningMethodRS256 {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return p.publicKey, nil
}
@@ -1,4 +1,4 @@
package provider
package jwtprovider
import (
"crypto/rsa"
@@ -1,79 +0,0 @@
package authidentity
import (
"encoding/json"
"strings"
"git.dev.mamont-optics.ru/mamont-optics/backend/application/internal/pkg/types"
)
type Status string
const (
StatusUndefined Status = "UNDEFINED"
StatusPending Status = "PENDING"
StatusActive Status = "ACTIVE"
StatusBlocked Status = "BLOCKED"
)
var allowedStatuses = map[Status]struct{}{
StatusUndefined: {},
StatusPending: {},
StatusActive: {},
StatusBlocked: {},
}
func ParseStatus(status string) Status {
s := Status(strings.ToUpper(status))
if !s.IsValid() {
return StatusUndefined
}
return s
}
func ParseAndValidateStatus(status string) (Status, error) {
parsed := ParseStatus(status)
if _, ok := allowedStatuses[parsed]; ok {
return parsed, nil
}
return StatusUndefined, types.ErrUnsupportedAuthIdentityStatus
}
func (t Status) String() string {
return string(t)
}
func (t Status) Validate() error {
if _, ok := allowedStatuses[t]; ok {
return nil
}
return types.ErrUnsupportedAuthIdentityStatus
}
func (t Status) IsValid() bool {
_, ok := allowedStatuses[t]
return ok
}
func (t Status) MarshalJSON() ([]byte, error) {
if err := t.Validate(); err != nil {
return nil, err
}
return json.Marshal(t.String())
}
func (t *Status) UnmarshalJSON(data []byte) error {
if t == nil {
return types.ErrUnmarshalAuthIdentityStatusIntoNilPointer
}
var value string
if err := json.Unmarshal(data, &value); err != nil {
return err
}
parsed := ParseStatus(value)
if err := parsed.Validate(); err != nil {
return err
}
*t = parsed
return nil
}
@@ -0,0 +1,71 @@
package encrypting
import (
"context"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
const (
argon2idMemory = 64 * 1024 // KiB
argon2idTime = 3
argon2idThreads = 4
argon2idSaltLen = 16
argon2idKeyLen = 32
// Only this bounded profile is accepted; stored parameters cannot request arbitrary resources.
argon2idPrefix = "$argon2id$v=19$m=65536,t=3,p=4$"
)
func (e *encryptor) EncryptSecretUsingArgon2id(ctx context.Context, secret string) (string, error) {
if err := ctx.Err(); err != nil {
return "", err
}
var salt [argon2idSaltLen]byte
if _, err := rand.Read(salt[:]); err != nil {
return "", fmt.Errorf("%w: %w", ErrFailedToEncryptPassword, err)
}
key := argon2.IDKey([]byte(secret), salt[:], argon2idTime, argon2idMemory, argon2idThreads, argon2idKeyLen)
if err := ctx.Err(); err != nil {
return "", err
}
return argon2idPrefix + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" + base64.RawStdEncoding.EncodeToString(key), nil
}
func (e *encryptor) CompareHashAndSecretUsingArgon2id(ctx context.Context, hash, secret string) error {
if err := ctx.Err(); err != nil {
return err
}
encoding := base64.RawStdEncoding.Strict()
if len(hash) != len(argon2idPrefix)+encoding.EncodedLen(argon2idSaltLen)+1+encoding.EncodedLen(argon2idKeyLen) {
return ErrFailedToComparePasswords
}
payload, ok := strings.CutPrefix(hash, argon2idPrefix)
if !ok {
return ErrFailedToComparePasswords
}
saltText, keyText, ok := strings.Cut(payload, "$")
if !ok {
return ErrFailedToComparePasswords
}
salt, err := encoding.DecodeString(saltText)
if err != nil || len(salt) != argon2idSaltLen {
return ErrFailedToComparePasswords
}
storedKey, err := encoding.DecodeString(keyText)
if err != nil || len(storedKey) != argon2idKeyLen {
return ErrFailedToComparePasswords
}
key := argon2.IDKey([]byte(secret), salt, argon2idTime, argon2idMemory, argon2idThreads, argon2idKeyLen)
if err = ctx.Err(); err != nil {
return err
}
if subtle.ConstantTimeCompare(storedKey, key) != 1 {
return ErrFailedToComparePasswords
}
return nil
}
@@ -0,0 +1,57 @@
package encrypting
import (
"context"
"crypto/sha256"
"encoding/hex"
"golang.org/x/crypto/bcrypt"
)
type encryptor struct {
cost int
generateFromPasswordFunc func([]byte, int) ([]byte, error)
compareHashAndPasswordFunc func([]byte, []byte) error
}
func New() Encryptor {
return &encryptor{
cost: bcrypt.DefaultCost,
generateFromPasswordFunc: bcrypt.GenerateFromPassword,
compareHashAndPasswordFunc: bcrypt.CompareHashAndPassword,
}
}
func (e *encryptor) EncryptSecret(_ context.Context, secret string) (string, error) {
res, err := e.generateFromPasswordFunc([]byte(secret), e.cost)
if err != nil {
return "", ErrFailedToEncryptPassword
}
return string(res), nil
}
func (e *encryptor) EncryptSecretUsingSum256(_ context.Context, secret string) (string, error) {
sum := sha256.Sum256([]byte(secret))
res, err := e.generateFromPasswordFunc([]byte(hex.EncodeToString(sum[:])), e.cost)
if err != nil {
return "", ErrFailedToEncryptPassword
}
return string(res), nil
}
func (e *encryptor) CompareHashAndSecret(_ context.Context, hash, password string) error {
err := e.compareHashAndPasswordFunc([]byte(hash), []byte(password))
if err != nil {
return ErrFailedToComparePasswords
}
return nil
}
func (e *encryptor) CompareHashAndSecretUsingSum256(_ context.Context, hash, password string) error {
sum := sha256.Sum256([]byte(password))
err := e.compareHashAndPasswordFunc([]byte(hash), []byte(hex.EncodeToString(sum[:])))
if err != nil {
return ErrFailedToComparePasswords
}
return nil
}
+8
View File
@@ -0,0 +1,8 @@
package encrypting
import "errors"
var (
ErrFailedToEncryptPassword = errors.New("failed to encrypt password")
ErrFailedToComparePasswords = errors.New("failed to compare passwords")
)
@@ -0,0 +1,12 @@
package encrypting
import "context"
type Encryptor interface {
EncryptSecretUsingArgon2id(ctx context.Context, secret string) (string, error)
CompareHashAndSecretUsingArgon2id(ctx context.Context, hash, secret string) error
EncryptSecret(ctx context.Context, secret string) (string, error)
EncryptSecretUsingSum256(_ context.Context, secret string) (string, error)
CompareHashAndSecret(ctx context.Context, hash, secret string) error
CompareHashAndSecretUsingSum256(ctx context.Context, hash, secret string) error
}
+168
View File
@@ -0,0 +1,168 @@
package migrator
import (
"context"
"io/fs"
"log/slog"
"github.com/jackc/pgx/v5"
"github.com/jackc/tern/v2/migrate"
"gitea.privcloud.tech/mtusi2026/internal/config"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/migrations"
)
type Migrator interface {
MigrateUp(ctx context.Context) error
MigrateDown(ctx context.Context) error
MigrateTo(ctx context.Context, version int32) error
GetVersion(ctx context.Context) (int32, error)
Configure(ctx context.Context) error
Close(ctx context.Context) error
Start(ctx context.Context) error
Stop(ctx context.Context) error
}
type migrator struct {
cfg *config.Config
conn *pgx.Conn
migrator *migrate.Migrator
migrations fs.FS
configured bool
closed bool
}
func New(cfg *config.Config) Migrator {
return &migrator{
cfg: cfg,
conn: nil,
migrator: nil,
migrations: migrations.Migrations,
configured: false,
closed: false,
}
}
func (m *migrator) MigrateUp(ctx context.Context) error {
if !m.configured {
return apperr.New(apperr.CodeInternal, "migrator was not configured")
}
return m.migrator.Migrate(ctx)
}
func (m *migrator) MigrateDown(ctx context.Context) error {
if !m.configured {
return apperr.New(apperr.CodeInternal, "migrator was not configured")
}
return m.migrator.MigrateTo(ctx, 0)
}
func (m *migrator) MigrateTo(ctx context.Context, version int32) error {
if !m.configured {
return apperr.New(apperr.CodeInternal, "migrator was not configured")
}
return m.migrator.MigrateTo(ctx, version)
}
func (m *migrator) GetVersion(ctx context.Context) (int32, error) {
if !m.configured {
return -1, apperr.New(apperr.CodeInternal, "migrator was not configured")
}
return m.migrator.GetCurrentVersion(ctx)
}
func (m *migrator) Configure(ctx context.Context) error {
if err := m.initConn(ctx); err != nil {
return err
}
if err := m.initMigrator(ctx); err != nil {
return err
}
if err := m.loadMigrations(); err != nil {
return err
}
m.configured = true
return nil
}
func (m *migrator) Close(ctx context.Context) error {
return m.closeConn(ctx)
}
func (m *migrator) Start(ctx context.Context) error {
if !m.cfg.Postgres.GetRunMigrations() {
slog.Info("flag run migrations is disabled: skipping migrating")
return nil
}
err := m.Configure(ctx)
if err != nil {
slog.Error("failed to configure migrator", "error", err)
return err
}
err = m.MigrateUp(ctx)
if err != nil {
slog.Error("failed to migrate database up", "error", err)
return err
}
if err = m.Close(ctx); err != nil {
slog.Error("failed close connection to database", "error", err)
return err
}
m.closed = true
return nil
}
func (m *migrator) Stop(ctx context.Context) error {
if !m.cfg.Postgres.GetRunMigrations() {
return nil
}
if !m.closed {
err := m.conn.Close(ctx)
if err != nil {
slog.Error("failed close connection to database", "error", err)
return err
}
}
return nil
}
func (m *migrator) loadMigrations() (err error) {
err = m.migrator.LoadMigrations(m.migrations)
if err != nil {
slog.Error("failed to load migrations", "error", err)
return apperr.New(apperr.CodeInternal, "failed to load migrations")
}
slog.Info("successfully loaded migrations", "error", err)
return nil
}
func (m *migrator) initConn(ctx context.Context) (err error) {
m.conn, err = pgx.Connect(ctx, m.cfg.Postgres.GetURI())
if err != nil {
slog.Error("failed to create connection to database", "error", err)
return apperr.New(apperr.CodeInternal, "failed to create connection to database")
}
slog.Info("connected to database", "db", m.cfg.Postgres.Database)
return nil
}
func (m *migrator) initMigrator(ctx context.Context) (err error) {
m.migrator, err = migrate.NewMigrator(ctx, m.conn, m.cfg.Postgres.GetVersionTableName())
if err != nil {
slog.Error("failed to initialize migrator", "error", err)
return apperr.New(apperr.CodeInternal, "failed to initialize migrator")
}
slog.Info("successfully initialized migrator")
return nil
}
func (m *migrator) closeConn(ctx context.Context) error {
return m.conn.Close(ctx)
}
@@ -0,0 +1,25 @@
package postgres
import (
"context"
"github.com/jackc/pgx/v5"
pgxUUID "github.com/vgarvardt/pgx-google-uuid/v5"
)
type AfterConnect func(ctx context.Context, conn *pgx.Conn) error
func AddUUIDSupport(_ context.Context, conn *pgx.Conn) error {
pgxUUID.Register(conn.TypeMap())
return nil
}
func WithEnumTypeSupport(enumName string) AfterConnect {
return func(ctx context.Context, conn *pgx.Conn) error {
dt, err := conn.LoadType(ctx, enumName)
if err != nil {
return err
}
conn.TypeMap().RegisterType(dt)
return nil
}
}
+7
View File
@@ -0,0 +1,7 @@
package postgres
type MigrationConfig interface {
GetURI() string
GetVersionTableName() string
GetRunMigrations() bool
}
+10
View File
@@ -0,0 +1,10 @@
package postgres
import (
"errors"
)
var (
errCreatingPool = errors.New("failed to create postgres pool")
errParseConfig = errors.New("failed to parse postgres config")
)
@@ -0,0 +1,15 @@
package postgres
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
type Conn interface {
SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults
Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error)
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}
+80
View File
@@ -0,0 +1,80 @@
package postgres
import (
"context"
"log/slog"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/tracelog"
pgxslog "github.com/mcosta74/pgx-slog"
)
type ConfigWithLog interface {
GetLogLevel() string
}
type ConfigWithMaxConn interface {
GetMaxConnections() int32
}
func getLevelFromConfig(cfg MigrationConfig) tracelog.LogLevel {
if logCfg, ok := cfg.(ConfigWithLog); ok {
lvl, _ := tracelog.LogLevelFromString(logCfg.GetLogLevel())
return lvl
}
return tracelog.LogLevelError
}
func addMaxConnectionsToCfg(cfg any, poolCfg *pgxpool.Config) {
if connCfg, ok := cfg.(ConfigWithMaxConn); ok {
poolCfg.MaxConns = connCfg.GetMaxConnections()
}
}
func New(cfg MigrationConfig, afterConnect ...AfterConnect) (*pgxpool.Pool, error) {
lvl := getLevelFromConfig(cfg)
if len(afterConnect) == 0 {
afterConnect = []AfterConnect{AddUUIDSupport}
}
poolConfig, err := pgxpool.ParseConfig(cfg.GetURI())
if err != nil {
slog.Error("failed to parse postgres config", "error", err)
return nil, errParseConfig
}
addMaxConnectionsToCfg(cfg, poolConfig)
poolConfig.ConnConfig.Tracer = &tracelog.TraceLog{
Logger: pgxslog.NewLogger(slog.Default()),
LogLevel: lvl,
Config: &tracelog.TraceLogConfig{
TimeKey: "ts",
},
}
poolConfig.AfterConnect = load(afterConnect...)
pool, err := pgxpool.NewWithConfig(context.Background(), poolConfig)
if err != nil {
slog.Error("failed to create postgres pool", "error", err)
return nil, errCreatingPool
}
slog.Info("successfully connected to postgres pool")
return pool, nil
}
func load(afterConnects ...AfterConnect) func(ctx context.Context, conn *pgx.Conn) error {
return func(ctx context.Context, conn *pgx.Conn) error {
for _, afterConnect := range afterConnects {
if err := afterConnect(ctx, conn); err != nil {
return err
}
}
return nil
}
}
@@ -0,0 +1,59 @@
package txmanager
import (
"context"
"errors"
"fmt"
"log/slog"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type TransactionManager struct {
pool *pgxpool.Pool
}
func New(pool *pgxpool.Pool) *TransactionManager {
return &TransactionManager{
pool: pool,
}
}
func (tm *TransactionManager) RunInTransaction(ctx context.Context, opts *pgx.TxOptions, fn func(tx pgx.Tx) error) (err error) {
var tx pgx.Tx
if opts != nil {
tx, err = tm.pool.BeginTx(ctx, *opts)
} else {
tx, err = tm.pool.Begin(ctx)
}
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
var committed bool
defer func() {
if p := recover(); p != nil {
err = fmt.Errorf("panic in transaction: %v", p)
}
if !committed {
rollbackErr := tx.Rollback(ctx)
if rollbackErr != nil && !errors.Is(rollbackErr, pgx.ErrTxClosed) {
slog.Error("failed to rollback transaction", "error", rollbackErr)
}
}
}()
if err = fn(tx); err != nil {
return fmt.Errorf("failed to execute transaction: %w", err)
}
if err = tx.Commit(ctx); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
committed = true
return nil
}
@@ -0,0 +1,245 @@
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())
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.Error("response", "error", err, "status", appErr.Code().HTTPStatus(), "requestId", 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
}
func ParseToken(r *http.Request, provider jwtprovider.Provider) (*dto.UserDataInToken, error) {
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,74 @@
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) {
if _, err := a.verifySession(r); err != nil {
framework.JSONError(r.Context(), w, err)
return
}
next.ServeHTTP(w, r)
}
}
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, r)
}
}
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,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))
})
}
}
+131
View File
@@ -0,0 +1,131 @@
package router
import (
"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) {
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) {
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) {
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
}
@@ -4,7 +4,7 @@ import (
"encoding/json"
"strings"
"git.dev.mamont-optics.ru/mamont-optics/backend/application/internal/pkg/types"
"gitea.privcloud.tech/mtusi2026/internal/pkg/types"
)
type Type string
@@ -4,7 +4,7 @@ import (
"encoding/json"
"strings"
"git.dev.mamont-optics.ru/mamont-optics/backend/application/internal/pkg/types"
"gitea.privcloud.tech/mtusi2026/internal/pkg/types"
)
type ApplicationEnvironment string
@@ -4,7 +4,7 @@ import (
"encoding/json"
"strings"
"git.dev.mamont-optics.ru/mamont-optics/backend/application/internal/pkg/types"
"gitea.privcloud.tech/mtusi2026/internal/pkg/types"
)
type Role string