forked from mtusi2026/mtusi2026lab6
Реализация на 5
This commit is contained in:
@@ -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:400}
|
||||
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.StatusBadRequest,
|
||||
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]]
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
grpcCodes "google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
type AppError struct {
|
||||
err error
|
||||
msg string
|
||||
code Code
|
||||
meta metadata
|
||||
}
|
||||
|
||||
func New(code Code, msg string) error {
|
||||
return &AppError{
|
||||
msg: msg,
|
||||
code: code,
|
||||
meta: metadata{},
|
||||
}
|
||||
}
|
||||
|
||||
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 ""
|
||||
}
|
||||
|
||||
if e.err == nil {
|
||||
if e.msg != "" {
|
||||
return e.msg
|
||||
}
|
||||
return e.code.String()
|
||||
}
|
||||
|
||||
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.err
|
||||
}
|
||||
|
||||
func (e *AppError) Code() Code {
|
||||
if e == nil {
|
||||
return CodeInternal
|
||||
}
|
||||
return e.code
|
||||
}
|
||||
|
||||
func (e *AppError) Message() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
return e.msg
|
||||
}
|
||||
|
||||
func (e *AppError) Cause() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.err
|
||||
}
|
||||
|
||||
func (e *AppError) Metadata() Metadata {
|
||||
return e.meta
|
||||
}
|
||||
|
||||
func (e *AppError) HTTPStatus() int {
|
||||
return e.Code().HTTPStatus()
|
||||
}
|
||||
|
||||
func (e *AppError) GRPCCode() grpcCodes.Code {
|
||||
return e.Code().GRPCCode()
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"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
|
||||
}
|
||||
|
||||
var networkError net.Error
|
||||
var connectError *pgconn.ConnectError
|
||||
if errors.Is(e.err, context.DeadlineExceeded) || errors.Is(e.err, io.EOF) ||
|
||||
errors.Is(e.err, io.ErrUnexpectedEOF) || errors.As(e.err, &networkError) || errors.As(e.err, &connectError) {
|
||||
e.code = CodeServiceUnavailable
|
||||
e.msg = "database unavailable"
|
||||
return
|
||||
}
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](e.err); ok {
|
||||
if strings.HasPrefix(pgErr.Code, "08") || pgErr.Code == "57014" ||
|
||||
pgErr.Code == "57P01" || pgErr.Code == "57P02" || pgErr.Code == "57P03" || pgErr.Code == "53300" {
|
||||
e.code = CodeServiceUnavailable
|
||||
e.msg = "database unavailable"
|
||||
return
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -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]
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
var _ Claims = (*jwtClaims)(nil)
|
||||
|
||||
type Claims interface {
|
||||
GetTopTokenID() (uuid.UUID, bool)
|
||||
GetTopUserID() (uuid.UUID, bool)
|
||||
GetTopRole() (role.Role, bool)
|
||||
GetTopIsAccess() (bool, bool)
|
||||
GetTopExpiresAt() (time.Time, bool)
|
||||
GetTopIssuedAt() (time.Time, bool)
|
||||
}
|
||||
|
||||
type claimsParseFunc func(token *dto.Token) (*jwtClaims, error)
|
||||
|
||||
type jwtClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
|
||||
Nonce string `json:"nonce,omitempty"`
|
||||
IsAccess bool `json:"is_access"`
|
||||
Role role.Role `json:"role"`
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) GetTopTokenID() (uuid.UUID, bool) {
|
||||
parsed, err := uuid.Parse(claims.ID)
|
||||
if err != nil {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
return parsed, true
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) GetTopUserID() (uuid.UUID, bool) {
|
||||
parsed, err := uuid.Parse(claims.Subject)
|
||||
if err != nil {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
return parsed, true
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) GetTopRole() (role.Role, bool) {
|
||||
return claims.Role, true
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) GetTopIsAccess() (bool, bool) {
|
||||
return claims.IsAccess, true
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) GetTopExpiresAt() (time.Time, bool) {
|
||||
if claims.ExpiresAt == nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return claims.ExpiresAt.Time, true
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) GetTopIssuedAt() (time.Time, bool) {
|
||||
if claims.IssuedAt == nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return claims.IssuedAt.Time, true
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) userData() (*dto.UserDataInToken, error) {
|
||||
var u dto.UserDataInToken
|
||||
|
||||
tokenID, err := uuid.Parse(claims.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse token id: %w", err)
|
||||
}
|
||||
u.TokenID = tokenID
|
||||
|
||||
userID, err := uuid.Parse(claims.Subject)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse user id from token %q: %w", claims.Subject, err)
|
||||
}
|
||||
u.UserID = userID
|
||||
|
||||
u.Role = claims.Role
|
||||
u.IsAccess = claims.IsAccess
|
||||
|
||||
if claims.ExpiresAt != nil {
|
||||
u.ExpiresAt = claims.ExpiresAt.Time
|
||||
}
|
||||
|
||||
if claims.IssuedAt != nil {
|
||||
u.IssuedAt = claims.IssuedAt.Time
|
||||
}
|
||||
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (p *provider) parseClaimsFromProtectedJWT(token *dto.Token) (*jwtClaims, error) {
|
||||
if token == nil {
|
||||
return nil, ErrTokenIsMissing
|
||||
}
|
||||
|
||||
claims := &jwtClaims{}
|
||||
|
||||
parsed, err := jwt.ParseWithClaims(
|
||||
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
|
||||
}
|
||||
|
||||
if !parsed.Valid {
|
||||
slog.Error("failed to parse token: provided invalid token", "valid", parsed.Valid)
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func (p *provider) parseClaimsFromExposedJWT(token *dto.Token) (*jwtClaims, error) {
|
||||
if token == nil {
|
||||
return nil, ErrTokenIsMissing
|
||||
}
|
||||
|
||||
claims := &jwtClaims{}
|
||||
|
||||
_, _, err := new(jwt.Parser).ParseUnverified(token.Payload, claims)
|
||||
if err != nil {
|
||||
slog.Error("failed to parse token: provided invalid token")
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const (
|
||||
accessTokenCookieKey = "auth-access-token"
|
||||
refreshTokenCookieKey = "auth-refresh-token"
|
||||
expiresAtCookieKey = "auth-exp"
|
||||
)
|
||||
|
||||
type CookieBuilderFabric struct {
|
||||
fabric func() http.Cookie
|
||||
}
|
||||
|
||||
func newCookieBuilder(
|
||||
domain string,
|
||||
path string,
|
||||
secure bool,
|
||||
sameSite http.SameSite,
|
||||
) *CookieBuilderFabric {
|
||||
return &CookieBuilderFabric{
|
||||
fabric: newCookieFabric(domain, path, secure, sameSite),
|
||||
}
|
||||
}
|
||||
|
||||
func (b *CookieBuilderFabric) Builder() *CookieBuilder {
|
||||
return &CookieBuilder{
|
||||
cookie: b.fabric(),
|
||||
}
|
||||
}
|
||||
|
||||
func newCookieFabric(
|
||||
_ string,
|
||||
path string,
|
||||
secure bool,
|
||||
sameSite http.SameSite) func() http.Cookie {
|
||||
return func() http.Cookie {
|
||||
return http.Cookie{
|
||||
Path: path,
|
||||
Secure: secure,
|
||||
SameSite: sameSite,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type CookieBuilder struct {
|
||||
cookie http.Cookie
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) AccessName() *CookieBuilder {
|
||||
b.cookie.Name = accessTokenCookieKey
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) ExpiresName() *CookieBuilder {
|
||||
b.cookie.Name = expiresAtCookieKey
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) RefreshName() *CookieBuilder {
|
||||
b.cookie.Name = refreshTokenCookieKey
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) Value(value string) *CookieBuilder {
|
||||
b.cookie.Value = value
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) HTTPOnly() *CookieBuilder {
|
||||
b.cookie.HttpOnly = true
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) MaxAge(maxAge int) *CookieBuilder {
|
||||
b.cookie.MaxAge = maxAge
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) Build() *http.Cookie {
|
||||
return new(b.cookie)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDecode = errors.New("failed to decode argument")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrUnexpectedAlgorithm = errors.New("unexpected signing algorithm")
|
||||
ErrTokenIsMissing = errors.New("token is missing")
|
||||
ErrInvalidToken = errors.New("provided invalid token")
|
||||
ErrInvalidUserDataInToken = errors.New("invalid user data in token")
|
||||
ErrInvalidTokenClaims = errors.New("provided invalid token claims")
|
||||
ErrInvalidBirthDateFormat = errors.New("provided invalid birth date format")
|
||||
ErrTokenExpired = errors.New("token is expired")
|
||||
ErrFailedToSign = errors.New("failed to sign jwt")
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
type Provider interface {
|
||||
Parse(token *dto.Token) (*dto.UserDataInToken, error)
|
||||
CreateRefreshAndAccessTokensForUser(userID uuid.UUID, role role.Role) (*dto.Tokens, error)
|
||||
ParseVerified(token *dto.Token) (*dto.UserDataInToken, error)
|
||||
ParseUnverified(token *dto.Token) (*dto.UserDataInToken, error)
|
||||
ValidateUserDataInToken(u *dto.UserDataInToken) error
|
||||
}
|
||||
|
||||
type Cookie interface {
|
||||
Enabled() bool
|
||||
Set(w http.ResponseWriter, tokens *dto.Tokens)
|
||||
Clear(w http.ResponseWriter)
|
||||
AccessToken(r *http.Request) *dto.AccessToken
|
||||
RefreshToken(r *http.Request) *dto.RefreshToken
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type manager struct {
|
||||
enabled bool
|
||||
cookieFabric *CookieBuilderFabric
|
||||
prv Provider
|
||||
}
|
||||
|
||||
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,
|
||||
//),
|
||||
prv: provider,
|
||||
}
|
||||
|
||||
if !m.enabled {
|
||||
return m
|
||||
}
|
||||
|
||||
if err := m.cookieFabric.
|
||||
Builder().
|
||||
AccessName().
|
||||
Value("test").
|
||||
HTTPOnly().
|
||||
MaxAge(0).
|
||||
Build().
|
||||
Valid(); err != nil {
|
||||
panic(fmt.Errorf("cookie validation failed: %w", err))
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *manager) Enabled() bool {
|
||||
return m.enabled
|
||||
}
|
||||
|
||||
func (m *manager) Set(w http.ResponseWriter, tokens *dto.Tokens) {
|
||||
if !m.enabled || tokens == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if tokens.AccessToken.Payload != "" {
|
||||
m.setAccess(tokens.AccessToken, w)
|
||||
}
|
||||
|
||||
if tokens.RefreshToken.Payload != "" {
|
||||
m.setRefresh(tokens.RefreshToken, w)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) Clear(w http.ResponseWriter) {
|
||||
if !m.enabled {
|
||||
return
|
||||
}
|
||||
|
||||
for _, name := range []string{accessTokenCookieKey, refreshTokenCookieKey, expiresAtCookieKey} {
|
||||
b := m.cookieFabric.
|
||||
Builder().
|
||||
MaxAge(-1)
|
||||
|
||||
switch name {
|
||||
case expiresAtCookieKey:
|
||||
b.ExpiresName()
|
||||
case refreshTokenCookieKey:
|
||||
b.RefreshName().
|
||||
HTTPOnly()
|
||||
case accessTokenCookieKey:
|
||||
b.AccessName().
|
||||
HTTPOnly()
|
||||
}
|
||||
http.SetCookie(w, b.Build())
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) AccessToken(r *http.Request) *dto.AccessToken {
|
||||
if !m.enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
c, err := r.Cookie(accessTokenCookieKey)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &dto.AccessToken{
|
||||
Payload: c.Value,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) RefreshToken(r *http.Request) *dto.RefreshToken {
|
||||
if !m.enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
c, err := r.Cookie(refreshTokenCookieKey)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &dto.RefreshToken{
|
||||
Payload: c.Value,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) setAccess(token dto.AccessToken, w http.ResponseWriter) {
|
||||
accessTTL := m.tokenTTL(token.Token())
|
||||
if accessTTL < 0 {
|
||||
http.SetCookie(w, m.cookieFabric.
|
||||
Builder().
|
||||
AccessName().
|
||||
HTTPOnly().
|
||||
MaxAge(-1).
|
||||
Build(),
|
||||
)
|
||||
http.SetCookie(w, m.cookieFabric.
|
||||
Builder().
|
||||
ExpiresName().
|
||||
MaxAge(-1).
|
||||
Build(),
|
||||
)
|
||||
} else if tokenExpiresAt := m.tokenExpiry(token.Token()); !tokenExpiresAt.IsZero() {
|
||||
http.SetCookie(w, m.cookieFabric.
|
||||
Builder().
|
||||
AccessName().
|
||||
Value(token.Payload).
|
||||
HTTPOnly().
|
||||
MaxAge(accessTTL).
|
||||
Build(),
|
||||
)
|
||||
http.SetCookie(w, m.cookieFabric.
|
||||
Builder().
|
||||
ExpiresName().
|
||||
Value(strconv.FormatInt(tokenExpiresAt.Unix(), 10)).
|
||||
MaxAge(accessTTL).
|
||||
Build(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) setRefresh(token dto.RefreshToken, w http.ResponseWriter) {
|
||||
refreshTTL := m.tokenTTL(token.Token())
|
||||
if refreshTTL < 0 {
|
||||
http.SetCookie(w, m.cookieFabric.
|
||||
Builder().
|
||||
RefreshName().
|
||||
HTTPOnly().
|
||||
MaxAge(-1).
|
||||
Build(),
|
||||
)
|
||||
} else {
|
||||
http.SetCookie(w, m.cookieFabric.
|
||||
Builder().
|
||||
RefreshName().
|
||||
Value(token.Payload).
|
||||
HTTPOnly().
|
||||
MaxAge(refreshTTL).
|
||||
Build(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) tokenTTL(token *dto.Token) int {
|
||||
expiresAt := m.tokenExpiry(token)
|
||||
|
||||
if expiresAt.IsZero() {
|
||||
return -1
|
||||
}
|
||||
|
||||
ttl := int(time.Until(expiresAt).Seconds())
|
||||
if ttl <= 0 {
|
||||
return -1
|
||||
}
|
||||
|
||||
return ttl
|
||||
}
|
||||
|
||||
func (m *manager) tokenExpiry(token *dto.Token) time.Time {
|
||||
data, err := m.prv.ParseUnverified(token)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return data.ExpiresAt
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/environment"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
var (
|
||||
_ Provider = (*provider)(nil)
|
||||
)
|
||||
|
||||
type provider struct {
|
||||
accessLifetime time.Duration
|
||||
refreshLifetime time.Duration
|
||||
publicKey *rsa.PublicKey
|
||||
privateKey *rsa.PrivateKey
|
||||
parseFunc claimsParseFunc
|
||||
}
|
||||
|
||||
func New(cfg *config.Config) Provider {
|
||||
p := provider{
|
||||
accessLifetime: cfg.JWT.AccessTokenLifetime,
|
||||
refreshLifetime: cfg.JWT.RefreshTokenLifetime,
|
||||
}
|
||||
p.parseFunc = p.parseClaimsFromProtectedJWT
|
||||
|
||||
if cfg.Application.Environment == environment.ApplicationEnvironmentDev {
|
||||
p.parseFunc = p.parseClaimsFromExposedJWT
|
||||
}
|
||||
|
||||
var err error
|
||||
if p.publicKey, err = readPublicKeyFromFile(cfg.JWT.PublicKeyPath); err != nil {
|
||||
slog.Error("failed to read public key", "error", err)
|
||||
panic(fmt.Errorf("failed to read public key: %w", err))
|
||||
}
|
||||
if p.privateKey, err = readPrivateKeyFromFile(cfg.JWT.PrivateKeyPath); err != nil {
|
||||
slog.Error("failed to read private key", "error", err)
|
||||
panic(fmt.Errorf("failed to read private key: %w", err))
|
||||
}
|
||||
|
||||
return &p
|
||||
}
|
||||
|
||||
func (p *provider) Parse(token *dto.Token) (*dto.UserDataInToken, error) {
|
||||
claims, err := p.parseFunc(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return claims.userData()
|
||||
}
|
||||
|
||||
func (p *provider) ParseUnverified(t *dto.Token) (*dto.UserDataInToken, error) {
|
||||
if t == nil {
|
||||
return nil, ErrTokenIsMissing
|
||||
}
|
||||
|
||||
claims, err := p.parseClaimsFromExposedJWT(t)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return claims.userData()
|
||||
}
|
||||
|
||||
func (p *provider) ParseVerified(t *dto.Token) (*dto.UserDataInToken, error) {
|
||||
if t == nil {
|
||||
return nil, ErrTokenIsMissing
|
||||
}
|
||||
claims, err := p.parseClaimsFromProtectedJWT(t)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse token: %w", err)
|
||||
}
|
||||
|
||||
return claims.userData()
|
||||
}
|
||||
|
||||
func (p *provider) CreateAccessTokenForUser(userID uuid.UUID, role role.Role) (*dto.AccessToken, error) {
|
||||
t, err := p.createTokenForUser(userID, true, role)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto.AccessToken{
|
||||
Payload: t.Payload,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *provider) CreateRefreshTokenForUser(userID uuid.UUID, role role.Role) (*dto.RefreshToken, error) {
|
||||
t, err := p.createTokenForUser(userID, false, role)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto.RefreshToken{
|
||||
Payload: t.Payload,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *provider) CreateRefreshAndAccessTokensForUser(userID uuid.UUID, role role.Role) (*dto.Tokens, error) {
|
||||
access, err := p.CreateAccessTokenForUser(userID, role)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
refresh, err := p.CreateRefreshTokenForUser(userID, role)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto.Tokens{
|
||||
AccessToken: *access,
|
||||
RefreshToken: *refresh,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *provider) createTokenForUser(userID uuid.UUID, isAccess bool, role role.Role) (*dto.Token, error) {
|
||||
now := time.Now()
|
||||
var tokenExpiresAt time.Time
|
||||
if isAccess {
|
||||
tokenExpiresAt = now.Add(p.accessLifetime)
|
||||
} else {
|
||||
tokenExpiresAt = now.Add(p.refreshLifetime)
|
||||
}
|
||||
var nonce [32]byte
|
||||
if _, err := rand.Read(nonce[:]); err != nil {
|
||||
return nil, fmt.Errorf("generate token nonce: %w", err)
|
||||
}
|
||||
claims := &jwtClaims{
|
||||
Nonce: base64.RawURLEncoding.EncodeToString(nonce[:]),
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: userID.String(),
|
||||
ExpiresAt: jwt.NewNumericDate(tokenExpiresAt),
|
||||
NotBefore: jwt.NewNumericDate(now),
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ID: uuid.NewString(),
|
||||
},
|
||||
IsAccess: isAccess,
|
||||
Role: role,
|
||||
}
|
||||
t := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
|
||||
|
||||
payload, err := t.SignedString(p.privateKey)
|
||||
if err != nil {
|
||||
slog.Error("failed to sign jwt", "error", err)
|
||||
return nil, ErrFailedToSign
|
||||
}
|
||||
return &dto.Token{Payload: payload}, nil
|
||||
}
|
||||
|
||||
// TODO refactor maybe delete
|
||||
func (p *provider) ValidateUserDataInToken(u *dto.UserDataInToken) error {
|
||||
if u == nil {
|
||||
return ErrInvalidUserDataInToken
|
||||
}
|
||||
|
||||
switch {
|
||||
case u.TokenID == uuid.Nil:
|
||||
return fmt.Errorf("%w: unexpected nil token id", ErrInvalidUserDataInToken)
|
||||
case u.UserID == uuid.Nil:
|
||||
return fmt.Errorf("%w: unexpected nil user id", ErrInvalidUserDataInToken)
|
||||
case u.IssuedAt.IsZero():
|
||||
return fmt.Errorf("%w: unexpected zero issued at", ErrInvalidUserDataInToken)
|
||||
case u.Email != nil && *u.Email == "":
|
||||
return fmt.Errorf("%w: unexpected empty email", ErrInvalidUserDataInToken)
|
||||
case u.PhoneNumber != nil && *u.PhoneNumber == "":
|
||||
return fmt.Errorf("%w: unexpected empty phone number", ErrInvalidUserDataInToken)
|
||||
case u.ExpiresAt.IsZero():
|
||||
return fmt.Errorf("%w: unexpected zero expires at", ErrInvalidUserDataInToken)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *provider) readKeyFunc(token *jwt.Token) (interface{}, error) {
|
||||
if token.Method != jwt.SigningMethodRS256 {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return p.publicKey, nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func readPrivateKeyFromFile(path string) (*rsa.PrivateKey, error) {
|
||||
key, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read public key: %w", err)
|
||||
}
|
||||
|
||||
privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse private key: %w", err)
|
||||
}
|
||||
return privateKey, nil
|
||||
}
|
||||
|
||||
func readPublicKeyFromFile(path string) (*rsa.PublicKey, error) {
|
||||
key, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read public key: %w", err)
|
||||
}
|
||||
|
||||
privateKey, err := jwt.ParseRSAPublicKeyFromPEM(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse private key: %w", err)
|
||||
}
|
||||
return privateKey, nil
|
||||
}
|
||||
Vendored
+43
@@ -0,0 +1,43 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
)
|
||||
|
||||
const defaultRedisPort = 6379
|
||||
|
||||
// OperationTimeout bounds each optional cache operation independently of the request.
|
||||
const OperationTimeout = 300 * time.Millisecond
|
||||
|
||||
type Client struct {
|
||||
*redis.Client
|
||||
}
|
||||
|
||||
func New(cfg *config.Config) *Client {
|
||||
if cfg.Redis.Port == 0 {
|
||||
cfg.Redis.Port = defaultRedisPort
|
||||
}
|
||||
|
||||
return &Client{
|
||||
Client: redis.NewClient(cfg.Redis.BuildRedisOptions()),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, OperationTimeout)
|
||||
defer cancel()
|
||||
return c.Client.Ping(ctx).Err()
|
||||
}
|
||||
|
||||
func (c *Client) Start(ctx context.Context) error {
|
||||
return c.Ping(ctx)
|
||||
}
|
||||
|
||||
func (c *Client) Stop(_ context.Context) error {
|
||||
return c.Client.Close()
|
||||
}
|
||||
@@ -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,72 @@
|
||||
package encrypting
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
|
||||
"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
|
||||
}
|
||||
|
||||
// EncryptSecretUsingSum256 hashes a high-entropy session token, not a password.
|
||||
func (e *encryptor) EncryptSecretUsingSum256(ctx context.Context, secret string) (string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
return "sha256:" + hex.EncodeToString(sum[:]), 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(ctx context.Context, hash, secret string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
if payload, ok := strings.CutPrefix(hash, "sha256:"); ok {
|
||||
stored, err := hex.DecodeString(payload)
|
||||
if err != nil || len(stored) != sha256.Size || subtle.ConstantTimeCompare(stored, sum[:]) != 1 {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Preserve existing lab2/lab3 sessions across a rolling deployment.
|
||||
// Passwords continue to use Argon2id; only old random-token fingerprints use this fallback.
|
||||
if strings.HasPrefix(hash, "$2") {
|
||||
if err := e.compareHashAndPasswordFunc([]byte(hash), []byte(hex.EncodeToString(sum[:]))); err == nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package encrypting
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSessionFingerprints(t *testing.T) {
|
||||
e := New()
|
||||
ctx := context.Background()
|
||||
token := "synthetic-high-entropy-session-value"
|
||||
hash, err := e.EncryptSecretUsingSum256(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = e.CompareHashAndSecretUsingSum256(ctx, hash, token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, bad := range []string{"sha256:00", "sha256:invalid", "unknown"} {
|
||||
if e.CompareHashAndSecretUsingSum256(ctx, bad, token) == nil {
|
||||
t.Fatal("accepted malformed fingerprint")
|
||||
}
|
||||
}
|
||||
if e.CompareHashAndSecretUsingSum256(ctx, hash, token+"x") == nil {
|
||||
t.Fatal("accepted wrong token")
|
||||
}
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
legacy, err := bcrypt.GenerateFromPassword([]byte(hex.EncodeToString(sum[:])), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = e.CompareHashAndSecretUsingSum256(ctx, string(legacy), token); err != nil {
|
||||
t.Fatal("legacy session rejected", err)
|
||||
}
|
||||
canceled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if e.CompareHashAndSecretUsingSum256(canceled, hash, token) == nil {
|
||||
t.Fatal("ignored cancellation")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// Package fault implements explicit, file-controlled barriers for the isolated lab.
|
||||
package fault
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Hit(ctx context.Context, point string, id uuid.UUID) {
|
||||
if os.Getenv("LAB5_FAULTS") != "1" {
|
||||
return
|
||||
}
|
||||
p := filepath.Join("/faults", point+"."+id.String())
|
||||
b, e := os.ReadFile(p)
|
||||
if e != nil {
|
||||
p = filepath.Join("/faults", point+".all")
|
||||
b, e = os.ReadFile(p)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
hit, e := os.OpenFile(p+".hit", os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
_, _ = hit.WriteString(id.String() + "\n")
|
||||
_ = hit.Close()
|
||||
switch strings.TrimSpace(string(b)) {
|
||||
case "crash":
|
||||
_ = os.Remove(p)
|
||||
os.Exit(86)
|
||||
case "pause":
|
||||
for {
|
||||
if _, e = os.Stat(p); os.IsNotExist(e) {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Error(point string, id uuid.UUID) error {
|
||||
if os.Getenv("LAB5_FAULTS") != "1" {
|
||||
return nil
|
||||
}
|
||||
b, e := os.ReadFile(filepath.Join("/faults", point+"."+id.String()))
|
||||
if e != nil {
|
||||
return nil
|
||||
}
|
||||
v := strings.TrimSpace(string(b))
|
||||
if v == "temporary" || v == "permanent" {
|
||||
return errors.New(v)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package imageprocessor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
func run(ctx context.Context, args ...string) error {
|
||||
cmd := exec.CommandContext(ctx, "magick", args...)
|
||||
cmd.Env = append(os.Environ(), "MAGICK_MEMORY_LIMIT=256MiB", "MAGICK_MAP_LIMIT=0", "MAGICK_DISK_LIMIT=256MiB", "MAGICK_THREAD_LIMIT=1", "MAGICK_TIME_LIMIT=60")
|
||||
cmd.WaitDelay = time.Second
|
||||
if err := cmd.Run(); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
return fmt.Errorf("image conversion failed: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func Validate(ctx context.Context, path string) error {
|
||||
return run(ctx, "-regard-warnings", path, "null:")
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Name, Path, MIME string
|
||||
Width, Height int
|
||||
}
|
||||
|
||||
func fit(w, h, limit int) (int, int) {
|
||||
if w <= limit && h <= limit {
|
||||
return w, h
|
||||
}
|
||||
if w >= h {
|
||||
return limit, max(1, h*limit/w)
|
||||
}
|
||||
return max(1, w*limit/h), limit
|
||||
}
|
||||
func Process(ctx context.Context, source, dir string, version int) ([]Result, error) {
|
||||
normalized := filepath.Join(dir, "normalized.png")
|
||||
if e := run(ctx, source, "-auto-orient", "-background", "white", "-alpha", "remove", "-alpha", "off", "-strip", "png:"+normalized); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
f, e := os.Open(normalized)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
cfg, _, e := image.DecodeConfig(f)
|
||||
f.Close()
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
tw, th := fit(cfg.Width, cfg.Height, 256)
|
||||
ow, oh := fit(cfg.Width, cfg.Height, 1280)
|
||||
out := []Result{{"thumbnail", filepath.Join(dir, "thumbnail.jpg"), "image/jpeg", tw, th}, {"crop", filepath.Join(dir, "crop.jpg"), "image/jpeg", 128, 128}, {"optimized", filepath.Join(dir, "optimized.webp"), "image/webp", ow, oh}}
|
||||
for _, v := range out {
|
||||
args := []string{normalized}
|
||||
if v.Name == "crop" {
|
||||
side := min(cfg.Width, cfg.Height)
|
||||
args = append(args, "-gravity", "center", "-crop", fmt.Sprintf("%dx%d+0+0", side, side), "+repage")
|
||||
}
|
||||
args = append(args, "-resize", fmt.Sprintf("%dx%d!", v.Width, v.Height), "-strip", "-quality")
|
||||
quality := "85"
|
||||
if v.Name == "optimized" && version == 1 {
|
||||
quality = "80"
|
||||
}
|
||||
coder := "jpeg:"
|
||||
if v.Name == "optimized" {
|
||||
coder = "webp:"
|
||||
}
|
||||
args = append(args, quality, coder+v.Path)
|
||||
if e = run(ctx, args...); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
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 {
|
||||
if m.conn == nil || m.closed {
|
||||
return nil
|
||||
}
|
||||
if err := m.closeConn(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
m.closed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
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 {
|
||||
return m.Close(ctx)
|
||||
}
|
||||
|
||||
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.closed = false
|
||||
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,97 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/telemetry"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/smithy-go"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
Client *s3.Client
|
||||
Bucket string
|
||||
}
|
||||
|
||||
func New(c *config.Attachment) *Store {
|
||||
return &Store{
|
||||
Bucket: c.Bucket,
|
||||
Client: s3.New(
|
||||
s3.Options{
|
||||
Region: c.Region,
|
||||
BaseEndpoint: aws.String(c.Endpoint),
|
||||
UsePathStyle: true,
|
||||
Credentials: credentials.NewStaticCredentialsProvider(
|
||||
c.AccessKey,
|
||||
c.SecretKey,
|
||||
"",
|
||||
),
|
||||
RetryMaxAttempts: 1,
|
||||
HTTPClient: &http.Client{Timeout: 30 * time.Second},
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) Put(ctx context.Context, key, mime string, r io.Reader, size int64) (err error) {
|
||||
ctx, sp := telemetry.Start(ctx, "s3.put", trace.SpanKindClient)
|
||||
defer func() { telemetry.End(sp, err) }()
|
||||
|
||||
_, err = s.Client.PutObject(ctx, &s3.PutObjectInput{Bucket: &s.Bucket, Key: &key, Body: r, ContentLength: &size, ContentType: &mime})
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) Get(ctx context.Context, key string) (out *s3.GetObjectOutput, err error) {
|
||||
ctx, sp := telemetry.Start(ctx, "s3.get", trace.SpanKindClient)
|
||||
defer func() { telemetry.End(sp, err) }()
|
||||
|
||||
return s.Client.GetObject(ctx, &s3.GetObjectInput{Bucket: &s.Bucket, Key: &key})
|
||||
}
|
||||
|
||||
func (s *Store) Head(ctx context.Context, key string) (out *s3.HeadObjectOutput, err error) {
|
||||
ctx, sp := telemetry.Start(ctx, "s3.head", trace.SpanKindClient)
|
||||
defer func() { telemetry.End(sp, err) }()
|
||||
|
||||
return s.Client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: &s.Bucket, Key: &key})
|
||||
}
|
||||
|
||||
func (s *Store) Delete(ctx context.Context, key string) (err error) {
|
||||
ctx, sp := telemetry.Start(ctx, "s3.delete", trace.SpanKindClient)
|
||||
defer func() { telemetry.End(sp, err) }()
|
||||
|
||||
_, err = s.Client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: &s.Bucket, Key: &key})
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) (err error) {
|
||||
ctx, sp := telemetry.Start(ctx, "s3.ping", trace.SpanKindClient)
|
||||
defer func() { telemetry.End(sp, err) }()
|
||||
|
||||
_, err = s.Client.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: &s.Bucket})
|
||||
return err
|
||||
}
|
||||
|
||||
func Missing(err error) bool {
|
||||
var api smithy.APIError
|
||||
return errors.As(err, &api) && (api.ErrorCode() == "NoSuchKey" || api.ErrorCode() == "NotFound" || api.ErrorCode() == "404")
|
||||
}
|
||||
|
||||
func (s *Store) List(ctx context.Context, token string) (out *s3.ListObjectsV2Output, err error) {
|
||||
ctx, sp := telemetry.Start(ctx, "s3.list", trace.SpanKindClient)
|
||||
defer func() { telemetry.End(sp, err) }()
|
||||
|
||||
q := &s3.ListObjectsV2Input{Bucket: &s.Bucket, MaxKeys: aws.Int32(100)}
|
||||
if token != "" {
|
||||
q.ContinuationToken = &token
|
||||
}
|
||||
return s.Client.ListObjectsV2(ctx, q)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package postgres
|
||||
|
||||
type MigrationConfig interface {
|
||||
GetURI() string
|
||||
GetVersionTableName() string
|
||||
GetRunMigrations() bool
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/tracelog"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/telemetry"
|
||||
)
|
||||
|
||||
type ConfigWithLog interface {
|
||||
GetLogLevel() string
|
||||
}
|
||||
|
||||
type ConfigWithTimeouts interface {
|
||||
GetConnectTimeout() time.Duration
|
||||
GetQueryTimeout() time.Duration
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
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)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
addMaxConnectionsToCfg(cfg, poolConfig)
|
||||
if timeoutCfg, ok := cfg.(ConfigWithTimeouts); ok {
|
||||
poolConfig.ConnConfig.ConnectTimeout = timeoutCfg.GetConnectTimeout()
|
||||
poolConfig.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(timeoutCfg.GetQueryTimeout().Milliseconds(), 10)
|
||||
}
|
||||
poolConfig.ConnConfig.RuntimeParams["application_name"] = "mtusi-api"
|
||||
slog.Info("postgres_pool_config", "max_conns", poolConfig.MaxConns,
|
||||
"connect_timeout", poolConfig.ConnConfig.ConnectTimeout,
|
||||
"statement_timeout_ms", poolConfig.ConnConfig.RuntimeParams["statement_timeout"])
|
||||
|
||||
poolConfig.ConnConfig.Tracer = telemetry.DBTracer{}
|
||||
|
||||
poolConfig.AfterConnect = load(afterConnect...)
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(context.Background(), poolConfig)
|
||||
if err != nil {
|
||||
slog.Error("failed to create postgres pool", "error", err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
slog.Info("successfully connected to postgres pool")
|
||||
return pool
|
||||
}
|
||||
|
||||
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,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))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/go-chi/chi/v5"
|
||||
mw "github.com/go-chi/chi/v5/middleware"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func HTTP(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, sp := Start(Extract(r.Context(), r.Header.Get("traceparent"), r.Header.Get("tracestate")), "HTTP", trace.SpanKindServer)
|
||||
start := time.Now()
|
||||
ww := mw.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
defer func() {
|
||||
route := chi.RouteContext(ctx).RoutePattern()
|
||||
if route == "" {
|
||||
route = "unmatched"
|
||||
}
|
||||
method := r.Method
|
||||
switch method {
|
||||
case "GET", "POST", "DELETE", "PUT", "PATCH", "HEAD", "OPTIONS":
|
||||
default:
|
||||
method = "OTHER"
|
||||
}
|
||||
status := ww.Status()
|
||||
if status == 0 {
|
||||
status = 200
|
||||
}
|
||||
sp.SetName(method + " " + route)
|
||||
sp.SetAttributes(attribute.String("http.route", route), attribute.String("http.request.method", method), attribute.Int("http.response.status_code", status))
|
||||
if status >= 500 {
|
||||
sp.SetStatus(codes.Error, "server_error")
|
||||
}
|
||||
a := []attribute.KeyValue{attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", strconv.Itoa(status/100)+"xx")}
|
||||
Count(ctx, "messenger.http.requests", 1, a...)
|
||||
Duration(ctx, "messenger.http.duration", time.Since(start), a[:2]...)
|
||||
slog.InfoContext(ctx, "http_request", "method", method, "route", route, "status", status, "request_id", w.Header().Get("X-Request-Id"))
|
||||
sp.End()
|
||||
}()
|
||||
next.ServeHTTP(ww, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// RegisterRoute publishes zero counters before any outcome, preserving the first spike.
|
||||
func RegisterRoute(method, route string) {
|
||||
for _, class := range []string{"1xx", "2xx", "3xx", "4xx", "5xx"} {
|
||||
Count(context.Background(), "messenger.http.requests", 0, attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", class))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
var QueueDepth atomic.Int64
|
||||
var observationMu sync.RWMutex
|
||||
|
||||
type observationSnapshot struct {
|
||||
Queued, Outbox, Good, Bad int64
|
||||
Locked int64
|
||||
Oldest float64
|
||||
}
|
||||
|
||||
var snapshot observationSnapshot
|
||||
var observed time.Time
|
||||
|
||||
func PublishObservation(queued, outbox, good, bad int64, oldest float64, locked int64) {
|
||||
s := observationSnapshot{Queued: queued, Outbox: outbox, Good: good, Bad: bad, Oldest: oldest, Locked: locked}
|
||||
observationMu.Lock()
|
||||
snapshot = s
|
||||
observed = time.Now()
|
||||
observationMu.Unlock()
|
||||
}
|
||||
func RegisterObservation() {
|
||||
locks, _ := meter.Int64ObservableGauge("messenger.db.locks.waiting")
|
||||
pending, _ := meter.Int64ObservableGauge("messenger.jobs.pending")
|
||||
outbox, _ := meter.Int64ObservableGauge("messenger.outbox.pending")
|
||||
queue, _ := meter.Int64ObservableGauge("messenger.queue.depth")
|
||||
age, _ := meter.Float64ObservableGauge("messenger.queue.oldest.age", metric.WithUnit("s"))
|
||||
fresh, _ := meter.Float64ObservableGauge("messenger.observation.timestamp")
|
||||
slo, _ := meter.Int64ObservableCounter("messenger.ready.slo")
|
||||
_, _ = meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
|
||||
observationMu.RLock()
|
||||
s, t := snapshot, observed
|
||||
observationMu.RUnlock()
|
||||
if t.IsZero() {
|
||||
return nil
|
||||
}
|
||||
o.ObserveInt64(locks, s.Locked)
|
||||
o.ObserveInt64(pending, s.Queued)
|
||||
o.ObserveInt64(outbox, s.Outbox)
|
||||
o.ObserveInt64(queue, QueueDepth.Load(), metric.WithAttributes(attribute.String("queue", "attachments.v1")))
|
||||
o.ObserveFloat64(age, s.Oldest, metric.WithAttributes(attribute.String("queue", "attachments.v1")))
|
||||
o.ObserveFloat64(fresh, float64(t.Unix()))
|
||||
o.ObserveInt64(slo, s.Good, metric.WithAttributes(attribute.String("outcome", "good")))
|
||||
o.ObserveInt64(slo, s.Bad, metric.WithAttributes(attribute.String("outcome", "bad")))
|
||||
return nil
|
||||
}, locks, pending, outbox, queue, age, fresh, slo)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/shirou/gopsutil/v4/process"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
var waiting atomic.Int64
|
||||
|
||||
func ObservePool(pool *pgxpool.Pool, capacity int) {
|
||||
names := []string{"messenger.db.pool.used", "messenger.db.pool.capacity", "messenger.db.pool.waiting", "messenger.worker.busy", "messenger.worker.capacity", "messenger.process.memory", "messenger.process.cpu", "messenger.telemetry.export_errors"}
|
||||
instruments := make([]metric.Float64ObservableGauge, len(names))
|
||||
for i, n := range names {
|
||||
instruments[i], _ = meter.Float64ObservableGauge(n)
|
||||
}
|
||||
p, _ := process.NewProcess(int32(os.Getpid()))
|
||||
obs := make([]metric.Observable, len(instruments))
|
||||
for i, g := range instruments {
|
||||
obs[i] = g
|
||||
}
|
||||
_, _ = meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
|
||||
st := pool.Stat()
|
||||
v := []float64{float64(st.AcquiredConns()), float64(st.MaxConns()), float64(waiting.Load()), float64(Busy.Load()), float64(capacity), 0, 0, float64(ExportErrors.Load())}
|
||||
if p != nil {
|
||||
if m, e := p.MemoryInfoWithContext(ctx); e == nil {
|
||||
v[5] = float64(m.RSS)
|
||||
}
|
||||
if t, e := p.TimesWithContext(ctx); e == nil {
|
||||
v[6] = t.User + t.System
|
||||
}
|
||||
}
|
||||
for i, g := range instruments {
|
||||
o.ObserveFloat64(g, v[i])
|
||||
}
|
||||
return nil
|
||||
}, obs...)
|
||||
}
|
||||
|
||||
type DBTracer struct{}
|
||||
type acquireKey struct{}
|
||||
|
||||
func (DBTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context {
|
||||
op := "OTHER"
|
||||
f := strings.Fields(d.SQL)
|
||||
if len(f) > 0 {
|
||||
switch strings.ToUpper(f[0]) {
|
||||
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK":
|
||||
op = strings.ToUpper(f[0])
|
||||
}
|
||||
}
|
||||
ctx, sp := Start(ctx, "postgresql "+op, trace.SpanKindClient)
|
||||
sp.SetAttributes(attribute.String("db.system.name", "postgresql"), attribute.String("db.operation.name", op))
|
||||
return ctx
|
||||
}
|
||||
func (DBTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryEndData) {
|
||||
End(trace.SpanFromContext(ctx), d.Err)
|
||||
}
|
||||
func (DBTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
|
||||
waiting.Add(1)
|
||||
return context.WithValue(ctx, acquireKey{}, time.Now())
|
||||
}
|
||||
func (DBTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, d pgxpool.TraceAcquireEndData) {
|
||||
waiting.Add(-1)
|
||||
if t, ok := ctx.Value(acquireKey{}).(time.Time); ok {
|
||||
Duration(ctx, "messenger.db.acquire.duration", time.Since(t))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// Package telemetry owns signal export and safe, low-cardinality instrumentation.
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.opentelemetry.io/contrib/bridges/otelslog"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
sdklog "go.opentelemetry.io/otel/sdk/log"
|
||||
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
var InstanceID = uuid.NewString()
|
||||
var Busy atomic.Int64
|
||||
var meter = otel.Meter("messenger")
|
||||
var tracer = otel.Tracer("messenger")
|
||||
|
||||
// A fanout retains local JSON and exports the same structured event over OTLP.
|
||||
type handler struct{ local, remote slog.Handler }
|
||||
|
||||
func (h handler) Enabled(c context.Context, l slog.Level) bool { return h.local.Enabled(c, l) }
|
||||
func (h handler) Handle(c context.Context, r slog.Record) error {
|
||||
// Errors can contain SQL values, credentials or invalid request content.
|
||||
safe := slog.NewRecord(r.Time, r.Level, r.Message, r.PC)
|
||||
r.Attrs(func(a slog.Attr) bool {
|
||||
key := strings.ToLower(a.Key)
|
||||
switch key {
|
||||
case "authorization", "password", "token", "session_token", "body", "filename", "url":
|
||||
return true
|
||||
case "error":
|
||||
a = slog.String("error.type", "operation_failed")
|
||||
}
|
||||
safe.AddAttrs(a)
|
||||
return true
|
||||
})
|
||||
r = safe
|
||||
sc := trace.SpanContextFromContext(c)
|
||||
r.AddAttrs(slog.String("event", r.Message))
|
||||
if sc.IsValid() {
|
||||
r.AddAttrs(slog.String("trace_id", sc.TraceID().String()), slog.String("span_id", sc.SpanID().String()))
|
||||
}
|
||||
_ = h.remote.Handle(c, r)
|
||||
return h.local.Handle(c, r)
|
||||
}
|
||||
func (h handler) WithAttrs(a []slog.Attr) slog.Handler {
|
||||
return handler{h.local.WithAttrs(a), h.remote.WithAttrs(a)}
|
||||
}
|
||||
func (h handler) WithGroup(g string) slog.Handler {
|
||||
return handler{h.local.WithGroup(g), h.remote.WithGroup(g)}
|
||||
}
|
||||
|
||||
func Init(ctx context.Context, name string) (func(), error) {
|
||||
otel.SetTextMapPropagator(propagation.TraceContext{})
|
||||
if os.Getenv("OTEL_SDK_DISABLED") == "true" {
|
||||
return func() {}, nil
|
||||
}
|
||||
res := resource.NewWithAttributes("", attribute.String("service.name", name), attribute.String("service.version", "lab6"), attribute.String("service.instance.id", InstanceID), attribute.String("deployment.environment.name", "lab"))
|
||||
te, e := otlptracehttp.New(ctx, otlptracehttp.WithTimeout(time.Second))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res), sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), sdktrace.WithBatcher(te, sdktrace.WithMaxQueueSize(1024), sdktrace.WithMaxExportBatchSize(128), sdktrace.WithBatchTimeout(time.Second), sdktrace.WithExportTimeout(time.Second)))
|
||||
me, e := otlpmetrichttp.New(ctx, otlpmetrichttp.WithTimeout(time.Second))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
mp := sdkmetric.NewMeterProvider(sdkmetric.WithResource(res), sdkmetric.WithReader(sdkmetric.NewPeriodicReader(me, sdkmetric.WithInterval(5*time.Second), sdkmetric.WithTimeout(time.Second))))
|
||||
le, e := otlploghttp.New(ctx, otlploghttp.WithTimeout(time.Second))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
lp := sdklog.NewLoggerProvider(sdklog.WithResource(res), sdklog.WithProcessor(sdklog.NewBatchProcessor(le, sdklog.WithMaxQueueSize(1024), sdklog.WithExportMaxBatchSize(128), sdklog.WithExportInterval(time.Second), sdklog.WithExportTimeout(time.Second))))
|
||||
otel.SetTracerProvider(tp)
|
||||
otel.SetMeterProvider(mp)
|
||||
if name == "messenger-worker" {
|
||||
for _, outcome := range []string{"ready", "retry", "failed", "duplicate"} {
|
||||
Count(ctx, "messenger.jobs", 0, attribute.String("job_type", "attachment.process.v1"), attribute.String("outcome", outcome))
|
||||
}
|
||||
}
|
||||
local := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}).WithAttrs([]slog.Attr{slog.String("service.name", name), slog.String("service.instance.id", InstanceID)})
|
||||
slog.SetDefault(slog.New(handler{local, otelslog.NewHandler("messenger", otelslog.WithLoggerProvider(lp))}))
|
||||
// Export failures are summarized safely and never include payloads or endpoints.
|
||||
otel.SetErrorHandler(otel.ErrorHandlerFunc(func(error) { ExportErrors.Add(1) }))
|
||||
return func() {
|
||||
c, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
defer cancel()
|
||||
_ = mp.Shutdown(c)
|
||||
_ = lp.Shutdown(c)
|
||||
_ = tp.Shutdown(c)
|
||||
}, nil
|
||||
}
|
||||
|
||||
var ExportErrors atomic.Int64
|
||||
|
||||
func Start(ctx context.Context, name string, kind trace.SpanKind) (context.Context, trace.Span) {
|
||||
return tracer.Start(ctx, name, trace.WithSpanKind(kind))
|
||||
}
|
||||
func End(span trace.Span, err error) {
|
||||
if err != nil {
|
||||
span.SetStatus(codes.Error, "operation_failed")
|
||||
span.SetAttributes(attribute.String("error.type", "dependency_or_processing"))
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
func Inject(ctx context.Context) (string, string) {
|
||||
c := propagation.MapCarrier{}
|
||||
otel.GetTextMapPropagator().Inject(ctx, c)
|
||||
return c.Get("traceparent"), c.Get("tracestate")
|
||||
}
|
||||
func Extract(ctx context.Context, p, s string) context.Context {
|
||||
return otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{"traceparent": p, "tracestate": s})
|
||||
}
|
||||
func Count(ctx context.Context, name string, n int64, a ...attribute.KeyValue) {
|
||||
c, _ := meter.Int64Counter(name)
|
||||
c.Add(ctx, n, metric.WithAttributes(a...))
|
||||
}
|
||||
func Duration(ctx context.Context, name string, d time.Duration, a ...attribute.KeyValue) {
|
||||
h, _ := meter.Float64Histogram(name, metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(.005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10, 20, 30, 60, 120, 300))
|
||||
h.Record(ctx, d.Seconds(), metric.WithAttributes(a...))
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package authprovider
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types"
|
||||
)
|
||||
|
||||
type Type string
|
||||
|
||||
const (
|
||||
TypeUndefined Type = "undefined"
|
||||
TypePassword Type = "password"
|
||||
TypeEmail Type = "email"
|
||||
TypePhone Type = "phone"
|
||||
TypeGoogle Type = "google"
|
||||
TypeTelegram Type = "telegram"
|
||||
)
|
||||
|
||||
var allowedTypes = map[Type]struct{}{
|
||||
TypePassword: {},
|
||||
TypeEmail: {},
|
||||
TypePhone: {},
|
||||
TypeGoogle: {},
|
||||
TypeTelegram: {},
|
||||
}
|
||||
|
||||
func ParseType(value string) Type {
|
||||
t := Type(strings.ToLower(value))
|
||||
if !t.IsValid() {
|
||||
return TypeUndefined
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func ParseAndValidateType(value string) (Type, error) {
|
||||
parsed := ParseType(value)
|
||||
if _, ok := allowedTypes[parsed]; ok {
|
||||
return parsed, nil
|
||||
}
|
||||
return TypeUndefined, types.ErrUnsupportedOTPStatus
|
||||
}
|
||||
|
||||
func (t Type) String() string {
|
||||
return string(t)
|
||||
}
|
||||
|
||||
func (t Type) Validate() error {
|
||||
if _, ok := allowedTypes[t]; ok {
|
||||
return nil
|
||||
}
|
||||
return types.ErrUnsupportedAuthProviderType
|
||||
}
|
||||
|
||||
func (t Type) IsValid() bool {
|
||||
_, ok := allowedTypes[t]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (t Type) MarshalJSON() ([]byte, error) {
|
||||
if err := t.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(t.String())
|
||||
}
|
||||
|
||||
func (t *Type) UnmarshalJSON(data []byte) error {
|
||||
if t == nil {
|
||||
return types.ErrUnmarshalAuthProviderTypeIntoNilPointer
|
||||
}
|
||||
var value string
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
parsed := ParseType(value)
|
||||
if err := parsed.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
*t = parsed
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package environment
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types"
|
||||
)
|
||||
|
||||
type ApplicationEnvironment string
|
||||
|
||||
const (
|
||||
ApplicationEnvironmentUndefined ApplicationEnvironment = "undefined"
|
||||
ApplicationEnvironmentDev ApplicationEnvironment = "dev"
|
||||
ApplicationEnvironmentProd ApplicationEnvironment = "prod"
|
||||
)
|
||||
|
||||
var allowedEnvironments = map[ApplicationEnvironment]struct{}{
|
||||
ApplicationEnvironmentUndefined: {},
|
||||
ApplicationEnvironmentDev: {},
|
||||
ApplicationEnvironmentProd: {},
|
||||
}
|
||||
|
||||
func ParseEnvironment(value string) ApplicationEnvironment {
|
||||
s := ApplicationEnvironment(strings.ToLower(value))
|
||||
if !s.IsValid() {
|
||||
return ApplicationEnvironmentUndefined
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func ParseAndValidateEnvironment(status string) (ApplicationEnvironment, error) {
|
||||
parsed := ParseEnvironment(status)
|
||||
if _, ok := allowedEnvironments[parsed]; ok {
|
||||
return parsed, nil
|
||||
}
|
||||
return ApplicationEnvironmentUndefined, types.ErrUnsupportedApplicationEnvironment
|
||||
}
|
||||
|
||||
func (t ApplicationEnvironment) String() string {
|
||||
return string(t)
|
||||
}
|
||||
|
||||
func (t ApplicationEnvironment) Validate() error {
|
||||
if _, ok := allowedEnvironments[t]; ok {
|
||||
return nil
|
||||
}
|
||||
return types.ErrUnsupportedApplicationEnvironment
|
||||
}
|
||||
|
||||
func (t ApplicationEnvironment) IsValid() bool {
|
||||
_, ok := allowedEnvironments[t]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (t ApplicationEnvironment) MarshalJSON() ([]byte, error) {
|
||||
if err := t.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(t.String())
|
||||
}
|
||||
|
||||
func (t *ApplicationEnvironment) UnmarshalJSON(data []byte) error {
|
||||
if t == nil {
|
||||
return types.ErrUnmarshalApplicationEnvironmentIntoNilPointer
|
||||
}
|
||||
var value string
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
parsed := ParseEnvironment(value)
|
||||
if err := parsed.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
*t = parsed
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package types
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrUnsupportedRole = errors.New("unsupported role")
|
||||
ErrUnsupportedOTPType = errors.New("unsupported OTP type")
|
||||
ErrUnsupportedAuthProviderType = errors.New("unsupported auth provider type")
|
||||
ErrUnsupportedContactType = errors.New("unsupported contact type")
|
||||
ErrUnsupportedOTPStatus = errors.New("unsupported OTP status")
|
||||
ErrUnsupportedOTPResult = errors.New("unsupported OTP result")
|
||||
ErrUnsupportedFormStatus = errors.New("unsupported form status")
|
||||
ErrUnsupportedAuthIdentityStatus = errors.New("unsupported auth identity status")
|
||||
ErrUnsupportedApplicationEnvironment = errors.New("unsupported application environment")
|
||||
|
||||
ErrUnmarshalRoleIntoNilPointer = errors.New("unmarshal role into nil pointer")
|
||||
ErrUnmarshalOTPTypeIntoNilPointer = errors.New("unmarshal OTP type into nil pointer")
|
||||
ErrUnmarshalAuthProviderTypeIntoNilPointer = errors.New("unmarshal auth provider into nil pointer")
|
||||
ErrUnmarshalContactTypeIntoNilPointer = errors.New("unmarshal contact into nil pointer")
|
||||
ErrUnmarshalOTPStatusIntoNilPointer = errors.New("unmarshal OTP status into nil pointer")
|
||||
ErrUnmarshalOTPResultIntoNilPointer = errors.New("unmarshal OTP result into nil pointer")
|
||||
ErrUnmarshalFormStatusIntoNilPointer = errors.New("unmarshal form status into nil pointer")
|
||||
ErrUnmarshalAuthIdentityStatusIntoNilPointer = errors.New("unmarshal auth identity status into nil pointer")
|
||||
ErrUnmarshalApplicationEnvironmentIntoNilPointer = errors.New("unmarshal application environment into nil pointer")
|
||||
)
|
||||
@@ -0,0 +1,105 @@
|
||||
package role
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types"
|
||||
)
|
||||
|
||||
type Role string
|
||||
|
||||
const (
|
||||
Undefined Role = "undefined"
|
||||
User Role = "user"
|
||||
Doctor Role = "doctor"
|
||||
Manager Role = "manager"
|
||||
Admin Role = "admin"
|
||||
)
|
||||
|
||||
var allowedRoles = map[Role]struct{}{
|
||||
User: {},
|
||||
Doctor: {},
|
||||
Manager: {},
|
||||
Admin: {},
|
||||
}
|
||||
|
||||
func ParseRole(s string) Role {
|
||||
r := Role(strings.ToLower(s))
|
||||
if !r.IsValid() {
|
||||
return Undefined
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func ParseAndValidateRole(s string) (Role, error) {
|
||||
parsed := ParseRole(s)
|
||||
if _, ok := allowedRoles[parsed]; ok {
|
||||
return parsed, nil
|
||||
}
|
||||
return Undefined, types.ErrUnsupportedRole
|
||||
}
|
||||
|
||||
func (t Role) String() string {
|
||||
return string(t)
|
||||
}
|
||||
|
||||
func (t Role) Validate() error {
|
||||
if _, ok := allowedRoles[t]; ok {
|
||||
return nil
|
||||
}
|
||||
return types.ErrUnsupportedRole
|
||||
}
|
||||
|
||||
func (t Role) IsValid() bool {
|
||||
_, ok := allowedRoles[t]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (t Role) MarshalJSON() ([]byte, error) {
|
||||
if err := t.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(t.String())
|
||||
}
|
||||
|
||||
func (t *Role) UnmarshalJSON(data []byte) error {
|
||||
if t == nil {
|
||||
return types.ErrUnmarshalRoleIntoNilPointer
|
||||
}
|
||||
var value string
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
parsed := ParseRole(value)
|
||||
if err := parsed.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
*t = parsed
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t Role) IsAdmin() bool {
|
||||
return t == Admin
|
||||
}
|
||||
|
||||
func (t Role) IsManager() bool {
|
||||
return t == Manager
|
||||
}
|
||||
|
||||
func (t Role) IsDoctor() bool {
|
||||
return t == Doctor
|
||||
}
|
||||
|
||||
func (t Role) IsUser() bool {
|
||||
return t == User
|
||||
}
|
||||
|
||||
func (t Role) IsPrivileged() bool {
|
||||
switch t {
|
||||
case Doctor, Manager, Admin:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package validator
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
type TagKey string
|
||||
|
||||
type ValidatorImpl struct {
|
||||
validator *validator.Validate
|
||||
}
|
||||
|
||||
func NewValidatorImpl() *ValidatorImpl {
|
||||
return &ValidatorImpl{validator: validator.New()}
|
||||
}
|
||||
|
||||
func (v *ValidatorImpl) Register(tag TagKey, fn validator.Func, callValidationEvenIfNull ...bool) error {
|
||||
return v.validator.RegisterValidation(string(tag), fn, callValidationEvenIfNull...)
|
||||
}
|
||||
|
||||
func (v *ValidatorImpl) ValidateCtx(ctx context.Context, value any) error {
|
||||
return v.validator.StructCtx(ctx, value)
|
||||
}
|
||||
|
||||
func (v *ValidatorImpl) Validate(value any) error {
|
||||
return v.validator.Struct(value)
|
||||
}
|
||||
Reference in New Issue
Block a user