Organize backend into product executable and shared Go modules

This commit is contained in:
Stephan D committed 2026-09-12 14:14:08 +02:00
1 parent 981e84a4b4
commit f0720ec66b
382 files changed
+1944 -6989

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
# SXCHNGE product BFF
This Go module is the customer-facing executable. `main.go` composes the copied
runtime and local customer service. Customers, auth, sessions and verification
own their models and supporting code; generic infrastructure comes from the
sibling `shared` library module.
## Run
Requires Go 1.27 and an SXCHNGE-owned MongoDB replica set for transactions.
Copy `config.example.yml` to an untracked `config.yml` in this directory. Set:
- `SXCHNGE_MONGO_URI`: URI for SXCHNGE's database.
- `SXCHNGE_JWT_SECRET`: random signing key, at least 32 bytes for HS256.
- `SXCHNGE_DOMAIN`: local hostname, such as `localhost:8082`.
- `SXCHNGE_API_PROTOCOL`: `http` locally, `https` in deployment.
- `SXCHNGE_API_ENDPOINT`: `/api/v1`.
From the repository root, run `make run-backend`, or run `go run .` here.
Flags: `-config.file`, `-version`, `-debug`. Configure exact browser origins in
YAML; browser refresh cookies require HTTPS. An empty local database needs no
organization, role, policy or seed; the runtime creates its indexes.
The runtime mounts health, login, API login, refresh, rotation and logout routes.
Customer/application-client records must exist for login. The customer service
supports atomic account/activation creation and deletion with session revocation.
Signup/profile HTTP wiring and verification delivery/completion remain follow-up
work. The frontend still uses dummy services.
Sendico integration is not wired. Its organization context belongs only to the
future public HTTP adapter. There is no unused public API snapshot in this module;
copy only the wire definitions consumed by an implemented adapter.
## Validate
`go test -race ./...` and `go vet ./...` validate this module. Tests require Docker
for disposable Mongo replica sets. Root `make test` and `make lint-backend` also
validate `shared`. See [source provenance](../PROVENANCE.md).
+23
View File
@@ -0,0 +1,23 @@
package api
import (
"context"
"git.sendico.io/tech/sxchnge/product/app/urls"
"git.sendico.io/tech/sxchnge/shared/database"
"git.sendico.io/tech/sxchnge/shared/logging"
"git.sendico.io/tech/sxchnge/shared/service"
)
type API interface {
LifecycleContext() context.Context
Logger() mlogger.Logger
DomainProvider() domainprovider.DomainProvider
Config() *Config
ProfileConfig() ConfigProvider
DBFactory() db.Factory
RuntimeComponent(name string) any
Register() Register
}
type MicroServiceFactoryT = func(API) (mservice.MicroService, error)
+16
View File
@@ -0,0 +1,16 @@
package api
import (
mwa "git.sendico.io/tech/sxchnge/product/auth/config"
verificationconfig "git.sendico.io/tech/sxchnge/product/verification/config"
)
type Config struct {
Mw *mwa.Config `yaml:"middleware"`
AuthStorage *mwa.AuthStorageConfig `yaml:"auth_storage"`
Verification *verificationconfig.Config `yaml:"verification"`
}
func (c *Config) SharedConfig() *Config {
return c
}
+13
View File
@@ -0,0 +1,13 @@
package api
import (
"git.sendico.io/tech/sxchnge/product/auth/response"
api "git.sendico.io/tech/sxchnge/shared/http"
"git.sendico.io/tech/sxchnge/shared/service"
)
type Register interface {
Handler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.HandlerFunc)
AccountHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.AccountHandlerFunc)
PendingAccountHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.PendingAccountHandlerFunc)
}
+39
View File
@@ -0,0 +1,39 @@
package api
import "git.sendico.io/tech/sxchnge/shared/service"
type ConfigProvider interface {
SharedConfig() *Config
}
type ConfigFactory func() ConfigProvider
type RuntimeComponents map[string]any
type RuntimeBootstrapFunc func(API) (RuntimeComponents, error)
type RuntimeFinishFunc func(API) error
type RuntimeConfig struct {
Name string
Services []ServiceFactory
ConfigFactory ConfigFactory
Bootstrap RuntimeBootstrapFunc
Finish RuntimeFinishFunc
}
type ServiceFactory struct {
Name mservice.Type
Factory MicroServiceFactoryT
}
func (cfg RuntimeConfig) RuntimeName() string {
if cfg.Name == "" {
return "edge"
}
return cfg.Name
}
func (cfg RuntimeConfig) NewConfig() ConfigProvider {
if cfg.ConfigFactory != nil {
return cfg.ConfigFactory()
}
return &Config{}
}
+18
View File
@@ -0,0 +1,18 @@
package routers
import (
"git.sendico.io/tech/sxchnge/product/app/health/internal"
"git.sendico.io/tech/sxchnge/product/app/health/status"
"git.sendico.io/tech/sxchnge/shared/logging"
"github.com/go-chi/chi/v5"
)
type Health interface {
SetStatus(status health.ServiceStatus)
SetStatusWithReason(status health.ServiceStatus, reason string)
Finish()
}
func NewHealthRouter(logger mlogger.Logger, router chi.Router, endpoint string) (Health, error) {
return healthimp.NewRouter(logger, router, endpoint), nil
}
@@ -0,0 +1,76 @@
package healthimp
import (
"net/http"
"strings"
"git.sendico.io/tech/sxchnge/product/app/health/status"
"git.sendico.io/tech/sxchnge/shared/logging"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"
)
type Router struct {
logger mlogger.Logger
status *Status
}
func (hr *Router) SetStatus(status health.ServiceStatus) {
hr.SetStatusWithReason(status, defaultReason(status))
}
func (hr *Router) SetStatusWithReason(status health.ServiceStatus, reason string) {
previous, changed := hr.status.transition(status)
if !changed {
return
}
reason = strings.TrimSpace(reason)
if reason == "" {
reason = defaultReason(status)
}
hr.logger.Info("Health status changed",
zap.String("previous_status", string(previous)),
zap.String("status", string(status)),
zap.String("reason", reason),
)
}
func (hr *Router) Finish() {
hr.status.Finish()
hr.logger.Debug("Stopped")
}
func (hr *Router) handle(w http.ResponseWriter, r *http.Request) {
hr.status.healthHandler()(w, r)
}
func NewRouter(logger mlogger.Logger, router chi.Router, endpoint string) *Router {
hr := Router{
logger: logger.Named("health_check"),
}
hr.status = StatusHandler(hr.logger)
logger.Debug("Installing healthcheck middleware...")
router.Group(func(r chi.Router) {
ep := endpoint + "/health"
r.Get(ep, hr.handle)
logger.Info("Health handler installed", zap.String("endpoint", ep))
})
return &hr
}
func defaultReason(status health.ServiceStatus) string {
switch status {
case health.SSCreated:
return "service created"
case health.SSStarting:
return "service is starting"
case health.SSRunning:
return "service is ready"
case health.SSTerminating:
return "service is shutting down"
default:
return "service health status changed"
}
}
@@ -0,0 +1,53 @@
package healthimp
import (
"testing"
"git.sendico.io/tech/sxchnge/product/app/health/status"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"
"go.uber.org/zap/zaptest/observer"
)
func TestSetStatusLogsOnlyTransitionsWithReason(t *testing.T) {
core, observed := observer.New(zap.InfoLevel)
router := NewRouter(zap.New(core), chi.NewRouter(), "")
router.SetStatusWithReason(health.SSStarting, "observability endpoint initialized")
router.SetStatusWithReason(health.SSStarting, "duplicate readiness report")
router.SetStatusWithReason(health.SSRunning, "all configured ingestion drivers are ready")
router.SetStatus(health.SSRunning)
entries := observed.FilterMessage("Health status changed").All()
if len(entries) != 2 {
t.Fatalf("health transition log count = %d, want 2", len(entries))
}
assertTransition(t, entries[0].ContextMap(), "created", "starting", "observability endpoint initialized")
assertTransition(t, entries[1].ContextMap(), "starting", "ok", "all configured ingestion drivers are ready")
}
func TestSetStatusUsesNonEmptyDefaultReason(t *testing.T) {
core, observed := observer.New(zap.InfoLevel)
router := NewRouter(zap.New(core), chi.NewRouter(), "")
router.SetStatusWithReason(health.SSTerminating, " ")
entries := observed.FilterMessage("Health status changed").All()
if len(entries) != 1 {
t.Fatalf("health transition log count = %d, want 1", len(entries))
}
assertTransition(t, entries[0].ContextMap(), "created", "deactivating", "service is shutting down")
}
func assertTransition(t *testing.T, fields map[string]any, previous, status, reason string) {
t.Helper()
for key, want := range map[string]string{
"previous_status": previous,
"status": status,
"reason": reason,
} {
if got, ok := fields[key].(string); !ok || got != want {
t.Fatalf("%s = %v, want %q", key, fields[key], want)
}
}
}
@@ -0,0 +1,50 @@
package healthimp
import (
"net/http"
"sync"
"git.sendico.io/tech/sxchnge/product/app/health/status"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/logging"
)
type Status struct {
logger mlogger.Logger
mu sync.RWMutex
status health.ServiceStatus
}
func (hs *Status) healthHandler() http.HandlerFunc {
hs.mu.RLock()
status := hs.status
hs.mu.RUnlock()
return response.Ok(hs.logger, struct {
Status health.ServiceStatus `json:"status"`
}{
status,
})
}
func (hr *Status) Finish() {
hr.logger.Info("Finished")
}
func (hs *Status) transition(status health.ServiceStatus) (health.ServiceStatus, bool) {
hs.mu.Lock()
defer hs.mu.Unlock()
previous := hs.status
if previous == status {
return previous, false
}
hs.status = status
return previous, true
}
func StatusHandler(logger mlogger.Logger) *Status {
hs := Status{
status: health.SSCreated,
logger: logger.Named("status"),
}
return &hs
}
@@ -0,0 +1,10 @@
package health
type ServiceStatus string
const (
SSCreated ServiceStatus = "created"
SSStarting ServiceStatus = "starting"
SSRunning ServiceStatus = "ok"
SSTerminating ServiceStatus = "deactivating"
)
+153
View File
@@ -0,0 +1,153 @@
package httptransport
import (
"net/http"
"os"
"path"
mr "git.sendico.io/tech/sxchnge/product/app/metrics"
"git.sendico.io/tech/sxchnge/product/auth/config"
httprouter "git.sendico.io/tech/sxchnge/product/auth/http"
"git.sendico.io/tech/sxchnge/product/auth/response"
authstorage "git.sendico.io/tech/sxchnge/product/auth/storage"
"git.sendico.io/tech/sxchnge/product/sessions/browser"
"git.sendico.io/tech/sxchnge/shared/database"
"git.sendico.io/tech/sxchnge/shared/errors"
api "git.sendico.io/tech/sxchnge/shared/http"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/logging"
"git.sendico.io/tech/sxchnge/shared/service"
"github.com/go-chi/chi/v5"
cm "github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/go-chi/metrics"
"go.uber.org/zap"
"moul.io/chizap"
)
type Middleware struct {
logger mlogger.Logger
router *chi.Mux
apiEndpoint string
metrics mr.Metrics
epdispatcher *httprouter.Dispatcher
}
func (mw *Middleware) Handler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.HandlerFunc) {
mw.epdispatcher.Handler(service, endpoint, method, handler)
}
func (mw *Middleware) AccountHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.AccountHandlerFunc) {
mw.epdispatcher.AccountHandler(service, endpoint, method, handler)
}
func (mw *Middleware) PendingAccountHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.PendingAccountHandlerFunc) {
mw.epdispatcher.PendingAccountHandler(service, endpoint, method, handler)
}
func (mw *Middleware) Finish() {
mw.metrics.Finish()
}
func (mw *Middleware) installMiddleware(config *middleware.Config, debug bool) {
mw.logger.Debug("Installing middleware stack...")
// Collect metrics for application traffic only. Scrapes and health probes are
// operational traffic and would otherwise distort request and in-flight SLIs.
mw.router.Use(metrics.Collector(metrics.CollectorOpts{
Host: false, // avoid high-cardinality "host" label
Proto: true, // include HTTP protocol label
Skip: func(r *http.Request) bool {
return isObservabilityRequest(mw.apiEndpoint, r.URL.Path)
},
}))
mw.router.Use(cm.RequestID)
if debug {
mw.router.Use(chizap.New(mw.logger.Named("http_trace"), &chizap.Opts{
WithReferer: true,
WithUserAgent: true,
}))
}
mw.router.Use(cors.Handler(cors.Options{
AllowedOrigins: config.CORS.AllowedOrigins,
AllowedMethods: config.CORS.AllowedMethods,
AllowedHeaders: config.CORS.AllowedHeaders,
ExposedHeaders: config.CORS.ExposedHeaders,
AllowCredentials: config.CORS.AllowCredentials,
MaxAge: config.CORS.MaxAge,
OptionsPassthrough: false,
Debug: debug,
}))
mw.router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := browser.ValidateCSRF(r, config.CORS.AllowedOrigins); err != nil {
mw.logger.Info("Rejected browser request with invalid CSRF context",
zap.String("method", r.Method), zap.String("path", r.URL.Path))
response.Forbidden(mw.logger, mservice.Accounts, "csrf_rejected", "browser request failed CSRF validation").ServeHTTP(w, r)
return
}
next.ServeHTTP(w, r)
})
})
mw.router.Use(cm.Recoverer)
mw.router.Handle("/metrics", metrics.Handler())
mw.logger.Info("Middleware stack installation complete")
}
func isObservabilityRequest(apiEndpoint, requestPath string) bool {
healthPath := path.Join("/", apiEndpoint, "health")
metricsPath := path.Join("/", apiEndpoint, "metrics")
return requestPath == healthPath || requestPath == metricsPath || requestPath == "/metrics"
}
func CreateMiddleware(
logger mlogger.Logger,
db db.Factory,
apiRouter *chi.Mux,
config *middleware.Config,
authStorage *middleware.AuthStorageConfig,
debug bool,
) (*Middleware, error) {
if config == nil {
return nil, merrors.InvalidArgument("middleware configuration is required", "middleware")
}
if err := config.Token.Validate(); err != nil {
return nil, err
}
if err := config.CORS.Validate(); err != nil {
return nil, err
}
loginRateLimits, err := config.ResolveLoginRateLimits()
if err != nil {
logger.Error("Invalid login rate limit configuration", zap.Error(err))
return nil, err
}
p := &Middleware{
logger: logger.Named("middleware"),
router: apiRouter,
apiEndpoint: os.Getenv(config.EndPointEnv),
}
p.logger.Info("Set endpoint", zap.String("endpoint", p.apiEndpoint))
p.installMiddleware(config, debug)
if p.metrics, err = mr.NewMetricsRouter(p.logger, p.router, p.apiEndpoint); err != nil {
p.logger.Error("Failed to create metrics router", zap.Error(err), zap.String("api_endpoint", p.apiEndpoint))
return nil, err
}
stores, err := authstorage.OpenStores(p.logger, db, authStorage)
if err != nil {
return nil, err
}
p.epdispatcher = httprouter.NewDispatcher(
p.logger,
p.router,
stores.Accounts,
stores.Verification,
stores.RefreshTokens,
stores.LoginAttempts,
config,
loginRateLimits,
)
return p, nil
}
+155
View File
@@ -0,0 +1,155 @@
package httptransport
import (
"context"
"net/http"
"net/http/httptest"
"testing"
amr "git.sendico.io/tech/sxchnge/product/app/health"
"git.sendico.io/tech/sxchnge/product/app/health/status"
"github.com/go-chi/chi/v5"
chimetrics "github.com/go-chi/metrics"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"moul.io/chizap"
)
func TestHTTPCollectorDoesNotGatherHealthOrMetricsRequests(t *testing.T) {
router := chi.NewRouter()
router.Use(chimetrics.Collector(chimetrics.CollectorOpts{
Proto: true,
Skip: func(r *http.Request) bool {
return isObservabilityRequest("/api/v1", r.URL.Path)
},
}))
router.Get("/api/v1/health", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
router.Handle("/metrics", chimetrics.Handler())
router.Handle("/api/v1/metrics", chimetrics.Handler())
router.Get("/api/v1/accounts", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
beforeHealth := gatheredHTTPRequestCount(t, "GET /api/v1/health")
beforeMetrics := gatheredHTTPRequestCount(t, "GET /metrics")
beforeAPIMetrics := gatheredHTTPRequestCount(t, "GET /api/v1/metrics")
beforeApplication := gatheredHTTPRequestCount(t, "GET /api/v1/accounts")
for _, requestPath := range []string{"/api/v1/health", "/metrics", "/api/v1/metrics", "/api/v1/accounts"} {
request := httptest.NewRequestWithContext(context.Background(), http.MethodGet, requestPath, nil)
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("GET %s returned %d", requestPath, response.Code)
}
}
if got := gatheredHTTPRequestCount(t, "GET /api/v1/health") - beforeHealth; got != 0 {
t.Fatalf("health probe changed http_requests_total by %v", got)
}
if got := gatheredHTTPRequestCount(t, "GET /metrics") - beforeMetrics; got != 0 {
t.Fatalf("metrics scrape changed http_requests_total by %v", got)
}
if got := gatheredHTTPRequestCount(t, "GET /api/v1/metrics") - beforeAPIMetrics; got != 0 {
t.Fatalf("API metrics scrape changed http_requests_total by %v", got)
}
if got := gatheredHTTPRequestCount(t, "GET /api/v1/accounts") - beforeApplication; got != 1 {
t.Fatalf("application request changed http_requests_total by %v, want 1", got)
}
}
func gatheredHTTPRequestCount(t *testing.T, endpoint string) float64 {
t.Helper()
families, err := prometheus.DefaultGatherer.Gather()
if err != nil {
t.Fatalf("gather metrics: %v", err)
}
for _, family := range families {
if family.GetName() != "http_requests_total" {
continue
}
var total float64
for _, metric := range family.GetMetric() {
for _, label := range metric.GetLabel() {
if label.GetName() == "endpoint" && label.GetValue() == endpoint {
total += metric.GetCounter().GetValue()
}
}
}
return total
}
return 0
}
func TestObservabilityRequestsAreExcludedFromHTTPMetrics(t *testing.T) {
tests := []struct {
name string
apiEndpoint string
requestPath string
want bool
}{
{name: "health under API endpoint", apiEndpoint: "/api/v1", requestPath: "/api/v1/health", want: true},
{name: "metrics at root", apiEndpoint: "/api/v1", requestPath: "/metrics", want: true},
{name: "metrics under API endpoint", apiEndpoint: "/api/v1", requestPath: "/api/v1/metrics", want: true},
{name: "trailing endpoint slash", apiEndpoint: "/api/v1/", requestPath: "/api/v1/health", want: true},
{name: "application endpoint", apiEndpoint: "/api/v1", requestPath: "/api/v1/accounts", want: false},
{name: "health suffix is not a probe", apiEndpoint: "/api/v1", requestPath: "/api/v1/health/history", want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isObservabilityRequest(tt.apiEndpoint, tt.requestPath); got != tt.want {
t.Fatalf("isObservabilityRequest(%q, %q) = %t, want %t", tt.apiEndpoint, tt.requestPath, got, tt.want)
}
})
}
}
func TestHealthMountedOutsideTraceMiddleware(t *testing.T) {
core, observed := observer.New(zapcore.InfoLevel)
logger := zap.New(core)
rootRouter := chi.NewRouter()
apiRouter := chi.NewRouter()
apiRouter.Use(chizap.New(logger.Named("middleware").Named("http_trace"), &chizap.Opts{}))
apiRouter.Get("/api/v1/accounts", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
healthRouter, err := amr.NewHealthRouter(logger.Named("middleware"), rootRouter, "/api/v1")
if err != nil {
t.Fatalf("failed to create health router: %v", err)
}
healthRouter.SetStatus(health.SSRunning)
rootRouter.Mount("/", apiRouter)
healthReq := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/v1/health", nil)
healthRes := httptest.NewRecorder()
rootRouter.ServeHTTP(healthRes, healthReq)
if healthRes.Code != http.StatusOK {
t.Fatalf("expected health status %d, got %d", http.StatusOK, healthRes.Code)
}
if got := observed.FilterMessage("Served").Len(); got != 0 {
t.Fatalf("expected no trace logs for /health, got %d", got)
}
apiReq := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/v1/accounts", nil)
apiRes := httptest.NewRecorder()
rootRouter.ServeHTTP(apiRes, apiReq)
if apiRes.Code != http.StatusOK {
t.Fatalf("expected api status %d, got %d", http.StatusOK, apiRes.Code)
}
entries := observed.FilterMessage("Served").All()
if len(entries) != 1 {
t.Fatalf("expected one trace log for non-health request, got %d", len(entries))
}
if got := entries[0].ContextMap()["path"]; got != "/api/v1/accounts" {
t.Fatalf("expected logged path %q, got %#v", "/api/v1/accounts", got)
}
}
+40
View File
@@ -0,0 +1,40 @@
package metrics
import (
"net/http"
"git.sendico.io/tech/sxchnge/shared/logging"
"github.com/go-chi/chi/v5"
"github.com/go-chi/metrics"
"go.uber.org/zap"
)
type metricsRouter struct {
logger mlogger.Logger
handler http.Handler
}
func (mr *metricsRouter) Finish() {
mr.logger.Debug("Stopped")
}
func (mr *metricsRouter) handle(w http.ResponseWriter, r *http.Request) {
mr.logger.Debug("Serving metrics request...")
mr.handler.ServeHTTP(w, r)
}
func newMetricsRouter(logger mlogger.Logger, router chi.Router, endpoint string) *metricsRouter {
mr := metricsRouter{
logger: logger.Named("metrics"),
handler: metrics.Handler(),
}
logger.Debug("Installing Prometheus middleware...")
router.Group(func(r chi.Router) {
ep := endpoint + "/metrics"
r.Get(ep, mr.handle)
logger.Info("Prometheus handler installed", zap.String("endpoint", ep))
})
return &mr
}
+14
View File
@@ -0,0 +1,14 @@
package metrics
import (
"git.sendico.io/tech/sxchnge/shared/logging"
"github.com/go-chi/chi/v5"
)
type Metrics interface {
Finish()
}
func NewMetricsRouter(logger mlogger.Logger, router chi.Router, endpoint string) (Metrics, error) {
return newMetricsRouter(logger, router, endpoint), nil
}
+5
View File
@@ -0,0 +1,5 @@
package server
import "git.sendico.io/tech/sxchnge/shared/logging"
type ServerFactoryT = func(logger mlogger.Logger, file string, debug bool) (Application, error)
@@ -0,0 +1,40 @@
package serverimp
import (
"git.sendico.io/tech/sxchnge/product/app/process"
"git.sendico.io/tech/sxchnge/shared/logging"
"go.uber.org/zap"
)
type Instance struct {
srv server.Application
logger mlogger.Logger
file string
debug bool
factory server.ServerFactoryT
}
func (i *Instance) Start() error {
var err error
if i.srv, err = i.factory(i.logger, i.file, i.debug); err != nil {
i.logger.Warn("Failed to create server instance", zap.Error(err))
return err
}
return i.srv.Start()
}
func (i *Instance) Shutdown() {
if i.srv != nil {
i.srv.Shutdown()
}
}
func NewInstance(factory server.ServerFactoryT, logger mlogger.Logger, file string, debug bool) *Instance {
return &Instance{
srv: nil,
logger: logger,
file: file,
debug: debug,
factory: factory,
}
}
@@ -0,0 +1,66 @@
package serverimp
import (
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"git.sendico.io/tech/sxchnge/product/app/process"
"git.sendico.io/tech/sxchnge/shared/logging"
lf "git.sendico.io/tech/sxchnge/shared/logging/factory"
"git.sendico.io/tech/sxchnge/shared/version"
"github.com/google/uuid"
"go.uber.org/zap"
)
var (
configFileFlag = flag.String("config.file", "config.yml", "Path to the configuration file.")
versionFlag = flag.Bool("version", false, "Show version information.")
debugFlag = flag.Bool("debug", false, "Show debug information.")
)
func prepareLogger() mlogger.Logger {
flag.Parse()
return lf.NewLogger(*debugFlag)
}
func RunServer(rootLoggerName string, av version.Printer, factory server.ServerFactoryT) error {
logger := mlogger.Named(prepareLogger(), rootLoggerName)
logger = logger.With(zap.String("instance_id", uuid.NewString()))
defer func() {
_ = logger.Sync()
}()
// Show version information
if *versionFlag {
if _, err := fmt.Fprintln(os.Stdout, av.Print()); err != nil {
logger.Warn("Failed to print version", zap.Error(err))
}
return nil
}
// Create server instance
instance := NewInstance(factory, logger, *configFileFlag, *debugFlag)
// Interrupt handler
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
sig := <-c
logger.Info("Received sigint/segterm signal, shutting down", zap.String("signal", sig.String()))
instance.Shutdown()
}()
// Start server
logger.Info(fmt.Sprintf("Starting %s", av.Program()), zap.String("version", av.Info()))
logger.Info("Build context", zap.String("context", av.Context()))
if err := instance.Start(); err != nil {
logger.Error("Failed to start service", zap.Error(err))
return err
}
logger.Info("Server stopped")
return nil
}
+11
View File
@@ -0,0 +1,11 @@
package server
import (
sd "git.sendico.io/tech/sxchnge/product/app/process"
serverimp "git.sendico.io/tech/sxchnge/product/app/process/internal"
"git.sendico.io/tech/sxchnge/shared/version"
)
func RunServer(rootLoggerName string, av version.Printer, factory sd.ServerFactoryT) error {
return serverimp.RunServer(rootLoggerName, av, factory)
}
+7
View File
@@ -0,0 +1,7 @@
package server
// Typical service interface
type Application interface {
Shutdown()
Start() error
}
+21
View File
@@ -0,0 +1,21 @@
// Package profile selects the locally owned components of the copied BFF.
package profile
import (
"git.sendico.io/tech/sxchnge/product/app/api"
"git.sendico.io/tech/sxchnge/product/customers"
)
const Accounts = "accounts"
func Runtime() api.RuntimeConfig {
return api.RuntimeConfig{Name: "sxchnge.bff", Bootstrap: bootstrap}
}
func bootstrap(a api.API) (api.RuntimeComponents, error) {
accounts, err := accountservice.NewAccountService(a.Logger(), a.DBFactory(), &a.Config().Mw.Password, a.Config().AuthStorage)
if err != nil {
return nil, err
}
return api.RuntimeComponents{Accounts: accounts}, nil
}
+69
View File
@@ -0,0 +1,69 @@
package runtime
import (
"context"
"git.sendico.io/tech/sxchnge/product/app/api"
amr "git.sendico.io/tech/sxchnge/product/app/health"
httptransport "git.sendico.io/tech/sxchnge/product/app/http"
"git.sendico.io/tech/sxchnge/product/app/urls"
"git.sendico.io/tech/sxchnge/shared/database"
"git.sendico.io/tech/sxchnge/shared/logging"
"git.sendico.io/tech/sxchnge/shared/service"
)
type Microservices = []mservice.MicroService
// APIImp represents the structure of the APIImp
type APIImp struct {
lifecycleCtx context.Context
logger mlogger.Logger
db db.Factory
domain domainprovider.DomainProvider
config *api.Config
profile api.ConfigProvider
runtime api.RuntimeConfig
components api.RuntimeComponents
services Microservices
health amr.Health
mw *httptransport.Middleware
}
func (a *APIImp) LifecycleContext() context.Context {
return a.lifecycleCtx
}
func (a *APIImp) Logger() mlogger.Logger {
return a.logger
}
func (a *APIImp) Config() *api.Config {
return a.config
}
func (a *APIImp) ProfileConfig() api.ConfigProvider {
return a.profile
}
func (a *APIImp) DBFactory() db.Factory {
return a.db
}
func (a *APIImp) DomainProvider() domainprovider.DomainProvider {
return a.domain
}
func (a *APIImp) Register() api.Register {
return a.mw
}
func (a *APIImp) RuntimeComponent(name string) any {
if a == nil || a.components == nil {
return nil
}
return a.components[name]
}
func (a *APIImp) Name() string {
return "api"
}
+107
View File
@@ -0,0 +1,107 @@
package runtime
import (
"context"
"os"
"git.sendico.io/tech/sxchnge/product/app/api"
amr "git.sendico.io/tech/sxchnge/product/app/health"
httptransport "git.sendico.io/tech/sxchnge/product/app/http"
"git.sendico.io/tech/sxchnge/product/app/urls"
"git.sendico.io/tech/sxchnge/shared/database"
"git.sendico.io/tech/sxchnge/shared/logging"
"git.sendico.io/tech/sxchnge/shared/service"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"
)
func CreateAPI(
lifecycleCtx context.Context,
logger mlogger.Logger,
config *api.Config,
profileConfig api.ConfigProvider,
db db.Factory,
rootRouter *chi.Mux,
apiRouter *chi.Mux,
debug bool,
runtime api.RuntimeConfig,
) (mservice.MicroService, error) {
p := &APIImp{
lifecycleCtx: lifecycleCtx,
logger: logger.Named("api"),
config: config,
profile: profileConfig,
db: db,
runtime: runtime,
}
if err := p.installRuntimeBasics(logger, db, rootRouter, apiRouter, debug); err != nil {
return nil, err
}
if err := p.bootstrapConfiguredRuntime(config, db); err != nil {
return nil, err
}
p.logger.Info("Installing microservices...", zap.String("runtime", runtime.RuntimeName()))
if err := p.installServices(); err != nil {
p.logger.Error("Failed to install a microservice", zap.Error(err))
return nil, err
}
p.logger.Info("Microservices installation complete", zap.Int("microservices", len(p.services)))
return p, nil
}
func (a *APIImp) installRuntimeBasics(
logger mlogger.Logger,
db db.Factory,
rootRouter *chi.Mux,
apiRouter *chi.Mux,
debug bool,
) error {
var err error
if a.domain, err = domainprovider.CreateDomainProvider(
a.logger,
a.config.Mw.DomainEnv,
a.config.Mw.APIProtocolEnv,
a.config.Mw.EndPointEnv,
); err != nil {
a.logger.Error("Failed to initialize domain provider")
return err
}
a.logger.Info("Domain provider installed")
apiEndpoint := os.Getenv(a.config.Mw.EndPointEnv)
if a.health, err = amr.NewHealthRouter(a.logger, rootRouter, apiEndpoint); err != nil {
a.logger.Error("Failed to create healthcheck router", zap.Error(err), zap.String("api_endpoint", apiEndpoint))
return err
}
if a.mw, err = httptransport.CreateMiddleware(
logger,
db,
apiRouter,
a.config.Mw,
a.config.AuthStorage,
debug,
); err != nil {
a.logger.Error("Failed to create middleware", zap.Error(err))
return err
}
a.logger.Info("Middleware installed", zap.Bool("debug_mode", debug))
return nil
}
func (a *APIImp) bootstrapConfiguredRuntime(_ *api.Config, _ db.Factory) error {
if a.runtime.Bootstrap != nil {
components, err := a.runtime.Bootstrap(a)
if err != nil {
a.logger.Error("Failed to bootstrap runtime profile", zap.Error(err), zap.String("runtime", a.runtime.RuntimeName()))
return err
}
a.components = components
a.logger.Info("Runtime profile bootstrap complete",
zap.String("runtime", a.runtime.RuntimeName()),
zap.Int("components", len(components)))
}
return nil
}
@@ -0,0 +1,63 @@
package runtime_test
import (
"context"
sharedmodel "git.sendico.io/tech/sxchnge/shared/model"
"net/http"
"net/http/httptest"
"net/url"
"os"
"testing"
"time"
"git.sendico.io/tech/sxchnge/product/app/api"
"git.sendico.io/tech/sxchnge/product/app/profile"
sharedruntime "git.sendico.io/tech/sxchnge/product/app/runtime"
"git.sendico.io/tech/sxchnge/shared/database"
"github.com/go-chi/chi/v5"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go/modules/mongodb"
"go.uber.org/zap"
"gopkg.in/yaml.v3"
)
func TestProfileStartsOnEmptyDatabase(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
container, err := mongodb.Run(ctx, "mongo:8", mongodb.WithReplicaSet("rs"))
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, container.Terminate(context.Background())) })
uri, err := container.ConnectionString(ctx)
require.NoError(t, err)
endpoint, err := url.Parse(uri)
require.NoError(t, err)
query := endpoint.Query()
query.Set("directConnection", "true")
endpoint.RawQuery = query.Encode()
uri = endpoint.String()
factory, err := db.NewConnection(zap.NewNop(), &db.Config{Driver: db.Mongo, Settings: sharedmodel.SettingsT{"uri": uri, "database": "sxchnge_runtime"}})
require.NoError(t, err)
t.Cleanup(factory.CloseConnection)
data, err := os.ReadFile("../../config.example.yml")
require.NoError(t, err)
var example struct {
API api.Config `yaml:"api"`
}
require.NoError(t, yaml.Unmarshal(data, &example))
t.Setenv("SXCHNGE_DOMAIN", "localhost")
t.Setenv("SXCHNGE_API_PROTOCOL", "http")
t.Setenv("SXCHNGE_API_ENDPOINT", "/api/v1")
t.Setenv("SXCHNGE_JWT_SECRET", "test-only-signing-key-at-least-32-bytes")
root, routes := chi.NewRouter(), chi.NewRouter()
runtime, err := sharedruntime.CreateAPI(ctx, zap.NewNop(), &example.API, &example.API, factory, root, routes, false, profile.Runtime())
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, runtime.Finish(context.Background())) })
root.Mount("/", routes)
result := httptest.NewRecorder()
root.ServeHTTP(result, httptest.NewRequest(http.MethodGet, "/api/v1/health", nil))
require.Equal(t, http.StatusOK, result.Code)
// Runtime auth routes are installed even with zero customers and no seed.
result = httptest.NewRecorder()
root.ServeHTTP(result, httptest.NewRequest(http.MethodPost, "/api/v1/accounts/login", nil))
require.Equal(t, http.StatusBadRequest, result.Code)
}
+31
View File
@@ -0,0 +1,31 @@
package runtime
import (
"context"
"git.sendico.io/tech/sxchnge/product/app/health/status"
"go.uber.org/zap"
)
func (a *APIImp) Finish(ctx context.Context) error {
a.health.SetStatus(health.SSTerminating)
a.health.Finish()
a.mw.Finish()
var lastError error
for i := len(a.services) - 1; i >= 0; i-- {
if err := (a.services[i]).Finish(ctx); err != nil {
lastError = err
a.logger.Warn("Error occurred when finishing service",
zap.Error(err), zap.String("service_name", (a.services[i]).Name()))
} else {
a.logger.Info("Microservice is down", zap.String("service_name", (a.services[i]).Name()))
}
}
if a.runtime.Finish != nil {
if err := a.runtime.Finish(a); err != nil {
lastError = err
a.logger.Warn("Error occurred when finishing runtime profile", zap.String("runtime", a.runtime.RuntimeName()), zap.Error(err))
}
}
return lastError
}
+39
View File
@@ -0,0 +1,39 @@
package runtime
import (
"git.sendico.io/tech/sxchnge/product/app/api"
"git.sendico.io/tech/sxchnge/product/app/health/status"
"git.sendico.io/tech/sxchnge/shared/errors"
"git.sendico.io/tech/sxchnge/shared/service"
"go.uber.org/zap"
)
func (a *APIImp) installMicroservice(srv mservice.MicroService) {
a.services = append(a.services, srv)
a.logger.Info("Microservice installed", zap.String("service", srv.Name()))
}
func (a *APIImp) addMicroservice(srvf api.MicroServiceFactoryT) error {
srv, err := srvf(a)
if err != nil {
a.logger.Error("Failed to install a microservice", zap.Error(err))
return err
}
a.installMicroservice(srv)
return nil
}
func (a *APIImp) installServices() error {
for _, service := range a.runtime.Services {
if service.Factory == nil {
return merrors.InvalidArgument("microservice factory is required", "runtime.services")
}
if err := a.addMicroservice(service.Factory); err != nil {
return err
}
}
a.health.SetStatus(health.SSRunning)
return nil
}
@@ -0,0 +1,34 @@
package server
import (
"errors"
"git.sendico.io/tech/sxchnge/product/app/api"
"git.sendico.io/tech/sxchnge/shared/errors"
"os"
"testing"
)
func TestIncompleteConfigReturnsProjectError(t *testing.T) {
for _, data := range []string{"api: {}", "api: {middleware: {}}\ndatabase: {driver: mongodb}", "api: {middleware: {}}\ndatabase: {driver: mongodb}\nhttp_server: {}"} {
instance := &Imp{runtime: api.RuntimeConfig{}}
if err := instance.decodeConfig([]byte(data)); !errors.Is(err, merrors.ErrInvalidArg) {
t.Fatalf("expected configuration error, got %v", err)
}
}
}
func TestExampleConfigMatchesCopiedRuntime(t *testing.T) {
data, err := os.ReadFile("../../../config.example.yml")
if err != nil {
t.Fatal(err)
}
instance := &Imp{runtime: api.RuntimeConfig{}}
if err := instance.decodeConfig(data); err != nil {
t.Fatal(err)
}
if err := instance.config.API.SharedConfig().Mw.Token.Validate(); err != nil {
t.Fatal(err)
}
if err := instance.config.API.SharedConfig().Mw.CORS.Validate(); err != nil {
t.Fatal(err)
}
}
@@ -0,0 +1,177 @@
package server
import (
"context"
"errors"
"net/http"
"os"
"time"
ac "git.sendico.io/tech/sxchnge/product/app/api"
sharedruntime "git.sendico.io/tech/sxchnge/product/app/runtime"
"git.sendico.io/tech/sxchnge/shared/database"
mduration "git.sendico.io/tech/sxchnge/shared/duration"
"git.sendico.io/tech/sxchnge/shared/errors"
"git.sendico.io/tech/sxchnge/shared/logging"
"git.sendico.io/tech/sxchnge/shared/service"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"
"gopkg.in/yaml.v3"
)
type httpServerConf struct {
ListenAddress string `yaml:"listen_address"`
ReadHeaderTimeout int `yaml:"read_header_timeout"`
ShutdownTimeout int `yaml:"shutdown_timeout"`
}
// Config represents the server configuration
type Config struct {
API ac.ConfigProvider
DB *db.Config `yaml:"database"`
HTTPServer *httpServerConf `yaml:"http_server"`
}
// Instance represents an instance of the server
type Imp struct {
lifecycleCtx context.Context
lifecycleCancel context.CancelFunc
logger mlogger.Logger
api mservice.MicroService
config *Config
db db.Factory
httpServer *http.Server
runtime ac.RuntimeConfig
debug bool
file string
}
// Shutdown stops the server
func (i *Imp) Shutdown() {
if i.lifecycleCancel != nil {
i.lifecycleCancel()
}
if i.httpServer == nil {
return
}
// Shutdown HTTP server
ctx, cancel := context.WithTimeout(context.Background(), mduration.Param2Duration(i.config.HTTPServer.ShutdownTimeout, time.Second))
i.logger.Info("Shutting HTTP server down...")
if err := i.httpServer.Shutdown(ctx); err != nil {
if !errors.Is(err, http.ErrServerClosed) {
i.logger.Warn("Failed to shutdown HTTP server gracefully", zap.Error(err))
cancel()
os.Exit(1)
}
}
cancel()
}
func (i *Imp) Run() error {
err := i.httpServer.ListenAndServe()
if errors.Is(err, http.ErrServerClosed) {
err = nil
}
i.logger.Info("HTTP Server stopped")
if err := i.api.Finish(context.Background()); err != nil {
i.logger.Warn("Error when finishing service", zap.Error(err))
}
i.db.CloseConnection()
if err != nil {
return merrors.OpaqueWrap(merrors.ErrInternal, err, "HTTP server stopped unexpectedly")
}
return nil
}
// Start starts the server
func (i *Imp) Start() error {
if i.lifecycleCancel != nil {
defer i.lifecycleCancel()
}
i.logger.Info("Starting...", zap.String("config_file", i.file), zap.Bool("debug_mode", i.debug))
// Load configuration file
data, err := os.ReadFile(i.file)
if err != nil {
i.logger.Error("Could not load configuration", zap.Error(err), zap.String("config_file", i.file))
return err
}
if err = i.decodeConfig(data); err != nil {
i.logger.Error("Failed to parse configuration", zap.Error(err))
return err
}
if i.db, err = db.NewConnection(i.logger, i.config.DB); err != nil {
i.logger.Error("Could not open database connection", zap.Error(err))
return err
}
rootRouter := chi.NewRouter()
apiRouter := chi.NewRouter()
if i.api, err = sharedruntime.CreateAPI(i.lifecycleCtx, i.logger, i.config.API.SharedConfig(), i.config.API, i.db, rootRouter, apiRouter, i.debug, i.runtime); err != nil {
i.db.CloseConnection()
return err
}
rootRouter.Mount("/", apiRouter)
// Startup the HTTP Server in a way that we can gracefully shut it down again
i.httpServer = &http.Server{
Addr: i.config.HTTPServer.ListenAddress,
Handler: rootRouter,
ReadHeaderTimeout: mduration.Param2Duration(i.config.HTTPServer.ReadHeaderTimeout, time.Second),
}
return i.Run()
}
func (i *Imp) decodeConfig(data []byte) error {
var raw struct {
API yaml.Node `yaml:"api"`
DB *db.Config `yaml:"database"`
HTTPServer *httpServerConf `yaml:"http_server"`
}
if err := yaml.Unmarshal(data, &raw); err != nil {
return err
}
apiConfig := i.runtime.NewConfig()
if apiConfig == nil {
return merrors.Internal("runtime config factory returned nil api config")
}
if raw.API.Kind == 0 {
return merrors.InvalidArgument("api configuration is required", "api")
}
if err := raw.API.Decode(apiConfig); err != nil {
return err
}
if raw.DB == nil || raw.HTTPServer == nil || apiConfig.SharedConfig() == nil || apiConfig.SharedConfig().Mw == nil {
return merrors.InvalidArgument("database, http_server and api.middleware configuration are required")
}
if raw.HTTPServer.ListenAddress == "" || raw.HTTPServer.ReadHeaderTimeout <= 0 || raw.HTTPServer.ShutdownTimeout <= 0 {
return merrors.InvalidArgument("HTTP address and positive timeouts are required")
}
i.config = &Config{
API: apiConfig,
DB: raw.DB,
HTTPServer: raw.HTTPServer,
}
return nil
}
func Create(logger mlogger.Logger, file string, debug bool, runtime ac.RuntimeConfig) (*Imp, error) {
lifecycleCtx, lifecycleCancel := context.WithCancel(context.Background())
srv := &Imp{
lifecycleCtx: lifecycleCtx,
lifecycleCancel: lifecycleCancel,
logger: logger,
debug: debug,
file: file,
runtime: runtime,
}
return srv, nil
}
@@ -0,0 +1,22 @@
package server
import (
"context"
"errors"
"testing"
"git.sendico.io/tech/sxchnge/product/app/api"
"go.uber.org/zap"
)
func TestShutdownCancelsLifecycleContextBeforeStartupCompletes(t *testing.T) {
instance, err := Create(zap.NewNop(), "config.yml", false, api.RuntimeConfig{})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
instance.Shutdown()
if !errors.Is(instance.lifecycleCtx.Err(), context.Canceled) {
t.Fatalf("lifecycle context error = %v, want context.Canceled", instance.lifecycleCtx.Err())
}
}
+12
View File
@@ -0,0 +1,12 @@
package server
import (
edgeapi "git.sendico.io/tech/sxchnge/product/app/api"
"git.sendico.io/tech/sxchnge/product/app/process"
internalserver "git.sendico.io/tech/sxchnge/product/app/server/internal"
"git.sendico.io/tech/sxchnge/shared/logging"
)
func Create(logger mlogger.Logger, file string, debug bool, runtime edgeapi.RuntimeConfig) (server.Application, error) {
return internalserver.Create(logger, file, debug, runtime)
}
@@ -0,0 +1,15 @@
package domainprovider
import (
dimp "git.sendico.io/tech/sxchnge/product/app/urls/internal"
"git.sendico.io/tech/sxchnge/shared/logging"
)
type DomainProvider interface {
GetFullLink(linkElem ...string) (string, error)
GetAPILink(linkElem ...string) (string, error)
}
func CreateDomainProvider(logger mlogger.Logger, domain, protocol, apiEndpoint string) (DomainProvider, error) {
return dimp.CreateDomainProviderImp(logger, domain, protocol, apiEndpoint)
}
@@ -0,0 +1,35 @@
package domainproviderimp
import (
"net/url"
"os"
"git.sendico.io/tech/sxchnge/shared/logging"
"go.uber.org/zap"
)
type DomainProviderImp struct {
domain string
apiEndpoint string
}
func (dp *DomainProviderImp) GetFullLink(linkElem ...string) (string, error) {
return url.JoinPath(dp.domain, linkElem...)
}
func (dp *DomainProviderImp) GetAPILink(linkElem ...string) (string, error) {
return url.JoinPath(dp.apiEndpoint, linkElem...)
}
func CreateDomainProviderImp(logger mlogger.Logger, domain, protocol, apiPointEnv string) (*DomainProviderImp, error) {
p := new(DomainProviderImp)
p.domain = os.Getenv(protocol) + "://" + os.Getenv(domain)
var err error
apiPath := os.Getenv(apiPointEnv)
if p.apiEndpoint, err = url.JoinPath(p.domain, apiPath); err != nil {
logger.Error("Failed to create domain provider", zap.String("domain", p.domain), zap.String("api_path", apiPath))
return nil, err
}
logger.Named("domain_provider").Info("Domain name provider is up", zap.String("domain", p.domain))
return p, nil
}
+27
View File
@@ -0,0 +1,27 @@
package appversion
import (
"git.sendico.io/tech/sxchnge/shared/version"
vf "git.sendico.io/tech/sxchnge/shared/version/factory"
)
// Build information. Populated at build-time.
var (
Version string
Revision string
Branch string
BuildUser string
BuildDate string
)
func Create() version.Printer {
vi := version.Info{
Program: "SXCHNGE BFF",
Revision: Revision,
Branch: Branch,
BuildUser: BuildUser,
BuildDate: BuildDate,
Version: Version,
}
return vf.Create(&vi)
}
@@ -0,0 +1,45 @@
package architecture
import (
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"strconv"
"strings"
"testing"
)
// Provider access is HTTP only. Local Mongo repositories belong to SXCHNGE.
func TestNoSendicoRuntimeOrPrivateTransportImports(t *testing.T) {
err := filepath.WalkDir("../..", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || filepath.Ext(path) != ".go" {
return nil
}
f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
if err != nil {
return err
}
for _, im := range f.Imports {
name, err := strconv.Unquote(im.Path.Value)
if err != nil {
return err
}
if strings.HasPrefix(filepath.ToSlash(path), "../../shared/") && strings.HasPrefix(name, "git.sendico.io/tech/sxchnge/") && !strings.HasPrefix(name, "git.sendico.io/tech/sxchnge/shared/") {
t.Errorf("shared library imports an executable module: %s in %s", name, path)
}
for _, blocked := range []string{"github.com/tech/sendico/", "google.golang.org/grpc", "github.com/nats-io/", "/pkg/discovery", "/pkg/proto/", "github.com/casbin/", "/pkg/auth", "/storage/organization", "/mongo/policiesdb", "/mongo/rolesdb", "/mongo/invitationdb"} {
if strings.Contains(name, blocked) {
t.Errorf("%s imports private provider transport or shared runtime: %s", path, name)
}
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
@@ -0,0 +1,47 @@
package architecture
import (
"go/ast"
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"strings"
"testing"
)
func TestLocalCustomerModelHasNoPlatformTenancy(t *testing.T) {
// Local customer models and storage must stay free of provider tenancy.
forbidden := map[string]bool{"organization": true, "organizationref": true, "orgref": true, "orgdb": true, "role": true, "roles": true, "roledescription": true, "rolemanager": true, "policy": true, "policies": true, "policydescription": true, "policydb": true, "permissionbound": true, "signup_provisioning": true}
err := filepath.WalkDir("../..", func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() || filepath.Ext(path) != ".go" || strings.HasSuffix(path, "_test.go") {
return nil
}
parsed, err := parser.ParseFile(token.NewFileSet(), path, nil, 0)
if err != nil {
return err
}
ast.Inspect(parsed, func(node ast.Node) bool {
var names []*ast.Ident
switch n := node.(type) {
case *ast.TypeSpec:
names = []*ast.Ident{n.Name}
case *ast.Field:
names = n.Names
}
for _, name := range names {
if forbidden[strings.ToLower(name.Name)] {
t.Errorf("%s reintroduces local platform tenancy: %s", path, name.Name)
}
}
return true
})
return nil
})
if err != nil {
t.Fatal(err)
}
}
@@ -0,0 +1,69 @@
package architecture
import (
"go/ast"
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"strconv"
"testing"
)
// Keep the backend error-model guideline executable, including aliased imports.
func TestErrorConstructorsUseProjectModel(t *testing.T) {
root := filepath.Join("..", "..")
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || filepath.Ext(path) != ".go" {
return nil
}
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, path, nil, 0)
if err != nil {
return err
}
imports := map[string]string{}
for _, imp := range file.Imports {
pkg, err := strconv.Unquote(imp.Path.Value)
if err != nil {
return err
}
if pkg != "errors" && pkg != "fmt" {
continue
}
alias := pkg
if imp.Name != nil {
alias = imp.Name.Name
}
if alias == "." {
t.Errorf("%s: dot import obscures error constructors", path)
}
imports[alias] = pkg
}
ast.Inspect(file, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
ident, ok := sel.X.(*ast.Ident)
if !ok {
return true
}
if (imports[ident.Name] == "errors" && sel.Sel.Name == "New") || (imports[ident.Name] == "fmt" && sel.Sel.Name == "Errorf") {
t.Errorf("%s: use backend/shared/errors", fset.Position(call.Pos()))
}
return true
})
return nil
})
if err != nil {
t.Fatal(err)
}
}
+29
View File
@@ -0,0 +1,29 @@
package client
import (
"context"
"errors"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"strings"
"git.sendico.io/tech/sxchnge/product/sessions/store"
"git.sendico.io/tech/sxchnge/shared/errors"
)
var ErrUnknownClientID = merrors.Define("unknown client id")
func Resolve(ctx context.Context, rtdb refreshtokens.DB, clientID string) (*sessionmodel.Client, error) {
clientID = strings.TrimSpace(clientID)
if clientID == "" {
return nil, ErrUnknownClientID
}
client, err := rtdb.GetClient(ctx, clientID)
if errors.Is(err, merrors.ErrNoData) || client == nil {
return nil, ErrUnknownClientID
}
if err != nil {
return nil, err
}
return client, nil
}
@@ -0,0 +1,53 @@
package client
import (
"context"
"errors"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"testing"
"git.sendico.io/tech/sxchnge/product/sessions/store"
)
type resolveClientDB struct {
refreshtokens.DB
calls int
client *sessionmodel.Client
err error
}
func (db *resolveClientDB) GetClient(ctx context.Context, clientID string) (*sessionmodel.Client, error) {
db.calls++
return db.client, db.err
}
func TestResolveRejectsBlankClientIDWithoutStorageLookup(t *testing.T) {
db := &resolveClientDB{}
client, err := Resolve(context.Background(), db, " ")
if !errors.Is(err, ErrUnknownClientID) {
t.Fatalf("expected unknown client id, got %v", err)
}
if client != nil {
t.Fatalf("expected nil client, got %#v", client)
}
if db.calls != 0 {
t.Fatalf("expected no storage lookup for blank client id, got %d", db.calls)
}
}
func TestResolveTrimsClientID(t *testing.T) {
want := &sessionmodel.Client{ClientID: "client-1"}
db := &resolveClientDB{client: want}
client, err := Resolve(context.Background(), db, " client-1 ")
if err != nil {
t.Fatalf("expected client resolution to succeed, got %v", err)
}
if client != want {
t.Fatalf("expected resolved client %#v, got %#v", want, client)
}
if db.calls != 1 {
t.Fatalf("expected one storage lookup, got %d", db.calls)
}
}
@@ -0,0 +1,36 @@
package middleware
type AuthStorageConfig struct {
AccountsCollection string `yaml:"accounts_collection"`
RefreshTokensCollection string `yaml:"refresh_tokens_collection"`
ClientsCollection string `yaml:"clients_collection"`
VerificationTokensCollection string `yaml:"verification_tokens_collection"`
LoginAttemptsCollection string `yaml:"login_attempts_collection"`
VerificationRateLimitsCollection string `yaml:"verification_rate_limits_collection"`
}
func (c *AuthStorageConfig) WithDefaults() AuthStorageConfig {
if c == nil {
c = &AuthStorageConfig{}
}
res := *c
if res.AccountsCollection == "" {
res.AccountsCollection = "accounts"
}
if res.RefreshTokensCollection == "" {
res.RefreshTokensCollection = "refresh_tokens"
}
if res.ClientsCollection == "" {
res.ClientsCollection = "clients"
}
if res.VerificationTokensCollection == "" {
res.VerificationTokensCollection = "verification_tokens"
}
if res.LoginAttemptsCollection == "" {
res.LoginAttemptsCollection = "login_attempts"
}
if res.VerificationRateLimitsCollection == "" {
res.VerificationRateLimitsCollection = "verification_rate_limits"
}
return res
}
+49
View File
@@ -0,0 +1,49 @@
package middleware
import "testing"
func TestCredentialedCORSRequiresExplicitOrigins(t *testing.T) {
tests := []struct {
name string
config CORSSettings
wantErr bool
}{
{
name: "explicit origin",
config: CORSSettings{
AllowCredentials: true,
AllowedOrigins: []string{"https://app.sendico.io"},
},
},
{
name: "wildcard",
config: CORSSettings{
AllowCredentials: true,
AllowedOrigins: []string{"*"},
},
wantErr: true,
},
{
name: "missing origin",
config: CORSSettings{
AllowCredentials: true,
},
wantErr: true,
},
{
name: "non-credentialed compatibility",
config: CORSSettings{
AllowedOrigins: []string{"*"},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.config.Validate()
if (err != nil) != tt.wantErr {
t.Fatalf("Validate() error = %v, wantErr %t", err, tt.wantErr)
}
})
}
}
@@ -0,0 +1,47 @@
package middleware
import (
"time"
sharedlimit "git.sendico.io/tech/sxchnge/shared/ratelimit"
)
const (
defaultLoginAccountLimit = 5
defaultLoginAccountWindow = 15 * time.Minute
defaultLoginIPLimit = 50
defaultLoginIPWindow = 15 * time.Minute
)
type LoginRateLimitWindowConfig = sharedlimit.WindowConfig
type LoginRateLimitsConfig struct {
PerAccount LoginRateLimitWindowConfig `yaml:"per_account"`
PerIP LoginRateLimitWindowConfig `yaml:"per_ip"`
}
type LoginRateLimitWindow = sharedlimit.Window
type LoginRateLimits struct {
PerAccount LoginRateLimitWindow
PerIP LoginRateLimitWindow
}
func (c *Config) ResolveLoginRateLimits() (LoginRateLimits, error) {
if c == nil || c.LoginRateLimits == nil {
return LoginRateLimits{
PerAccount: LoginRateLimitWindow{Limit: defaultLoginAccountLimit, Window: defaultLoginAccountWindow},
PerIP: LoginRateLimitWindow{Limit: defaultLoginIPLimit, Window: defaultLoginIPWindow},
}, nil
}
account, err := sharedlimit.ResolveWindow(c.LoginRateLimits.PerAccount, "middleware.login_rate_limits.per_account")
if err != nil {
return LoginRateLimits{}, err
}
ip, err := sharedlimit.ResolveWindow(c.LoginRateLimits.PerIP, "middleware.login_rate_limits.per_ip")
if err != nil {
return LoginRateLimits{}, err
}
return LoginRateLimits{PerAccount: account, PerIP: ip}, nil
}
@@ -0,0 +1,60 @@
package middleware
import (
"errors"
"testing"
"time"
"git.sendico.io/tech/sxchnge/shared/errors"
)
func TestResolveLoginRateLimitsUsesSecureDefaults(t *testing.T) {
got, err := (&Config{}).ResolveLoginRateLimits()
if err != nil {
t.Fatalf("resolve defaults: %v", err)
}
if got.PerAccount.Limit != 5 || got.PerAccount.Window != 15*time.Minute {
t.Fatalf("unexpected account defaults: %+v", got.PerAccount)
}
if got.PerIP.Limit != 50 || got.PerIP.Window != 15*time.Minute {
t.Fatalf("unexpected IP defaults: %+v", got.PerIP)
}
}
func TestResolveLoginRateLimitsRejectsUnsafeConfiguration(t *testing.T) {
tests := []struct {
name string
cfg *LoginRateLimitsConfig
}{
{
name: "zero account threshold",
cfg: &LoginRateLimitsConfig{
PerAccount: LoginRateLimitWindowConfig{Window: "15m"},
PerIP: LoginRateLimitWindowConfig{Limit: 50, Window: "15m"},
},
},
{
name: "invalid IP window",
cfg: &LoginRateLimitsConfig{
PerAccount: LoginRateLimitWindowConfig{Limit: 5, Window: "15m"},
PerIP: LoginRateLimitWindowConfig{Limit: 50, Window: "forever"},
},
},
{
name: "excessive account window",
cfg: &LoginRateLimitsConfig{
PerAccount: LoginRateLimitWindowConfig{Limit: 5, Window: "25h"},
PerIP: LoginRateLimitWindowConfig{Limit: 50, Window: "15m"},
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := (&Config{LoginRateLimits: test.cfg}).ResolveLoginRateLimits()
if !errors.Is(err, merrors.ErrInvalidArg) {
t.Fatalf("expected invalid argument, got %v", err)
}
})
}
}
+110
View File
@@ -0,0 +1,110 @@
package middleware
import (
"os"
"strings"
"git.sendico.io/tech/sxchnge/shared/errors"
)
type CORSSettings struct {
MaxAge int `yaml:"max_age"`
AllowedOrigins []string `yaml:"allowed_origins"`
AllowedMethods []string `yaml:"allowed_methods"`
AllowedHeaders []string `yaml:"allowed_headers"`
ExposedHeaders []string `yaml:"exposed_headers"`
AllowCredentials bool `yaml:"allow_credentials"`
}
func (c CORSSettings) Validate() error {
if !c.AllowCredentials {
return nil
}
if len(c.AllowedOrigins) == 0 {
return merrors.InvalidArgument("credentialed CORS requires explicit allowed origins", "middleware.CORS.allowed_origins")
}
for _, origin := range c.AllowedOrigins {
if strings.TrimSpace(origin) == "*" {
return merrors.InvalidArgument("credentialed CORS does not allow wildcard origins", "middleware.CORS.allowed_origins")
}
}
return nil
}
type Signature struct {
PublicKey any
PrivateKey []byte
Algorithm string
}
type SignatureConfig struct {
PublicKeyEnv string `yaml:"public_key_env,omitempty"`
PrivateKeyEnv string `yaml:"secret_key_env"`
Algorithm string `yaml:"algorithm"`
}
type TokenExpiration struct {
Account int `yaml:"account"`
Refresh int `yaml:"refresh"`
}
type TokenConfig struct {
Expiration TokenExpiration `yaml:"expiration_hours"`
Length int `yaml:"length"`
}
const MaxAccessTokenTTLHours = 1
func (c TokenConfig) Validate() error {
if c.Expiration.Account <= 0 || c.Expiration.Account > MaxAccessTokenTTLHours {
return merrors.InvalidArgument("access token expiration must be between 1 and 1 hour", "middleware.token.expiration_hours.account")
}
if c.Expiration.Refresh <= c.Expiration.Account {
return merrors.InvalidArgument("refresh token expiration must exceed access token expiration", "middleware.token.expiration_hours.refresh")
}
if c.Length < 32 {
return merrors.InvalidArgument("refresh token length must be at least 32 bytes", "middleware.token.length")
}
return nil
}
type PasswordChecks struct {
Digit bool `yaml:"digit"`
Upper bool `yaml:"upper"`
Lower bool `yaml:"lower"`
Special bool `yaml:"special"`
MinLength int `yaml:"min_length"`
}
type PasswordConfig struct {
TokenLength int `yaml:"token_length"`
Check PasswordChecks `yaml:"check"`
}
type Config struct {
DomainEnv string `yaml:"domain_env"`
EndPointEnv string `yaml:"api_endpoint_env"`
APIProtocolEnv string `yaml:"api_protocol_env"`
Signature SignatureConfig `yaml:"signature"`
CORS CORSSettings `yaml:"CORS"`
Token TokenConfig `yaml:"token"`
Password PasswordConfig `yaml:"password"`
LoginRateLimits *LoginRateLimitsConfig `yaml:"login_rate_limits"`
}
type MapClaims = map[string]any
func getKey(osEnv string) any {
if len(osEnv) == 0 {
return nil
}
return []byte(os.Getenv(osEnv))
}
func SignatureConf(conf *Config) Signature {
return Signature{
PrivateKey: []byte(os.Getenv(conf.Signature.PrivateKeyEnv)),
PublicKey: getKey(conf.Signature.PublicKeyEnv),
Algorithm: conf.Signature.Algorithm,
}
}
+52
View File
@@ -0,0 +1,52 @@
package middleware
import "testing"
func TestTokenConfigValidate(t *testing.T) {
tests := []struct {
name string
config TokenConfig
wantErr bool
}{
{
name: "secure explicit TTLs",
config: TokenConfig{
Expiration: TokenExpiration{Account: 1, Refresh: 720},
Length: 32,
},
},
{
name: "rejects legacy 24 hour access token",
config: TokenConfig{
Expiration: TokenExpiration{Account: 24, Refresh: 720},
Length: 32,
},
wantErr: true,
},
{
name: "rejects missing access TTL",
config: TokenConfig{
Expiration: TokenExpiration{Refresh: 720},
Length: 32,
},
wantErr: true,
},
{
name: "rejects weak refresh token",
config: TokenConfig{
Expiration: TokenExpiration{Account: 1, Refresh: 720},
Length: 16,
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.config.Validate()
if (err != nil) != tt.wantErr {
t.Fatalf("Validate() error = %v, wantErr %t", err, tt.wantErr)
}
})
}
}
@@ -0,0 +1,75 @@
package authorized
import (
"context"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"net/http"
"net/http/httptest"
"testing"
"git.sendico.io/tech/sxchnge/product/auth/config"
emodel "git.sendico.io/tech/sxchnge/product/auth/model"
"git.sendico.io/tech/sxchnge/product/auth/response"
"git.sendico.io/tech/sxchnge/product/customers/store"
"git.sendico.io/tech/sxchnge/shared/errors"
api "git.sendico.io/tech/sxchnge/shared/http"
"git.sendico.io/tech/sxchnge/shared/service"
"github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/v2/bson"
"go.uber.org/zap"
)
type customerDB struct {
account.DB
customer customermodel.Account
requested bson.ObjectID
}
func (d *customerDB) Get(_ context.Context, id bson.ObjectID, result *customermodel.Account) error {
d.requested = id
if id != d.customer.ID {
return merrors.NoData("customer not found")
}
*result = d.customer
return nil
}
func (d *sessionDB) GetClient(context.Context, string) (*sessionmodel.Client, error) {
return &sessionmodel.Client{ClientID: "web"}, nil
}
func TestCustomerHandlerResolvesIdentityWithoutRoles(t *testing.T) {
for _, status := range []customermodel.AccountStatus{customermodel.AccountActive, customermodel.AccountBlocked, customermodel.AccountPendingVerification} {
t.Run(string(status), func(t *testing.T) {
accounts := &customerDB{}
accounts.customer.ID = bson.NewObjectID()
accounts.customer.Status = status
routes := chi.NewRouter()
signature := &middleware.Signature{Algorithm: "HS256", PrivateKey: []byte("test-only-signing-key-at-least-32-bytes")}
router := NewRouter(zap.NewNop(), "/api/v1", routes, accounts, &sessionDB{token: &sessionmodel.RefreshToken{}}, &middleware.TokenConfig{Expiration: middleware.TokenExpiration{Account: 1}}, signature)
called := false
router.AccountHandler(mservice.Accounts, "/me", api.Get, func(_ *http.Request, c *customermodel.Account, _ *sresponse.TokenData) http.HandlerFunc {
called = true
require.Equal(t, accounts.customer.ID, c.ID)
return func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }
})
ja := jwtauth.New(signature.Algorithm, signature.PrivateKey, nil)
_, token, err := ja.Encode(emodel.Account2ClaimsForSession(&accounts.customer, 1, sessionmodel.SessionIdentifier{ClientID: "web", DeviceID: "device", SessionVersion: "v1"}))
require.NoError(t, err)
req := httptest.NewRequest(http.MethodGet, "/api/v1/accounts/me?accountRef="+bson.NewObjectID().Hex(), nil)
req.Header.Set("Authorization", "Bearer "+token)
recorder := httptest.NewRecorder()
routes.ServeHTTP(recorder, req)
require.Equal(t, accounts.customer.ID, accounts.requested)
if status == customermodel.AccountActive {
require.Equal(t, http.StatusNoContent, recorder.Code)
require.True(t, called)
} else {
require.Equal(t, http.StatusUnauthorized, recorder.Code)
require.False(t, called)
}
})
}
}
@@ -0,0 +1,161 @@
package authorized
import (
"errors"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
"net/http"
"strings"
"git.sendico.io/tech/sxchnge/product/auth/ipguard"
emodel "git.sendico.io/tech/sxchnge/product/auth/model"
"git.sendico.io/tech/sxchnge/product/auth/response"
"git.sendico.io/tech/sxchnge/product/sessions/metrics"
"git.sendico.io/tech/sxchnge/shared/errors"
api "git.sendico.io/tech/sxchnge/shared/http"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/logging/fields"
"git.sendico.io/tech/sxchnge/shared/service"
"github.com/go-chi/jwtauth/v5"
"go.uber.org/zap"
)
type tokenHandlerFunc = func(r *http.Request, t *emodel.AccountToken) http.HandlerFunc
func (ar *AuthorizedRouter) validateClientPolicy(r *http.Request, t *emodel.AccountToken) http.HandlerFunc {
clientID := strings.TrimSpace(t.ClientID)
if clientID == "" {
// Legacy tokens without client_id remain valid until expiration.
return nil
}
client, err := ar.rtdb.GetClient(r.Context(), clientID)
if errors.Is(err, merrors.ErrNoData) || client == nil {
ar.logger.Debug("Client not found for access token", zap.String("client_id", clientID))
return response.Unauthorized(ar.logger, ar.service, "client not found")
}
if err != nil {
ar.logger.Warn("Failed to resolve client for access token", zap.Error(err), zap.String("client_id", clientID))
return response.Internal(ar.logger, ar.service, err)
}
if client.IsRevoked {
return response.Unauthorized(ar.logger, ar.service, "client has been revoked")
}
if client.AccountRef != nil && *client.AccountRef != t.AccountRef {
return response.Unauthorized(ar.logger, ar.service, "client account mismatch")
}
clientIP := ipguard.ClientIP(r)
allowed, err := ipguard.Allowed(clientIP, client.AllowedCIDRs)
if err != nil {
ar.logger.Warn("Client IP policy contains invalid CIDR", zap.Error(err), zap.String("client_id", clientID))
return response.Forbidden(ar.logger, ar.service, "client_ip_policy_invalid", "client ip policy is invalid")
}
if !allowed {
rawIP := ""
if clientIP != nil {
rawIP = clientIP.String()
}
ar.logger.Info("Client IP policy denied authorized request", zap.String("client_id", clientID), zap.String("remote_ip", rawIP))
return response.Forbidden(ar.logger, ar.service, "ip_not_allowed", "request ip is not allowed for this client")
}
return nil
}
func (ar *AuthorizedRouter) validateSession(r *http.Request, t *emodel.AccountToken) http.HandlerFunc {
if t.Pending {
return nil
}
if strings.TrimSpace(t.ClientID) == "" || strings.TrimSpace(t.DeviceID) == "" || strings.TrimSpace(t.SessionVersion) == "" {
sessionmetrics.Observe(sessionmetrics.Validation, sessionmetrics.MissingIdentity)
ar.logger.Debug("Access token has no session identifier", mzap.AccRef(t.AccountRef))
return response.Unauthorized(ar.logger, ar.service, "session identifier is required")
}
if _, err := ar.rtdb.GetSession(r.Context(), t.AccountRef, &t.SessionIdentifier); err != nil {
if errors.Is(err, merrors.ErrNoData) || errors.Is(err, merrors.ErrAccessDenied) {
sessionmetrics.Observe(sessionmetrics.Validation, sessionmetrics.AlreadyInactive)
ar.logger.Debug("Access token session is not active", mzap.AccRef(t.AccountRef),
zap.String("client_id", t.ClientID), zap.String("device_id", t.DeviceID))
return response.Unauthorized(ar.logger, ar.service, "session is not active")
}
sessionmetrics.Observe(sessionmetrics.Validation, sessionmetrics.StorageError)
ar.logger.Warn("Failed to validate access token session", zap.Error(err), mzap.AccRef(t.AccountRef),
zap.String("client_id", t.ClientID), zap.String("device_id", t.DeviceID))
return response.Internal(ar.logger, ar.service, err)
}
sessionmetrics.Observe(sessionmetrics.Validation, sessionmetrics.Active)
return nil
}
func (ar *AuthorizedRouter) tokenHandlerWithSessionCheck(service mservice.Type, endpoint string, method api.HTTPMethod, checkSession bool, handler tokenHandlerFunc) {
hndlr := func(r *http.Request) http.HandlerFunc {
_, claims, err := jwtauth.FromContext(r.Context())
if err != nil {
ar.logger.Debug("Authorization failed", zap.Error(err), zap.String("request", r.URL.Path))
return response.Unauthorized(ar.logger, ar.service, "credentials required")
}
t, err := emodel.Claims2Token(claims)
if err != nil {
ar.logger.Debug("Failed to decode account token", zap.Error(err))
return response.BadRequest(ar.logger, ar.service, "credentials_unreadable", "faild to parse credentials")
}
if h := ar.validateClientPolicy(r, t); h != nil {
return h
}
if checkSession {
if h := ar.validateSession(r, t); h != nil {
return h
}
}
return handler(r, t)
}
ar.imp.InstallHandler(service, endpoint, method, hndlr)
}
func (ar *AuthorizedRouter) tokenHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler tokenHandlerFunc) {
ar.tokenHandlerWithSessionCheck(service, endpoint, method, true, handler)
}
func (ar *AuthorizedRouter) AccountHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.AccountHandlerFunc) {
hndlr := func(r *http.Request, t *emodel.AccountToken) http.HandlerFunc {
if t.Pending {
return response.Unauthorized(ar.logger, ar.service, "additional verification required")
}
var a customermodel.Account
if err := ar.db.Get(r.Context(), t.AccountRef, &a); err != nil {
if errors.Is(err, merrors.ErrNoData) {
ar.logger.Debug("Failed to find related user", zap.Error(err), mzap.AccRef(t.AccountRef))
return response.NotFound(ar.logger, ar.service, err.Error())
}
return response.Internal(ar.logger, ar.service, err)
}
if !a.IsActive() || a.IsArchived() {
return response.Unauthorized(ar.logger, ar.service, "customer is inactive")
}
accessToken, err := ar.imp.CreateAccessTokenForSession(&a, t.SessionIdentifier)
if err != nil {
ar.logger.Warn("Failed to generate access token", zap.Error(err))
return response.Internal(ar.logger, ar.service, err)
}
return handler(r, &a, &accessToken)
}
ar.tokenHandler(service, endpoint, method, hndlr)
}
func (ar *AuthorizedRouter) PendingAccountHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.PendingAccountHandlerFunc) {
hndlr := func(r *http.Request, t *emodel.AccountToken) http.HandlerFunc {
var a customermodel.Account
if err := ar.db.Get(r.Context(), t.AccountRef, &a); err != nil {
if errors.Is(err, merrors.ErrNoData) {
ar.logger.Debug("Failed to find related user", zap.Error(err), mzap.AccRef(t.AccountRef))
return response.NotFound(ar.logger, ar.service, err.Error())
}
return response.Internal(ar.logger, ar.service, err)
}
if a.Status == customermodel.AccountBlocked || a.IsArchived() {
return response.Unauthorized(ar.logger, ar.service, "customer is inactive")
}
return handler(r, &a, t)
}
ar.tokenHandler(service, endpoint, method, hndlr)
}
@@ -0,0 +1,60 @@
package authorized
import (
"net/http"
"git.sendico.io/tech/sxchnge/product/auth/config"
re "git.sendico.io/tech/sxchnge/product/auth/http/endpoint"
emodel "git.sendico.io/tech/sxchnge/product/auth/model"
"git.sendico.io/tech/sxchnge/product/customers/store"
"git.sendico.io/tech/sxchnge/product/sessions/metrics"
"git.sendico.io/tech/sxchnge/product/sessions/store"
api "git.sendico.io/tech/sxchnge/shared/http"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/logging"
"git.sendico.io/tech/sxchnge/shared/logging/fields"
"git.sendico.io/tech/sxchnge/shared/service"
"github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
"go.uber.org/zap"
)
type AuthorizedRouter struct {
logger mlogger.Logger
db account.DB
rtdb refreshtokens.DB
imp *re.HttpEndpointRouter
service mservice.Type
}
func NewRouter(logger mlogger.Logger, apiEndpoint string, router chi.Router, db account.DB, rtdb refreshtokens.DB, config *middleware.TokenConfig, signature *middleware.Signature) *AuthorizedRouter {
ja := jwtauth.New(signature.Algorithm, signature.PrivateKey, signature.PublicKey)
router.Use(jwtauth.Verifier(ja))
router.Use(jwtauth.Authenticator(ja))
l := logger.Named("authorized")
ar := AuthorizedRouter{
logger: l,
db: db,
rtdb: rtdb,
imp: re.NewHttpEndpointRouter(l, apiEndpoint, router, config, signature),
service: mservice.Accounts,
}
ar.tokenHandlerWithSessionCheck(mservice.Accounts, "/logout/all", api.Post, false, ar.logoutAll)
return &ar
}
func (ar *AuthorizedRouter) logoutAll(r *http.Request, token *emodel.AccountToken) http.HandlerFunc {
if token.ClientID == "" || token.DeviceID == "" || token.SessionVersion == "" {
sessionmetrics.Observe(sessionmetrics.AllLogout, sessionmetrics.MissingIdentity)
return response.Unauthorized(ar.logger, ar.service, "session identifier is required")
}
if err := ar.rtdb.RevokeAll(r.Context(), token.AccountRef, ""); err != nil {
sessionmetrics.Observe(sessionmetrics.AllLogout, sessionmetrics.StorageError)
ar.logger.Warn("Failed to revoke all account sessions", zap.Error(err), mzap.AccRef(token.AccountRef))
return response.Internal(ar.logger, ar.service, err)
}
sessionmetrics.Observe(sessionmetrics.AllLogout, sessionmetrics.Succeeded)
ar.logger.Info("All account sessions revoked", mzap.AccRef(token.AccountRef))
return response.Success(ar.logger)
}
@@ -0,0 +1,113 @@
package authorized
import (
"context"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"net/http"
"net/http/httptest"
"testing"
emodel "git.sendico.io/tech/sxchnge/product/auth/model"
"git.sendico.io/tech/sxchnge/product/sessions/store"
"git.sendico.io/tech/sxchnge/shared/errors"
"git.sendico.io/tech/sxchnge/shared/service"
"go.mongodb.org/mongo-driver/v2/bson"
"go.uber.org/zap"
)
type sessionDB struct {
refreshtokens.DB
token *sessionmodel.RefreshToken
err error
revokeAllID string
}
func (db *sessionDB) GetSession(context.Context, bson.ObjectID, *sessionmodel.SessionIdentifier) (*sessionmodel.RefreshToken, error) {
return db.token, db.err
}
func (db *sessionDB) RevokeAll(_ context.Context, _ bson.ObjectID, deviceID string) error {
db.revokeAllID = deviceID
return db.err
}
func TestValidateSessionFailsClosed(t *testing.T) {
accountRef := bson.NewObjectID()
token := &emodel.AccountToken{
AccountRef: accountRef,
SessionIdentifier: sessionmodel.SessionIdentifier{
ClientID: "web",
DeviceID: "device-a",
SessionVersion: "version-a",
},
}
request := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/accounts", nil)
tests := []struct {
name string
db *sessionDB
mutate func(*emodel.AccountToken)
wantStatus int
}{
{name: "active", db: &sessionDB{token: &sessionmodel.RefreshToken{}}, wantStatus: 0},
{name: "revoked", db: &sessionDB{err: merrors.ErrNoData}, wantStatus: http.StatusUnauthorized},
{name: "storage unavailable", db: &sessionDB{err: merrors.Internal("database unavailable")}, wantStatus: http.StatusInternalServerError},
{
name: "missing version",
db: &sessionDB{},
mutate: func(token *emodel.AccountToken) {
token.SessionVersion = ""
},
wantStatus: http.StatusUnauthorized,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
candidate := *token
if tt.mutate != nil {
tt.mutate(&candidate)
}
router := &AuthorizedRouter{logger: zap.NewNop(), rtdb: tt.db, service: mservice.Accounts}
handler := router.validateSession(request, &candidate)
if tt.wantStatus == 0 {
if handler != nil {
t.Fatal("active session was rejected")
}
return
}
if handler == nil {
t.Fatal("invalid session was accepted")
}
response := httptest.NewRecorder()
handler(response, request)
if response.Code != tt.wantStatus {
t.Fatalf("status = %d, want %d", response.Code, tt.wantStatus)
}
})
}
}
func TestLogoutAllRevokesEveryDevice(t *testing.T) {
db := &sessionDB{}
router := &AuthorizedRouter{logger: zap.NewNop(), rtdb: db, service: mservice.Accounts}
token := &emodel.AccountToken{
AccountRef: bson.NewObjectID(),
SessionIdentifier: sessionmodel.SessionIdentifier{
ClientID: "web",
DeviceID: "device-a",
SessionVersion: "version-a",
},
}
request := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/accounts/logout/all", nil)
response := httptest.NewRecorder()
router.logoutAll(request, token)(response, request)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", response.Code, http.StatusOK)
}
if db.revokeAllID != "" {
t.Fatalf("device exclusion = %q, want all devices", db.revokeAllID)
}
}
+64
View File
@@ -0,0 +1,64 @@
package router
import (
"os"
"github.com/go-chi/chi/v5"
"git.sendico.io/tech/sxchnge/product/auth/config"
rauthorized "git.sendico.io/tech/sxchnge/product/auth/http/authorized"
rpublic "git.sendico.io/tech/sxchnge/product/auth/http/public"
"git.sendico.io/tech/sxchnge/product/auth/response"
"git.sendico.io/tech/sxchnge/product/customers/store"
"git.sendico.io/tech/sxchnge/product/sessions/store"
"git.sendico.io/tech/sxchnge/product/verification/store"
api "git.sendico.io/tech/sxchnge/shared/http"
"git.sendico.io/tech/sxchnge/shared/logging"
"git.sendico.io/tech/sxchnge/shared/ratelimit/store"
"git.sendico.io/tech/sxchnge/shared/service"
)
type Dispatcher struct {
logger mlogger.Logger
public APIRouter
protected ProtectedAPIRouter
}
func (d *Dispatcher) Handler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.HandlerFunc) {
d.public.InstallHandler(service, endpoint, method, handler)
}
func (d *Dispatcher) AccountHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.AccountHandlerFunc) {
d.protected.AccountHandler(service, endpoint, method, handler)
}
func (d *Dispatcher) PendingAccountHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.PendingAccountHandlerFunc) {
d.protected.PendingAccountHandler(service, endpoint, method, handler)
}
func NewDispatcher(
logger mlogger.Logger,
router chi.Router,
db account.DB,
vdb verification.DB,
rtdb refreshtokens.DB,
attempts ratelimits.Store,
config *middleware.Config,
loginRateLimits middleware.LoginRateLimits,
) *Dispatcher {
d := &Dispatcher{
logger: logger.Named("api_dispatcher"),
}
d.logger.Debug("Installing endpoints middleware...")
endpoint := os.Getenv(config.EndPointEnv)
signature := middleware.SignatureConf(config)
router.Group(func(r chi.Router) {
d.public = rpublic.NewRouter(d.logger, endpoint, db, vdb, rtdb, attempts, r, &config.Token, &signature, loginRateLimits)
})
router.Group(func(r chi.Router) {
d.protected = rauthorized.NewRouter(d.logger, endpoint, r, db, rtdb, &config.Token, &signature)
})
return d
}
@@ -0,0 +1,37 @@
package endpoint
import (
"context"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"net/http"
"git.sendico.io/tech/sxchnge/product/auth/config"
"git.sendico.io/tech/sxchnge/product/auth/response"
"git.sendico.io/tech/sxchnge/shared/logging"
"github.com/go-chi/chi/v5"
)
type (
RegistratorT = func(chi.Router, string, http.HandlerFunc)
ResponderFunc = func(ctx context.Context, r *http.Request, session *sessionmodel.SessionIdentifier, account *customermodel.Account, accessToken *sresponse.TokenData) http.HandlerFunc
)
type HttpEndpointRouter struct {
logger mlogger.Logger
apiEndpoint string
router chi.Router
config middleware.TokenConfig
signature middleware.Signature
}
func NewHttpEndpointRouter(logger mlogger.Logger, apiEndpoint string, router chi.Router, config *middleware.TokenConfig, signature *middleware.Signature) *HttpEndpointRouter {
er := HttpEndpointRouter{
logger: logger.Named("http"),
apiEndpoint: apiEndpoint,
router: router,
signature: *signature,
config: *config,
}
return &er
}
@@ -0,0 +1,55 @@
package endpoint
import (
"net/http"
"path"
"git.sendico.io/tech/sxchnge/product/auth/response"
api "git.sendico.io/tech/sxchnge/shared/http"
"git.sendico.io/tech/sxchnge/shared/service"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"
)
func (er *HttpEndpointRouter) chooseMethod(method api.HTTPMethod) RegistratorT {
switch method {
case api.Get:
return func(r chi.Router, p string, h http.HandlerFunc) { r.Get(p, h) }
case api.Post:
return func(r chi.Router, p string, h http.HandlerFunc) { r.Post(p, h) }
case api.Put:
return func(r chi.Router, p string, h http.HandlerFunc) { r.Put(p, h) }
case api.Delete:
return func(r chi.Router, p string, h http.HandlerFunc) { r.Delete(p, h) }
case api.Patch:
return func(r chi.Router, p string, h http.HandlerFunc) { r.Patch(p, h) }
case api.Options:
return func(r chi.Router, p string, h http.HandlerFunc) { r.Options(p, h) }
case api.Head:
return func(r chi.Router, p string, h http.HandlerFunc) { r.Head(p, h) }
default:
return nil
}
}
func (er *HttpEndpointRouter) endpoint(service mservice.Type, handler string) string {
return path.Join(er.apiEndpoint, service, handler)
}
func (er *HttpEndpointRouter) InstallHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.HandlerFunc) {
ep := er.endpoint(service, endpoint)
hm := er.chooseMethod(method)
if hm == nil {
er.logger.Warn("Handler install skipped because method is unsupported",
zap.String("endpoint", ep),
zap.String("method", api.HTTPMethod2String(method)),
)
return
}
hndlr := func(w http.ResponseWriter, r *http.Request) {
res := handler(r)
res(w, r)
}
hm(er.router, ep, hndlr)
er.logger.Info("Handler installed", zap.String("endpoint", ep), zap.String("method", api.HTTPMethod2String(method)))
}
@@ -0,0 +1,31 @@
package endpoint
import (
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"time"
emodel "git.sendico.io/tech/sxchnge/product/auth/model"
"git.sendico.io/tech/sxchnge/product/auth/response"
"github.com/go-chi/jwtauth/v5"
)
func (er *HttpEndpointRouter) CreateAccessTokenForSession(user *customermodel.Account, session sessionmodel.SessionIdentifier) (sresponse.TokenData, error) {
ja := jwtauth.New(er.signature.Algorithm, er.signature.PrivateKey, er.signature.PublicKey)
_, res, err := ja.Encode(emodel.Account2ClaimsForSession(user, er.config.Expiration.Account, session))
token := sresponse.TokenData{
Token: res,
Expiration: time.Now().Add(time.Duration(er.config.Expiration.Account) * time.Hour),
}
return token, err
}
func (er *HttpEndpointRouter) CreatePendingToken(user *customermodel.Account, ttlMinutes int) (sresponse.TokenData, error) {
ja := jwtauth.New(er.signature.Algorithm, er.signature.PrivateKey, er.signature.PublicKey)
_, res, err := ja.Encode(emodel.PendingAccount2Claims(user, ttlMinutes))
token := sresponse.TokenData{
Token: res,
Expiration: time.Now().Add(time.Duration(ttlMinutes) * time.Minute),
}
return token, err
}
+250
View File
@@ -0,0 +1,250 @@
package public
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"net/http"
"strings"
clientauth "git.sendico.io/tech/sxchnge/product/auth/client"
"git.sendico.io/tech/sxchnge/product/auth/ipguard"
"git.sendico.io/tech/sxchnge/product/auth/request"
"git.sendico.io/tech/sxchnge/product/auth/response"
"git.sendico.io/tech/sxchnge/shared/errors"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/logging"
"git.sendico.io/tech/sxchnge/shared/logging/mask"
"git.sendico.io/tech/sxchnge/shared/service"
"go.uber.org/zap"
)
const pendingLoginTTLMinutes = 10
const apiLoginGrantType = "password"
const apiLoginClientAuthMethod = "client_secret_post"
const dummyPasswordHash = "$2y$10$pmvNFN5zyooml6Oqh.cGFenBF/indHDE.dyLwjNJW1.Tk2Suvdvve"
func (pr *PublicRouter) authenticateAccount(ctx context.Context, req *srequest.Login) (*customermodel.Account, bool, http.HandlerFunc) {
// Get the account database entry
trimmedLogin := strings.TrimSpace(req.Login)
account, err := pr.db.GetByEmail(ctx, strings.ToLower(trimmedLogin))
if errors.Is(err, merrors.ErrNoData) || (err == nil && account == nil) {
(&customermodel.Account{Password: dummyPasswordHash}).MatchPassword(req.Password)
pr.logger.Debug("Login rejected: invalid credentials")
return nil, true, response.Unauthorized(pr.logger, pr.service, "invalid credentials")
}
if err != nil {
pr.logger.Warn("Failed to query user during login", zap.Error(err))
return nil, false, response.Internal(pr.logger, pr.service, err)
}
if !account.MatchPassword(req.Password) {
pr.logger.Debug("Login rejected: invalid credentials")
return nil, true, response.Unauthorized(pr.logger, pr.service, "invalid credentials")
}
if !account.IsActive() || account.IsArchived() {
return nil, false, response.Forbidden(pr.logger, pr.service, "account_not_verified", "Account verification required")
}
return account, false, nil
}
func (pr *PublicRouter) respondPendingLogin(account *customermodel.Account) http.HandlerFunc {
pendingToken, err := pr.imp.CreatePendingToken(account, pendingLoginTTLMinutes)
if err != nil {
pr.logger.Warn("Failed to generate pending token", zap.Error(err))
return response.Internal(pr.logger, pr.service, err)
}
return sresponse.LoginPending(pr.logger, account, &pendingToken, mask.Email(account.Login))
}
func hasGrantType(grants []string, target string) bool {
for _, grant := range grants {
if strings.EqualFold(strings.TrimSpace(grant), target) {
return true
}
}
return false
}
func (pr *PublicRouter) validateClientIPPolicy(r *http.Request, clientID string, client *sessionmodel.Client) http.HandlerFunc {
if client == nil {
pr.logger.Debug("Client not found, rejecting authorization", zap.String("client_id", clientID))
return response.Unauthorized(pr.logger, pr.service, clientauth.ErrUnknownClientID.Error())
}
clientIP := ipguard.ClientIP(r)
allowed, err := ipguard.Allowed(clientIP, client.AllowedCIDRs)
if err != nil {
pr.logger.Warn("Client IP policy contains invalid CIDR", zap.Error(err), zap.String("client_id", clientID))
return response.Forbidden(pr.logger, pr.service, "client_ip_policy_invalid", "client ip policy is invalid")
}
if !allowed {
rawIP := ""
if clientIP != nil {
rawIP = clientIP.String()
}
pr.logger.Info("Client IP policy denied request", zap.String("client_id", clientID), zap.String("remote_ip", rawIP))
return response.Forbidden(pr.logger, pr.service, "ip_not_allowed", "request ip is not allowed for this client")
}
return nil
}
func (pr *PublicRouter) loadClient(ctx context.Context, clientID string) (*sessionmodel.Client, http.HandlerFunc) {
client, err := clientauth.Resolve(ctx, pr.rtdb, clientID)
if errors.Is(err, clientauth.ErrUnknownClientID) {
pr.logger.Debug("Login rejected: unknown client id", zap.String("client_id", clientID))
return nil, response.Unauthorized(pr.logger, pr.service, clientauth.ErrUnknownClientID.Error())
}
if err != nil {
pr.logger.Warn("Login rejected: failed to load client", zap.Error(err), zap.String("client_id", clientID))
return nil, response.Internal(pr.logger, pr.service, err)
}
return client, nil
}
func (pr *PublicRouter) validateClientAccountBinding(client *sessionmodel.Client, account *customermodel.Account) http.HandlerFunc {
if client == nil || client.AccountRef == nil {
return nil
}
accountRef := account.GetID()
if accountRef == nil || *client.AccountRef != *accountRef {
return response.Forbidden(pr.logger, pr.service, "client_account_mismatch", "client is bound to another account")
}
return nil
}
func (pr *PublicRouter) validateClientState(r *http.Request, clientID string, client *sessionmodel.Client) http.HandlerFunc {
if client == nil {
return response.Unauthorized(pr.logger, pr.service, clientauth.ErrUnknownClientID.Error())
}
if client.IsRevoked {
return response.Forbidden(pr.logger, pr.service, "client_revoked", "client has been revoked")
}
if h := pr.validateClientIPPolicy(r, clientID, client); h != nil {
return h
}
return nil
}
func (pr *PublicRouter) validateAPIClient(ctx context.Context, r *http.Request, req *srequest.Login, account *customermodel.Account) http.HandlerFunc {
client, h := pr.loadClient(ctx, req.ClientID)
if h != nil {
return h
}
if h := pr.validateClientState(r, req.ClientID, client); h != nil {
return h
}
if !hasGrantType(client.GrantTypes, apiLoginGrantType) {
return response.Forbidden(pr.logger, pr.service, "client_grant_not_allowed", "client does not allow password grant")
}
method := strings.ToLower(strings.TrimSpace(client.TokenEndpointAuthMethod))
if method == "" {
method = apiLoginClientAuthMethod
}
if method != apiLoginClientAuthMethod {
return response.Forbidden(pr.logger, pr.service, "client_auth_method_unsupported", "unsupported client auth method")
}
storedSecret := strings.TrimSpace(client.ClientSecret)
if storedSecret == "" {
return response.Forbidden(pr.logger, pr.service, "client_secret_missing", "client secret is not configured")
}
if subtle.ConstantTimeCompare([]byte(storedSecret), []byte(req.ClientSecret)) != 1 {
pr.logger.Debug("API login rejected: invalid client secret", zap.String("client_id", req.ClientID))
return response.Unauthorized(pr.logger, pr.service, "invalid client secret")
}
if h := pr.validateClientAccountBinding(client, account); h != nil {
return h
}
return nil
}
func (pr *PublicRouter) resolveLoginClient(ctx context.Context, r *http.Request, clientID string) (*sessionmodel.Client, http.HandlerFunc) {
clientID = strings.TrimSpace(clientID)
if clientID == "" {
return nil, nil
}
client, h := pr.loadClient(ctx, clientID)
if h != nil {
return nil, h
}
if h := pr.validateClientState(r, clientID, client); h != nil {
return nil, h
}
return client, nil
}
func (pr *PublicRouter) respondAPILogin(ctx context.Context, r *http.Request, req *srequest.Login, account *customermodel.Account) http.HandlerFunc {
if req.ClientID == "" || req.DeviceID == "" {
return response.BadRequest(pr.logger, pr.service, "missing_session", "session identifier is required")
}
return pr.refreshAndRespondLogin(ctx, r, &req.SessionIdentifier, account)
}
func decodeLogin(r *http.Request, logger mlogger.Logger) (*srequest.Login, http.HandlerFunc) {
var req srequest.Login
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
logger.Info("Failed to decode login request", zap.Error(err))
return nil, response.BadPayload(logger, mservice.Accounts, err)
}
req.Login = strings.TrimSpace(req.Login)
req.Password = strings.TrimSpace(req.Password)
req.ClientID = strings.TrimSpace(req.ClientID)
req.DeviceID = strings.TrimSpace(req.DeviceID)
req.ClientSecret = strings.TrimSpace(req.ClientSecret)
if req.Login == "" {
return nil, response.BadRequest(logger, mservice.Accounts, "email_missing", "login request has no user name")
}
if req.Password == "" {
return nil, response.BadRequest(logger, mservice.Accounts, "password_missing", "login request has no password")
}
return &req, nil
}
func (a *PublicRouter) login(r *http.Request) http.HandlerFunc {
req, h := decodeLogin(r, a.logger)
if h != nil {
return h
}
client, h := a.resolveLoginClient(r.Context(), r, req.ClientID)
if h != nil {
return h
}
account, h := a.authenticateRateLimited(r, req)
if h != nil {
return h
}
if h = a.validateClientAccountBinding(client, account); h != nil {
return h
}
return a.respondPendingLogin(account)
}
func (a *PublicRouter) apiLogin(r *http.Request) http.HandlerFunc {
req, h := decodeLogin(r, a.logger)
if h != nil {
return h
}
if req.ClientID == "" {
return response.BadRequest(a.logger, mservice.Accounts, "client_id_missing", "clientId is required")
}
if req.ClientSecret == "" {
return response.BadRequest(a.logger, mservice.Accounts, "client_secret_missing", "clientSecret is required")
}
account, h := a.authenticateRateLimited(r, req)
if h != nil {
return h
}
if h = a.validateAPIClient(r.Context(), r, req, account); h != nil {
return h
}
return a.respondAPILogin(r.Context(), r, req, account)
}
@@ -0,0 +1,179 @@
package public
import (
"context"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
"net/http"
"strconv"
"strings"
"time"
"git.sendico.io/tech/sxchnge/product/auth/config"
"git.sendico.io/tech/sxchnge/product/auth/ipguard"
"git.sendico.io/tech/sxchnge/product/auth/request"
"git.sendico.io/tech/sxchnge/shared/errors"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/ratelimit/store"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.uber.org/zap"
)
const (
loginScopeAccount = "account"
loginScopeIP = "ip"
)
var loginRateLimitDecisions = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "sendico_login_rate_limit_decisions_total",
Help: "Login rate-limit decisions grouped by scope kind and outcome.",
}, []string{"scope_kind", "outcome"})
type loginRateScope struct {
kind string
hash string
limit int
windowStart time.Time
expiresAt time.Time
}
func (pr *PublicRouter) authenticateRateLimited(
r *http.Request,
req *srequest.Login,
) (*customermodel.Account, http.HandlerFunc) {
if pr.attempts == nil {
account, _, h := pr.authenticateAccount(r.Context(), req)
return account, h
}
clock := pr.now
if clock == nil {
clock = time.Now
}
now := clock().UTC()
scopes := pr.loginRateScopes(r, req.Login, now)
if h := pr.checkLoginRateLimits(r.Context(), scopes, now); h != nil {
return nil, h
}
account, credentialFailure, h := pr.authenticateAccount(r.Context(), req)
if !credentialFailure {
for _, scope := range scopes {
loginRateLimitDecisions.WithLabelValues(scope.kind, "allowed").Inc()
}
return account, h
}
limited, retryAfter, failureHandler := pr.recordLoginFailure(r.Context(), scopes, now)
if failureHandler != nil {
return nil, failureHandler
}
if limited {
return nil, pr.loginRateLimited(retryAfter)
}
return nil, h
}
func (pr *PublicRouter) loginRateScopes(r *http.Request, login string, now time.Time) []loginRateScope {
normalizedLogin := strings.ToLower(strings.TrimSpace(login))
clientIP := "unresolved"
if resolved := ipguard.ClientIP(r); resolved != nil {
clientIP = resolved.String()
}
return []loginRateScope{
newLoginRateScope(loginScopeAccount, normalizedLogin, pr.limits.PerAccount, now),
newLoginRateScope(loginScopeIP, clientIP, pr.limits.PerIP, now),
}
}
func newLoginRateScope(kind, value string, limit middleware.LoginRateLimitWindow, now time.Time) loginRateScope {
windowStart := now.Truncate(limit.Window)
return loginRateScope{
kind: kind,
hash: ratelimits.HashScope(kind, value),
limit: limit.Limit,
windowStart: windowStart,
expiresAt: windowStart.Add(limit.Window),
}
}
func (pr *PublicRouter) checkLoginRateLimits(
ctx context.Context,
scopes []loginRateScope,
now time.Time,
) http.HandlerFunc {
for _, scope := range scopes {
count, err := pr.attempts.Current(ctx, scope.kind, scope.hash, scope.windowStart)
if err != nil {
return pr.loginRateLimitStorageFailure(scope.kind, err)
}
if count >= scope.limit {
loginRateLimitDecisions.WithLabelValues(scope.kind, "denied").Inc()
retryAfter := retryAfterDuration(now, scope.expiresAt)
pr.logger.Info("Denied login request at rate limit",
zap.String("scope_kind", scope.kind),
zap.Int64("retry_after_seconds", retryAfterSeconds(retryAfter)))
return pr.loginRateLimited(retryAfter)
}
}
return nil
}
func (pr *PublicRouter) recordLoginFailure(
ctx context.Context,
scopes []loginRateScope,
now time.Time,
) (bool, time.Duration, http.HandlerFunc) {
limited := false
var retryAfter time.Duration
for _, scope := range scopes {
count, err := pr.attempts.Increment(ctx, scope.kind, scope.hash, scope.windowStart, scope.expiresAt)
if err != nil {
return false, 0, pr.loginRateLimitStorageFailure(scope.kind, err)
}
if count >= scope.limit {
limited = true
loginRateLimitDecisions.WithLabelValues(scope.kind, "denied").Inc()
scopeRetry := retryAfterDuration(now, scope.expiresAt)
if retryAfter == 0 || scopeRetry < retryAfter {
retryAfter = scopeRetry
}
pr.logger.Info("Login failure reached rate limit",
zap.String("scope_kind", scope.kind),
zap.Int64("retry_after_seconds", retryAfterSeconds(scopeRetry)))
continue
}
loginRateLimitDecisions.WithLabelValues(scope.kind, "allowed").Inc()
}
return limited, retryAfter, nil
}
func (pr *PublicRouter) loginRateLimitStorageFailure(scopeKind string, cause error) http.HandlerFunc {
loginRateLimitDecisions.WithLabelValues(scopeKind, "error").Inc()
pr.logger.Warn("Login protection storage failed", zap.Error(cause), zap.String("scope_kind", scopeKind))
err := merrors.OpaqueWrap(merrors.ErrServiceUnavailable, cause, "login protection is temporarily unavailable")
return response.Auto(pr.logger, pr.service, err)
}
func (pr *PublicRouter) loginRateLimited(retryAfter time.Duration) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Retry-After", strconv.FormatInt(retryAfterSeconds(retryAfter), 10))
response.TooManyRequests(pr.logger, pr.service, "too many login attempts; try again later")(w, r)
}
}
func retryAfterDuration(now, expiresAt time.Time) time.Duration {
retryAfter := expiresAt.Sub(now)
if retryAfter <= 0 {
return time.Second
}
return retryAfter
}
func retryAfterSeconds(retryAfter time.Duration) int64 {
seconds := int64((retryAfter + time.Second - 1) / time.Second)
if seconds < 1 {
return 1
}
return seconds
}
@@ -0,0 +1,316 @@
package public
import (
"context"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"git.sendico.io/tech/sxchnge/product/auth/config"
"git.sendico.io/tech/sxchnge/product/auth/request"
"git.sendico.io/tech/sxchnge/shared/errors"
"git.sendico.io/tech/sxchnge/shared/service"
"go.uber.org/zap"
)
type fakeLoginAttemptStore struct {
mu sync.Mutex
counts map[string]int
currentErr error
incrementErr error
}
func newFakeLoginAttemptStore() *fakeLoginAttemptStore {
return &fakeLoginAttemptStore{counts: make(map[string]int)}
}
func (s *fakeLoginAttemptStore) Current(_ context.Context, kind, hash string, start time.Time) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.currentErr != nil {
return 0, s.currentErr
}
return s.counts[attemptKey(kind, hash, start)], nil
}
func (s *fakeLoginAttemptStore) Increment(
_ context.Context,
kind, hash string,
start, _ time.Time,
) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.incrementErr != nil {
return 0, s.incrementErr
}
key := attemptKey(kind, hash, start)
s.counts[key]++
return s.counts[key], nil
}
func attemptKey(kind, hash string, start time.Time) string {
return kind + ":" + hash + ":" + start.UTC().Format(time.RFC3339Nano)
}
func testLoginLimits(accountLimit, ipLimit int, window time.Duration) middleware.LoginRateLimits {
return middleware.LoginRateLimits{
PerAccount: middleware.LoginRateLimitWindow{Limit: accountLimit, Window: window},
PerIP: middleware.LoginRateLimitWindow{Limit: ipLimit, Window: window},
}
}
func testRateLimitedRouter(
db *testAccountDB,
store *fakeLoginAttemptStore,
limits middleware.LoginRateLimits,
now *time.Time,
) *PublicRouter {
return &PublicRouter{
logger: zap.NewNop(),
db: db,
service: mservice.Accounts,
attempts: store,
limits: limits,
now: func() time.Time {
return *now
},
}
}
func loginRequest(login, password, remoteAddr string) (*http.Request, *srequest.Login) {
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/login", nil)
req.RemoteAddr = remoteAddr
return req, &srequest.Login{LoginData: customermodel.LoginData{
UserDataBase: customermodel.UserDataBase{Login: login},
Password: password,
}}
}
func executeLoginHandler(t *testing.T, h http.HandlerFunc, req *http.Request) *httptest.ResponseRecorder {
t.Helper()
if h == nil {
t.Fatal("expected response handler")
}
recorder := httptest.NewRecorder()
h(recorder, req)
return recorder
}
func TestLoginRateLimitNormalizesAccountAndBoundsDistributedAttempts(t *testing.T) {
now := time.Date(2026, time.August, 13, 9, 0, 0, 0, time.UTC)
store := newFakeLoginAttemptStore()
db := &testAccountDB{result: testActiveAccount(t)}
router := testRateLimitedRouter(db, store, testLoginLimits(3, 100, 10*time.Minute), &now)
attempts := []struct {
login string
remote string
status int
}{
{login: " User@Example.com ", remote: "192.0.2.1:1000", status: http.StatusUnauthorized},
{login: "user@example.com", remote: "192.0.2.2:1000", status: http.StatusUnauthorized},
{login: "USER@EXAMPLE.COM", remote: "192.0.2.3:1000", status: http.StatusTooManyRequests},
}
for _, attempt := range attempts {
req, login := loginRequest(attempt.login, "wrong password", attempt.remote)
_, h := router.authenticateRateLimited(req, login)
recorder := executeLoginHandler(t, h, req)
if recorder.Code != attempt.status {
t.Fatalf("login %q status: got %d want %d", attempt.login, recorder.Code, attempt.status)
}
}
req, login := loginRequest("user@example.com", "correct horse battery staple", "192.0.2.4:1000")
_, h := router.authenticateRateLimited(req, login)
recorder := executeLoginHandler(t, h, req)
if recorder.Code != http.StatusTooManyRequests || recorder.Header().Get("Retry-After") != "600" {
t.Fatalf("blocked recovery mismatch: status=%d retry=%q", recorder.Code, recorder.Header().Get("Retry-After"))
}
now = now.Add(10 * time.Minute)
account, h := router.authenticateRateLimited(req, login)
if h != nil || account == nil {
t.Fatalf("expected legitimate login after window expiry, account=%v handler=%v", account, h)
}
}
func TestLoginRateLimitBoundsOneSourceAcrossAccounts(t *testing.T) {
now := time.Date(2026, time.August, 13, 9, 0, 0, 0, time.UTC)
store := newFakeLoginAttemptStore()
router := testRateLimitedRouter(
&testAccountDB{err: merrors.ErrNoData},
store,
testLoginLimits(100, 3, 15*time.Minute),
&now,
)
for i, loginValue := range []string{"one@example.com", "two@example.com", "three@example.com"} {
req, login := loginRequest(loginValue, "wrong password", "198.51.100.10:9000")
_, h := router.authenticateRateLimited(req, login)
recorder := executeLoginHandler(t, h, req)
want := http.StatusUnauthorized
if i == 2 {
want = http.StatusTooManyRequests
}
if recorder.Code != want {
t.Fatalf("attempt %d status: got %d want %d", i+1, recorder.Code, want)
}
}
}
func TestLoginEndpointReturnsStableRateLimitResponse(t *testing.T) {
now := time.Date(2026, time.August, 13, 9, 0, 0, 0, time.UTC)
router := testRateLimitedRouter(
&testAccountDB{err: merrors.ErrNoData},
newFakeLoginAttemptStore(),
testLoginLimits(2, 50, 15*time.Minute),
&now,
)
body := `{"login":{"login":"missing@example.com","password":"wrong password"}}`
for attempt := 1; attempt <= 2; attempt++ {
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/login", strings.NewReader(body))
req.RemoteAddr = "198.51.100.20:9000"
recorder := httptest.NewRecorder()
router.login(req)(recorder, req)
want := http.StatusUnauthorized
if attempt == 2 {
want = http.StatusTooManyRequests
}
if recorder.Code != want {
t.Fatalf("attempt %d status: got %d want %d", attempt, recorder.Code, want)
}
if attempt == 2 {
if recorder.Header().Get("Retry-After") != "900" {
t.Fatalf("unexpected Retry-After: %q", recorder.Header().Get("Retry-After"))
}
if !strings.Contains(recorder.Body.String(), `"error":"too_many_requests"`) {
t.Fatalf("unexpected 429 body: %s", recorder.Body.String())
}
}
}
}
func TestInvalidCredentialsDoNotDiscloseAccountExistence(t *testing.T) {
request := &srequest.Login{LoginData: customermodel.LoginData{
UserDataBase: customermodel.UserDataBase{Login: "user@example.com"},
Password: "wrong password",
}}
responses := make([]*httptest.ResponseRecorder, 0, 2)
for _, db := range []*testAccountDB{
{result: testActiveAccount(t)},
{err: merrors.ErrNoData},
} {
router := &PublicRouter{logger: zap.NewNop(), db: db, service: mservice.Accounts}
_, failed, h := router.authenticateAccount(context.Background(), request)
if !failed {
t.Fatal("invalid credentials were not classified as a failure")
}
req, _ := loginRequest("user@example.com", "wrong password", "192.0.2.1:1000")
responses = append(responses, executeLoginHandler(t, h, req))
}
if responses[0].Code != http.StatusUnauthorized || responses[1].Code != http.StatusUnauthorized {
t.Fatalf("unexpected statuses: existing=%d unknown=%d", responses[0].Code, responses[1].Code)
}
if responses[0].Body.String() != responses[1].Body.String() ||
!strings.Contains(responses[0].Body.String(), "invalid credentials") {
t.Fatalf("credential responses differ: existing=%s unknown=%s", responses[0].Body.String(), responses[1].Body.String())
}
}
func TestLoginRateLimitIsAtomicAcrossRouterInstances(t *testing.T) {
now := time.Date(2026, time.August, 13, 9, 0, 0, 0, time.UTC)
store := newFakeLoginAttemptStore()
db := &testAccountDB{err: merrors.ErrNoData}
limits := testLoginLimits(5, 1000, 15*time.Minute)
routers := []*PublicRouter{
testRateLimitedRouter(db, store, limits, &now),
testRateLimitedRouter(db, store, limits, &now),
}
var unauthorized atomic.Int64
var limited atomic.Int64
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func(index int) {
defer wg.Done()
req, login := loginRequest("shared@example.com", "wrong password", "203.0.113."+strconv.Itoa(index+1)+":9000")
_, h := routers[index%len(routers)].authenticateRateLimited(req, login)
recorder := httptest.NewRecorder()
h(recorder, req)
switch recorder.Code {
case http.StatusUnauthorized:
unauthorized.Add(1)
case http.StatusTooManyRequests:
limited.Add(1)
}
}(i)
}
wg.Wait()
if unauthorized.Load() != 4 || limited.Load() != 16 {
t.Fatalf("concurrent decisions: unauthorized=%d limited=%d", unauthorized.Load(), limited.Load())
}
}
func TestLoginRateLimitFailsClosedOnStorageError(t *testing.T) {
now := time.Date(2026, time.August, 13, 9, 0, 0, 0, time.UTC)
store := newFakeLoginAttemptStore()
store.currentErr = merrors.Internal("database unavailable")
db := &testAccountDB{result: testActiveAccount(t)}
router := testRateLimitedRouter(db, store, testLoginLimits(5, 50, 15*time.Minute), &now)
req, login := loginRequest("user@example.com", "correct horse battery staple", "192.0.2.1:1000")
_, h := router.authenticateRateLimited(req, login)
recorder := executeLoginHandler(t, h, req)
if recorder.Code != http.StatusServiceUnavailable {
t.Fatalf("expected service unavailable, got %d", recorder.Code)
}
if db.getByEmailCalls != 0 {
t.Fatalf("storage failure must stop before password lookup, got %d lookups", db.getByEmailCalls)
}
if strings.Contains(recorder.Body.String(), "database unavailable") {
t.Fatal("storage cause leaked to the public response")
}
}
func TestLoginRateLimitFailsClosedWhenFailureCannotBeRecorded(t *testing.T) {
now := time.Date(2026, time.August, 13, 9, 0, 0, 0, time.UTC)
store := newFakeLoginAttemptStore()
store.incrementErr = merrors.Internal("write unavailable")
router := testRateLimitedRouter(
&testAccountDB{err: merrors.ErrNoData},
store,
testLoginLimits(5, 50, 15*time.Minute),
&now,
)
req, login := loginRequest("missing@example.com", "wrong password", "192.0.2.1:1000")
_, h := router.authenticateRateLimited(req, login)
recorder := executeLoginHandler(t, h, req)
if recorder.Code != http.StatusServiceUnavailable {
t.Fatalf("expected service unavailable, got %d", recorder.Code)
}
if !strings.Contains(recorder.Body.String(), "login protection is temporarily unavailable") {
t.Fatalf("unexpected public failure body: %s", recorder.Body.String())
}
}
func TestDummyPasswordHashRemainsValid(t *testing.T) {
if !(&customermodel.Account{Password: dummyPasswordHash}).MatchPassword("sendico-login-dummy-password") {
t.Fatal("dummy password hash is not a valid bcrypt hash")
}
if (&customermodel.Account{Password: dummyPasswordHash}).MatchPassword("different") {
t.Fatal("dummy password hash unexpectedly matched another password")
}
}
@@ -0,0 +1,269 @@
package public
import (
"context"
"errors"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.sendico.io/tech/sxchnge/product/auth/config"
"git.sendico.io/tech/sxchnge/product/auth/request"
"git.sendico.io/tech/sxchnge/shared/errors"
"git.sendico.io/tech/sxchnge/shared/service"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"
)
func TestLoginRejectsUnknownClientID(t *testing.T) {
testRejectsUnknownClientID(t, "/login", `{
"login":{"login":"user@example.com","password":"correct horse battery staple"},
"clientId":"missing-client",
"deviceId":"device-1"
}`, 0, func(router *PublicRouter, req *http.Request) http.HandlerFunc {
return router.login(req)
})
}
func TestAPILoginRejectsUnknownClientID(t *testing.T) {
testRejectsUnknownClientID(t, "/login/api", `{
"login":{"login":"user@example.com","password":"correct horse battery staple"},
"clientId":"missing-client",
"deviceId":"device-1",
"clientSecret":"secret"
}`, 1, func(router *PublicRouter, req *http.Request) http.HandlerFunc {
return router.apiLogin(req)
})
}
func TestLoginAuthenticatesAgainstInjectedAccountStorage(t *testing.T) {
account := testActiveAccount(t)
unusedDB := &testAccountDB{err: merrors.ErrNoData}
activeDB := &testAccountDB{result: account}
router := &PublicRouter{
logger: zap.NewNop(),
db: activeDB,
service: mservice.Accounts,
}
got, failed, h := router.authenticateAccount(context.Background(), &srequest.Login{
LoginData: customermodel.LoginData{
UserDataBase: customermodel.UserDataBase{
Login: "user@example.com",
},
Password: "correct horse battery staple",
},
})
if h != nil {
t.Fatal("expected login authentication to succeed against injected account store")
}
if failed {
t.Fatal("successful login was classified as a credential failure")
}
if got == nil || got.Login != account.Login {
t.Fatalf("expected account %q, got %#v", account.Login, got)
}
if activeDB.getByEmailCalls != 1 {
t.Fatalf("expected one active account store lookup, got %d", activeDB.getByEmailCalls)
}
if unusedDB.getByEmailCalls != 0 {
t.Fatalf("expected no unused account store lookups, got %d", unusedDB.getByEmailCalls)
}
}
func testRejectsUnknownClientID(
t *testing.T,
path string,
body string,
wantLookups int,
handler func(*PublicRouter, *http.Request) http.HandlerFunc,
) {
t.Helper()
account := testActiveAccount(t)
accountDB := &testAccountDB{result: account}
router := &PublicRouter{
logger: zap.NewNop(),
db: accountDB,
rtdb: &testRefreshTokenDB{clientErr: merrors.ErrNoData},
service: mservice.Accounts,
}
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, path, strings.NewReader(body))
rec := httptest.NewRecorder()
handler(router, req)(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected status %d, got %d", http.StatusUnauthorized, rec.Code)
}
if accountDB.getByEmailCalls != wantLookups {
t.Fatalf("expected %d account lookups, got %d", wantLookups, accountDB.getByEmailCalls)
}
resp := decodeErrorResponse(t, rec.Body.Bytes())
if resp.Data.Details != "unknown client id" {
t.Fatalf("expected unknown client id message, got %q", resp.Data.Details)
}
}
func TestLoginRejectsPendingVerificationAccount(t *testing.T) {
account := testAccountWithStatus(t, customermodel.AccountPendingVerification)
router := &PublicRouter{
logger: zap.NewNop(),
db: &testAccountDB{result: account},
service: mservice.Accounts,
}
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/login", strings.NewReader(`{
"login":{"login":"user@example.com","password":"correct horse battery staple"}
}`))
rec := httptest.NewRecorder()
router.login(req)(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("expected status %d, got %d", http.StatusForbidden, rec.Code)
}
resp := decodeErrorResponse(t, rec.Body.Bytes())
if resp.Data.Details != "Account verification required" {
t.Fatalf("expected account verification required message, got %q", resp.Data.Details)
}
}
func TestLoginRejectsBlockedAccount(t *testing.T) {
account := testAccountWithStatus(t, customermodel.AccountBlocked)
router := &PublicRouter{
logger: zap.NewNop(),
db: &testAccountDB{result: account},
service: mservice.Accounts,
}
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/login", strings.NewReader(`{
"login":{"login":"user@example.com","password":"correct horse battery staple"}
}`))
rec := httptest.NewRecorder()
router.login(req)(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("expected status %d, got %d", http.StatusForbidden, rec.Code)
}
resp := decodeErrorResponse(t, rec.Body.Bytes())
if resp.Data.Details != "Account verification required" {
t.Fatalf("expected account verification required message, got %q", resp.Data.Details)
}
}
func TestAPILoginAllowsLoginAgainAfterRevokeSameSession(t *testing.T) {
account := testActiveAccount(t)
clientID := "api-client"
deviceID := "device-1"
rtdb := &testRefreshTokenDB{
client: &sessionmodel.Client{
ClientID: clientID,
ClientSecret: "secret",
GrantTypes: []string{"password"},
TokenEndpointAuthMethod: "client_secret_post",
AccountRef: account.GetID(),
},
}
var cfg middleware.TokenConfig
cfg.Length = 16
cfg.Expiration.Account = 1
cfg.Expiration.Refresh = 24
signature := middleware.Signature{
Algorithm: "HS256",
PrivateKey: []byte("test-secret"),
}
router := NewRouter(
zap.NewNop(),
"/",
&testAccountDB{result: account},
nil,
rtdb,
nil,
chi.NewRouter(),
&cfg,
&signature,
middleware.LoginRateLimits{},
)
body := `{
"login":{"login":"user@example.com","password":"correct horse battery staple"},
"clientId":"api-client",
"deviceId":"device-1",
"clientSecret":"secret"
}`
firstReq := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/login/api", strings.NewReader(body))
firstRec := httptest.NewRecorder()
router.apiLogin(firstReq)(firstRec, firstReq)
if firstRec.Code != http.StatusOK {
t.Fatalf("expected first login status %d, got %d", http.StatusOK, firstRec.Code)
}
firstResp := decodeLoginResponse(t, firstRec.Body.Bytes())
if firstResp.Data.RefreshToken.Token == "" {
t.Fatal("expected first login to return refresh token")
}
err := rtdb.Revoke(context.Background(), *account.GetID(), &sessionmodel.SessionIdentifier{
ClientID: clientID,
DeviceID: deviceID,
})
if err != nil {
t.Fatalf("failed to revoke refresh token: %v", err)
}
secondReq := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/login/api", strings.NewReader(body))
secondRec := httptest.NewRecorder()
router.apiLogin(secondReq)(secondRec, secondReq)
if secondRec.Code != http.StatusOK {
t.Fatalf("expected second login status %d, got %d", http.StatusOK, secondRec.Code)
}
secondResp := decodeLoginResponse(t, secondRec.Body.Bytes())
if secondResp.Data.RefreshToken.Token == "" {
t.Fatal("expected second login to return refresh token")
}
if secondResp.Data.RefreshToken.Token == firstResp.Data.RefreshToken.Token {
t.Fatal("expected second login to issue a different refresh token after revocation")
}
_, err = rtdb.GetByCRT(context.Background(), &sessionmodel.ClientRefreshToken{
SessionIdentifier: sessionmodel.SessionIdentifier{
ClientID: clientID,
DeviceID: deviceID,
},
RefreshToken: firstResp.Data.RefreshToken.Token,
})
if !errors.Is(err, merrors.ErrNoData) {
t.Fatalf("expected old refresh token to be unusable, got %v", err)
}
_, err = rtdb.GetByCRT(context.Background(), &sessionmodel.ClientRefreshToken{
SessionIdentifier: sessionmodel.SessionIdentifier{
ClientID: clientID,
DeviceID: deviceID,
},
RefreshToken: secondResp.Data.RefreshToken.Token,
})
if err != nil {
t.Fatalf("expected new refresh token to be active, got %v", err)
}
if got := rtdb.tokenCountForSession(*account.GetID(), clientID, deviceID); got != 2 {
t.Fatalf("expected 2 refresh token records for session, got %d", got)
}
if got := rtdb.activeTokenCountForSession(*account.GetID(), clientID, deviceID); got != 1 {
t.Fatalf("expected 1 active refresh token for session, got %d", got)
}
}
@@ -0,0 +1,285 @@
package public
import (
"context"
"encoding/json"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"sync"
"testing"
"git.sendico.io/tech/sxchnge/shared/database/repository/builder"
"git.sendico.io/tech/sxchnge/shared/errors"
"go.mongodb.org/mongo-driver/v2/bson"
)
type testErrorResponse struct {
Data struct {
Details string `json:"details"`
} `json:"data"`
}
type testLoginResponse struct {
Data struct {
AccessToken struct {
Token string `json:"token"`
} `json:"accessToken"`
RefreshToken struct {
Token string `json:"token"`
} `json:"refreshToken"`
} `json:"data"`
}
func decodeErrorResponse(t *testing.T, body []byte) testErrorResponse {
t.Helper()
var resp testErrorResponse
if err := json.Unmarshal(body, &resp); err != nil {
t.Fatalf("failed to decode response body: %v", err)
}
return resp
}
func decodeLoginResponse(t *testing.T, body []byte) testLoginResponse {
t.Helper()
var resp testLoginResponse
if err := json.Unmarshal(body, &resp); err != nil {
t.Fatalf("failed to decode login response body: %v", err)
}
return resp
}
func testActiveAccount(t *testing.T) *customermodel.Account {
t.Helper()
return testAccountWithStatus(t, customermodel.AccountActive)
}
func testAccountWithStatus(t *testing.T, status customermodel.AccountStatus) *customermodel.Account {
t.Helper()
account := &customermodel.Account{
AccountPublic: customermodel.AccountPublic{
UserDataBase: customermodel.UserDataBase{
Login: "user@example.com",
},
},
Password: "correct horse battery staple",
Status: status,
}
account.SetID(bson.NewObjectID())
if err := account.HashPassword(); err != nil {
t.Fatalf("failed to hash password: %v", err)
}
return account
}
type testAccountDB struct {
mu sync.Mutex
result *customermodel.Account
err error
getByEmailCalls int
}
func (db *testAccountDB) GetByEmail(ctx context.Context, email string) (*customermodel.Account, error) {
db.mu.Lock()
defer db.mu.Unlock()
db.getByEmailCalls++
return db.result, db.err
}
func (db *testAccountDB) Create(ctx context.Context, object *customermodel.Account) error {
return merrors.NotImplemented("stub")
}
func (db *testAccountDB) InsertMany(ctx context.Context, objects []*customermodel.Account) error {
return merrors.NotImplemented("stub")
}
func (db *testAccountDB) Get(ctx context.Context, objectRef bson.ObjectID, result *customermodel.Account) error {
if db.err != nil {
return db.err
}
if db.result == nil || db.result.GetID() == nil || *db.result.GetID() != objectRef {
return merrors.ErrNoData
}
*result = *db.result
return nil
}
func (db *testAccountDB) Update(ctx context.Context, object *customermodel.Account) error {
return merrors.NotImplemented("stub")
}
func (db *testAccountDB) Patch(ctx context.Context, objectRef bson.ObjectID, patch builder.Patch) error {
return merrors.NotImplemented("stub")
}
func (db *testAccountDB) Delete(ctx context.Context, objectRef bson.ObjectID) error {
return merrors.NotImplemented("stub")
}
func (db *testAccountDB) DeleteMany(ctx context.Context, query builder.Query) error {
return merrors.NotImplemented("stub")
}
func (db *testAccountDB) DeleteCascade(ctx context.Context, objectRef bson.ObjectID) error {
return merrors.NotImplemented("stub")
}
func (db *testAccountDB) FindOne(ctx context.Context, query builder.Query, result *customermodel.Account) error {
return merrors.NotImplemented("stub")
}
type testRefreshTokenDB struct {
client *sessionmodel.Client
clientErr error
tokens []*sessionmodel.RefreshToken
}
func (db *testRefreshTokenDB) GetClient(ctx context.Context, clientID string) (*sessionmodel.Client, error) {
return db.client, db.clientErr
}
func (db *testRefreshTokenDB) Revoke(ctx context.Context, accountRef bson.ObjectID, session *sessionmodel.SessionIdentifier) error {
for _, token := range db.tokens {
if token.AccountRef == nil || *token.AccountRef != accountRef {
continue
}
if token.ClientID == session.ClientID && token.DeviceID == session.DeviceID && !token.IsRevoked {
token.IsRevoked = true
return nil
}
}
return nil
}
func (db *testRefreshTokenDB) RevokeToken(ctx context.Context, token *sessionmodel.ClientRefreshToken) (bool, error) {
for _, stored := range db.tokens {
if stored.ClientID == token.ClientID && stored.DeviceID == token.DeviceID && stored.RefreshToken == token.RefreshToken && !stored.IsRevoked {
stored.IsRevoked = true
return true, nil
}
}
return false, nil
}
func (db *testRefreshTokenDB) RevokeAll(ctx context.Context, accountRef bson.ObjectID, deviceID string) error {
return merrors.NotImplemented("stub")
}
func (db *testRefreshTokenDB) GetSession(ctx context.Context, accountRef bson.ObjectID, session *sessionmodel.SessionIdentifier) (*sessionmodel.RefreshToken, error) {
for _, token := range db.tokens {
if token.AccountRef != nil && *token.AccountRef == accountRef && token.ClientID == session.ClientID && token.DeviceID == session.DeviceID && !token.IsRevoked {
return cloneRefreshToken(token), nil
}
}
return nil, merrors.ErrNoData
}
func (db *testRefreshTokenDB) GetByCRT(ctx context.Context, t *sessionmodel.ClientRefreshToken) (*sessionmodel.RefreshToken, error) {
for _, token := range db.tokens {
if token.ClientID == t.ClientID && token.DeviceID == t.DeviceID && token.RefreshToken == t.RefreshToken {
if token.IsRevoked {
return nil, merrors.ErrNoData
}
return cloneRefreshToken(token), nil
}
}
return nil, merrors.ErrNoData
}
func (db *testRefreshTokenDB) Create(ctx context.Context, object *sessionmodel.RefreshToken) error {
for _, token := range db.tokens {
if token.AccountRef == nil || object.AccountRef == nil {
continue
}
if *token.AccountRef == *object.AccountRef && token.ClientID == object.ClientID && token.DeviceID == object.DeviceID && !token.IsRevoked {
token.RefreshToken = object.RefreshToken
token.SessionVersion = object.SessionVersion
token.ExpiresAt = object.ExpiresAt
token.UserAgent = object.UserAgent
token.IPAddress = object.IPAddress
token.LastUsedAt = object.LastUsedAt
token.IsRevoked = object.IsRevoked
if token.GetID() == nil || token.GetID().IsZero() {
token.SetID(bson.NewObjectID())
}
object.SetID(*token.GetID())
return nil
}
}
clone := cloneRefreshToken(object)
if clone.GetID() == nil || clone.GetID().IsZero() {
clone.SetID(bson.NewObjectID())
}
object.SetID(*clone.GetID())
db.tokens = append(db.tokens, clone)
return nil
}
func (db *testRefreshTokenDB) InsertMany(ctx context.Context, objects []*sessionmodel.RefreshToken) error {
return merrors.NotImplemented("stub")
}
func (db *testRefreshTokenDB) Get(ctx context.Context, objectRef bson.ObjectID, result *sessionmodel.RefreshToken) error {
return merrors.NotImplemented("stub")
}
func (db *testRefreshTokenDB) Update(ctx context.Context, object *sessionmodel.RefreshToken) error {
return merrors.NotImplemented("stub")
}
func (db *testRefreshTokenDB) Patch(ctx context.Context, objectRef bson.ObjectID, patch builder.Patch) error {
return merrors.NotImplemented("stub")
}
func (db *testRefreshTokenDB) Delete(ctx context.Context, objectRef bson.ObjectID) error {
return merrors.NotImplemented("stub")
}
func (db *testRefreshTokenDB) DeleteMany(ctx context.Context, query builder.Query) error {
return merrors.NotImplemented("stub")
}
func (db *testRefreshTokenDB) DeleteCascade(ctx context.Context, objectRef bson.ObjectID) error {
return merrors.NotImplemented("stub")
}
func (db *testRefreshTokenDB) FindOne(ctx context.Context, query builder.Query, result *sessionmodel.RefreshToken) error {
return merrors.NotImplemented("stub")
}
func (db *testRefreshTokenDB) tokenCountForSession(accountRef bson.ObjectID, clientID, deviceID string) int {
count := 0
for _, token := range db.tokens {
if token.AccountRef != nil && *token.AccountRef == accountRef && token.ClientID == clientID && token.DeviceID == deviceID {
count++
}
}
return count
}
func (db *testRefreshTokenDB) activeTokenCountForSession(accountRef bson.ObjectID, clientID, deviceID string) int {
count := 0
for _, token := range db.tokens {
if token.AccountRef != nil && *token.AccountRef == accountRef && token.ClientID == clientID && token.DeviceID == deviceID && !token.IsRevoked {
count++
}
}
return count
}
func cloneRefreshToken(token *sessionmodel.RefreshToken) *sessionmodel.RefreshToken {
if token == nil {
return nil
}
cloned := *token
if token.AccountRef != nil {
accountRef := *token.AccountRef
cloned.AccountRef = &accountRef
}
return &cloned
}
@@ -0,0 +1,55 @@
package public
import (
"encoding/json"
"net/http"
"git.sendico.io/tech/sxchnge/product/auth/request"
"git.sendico.io/tech/sxchnge/product/sessions/browser"
"git.sendico.io/tech/sxchnge/product/sessions/metrics"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/service"
"go.uber.org/zap"
)
func (pr *PublicRouter) logout(r *http.Request) http.HandlerFunc {
respond := func(handler http.HandlerFunc, clearCookie bool) http.HandlerFunc {
if !clearCookie || !browser.UsesCookie(r) {
return handler
}
return func(w http.ResponseWriter, request *http.Request) {
browser.ClearRefreshCookie(w, request)
handler.ServeHTTP(w, request)
}
}
var req srequest.AccessTokenRefresh
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
pr.logger.Info("Rejected malformed logout request", zap.Error(err))
return respond(response.BadPayload(pr.logger, mservice.RefreshTokens, err), false)
}
credential, err := browser.RefreshCredential(r, req.RefreshToken)
if err != nil {
sessionmetrics.Observe(sessionmetrics.CurrentLogout, sessionmetrics.AlreadyInactive)
return respond(response.Success(pr.logger), true)
}
req.RefreshToken = credential
if req.ClientID == "" || req.DeviceID == "" || req.RefreshToken == "" {
sessionmetrics.Observe(sessionmetrics.CurrentLogout, sessionmetrics.MissingIdentity)
return respond(response.BadRequest(pr.logger, pr.service, "missing_session", "refresh token and session identifier are required"), false)
}
revoked, err := pr.rtdb.RevokeToken(r.Context(), &req)
if err != nil {
sessionmetrics.Observe(sessionmetrics.CurrentLogout, sessionmetrics.StorageError)
pr.logger.Warn("Failed to revoke current session", zap.Error(err),
zap.String("client_id", req.ClientID), zap.String("device_id", req.DeviceID))
return respond(response.Internal(pr.logger, pr.service, err), false)
}
if !revoked {
sessionmetrics.Observe(sessionmetrics.CurrentLogout, sessionmetrics.AlreadyInactive)
return respond(response.Success(pr.logger), true)
}
sessionmetrics.Observe(sessionmetrics.CurrentLogout, sessionmetrics.Succeeded)
pr.logger.Info("Current session revoked", zap.String("client_id", req.ClientID), zap.String("device_id", req.DeviceID))
return respond(response.Success(pr.logger), true)
}
@@ -0,0 +1,204 @@
package public
import (
"context"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"git.sendico.io/tech/sxchnge/product/sessions/browser"
"git.sendico.io/tech/sxchnge/product/sessions/store"
"git.sendico.io/tech/sxchnge/shared/errors"
"git.sendico.io/tech/sxchnge/shared/service"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/v2/bson"
"go.uber.org/zap"
)
type logoutDB struct {
refreshtokens.DB
mu sync.Mutex
tokens map[string]*sessionmodel.RefreshToken
lookupErr error
revokeErr error
}
func (db *logoutDB) RevokeToken(_ context.Context, request *sessionmodel.ClientRefreshToken) (bool, error) {
db.mu.Lock()
defer db.mu.Unlock()
if db.lookupErr != nil {
return false, db.lookupErr
}
token := db.tokens[request.DeviceID]
if token == nil || token.IsRevoked || token.RefreshToken != request.RefreshToken {
return false, nil
}
if db.revokeErr != nil {
return false, db.revokeErr
}
token.IsRevoked = true
return true, nil
}
func newLogoutToken(accountRef bson.ObjectID, deviceID, value string) *sessionmodel.RefreshToken {
return &sessionmodel.RefreshToken{
ClientRefreshToken: sessionmodel.ClientRefreshToken{
SessionIdentifier: sessionmodel.SessionIdentifier{ClientID: "web", DeviceID: deviceID, SessionVersion: "version-" + deviceID},
RefreshToken: value,
},
AccountRef: &accountRef,
ExpiresAt: time.Now().Add(time.Hour),
}
}
func executeLogout(router *PublicRouter, deviceID, refreshToken string) int {
body := `{"clientId":"web","deviceId":"` + deviceID + `","token":"` + refreshToken + `"}`
request := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/accounts/logout", strings.NewReader(body))
response := httptest.NewRecorder()
router.logout(request)(response, request)
return response.Code
}
func TestLogoutRevokesOnlyCurrentSessionAndIsIdempotent(t *testing.T) {
accountRef := bson.NewObjectID()
db := &logoutDB{tokens: map[string]*sessionmodel.RefreshToken{
"device-a": newLogoutToken(accountRef, "device-a", "refresh-a"),
"device-b": newLogoutToken(accountRef, "device-b", "refresh-b"),
}}
router := &PublicRouter{logger: zap.NewNop(), rtdb: db, service: mservice.Accounts}
if status := executeLogout(router, "device-a", "refresh-a"); status != http.StatusOK {
t.Fatalf("first logout status = %d", status)
}
if status := executeLogout(router, "device-a", "refresh-a"); status != http.StatusOK {
t.Fatalf("repeated logout status = %d", status)
}
if !db.tokens["device-a"].IsRevoked {
t.Fatal("current device session was not revoked")
}
if db.tokens["device-b"].IsRevoked {
t.Fatal("another device session was revoked")
}
}
func TestConcurrentLogoutIsIdempotent(t *testing.T) {
accountRef := bson.NewObjectID()
db := &logoutDB{tokens: map[string]*sessionmodel.RefreshToken{
"device-a": newLogoutToken(accountRef, "device-a", "refresh-a"),
}}
router := &PublicRouter{logger: zap.NewNop(), rtdb: db, service: mservice.Accounts}
statuses := make(chan int, 8)
var workers sync.WaitGroup
for range 8 {
workers.Add(1)
go func() {
defer workers.Done()
statuses <- executeLogout(router, "device-a", "refresh-a")
}()
}
workers.Wait()
close(statuses)
for status := range statuses {
if status != http.StatusOK {
t.Fatalf("concurrent logout status = %d", status)
}
}
}
func TestDelayedLogoutDoesNotRevokeReplacementSession(t *testing.T) {
accountRef := bson.NewObjectID()
db := &logoutDB{tokens: map[string]*sessionmodel.RefreshToken{
"device-a": newLogoutToken(accountRef, "device-a", "new-refresh"),
}}
router := &PublicRouter{logger: zap.NewNop(), rtdb: db, service: mservice.Accounts}
if status := executeLogout(router, "device-a", "old-refresh"); status != http.StatusOK {
t.Fatalf("delayed logout status = %d", status)
}
if db.tokens["device-a"].IsRevoked {
t.Fatal("replacement session was revoked by a stale logout request")
}
}
func TestLogoutAcceptsAnAlreadyExpiredSession(t *testing.T) {
accountRef := bson.NewObjectID()
expired := newLogoutToken(accountRef, "device-a", "expired-refresh")
expired.ExpiresAt = time.Now().Add(-time.Hour)
db := &logoutDB{tokens: map[string]*sessionmodel.RefreshToken{"device-a": expired}}
router := &PublicRouter{logger: zap.NewNop(), rtdb: db, service: mservice.Accounts}
if status := executeLogout(router, "device-a", "expired-refresh"); status != http.StatusOK {
t.Fatalf("expired logout status = %d", status)
}
if !expired.IsRevoked {
t.Fatal("expired session was not marked revoked before cleanup")
}
}
func TestLogoutFailsClosedWhenSessionStoreIsUnavailable(t *testing.T) {
db := &logoutDB{lookupErr: merrors.Internal("database unavailable")}
router := &PublicRouter{logger: zap.NewNop(), rtdb: db, service: mservice.Accounts}
if status := executeLogout(router, "device-a", "refresh-a"); status != http.StatusInternalServerError {
t.Fatalf("logout status = %d, want %d", status, http.StatusInternalServerError)
}
}
func TestBrowserLogoutUsesCookieCredentialAndClearsIt(t *testing.T) {
accountRef := bson.NewObjectID()
token := newLogoutToken(accountRef, "device-a", "cookie-refresh")
db := &logoutDB{tokens: map[string]*sessionmodel.RefreshToken{"device-a": token}}
router := &PublicRouter{logger: zap.NewNop(), rtdb: db, service: mservice.Accounts}
body := `{"clientId":"web","deviceId":"device-a","token":"body-must-be-ignored"}`
request := httptest.NewRequest(http.MethodPost, "https://app.sendico.io/api/v1/accounts/logout", strings.NewReader(body))
request.Header.Set(browser.TransportHeader, browser.TransportCookie)
request.AddCookie(&http.Cookie{Name: browser.RefreshCookie, Value: "cookie-refresh"})
response := httptest.NewRecorder()
router.logout(request)(response, request)
require.Equal(t, http.StatusOK, response.Code)
require.True(t, token.IsRevoked)
cookies := response.Result().Cookies()
require.Len(t, cookies, 1)
require.Equal(t, browser.RefreshCookie, cookies[0].Name)
require.Equal(t, -1, cookies[0].MaxAge)
require.Equal(t, "/api/v1/accounts", cookies[0].Path)
}
func TestBrowserLogoutWithoutCookieIsIdempotentAndClearsBrowserState(t *testing.T) {
db := &logoutDB{tokens: map[string]*sessionmodel.RefreshToken{}}
router := &PublicRouter{logger: zap.NewNop(), rtdb: db, service: mservice.Accounts}
body := `{"clientId":"web","deviceId":"device-a","token":"body-must-be-ignored"}`
request := httptest.NewRequest(http.MethodPost, "https://app.sendico.io/api/v1/accounts/logout", strings.NewReader(body))
request.Header.Set(browser.TransportHeader, browser.TransportCookie)
response := httptest.NewRecorder()
router.logout(request)(response, request)
require.Equal(t, http.StatusOK, response.Code)
require.Contains(t, response.Header().Get("Set-Cookie"), browser.RefreshCookie+"=")
require.Contains(t, response.Header().Get("Set-Cookie"), "Max-Age=0")
}
func TestBrowserLogoutKeepsCookieWhenRevocationFails(t *testing.T) {
db := &logoutDB{
tokens: map[string]*sessionmodel.RefreshToken{},
lookupErr: merrors.Internal("database unavailable"),
}
router := &PublicRouter{logger: zap.NewNop(), rtdb: db, service: mservice.Accounts}
body := `{"clientId":"web","deviceId":"device-a"}`
request := httptest.NewRequest(http.MethodPost, "https://app.sendico.io/api/v1/accounts/logout", strings.NewReader(body))
request.Header.Set(browser.TransportHeader, browser.TransportCookie)
request.AddCookie(&http.Cookie{Name: browser.RefreshCookie, Value: "cookie-refresh"})
response := httptest.NewRecorder()
router.logout(request)(response, request)
require.Equal(t, http.StatusInternalServerError, response.Code)
require.Empty(t, response.Header().Get("Set-Cookie"), "client must retain the cookie so logout can retry revocation")
}
@@ -0,0 +1,53 @@
package public
import (
"encoding/json"
"errors"
"net/http"
"time"
"git.sendico.io/tech/sxchnge/product/auth/request"
"git.sendico.io/tech/sxchnge/product/auth/response"
"git.sendico.io/tech/sxchnge/product/sessions/browser"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/service"
"go.uber.org/zap"
)
func (pr *PublicRouter) refreshAccessToken(r *http.Request) http.HandlerFunc {
pr.logger.Debug("Processing access token refresh request")
var req srequest.AccessTokenRefresh
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
pr.logger.Info("Failed to decode token rotation request", zap.Error(err))
return response.BadPayload(pr.logger, mservice.RefreshTokens, err)
}
account, token, refreshToken, err := pr.validateRefreshToken(r.Context(), r, &req)
if err != nil {
if errors.Is(err, errClientIPNotAllowed) {
return response.Forbidden(pr.logger, pr.service, "ip_not_allowed", "request ip is not allowed for this client")
}
if isExpectedRefreshValidationError(err) {
pr.logger.Debug("Access token refresh rejected", zap.Error(err))
return pr.rejectRefresh(r, err)
}
pr.logger.Warn("Failed to process access token refreshment request", zap.Error(err))
return response.Auto(pr.logger, pr.service, err)
}
if browser.UsesCookie(r) && refreshToken.ExpiresAt.Before(time.Now().Add(7*24*time.Hour)) {
return pr.refreshAndRespondLogin(r.Context(), r, &refreshToken.SessionIdentifier, account)
}
return sresponse.Account(pr.logger, account, token)
}
func (pr *PublicRouter) rejectRefresh(r *http.Request, err error) http.HandlerFunc {
handler := response.Auto(pr.logger, pr.service, err)
if !browser.UsesCookie(r) {
return handler
}
return func(w http.ResponseWriter, request *http.Request) {
browser.ClearRefreshCookie(w, request)
handler.ServeHTTP(w, request)
}
}
@@ -0,0 +1,152 @@
package public
import (
"context"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"git.sendico.io/tech/sxchnge/product/auth/config"
"git.sendico.io/tech/sxchnge/product/sessions/browser"
"github.com/go-chi/chi/v5"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
)
func newBrowserRefreshRouter(t *testing.T, expiresAt time.Time) (*PublicRouter, *testRefreshTokenDB) {
t.Helper()
account := testActiveAccount(t)
clientID := "web"
deviceID := "browser-1"
rtdb := &testRefreshTokenDB{
client: &sessionmodel.Client{ClientID: clientID},
tokens: []*sessionmodel.RefreshToken{
{
ClientRefreshToken: sessionmodel.ClientRefreshToken{
SessionIdentifier: sessionmodel.SessionIdentifier{
ClientID: clientID,
DeviceID: deviceID,
SessionVersion: "version-1",
},
RefreshToken: "cookie-refresh",
},
AccountRef: account.GetID(),
ExpiresAt: expiresAt,
},
},
}
config := middleware.TokenConfig{
Expiration: middleware.TokenExpiration{Account: 1, Refresh: 720},
Length: 32,
}
signature := middleware.Signature{
Algorithm: "HS256",
PrivateKey: []byte("browser-refresh-test-secret"),
}
return NewRouter(
zap.NewNop(),
"/api/v1",
&testAccountDB{result: account},
nil,
rtdb,
nil,
chi.NewRouter(),
&config,
&signature,
middleware.LoginRateLimits{},
), rtdb
}
func executeBrowserRefresh(t *testing.T, router *PublicRouter) *httptest.ResponseRecorder {
t.Helper()
body := `{"clientId":"web","deviceId":"browser-1","token":"body-must-be-ignored"}`
request := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "https://app.sendico.io/api/v1/accounts/refresh", strings.NewReader(body))
request.Header.Set(browser.TransportHeader, browser.TransportCookie)
request.AddCookie(&http.Cookie{Name: browser.RefreshCookie, Value: "cookie-refresh"})
response := httptest.NewRecorder()
router.refreshAccessToken(request)(response, request)
return response
}
func executeNativeRefresh(t *testing.T, router *PublicRouter, token string) *httptest.ResponseRecorder {
t.Helper()
body := `{"clientId":"web","deviceId":"browser-1","token":"` + token + `"}`
request := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "https://app.sendico.io/api/v1/accounts/refresh", strings.NewReader(body))
response := httptest.NewRecorder()
router.refreshAccessToken(request)(response, request)
return response
}
func TestBrowserRefreshRestoresAccessWithoutExposingRefreshCredential(t *testing.T) {
router, _ := newBrowserRefreshRouter(t, time.Now().Add(30*24*time.Hour))
response := executeBrowserRefresh(t, router)
require.Equal(t, http.StatusOK, response.Code)
require.NotContains(t, response.Body.String(), "cookie-refresh")
require.NotEmpty(t, decodeLoginResponse(t, response.Body.Bytes()).Data.AccessToken.Token)
require.Empty(t, response.Header().Get("Set-Cookie"))
}
func TestBrowserRefreshRotatesExpiringCookieServerSide(t *testing.T) {
t.Setenv("API_ENDPOINT", "/api/v1")
router, rtdb := newBrowserRefreshRouter(t, time.Now().Add(24*time.Hour))
response := executeBrowserRefresh(t, router)
require.Equal(t, http.StatusOK, response.Code)
require.NotContains(t, response.Body.String(), "cookie-refresh")
cookies := response.Result().Cookies()
require.Len(t, cookies, 1)
require.Equal(t, browser.RefreshCookie, cookies[0].Name)
require.NotEqual(t, "cookie-refresh", cookies[0].Value)
require.Empty(t, decodeLoginResponse(t, response.Body.Bytes()).Data.RefreshToken.Token)
require.Equal(t, cookies[0].Value, rtdb.tokens[0].RefreshToken)
}
func TestBrowserRefreshRejectsStaleCookieAndClearsIt(t *testing.T) {
t.Setenv("API_ENDPOINT", "/api/v1")
router, rtdb := newBrowserRefreshRouter(t, time.Now().Add(30*24*time.Hour))
rtdb.tokens = nil
response := executeBrowserRefresh(t, router)
require.Equal(t, http.StatusUnauthorized, response.Code)
require.Contains(t, response.Body.String(), `"error":"unauthorized"`)
require.NotContains(t, response.Body.String(), "cookie-refresh")
cookies := response.Result().Cookies()
require.Len(t, cookies, 1)
require.Equal(t, browser.RefreshCookie, cookies[0].Name)
require.Empty(t, cookies[0].Value)
require.Equal(t, -1, cookies[0].MaxAge)
require.True(t, cookies[0].HttpOnly)
require.True(t, cookies[0].Secure)
}
func TestNativeRefreshRejectsStaleTokenWithoutCookieMutation(t *testing.T) {
router, _ := newBrowserRefreshRouter(t, time.Now().Add(30*24*time.Hour))
response := executeNativeRefresh(t, router, "stale-refresh")
require.Equal(t, http.StatusUnauthorized, response.Code)
require.Contains(t, response.Body.String(), `"error":"unauthorized"`)
require.Empty(t, response.Header().Get("Set-Cookie"))
}
func TestRefreshRejectsInactiveCustomerAndClientMismatch(t *testing.T) {
for _, status := range []customermodel.AccountStatus{customermodel.AccountBlocked, customermodel.AccountPendingVerification} {
t.Run(string(status), func(t *testing.T) {
router, _ := newBrowserRefreshRouter(t, time.Now().Add(24*time.Hour))
router.db.(*testAccountDB).result.Status = status
require.Equal(t, http.StatusUnauthorized, executeBrowserRefresh(t, router).Code)
})
}
router, sessions := newBrowserRefreshRouter(t, time.Now().Add(24*time.Hour))
other := testActiveAccount(t)
sessions.client.AccountRef = &other.ID
require.Equal(t, http.StatusUnauthorized, executeBrowserRefresh(t, router).Code)
}
@@ -0,0 +1,49 @@
package public
import (
"context"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"net/http"
"git.sendico.io/tech/sxchnge/product/auth/response"
rtokens "git.sendico.io/tech/sxchnge/product/sessions/tokens"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/logging/fields"
"go.uber.org/zap"
)
func (pr *PublicRouter) refreshAndRespondLogin(
ctx context.Context,
r *http.Request,
session *sessionmodel.SessionIdentifier,
account *customermodel.Account,
) http.HandlerFunc {
refreshToken, err := rtokens.PrepareRefreshToken(
ctx,
r,
pr.rtdb,
pr.config.Length,
pr.config.Expiration.Refresh,
session,
account,
pr.logger,
)
if err != nil {
pr.logger.Warn("Failed to create refresh token", zap.Error(err), mzap.StorableRef(account),
zap.String("client_id", session.ClientID), zap.String("device_id", session.DeviceID))
return response.Internal(pr.logger, pr.service, err)
}
accessToken, err := pr.imp.CreateAccessTokenForSession(account, refreshToken.SessionIdentifier)
if err != nil {
pr.logger.Warn("Failed to generate access token", zap.Error(err), mzap.StorableRef(account),
zap.String("client_id", session.ClientID), zap.String("device_id", session.DeviceID))
return response.Internal(pr.logger, pr.service, err)
}
token := sresponse.TokenData{
Token: refreshToken.RefreshToken,
Expiration: refreshToken.ExpiresAt,
}
return sresponse.Login(pr.logger, account, &accessToken, &token)
}
@@ -0,0 +1,36 @@
package public
import (
"encoding/json"
"errors"
"net/http"
"git.sendico.io/tech/sxchnge/product/auth/request"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/service"
"go.uber.org/zap"
)
func (pr *PublicRouter) rotateRefreshToken(r *http.Request) http.HandlerFunc {
pr.logger.Debug("Processing token rotation request...")
var req srequest.TokenRefreshRotate
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
pr.logger.Info("Failed to decode token rotation request", zap.Error(err))
return response.BadPayload(pr.logger, mservice.RefreshTokens, err)
}
account, _, _, err := pr.validateRefreshToken(r.Context(), r, &req)
if err != nil {
if errors.Is(err, errClientIPNotAllowed) {
return response.Forbidden(pr.logger, pr.service, "ip_not_allowed", "request ip is not allowed for this client")
}
if isExpectedRefreshValidationError(err) {
pr.logger.Debug("Refresh token rotation rejected", zap.Error(err))
return pr.rejectRefresh(r, err)
}
pr.logger.Warn("Failed to validate refresh token", zap.Error(err))
return response.Auto(pr.logger, pr.service, err)
}
return pr.refreshAndRespondLogin(r.Context(), r, &req.SessionIdentifier, account)
}
@@ -0,0 +1,69 @@
package public
import (
"time"
"git.sendico.io/tech/sxchnge/product/auth/config"
re "git.sendico.io/tech/sxchnge/product/auth/http/endpoint"
"git.sendico.io/tech/sxchnge/product/auth/response"
"git.sendico.io/tech/sxchnge/product/customers/store"
"git.sendico.io/tech/sxchnge/product/sessions/store"
"git.sendico.io/tech/sxchnge/product/verification/store"
api "git.sendico.io/tech/sxchnge/shared/http"
"git.sendico.io/tech/sxchnge/shared/logging"
"git.sendico.io/tech/sxchnge/shared/ratelimit/store"
"git.sendico.io/tech/sxchnge/shared/service"
"github.com/go-chi/chi/v5"
)
type PublicRouter struct {
logger mlogger.Logger
db account.DB
imp *re.HttpEndpointRouter
rtdb refreshtokens.DB
config middleware.TokenConfig
signature middleware.Signature
service mservice.Type
attempts ratelimits.Store
limits middleware.LoginRateLimits
now func() time.Time
}
func (pr *PublicRouter) InstallHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.HandlerFunc) {
pr.imp.InstallHandler(service, endpoint, method, handler)
}
func NewRouter(
logger mlogger.Logger,
apiEndpoint string,
db account.DB,
vdb verification.DB,
rtdb refreshtokens.DB,
attempts ratelimits.Store,
router chi.Router,
config *middleware.TokenConfig,
signature *middleware.Signature,
limits middleware.LoginRateLimits,
) *PublicRouter {
l := logger.Named("public")
hr := PublicRouter{
logger: l,
db: db,
rtdb: rtdb,
config: *config,
signature: *signature,
imp: re.NewHttpEndpointRouter(l, apiEndpoint, router, config, signature),
service: mservice.Accounts,
attempts: attempts,
limits: limits,
now: time.Now,
}
hr.InstallHandler(hr.service, "/login", api.Post, hr.login)
hr.InstallHandler(hr.service, "/login/api", api.Post, hr.apiLogin)
hr.InstallHandler(hr.service, "/rotate", api.Post, hr.rotateRefreshToken)
hr.InstallHandler(hr.service, "/refresh", api.Post, hr.refreshAccessToken)
hr.InstallHandler(hr.service, "/logout", api.Post, hr.logout)
return &hr
}
@@ -0,0 +1,106 @@
package public
import (
"context"
"errors"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"net/http"
"time"
"git.sendico.io/tech/sxchnge/product/auth/request"
"git.sendico.io/tech/sxchnge/product/auth/response"
"git.sendico.io/tech/sxchnge/product/sessions/browser"
"git.sendico.io/tech/sxchnge/shared/errors"
"git.sendico.io/tech/sxchnge/shared/logging/fields"
"go.uber.org/zap"
)
var errClientIPNotAllowed = merrors.Define("client_ip_not_allowed")
func isExpectedRefreshValidationError(err error) bool {
return errors.Is(err, merrors.ErrUnauthorized)
}
func validateToken(token string, rt *sessionmodel.RefreshToken) string {
if rt.AccountRef == nil {
return "missing account reference"
}
if token != rt.RefreshToken {
return "tokens do not match"
}
if rt.ExpiresAt.Before(time.Now()) {
return "token expired"
}
if rt.IsRevoked {
return "token has been revoked"
}
return ""
}
func (pr *PublicRouter) validateRefreshToken(ctx context.Context, r *http.Request, req *srequest.TokenRefreshRotate) (*customermodel.Account, *sresponse.TokenData, *sessionmodel.RefreshToken, error) {
credential, err := browser.RefreshCredential(r, req.RefreshToken)
if err != nil {
return nil, nil, nil, err
}
req.RefreshToken = credential
client, err := pr.rtdb.GetClient(ctx, req.ClientID)
if errors.Is(err, merrors.ErrNoData) || client == nil {
pr.logger.Debug("Refresh token rejected: client not found", zap.String("client_id", req.ClientID))
return nil, nil, nil, merrors.Unauthorized("client not found")
}
if err != nil {
pr.logger.Warn("Failed to fetch client for refresh token validation", zap.Error(err), zap.String("client_id", req.ClientID))
return nil, nil, nil, err
}
if client.IsRevoked {
return nil, nil, nil, merrors.Unauthorized("client has been revoked")
}
if h := pr.validateClientIPPolicy(r, req.ClientID, client); h != nil {
return nil, nil, nil, errClientIPNotAllowed
}
rt, err := pr.rtdb.GetByCRT(ctx, req)
if errors.Is(err, merrors.ErrNoData) || errors.Is(err, merrors.ErrAccessDenied) {
pr.logger.Debug("Refresh session is inactive", zap.String("client_id", req.ClientID), zap.String("device_id", req.DeviceID))
return nil, nil, nil, merrors.Unauthorized("refresh session is inactive")
}
if err != nil {
return nil, nil, nil, err
}
if rt.SessionVersion == "" {
pr.logger.Debug("Refresh token rejected: legacy session requires reauthentication",
zap.String("client_id", req.ClientID), zap.String("device_id", req.DeviceID))
return nil, nil, nil, merrors.Unauthorized("session reauthentication required")
}
if reason := validateToken(req.RefreshToken, rt); len(reason) > 0 {
pr.logger.Debug("Token validation failed", zap.String("reason", reason))
return nil, nil, nil, merrors.Unauthorized(reason)
}
var account customermodel.Account
if err := pr.db.Get(ctx, *rt.AccountRef, &account); errors.Is(err, merrors.ErrNoData) {
pr.logger.Debug("User not found while rotating refresh token", zap.Error(err), mzap.AccRef(*rt.AccountRef))
return nil, nil, nil, merrors.Unauthorized("user not found")
} else if err != nil {
pr.logger.Warn("Failed to fetch user while validating refresh token", zap.Error(err), mzap.AccRef(*rt.AccountRef))
return nil, nil, nil, err
}
if !account.IsActive() || account.IsArchived() {
return nil, nil, nil, merrors.Unauthorized("customer is inactive")
}
if client.AccountRef != nil && *client.AccountRef != account.ID {
return nil, nil, nil, merrors.Unauthorized("client account mismatch")
}
accessToken, err := pr.imp.CreateAccessTokenForSession(&account, rt.SessionIdentifier)
if err != nil {
pr.logger.Warn("Failed to generate access token", zap.Error(err))
return nil, nil, nil, err
}
return &account, &accessToken, rt, nil
}
+16
View File
@@ -0,0 +1,16 @@
package router
import (
"git.sendico.io/tech/sxchnge/product/auth/response"
api "git.sendico.io/tech/sxchnge/shared/http"
"git.sendico.io/tech/sxchnge/shared/service"
)
type APIRouter interface {
InstallHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.HandlerFunc)
}
type ProtectedAPIRouter interface {
AccountHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.AccountHandlerFunc)
PendingAccountHandler(service mservice.Type, endpoint string, method api.HTTPMethod, handler sresponse.PendingAccountHandlerFunc)
}
+73
View File
@@ -0,0 +1,73 @@
package ipguard
import (
"net"
"net/http"
"strings"
)
// ClientIP resolves the real caller IP from the request.
// When the request arrives via the Caddy reverse proxy, the real client IP is
// forwarded in the X-Real-IP header (set via "header_up X-Real-IP {remote_host}"
// in the Caddyfile). RemoteAddr is used as a fallback for direct connections
// (local development, health checks, etc.).
func ClientIP(r *http.Request) net.IP {
if r == nil {
return nil
}
// Prefer X-Real-IP set by the trusted Caddy reverse proxy.
if xri := strings.TrimSpace(r.Header.Get("X-Real-IP")); xri != "" {
if ip := net.ParseIP(xri); ip != nil {
return ip
}
}
raw := strings.TrimSpace(r.RemoteAddr)
if raw == "" {
return nil
}
if ip := net.ParseIP(raw); ip != nil {
return ip
}
host, _, err := net.SplitHostPort(raw)
if err != nil {
return nil
}
return net.ParseIP(host)
}
func parseCIDRs(raw []string) ([]*net.IPNet, error) {
blocks := make([]*net.IPNet, 0, len(raw))
for _, item := range raw {
clean := strings.TrimSpace(item)
if clean == "" {
continue
}
_, block, err := net.ParseCIDR(clean)
if err != nil {
return nil, err
}
blocks = append(blocks, block)
}
return blocks, nil
}
// Allowed reports whether clientIP is allowed by configured CIDRs.
// Empty CIDR list means unrestricted access.
func Allowed(clientIP net.IP, cidrs []string) (bool, error) {
blocks, err := parseCIDRs(cidrs)
if err != nil {
return false, err
}
if len(blocks) == 0 {
return true, nil
}
if clientIP == nil {
return false, nil
}
for _, block := range blocks {
if block.Contains(clientIP) {
return true, nil
}
}
return false, nil
}
@@ -0,0 +1,116 @@
package ipguard
import (
"net"
"net/http"
"testing"
)
func TestClientIP(t *testing.T) {
t.Run("extracts host from remote addr", func(t *testing.T) {
req := &http.Request{RemoteAddr: "10.1.2.3:1234"}
ip := ClientIP(req)
if ip == nil || ip.String() != "10.1.2.3" {
t.Fatalf("unexpected ip: %v", ip)
}
})
t.Run("supports plain ip", func(t *testing.T) {
req := &http.Request{RemoteAddr: "8.8.8.8"}
ip := ClientIP(req)
if ip == nil || ip.String() != "8.8.8.8" {
t.Fatalf("unexpected ip: %v", ip)
}
})
t.Run("invalid remote addr", func(t *testing.T) {
req := &http.Request{RemoteAddr: "invalid"}
if ip := ClientIP(req); ip != nil {
t.Fatalf("expected nil ip, got %v", ip)
}
})
t.Run("prefers X-Real-IP over remote addr", func(t *testing.T) {
req := &http.Request{
RemoteAddr: "172.19.0.31:5000",
Header: http.Header{"X-Real-Ip": []string{"178.57.67.154"}},
}
ip := ClientIP(req)
if ip == nil || ip.String() != "178.57.67.154" {
t.Fatalf("expected real client ip, got %v", ip)
}
})
t.Run("falls back to remote addr when X-Real-IP absent", func(t *testing.T) {
req := &http.Request{RemoteAddr: "10.0.0.1:9000"}
ip := ClientIP(req)
if ip == nil || ip.String() != "10.0.0.1" {
t.Fatalf("expected remote addr ip, got %v", ip)
}
})
t.Run("falls back to remote addr when X-Real-IP invalid", func(t *testing.T) {
req := &http.Request{
RemoteAddr: "10.0.0.1:9000",
Header: http.Header{"X-Real-Ip": []string{"not-an-ip"}},
}
ip := ClientIP(req)
if ip == nil || ip.String() != "10.0.0.1" {
t.Fatalf("expected fallback to remote addr, got %v", ip)
}
})
}
func TestAllowed(t *testing.T) {
clientIP := net.ParseIP("10.1.2.3")
if clientIP == nil {
t.Fatal("failed to parse test ip")
}
t.Run("allows when cidr matches", func(t *testing.T) {
allowed, err := Allowed(clientIP, []string{"10.0.0.0/8"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !allowed {
t.Fatal("expected allowed")
}
})
t.Run("denies when cidr does not match", func(t *testing.T) {
allowed, err := Allowed(clientIP, []string{"192.168.0.0/16"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if allowed {
t.Fatal("expected denied")
}
})
t.Run("allows when cidr list is empty", func(t *testing.T) {
allowed, err := Allowed(clientIP, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !allowed {
t.Fatal("expected allowed")
}
})
t.Run("invalid cidr fails", func(t *testing.T) {
_, err := Allowed(clientIP, []string{"not-a-cidr"})
if err == nil {
t.Fatal("expected error")
}
})
t.Run("nil client ip denied when cidrs configured", func(t *testing.T) {
allowed, err := Allowed(nil, []string{"10.0.0.0/8"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if allowed {
t.Fatal("expected denied")
}
})
}
+141
View File
@@ -0,0 +1,141 @@
package model
import (
"fmt"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"time"
"git.sendico.io/tech/sxchnge/product/auth/config"
mduration "git.sendico.io/tech/sxchnge/shared/duration"
"git.sendico.io/tech/sxchnge/shared/errors"
"go.mongodb.org/mongo-driver/v2/bson"
)
type AccountToken struct {
AccountRef bson.ObjectID
Login string
Name string
Locale string
sessionmodel.SessionIdentifier
Expiration time.Time
Pending bool
}
func createAccountToken(a *customermodel.Account, expiration int, session sessionmodel.SessionIdentifier) AccountToken {
return AccountToken{
AccountRef: *a.GetID(),
Login: a.Login,
Name: a.Name,
Locale: a.Locale,
SessionIdentifier: session,
Expiration: time.Now().Add(mduration.Param2Duration(expiration, time.Hour)),
Pending: false,
}
}
func getTokenParam(claims middleware.MapClaims, param string) (string, error) {
id, ok := claims[param].(string)
if !ok {
return "", merrors.NoData(fmt.Sprintf("param '%s' not found", param))
}
return id, nil
}
const (
paramNameID = "id"
paramNameName = "name"
paramNameLocale = "locale"
paramNameLogin = "login"
paramNameClientID = "clientId"
paramNameDeviceID = "deviceId"
paramNameSessionVersion = "sessionVersion"
paramNameExpiration = "exp"
paramNamePending = "pending"
)
func Claims2Token(claims middleware.MapClaims) (*AccountToken, error) {
var at AccountToken
var err error
var account string
if account, err = getTokenParam(claims, paramNameID); err != nil {
return nil, err
}
if at.AccountRef, err = bson.ObjectIDFromHex(account); err != nil {
return nil, err
}
if at.Login, err = getTokenParam(claims, paramNameLogin); err != nil {
return nil, err
}
if at.Name, err = getTokenParam(claims, paramNameName); err != nil {
return nil, err
}
if at.Locale, err = getTokenParam(claims, paramNameLocale); err != nil {
return nil, err
}
if clientID, ok := claims[paramNameClientID]; ok {
if clientIDText, ok := clientID.(string); ok {
at.ClientID = clientIDText
}
}
if deviceID, ok := claims[paramNameDeviceID]; ok {
if deviceIDText, ok := deviceID.(string); ok {
at.DeviceID = deviceIDText
}
}
if version, ok := claims[paramNameSessionVersion]; ok {
if versionText, ok := version.(string); ok {
at.SessionVersion = versionText
}
}
if pending, ok := claims[paramNamePending]; ok {
if pbool, ok := pending.(bool); ok {
at.Pending = pbool
}
}
if expValue, ok := claims[paramNameExpiration]; ok {
switch exp := expValue.(type) {
case time.Time:
at.Expiration = exp
case float64:
at.Expiration = time.Unix(int64(exp), 0)
case int64:
at.Expiration = time.Unix(exp, 0)
default:
return nil, merrors.InvalidDataType(fmt.Sprintf("expiration param is of invalid type: %T", expValue))
}
} else {
return nil, merrors.InvalidDataType(fmt.Sprintf("expiration param is of invalid type: %T", expValue))
}
return &at, nil
}
func Account2ClaimsForSession(a *customermodel.Account, expiration int, session sessionmodel.SessionIdentifier) middleware.MapClaims {
t := createAccountToken(a, expiration, session)
return middleware.MapClaims{
paramNameID: t.AccountRef.Hex(),
paramNameLogin: t.Login,
paramNameName: t.Name,
paramNameLocale: t.Locale,
paramNameClientID: t.ClientID,
paramNameDeviceID: t.DeviceID,
paramNameSessionVersion: t.SessionVersion,
paramNameExpiration: t.Expiration.Unix(),
paramNamePending: t.Pending,
}
}
func PendingAccount2Claims(a *customermodel.Account, expirationMinutes int) middleware.MapClaims {
t := createAccountToken(a, expirationMinutes/60, sessionmodel.SessionIdentifier{})
t.Expiration = time.Now().Add(time.Duration(expirationMinutes) * time.Minute)
t.Pending = true
return middleware.MapClaims{
paramNameID: t.AccountRef.Hex(),
paramNameLogin: t.Login,
paramNameName: t.Name,
paramNameLocale: t.Locale,
paramNameExpiration: t.Expiration.Unix(),
paramNamePending: t.Pending,
}
}
+32
View File
@@ -0,0 +1,32 @@
package model
import (
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
"go.mongodb.org/mongo-driver/v2/bson"
"testing"
)
func TestAccountTokenPreservesSessionIdentity(t *testing.T) {
account := &customermodel.Account{}
account.SetID(bson.NewObjectID())
account.Login = "security@example.com"
account.Name = "Security"
account.Locale = "en"
session := sessionmodel.SessionIdentifier{
ClientID: "web",
DeviceID: "device-a",
SessionVersion: "session-version-a",
}
token, err := Claims2Token(Account2ClaimsForSession(account, 1, session))
if err != nil {
t.Fatalf("decode account claims: %v", err)
}
if token.SessionIdentifier != session {
t.Fatalf("session identity = %#v, want %#v", token.SessionIdentifier, session)
}
if token.Expiration.IsZero() {
t.Fatal("access token expiration is missing")
}
}
+11
View File
@@ -0,0 +1,11 @@
package srequest
import sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
import customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
type Login struct {
sessionmodel.SessionIdentifier `json:",inline"`
customermodel.LoginData `json:"login"`
ClientSecret string `json:"clientSecret,omitempty"`
}
+5
View File
@@ -0,0 +1,5 @@
package srequest
import sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
type AccessTokenRefresh = sessionmodel.ClientRefreshToken
+5
View File
@@ -0,0 +1,5 @@
package srequest
import sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
type TokenRefreshRotate = sessionmodel.ClientRefreshToken
@@ -0,0 +1,5 @@
package srequest
type Validatable interface {
Validate() error
}
@@ -0,0 +1,15 @@
package srequest
import sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
type VerificationCodeRequest struct {
Purpose string `json:"purpose"`
Target string `json:"target,omitempty"`
IdempotencyKey string `json:"idempotencyKey"`
}
type CodeVerificationRequest struct {
VerificationCodeRequest `json:",inline"`
Code string `json:"code"`
SessionIdentifier sessionmodel.SessionIdentifier `json:"sessionIdentifier"`
}
+40
View File
@@ -0,0 +1,40 @@
package sresponse
import (
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
"net/http"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/logging"
)
type AccountData struct {
ID string `json:"id"`
Name string `json:"name"`
LastName string `json:"lastName"`
Login string `json:"login"`
Locale string `json:"locale"`
AvatarURL *string `json:"avatarUrl,omitempty"`
}
type accountResponse struct {
authResponse `json:",inline"`
Account AccountData `json:"account"`
}
func NewAccountData(account *customermodel.Account) *AccountData {
return &AccountData{
ID: account.ID.Hex(), Name: account.Name, LastName: account.LastName,
Login: account.Login, Locale: account.Locale, AvatarURL: account.AvatarURL,
}
}
func Account(logger mlogger.Logger, account *customermodel.Account, accessToken *TokenData) http.HandlerFunc {
return response.Ok(
logger,
&accountResponse{
Account: *NewAccountData(account),
authResponse: authResponse{AccessToken: *accessToken},
},
)
}
@@ -0,0 +1,7 @@
package sresponse
type AuthResponse struct {
AccessToken TokenData `json:"accessToken"`
}
type authResponse = AuthResponse
+16
View File
@@ -0,0 +1,16 @@
package sresponse
import (
"net/http"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/logging"
)
type fileUploaded struct {
URL string `json:"url"`
}
func FileUploaded(logger mlogger.Logger, url string) http.HandlerFunc {
return response.Ok(logger, &fileUploaded{URL: url})
}
+35
View File
@@ -0,0 +1,35 @@
package sresponse
import (
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
"net/http"
"git.sendico.io/tech/sxchnge/product/sessions/browser"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/logging"
)
type loginResponse struct {
accountResponse
RefreshToken TokenData `json:"refreshToken"`
}
func Login(logger mlogger.Logger, account *customermodel.Account, accessToken, refreshToken *TokenData) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
responseRefreshToken := *refreshToken
if browser.UsesCookie(r) {
browser.SetRefreshCookie(w, r, refreshToken.Token, refreshToken.Expiration)
responseRefreshToken.Token = ""
}
response.Ok(
logger,
&loginResponse{
accountResponse: accountResponse{
Account: *NewAccountData(account),
authResponse: authResponse{AccessToken: *accessToken},
},
RefreshToken: responseRefreshToken,
},
).ServeHTTP(w, r)
}
}
@@ -0,0 +1,29 @@
package sresponse
import (
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
"net/http"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/logging"
)
type pendingLoginResponse struct {
Account accountResponse `json:"account"`
PendingToken TokenData `json:"pendingToken"`
Target string `json:"target"`
}
func LoginPending(logger mlogger.Logger, account *customermodel.Account, pendingToken *TokenData, target string) http.HandlerFunc {
return response.Accepted(
logger,
&pendingLoginResponse{
Account: accountResponse{
Account: *NewAccountData(account),
authResponse: authResponse{},
},
PendingToken: *pendingToken,
Target: target,
},
)
}
@@ -0,0 +1,58 @@
package sresponse
import (
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"git.sendico.io/tech/sxchnge/product/sessions/browser"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
)
func TestBrowserLoginMovesRefreshCredentialToHttpOnlyCookie(t *testing.T) {
refresh := &TokenData{Token: "refresh-secret", Expiration: time.Now().Add(time.Hour)}
access := &TokenData{Token: "access-secret", Expiration: time.Now().Add(time.Minute)}
req := httptest.NewRequest(http.MethodPost, "http://app.sendico.io/api/v1/accounts/login", nil)
req.Header.Set(browser.TransportHeader, browser.TransportCookie)
req.Header.Set("X-Forwarded-Proto", "https")
recorder := httptest.NewRecorder()
Login(zap.NewNop(), &customermodel.Account{}, access, refresh).ServeHTTP(recorder, req)
require.Equal(t, http.StatusOK, recorder.Code)
require.NotContains(t, recorder.Body.String(), refresh.Token)
require.Contains(t, recorder.Body.String(), access.Token)
setCookie := recorder.Header().Get("Set-Cookie")
require.True(t, strings.HasPrefix(setCookie, browser.RefreshCookie+"="))
require.Contains(t, setCookie, "HttpOnly")
require.Contains(t, setCookie, "Secure")
require.Contains(t, setCookie, "SameSite=Strict")
}
func TestNativeLoginKeepsRefreshCredentialInResponse(t *testing.T) {
refresh := &TokenData{Token: "native-refresh", Expiration: time.Now().Add(time.Hour)}
access := &TokenData{Token: "native-access", Expiration: time.Now().Add(time.Minute)}
req := httptest.NewRequest(http.MethodPost, "http://native.test/api/v1/accounts/login", nil)
recorder := httptest.NewRecorder()
Login(zap.NewNop(), &customermodel.Account{}, access, refresh).ServeHTTP(recorder, req)
require.Contains(t, recorder.Body.String(), refresh.Token)
require.Empty(t, recorder.Header().Get("Set-Cookie"))
}
func TestCustomerResponseExcludesStorageAndPlatformFields(t *testing.T) {
account := &customermodel.Account{Password: "private-password-hash", Status: customermodel.AccountActive}
account.Login = "customer@example.test"
account.Name = "Customer"
recorder := httptest.NewRecorder()
Account(zap.NewNop(), account, &TokenData{}).ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/accounts/me", nil))
require.Contains(t, recorder.Body.String(), "customer@example.test")
for _, field := range []string{"private-password-hash", "password", "status\":\"active", "organization", "role", "policy", "isAnonymous", "createdAt", "isArchived"} {
require.NotContains(t, recorder.Body.String(), field)
}
}
+14
View File
@@ -0,0 +1,14 @@
package sresponse
import (
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
"net/http"
emodel "git.sendico.io/tech/sxchnge/product/auth/model"
)
type (
HandlerFunc = func(r *http.Request) http.HandlerFunc
AccountHandlerFunc = func(r *http.Request, account *customermodel.Account, accessToken *TokenData) http.HandlerFunc
PendingAccountHandlerFunc = func(r *http.Request, account *customermodel.Account, token *emodel.AccountToken) http.HandlerFunc
)
+27
View File
@@ -0,0 +1,27 @@
package sresponse
import (
"net/http"
"git.sendico.io/tech/sxchnge/shared/http/response"
"git.sendico.io/tech/sxchnge/shared/logging"
)
type resultAuth struct {
authResponse `json:",inline"`
response.Result `json:",inline"`
}
func Success(logger mlogger.Logger, accessToken *TokenData) http.HandlerFunc {
return response.Ok(logger, &resultAuth{
Result: response.Result{Result: true},
authResponse: authResponse{AccessToken: *accessToken},
})
}
func Failed(logger mlogger.Logger, accessToken *TokenData) http.HandlerFunc {
return response.Accepted(logger, &resultAuth{
Result: response.Result{Result: false},
authResponse: authResponse{AccessToken: *accessToken},
})
}
+8
View File
@@ -0,0 +1,8 @@
package sresponse
import "time"
type TokenData struct {
Token string `json:"token"`
Expiration time.Time `json:"expiration"`
}
@@ -0,0 +1,8 @@
package sresponse
type VerificationResponse struct {
IdempotencyKey string `json:"idempotencyKey"`
TTLSeconds int `json:"ttl_seconds"`
CooldownSeconds int `json:"cooldown_seconds"`
Target string `json:"target"`
}
+149
View File
@@ -0,0 +1,149 @@
package storage
import (
"git.sendico.io/tech/sxchnge/product/auth/config"
"git.sendico.io/tech/sxchnge/product/customers/store"
"git.sendico.io/tech/sxchnge/product/customers/store/mongo"
"git.sendico.io/tech/sxchnge/product/sessions/store"
"git.sendico.io/tech/sxchnge/product/verification/store"
"git.sendico.io/tech/sxchnge/shared/database"
edgemongo "git.sendico.io/tech/sxchnge/shared/database/dependencies"
"git.sendico.io/tech/sxchnge/shared/logging"
"git.sendico.io/tech/sxchnge/shared/ratelimit/store"
"go.uber.org/zap"
)
type Stores struct {
Accounts account.DB
Verification verification.DB
RefreshTokens refreshtokens.DB
LoginAttempts ratelimits.Store
}
type TokenStores struct {
Verification verification.DB
RefreshTokens refreshtokens.DB
}
type resolvedConfig struct {
deps *edgemongo.Dependencies
storage middleware.AuthStorageConfig
}
func OpenStores(
logger mlogger.Logger,
dbf db.Factory,
config *middleware.AuthStorageConfig,
) (*Stores, error) {
resolved, err := resolve(logger, dbf, config)
if err != nil {
return nil, err
}
logger.Info(
"Auth storage configured",
zap.String("accounts_collection", resolved.storage.AccountsCollection),
zap.String("refresh_tokens_collection", resolved.storage.RefreshTokensCollection),
zap.String("clients_collection", resolved.storage.ClientsCollection),
zap.String("verification_tokens_collection", resolved.storage.VerificationTokensCollection),
zap.String("login_attempts_collection", resolved.storage.LoginAttemptsCollection),
zap.String("verification_rate_limits_collection", resolved.storage.VerificationRateLimitsCollection),
)
adb, err := accountdb.CreateWithCollection(logger, resolved.deps.Database, resolved.storage.AccountsCollection)
if err != nil {
logger.Error("Failed to create account database", zap.Error(err), zap.String("collection", resolved.storage.AccountsCollection))
return nil, err
}
tokens, err := openTokenStores(logger, resolved)
if err != nil {
return nil, err
}
attempts, err := ratelimits.Create(logger, resolved.deps.Database, resolved.storage.LoginAttemptsCollection)
if err != nil {
logger.Error("Failed to create login attempt database", zap.Error(err), zap.String("collection", resolved.storage.LoginAttemptsCollection))
return nil, err
}
return &Stores{
Accounts: adb,
Verification: tokens.Verification,
RefreshTokens: tokens.RefreshTokens,
LoginAttempts: attempts,
}, nil
}
func OpenTokenStores(
logger mlogger.Logger,
dbf db.Factory,
config *middleware.AuthStorageConfig,
) (*TokenStores, error) {
resolved, err := resolve(logger, dbf, config)
if err != nil {
return nil, err
}
logger.Info(
"Auth token storage configured",
zap.String("refresh_tokens_collection", resolved.storage.RefreshTokensCollection),
zap.String("clients_collection", resolved.storage.ClientsCollection),
zap.String("verification_tokens_collection", resolved.storage.VerificationTokensCollection),
zap.String("verification_rate_limits_collection", resolved.storage.VerificationRateLimitsCollection),
)
return openTokenStores(logger, resolved)
}
func resolve(
logger mlogger.Logger,
dbf db.Factory,
config *middleware.AuthStorageConfig,
) (*resolvedConfig, error) {
deps, err := edgemongo.ResolveDependencies(dbf)
if err != nil {
logger.Error("Failed to resolve local auth storage dependencies", zap.Error(err))
return nil, err
}
return &resolvedConfig{
deps: deps,
storage: config.WithDefaults(),
}, nil
}
func openTokenStores(logger mlogger.Logger, resolved *resolvedConfig) (*TokenStores, error) {
rtdb, err := refreshtokens.CreateWithCollections(logger, resolved.deps.Database, refreshtokens.Collections{
RefreshTokens: resolved.storage.RefreshTokensCollection,
Clients: resolved.storage.ClientsCollection,
})
if err != nil {
logger.Error(
"Failed to create refresh token management database",
zap.Error(err),
zap.String("refresh_tokens_collection", resolved.storage.RefreshTokensCollection),
zap.String("clients_collection", resolved.storage.ClientsCollection),
)
return nil, err
}
verificationLimits, err := ratelimits.Create(logger, resolved.deps.Database, resolved.storage.VerificationRateLimitsCollection)
if err != nil {
logger.Error("Failed to create verification rate-limit database", zap.Error(err), zap.String("collection", resolved.storage.VerificationRateLimitsCollection))
return nil, err
}
cdb, err := verification.CreateWithCollection(
logger,
resolved.deps.Database,
resolved.deps.Transactions,
resolved.storage.VerificationTokensCollection,
)
if err != nil {
logger.Error("Failed to create verification token database", zap.Error(err), zap.String("collection", resolved.storage.VerificationTokensCollection))
return nil, err
}
cdb.WithIssuanceLimits(verificationLimits)
return &TokenStores{
Verification: cdb,
RefreshTokens: rtdb,
}, nil
}
+33
View File
@@ -0,0 +1,33 @@
# SXCHNGE-owned Mongo database and JWT key. Never point these at Sendico.
http_server:
listen_address: 127.0.0.1:8082
read_header_timeout: 5
shutdown_timeout: 10
database:
driver: mongodb
settings:
uri_env: SXCHNGE_MONGO_URI
database: sxchnge
api:
middleware:
domain_env: SXCHNGE_DOMAIN
api_endpoint_env: SXCHNGE_API_ENDPOINT
api_protocol_env: SXCHNGE_API_PROTOCOL
signature:
algorithm: HS256
secret_key_env: SXCHNGE_JWT_SECRET
CORS:
allowed_origins: ["http://localhost:5126"]
allowed_methods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"]
allowed_headers: ["Content-Type", "Authorization", "X-Auth-Transport", "X-CSRF-Protection"]
allow_credentials: true
max_age: 300
token:
expiration_hours:
account: 1
refresh: 720
length: 32
password:
token_length: 32
check:
min_length: 12
@@ -0,0 +1,131 @@
package accountserviceimp
import (
"context"
"git.sendico.io/tech/sxchnge/product/auth/config"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sessionmodel "git.sendico.io/tech/sxchnge/product/sessions/model"
verificationmodel "git.sendico.io/tech/sxchnge/product/verification/model"
"git.sendico.io/tech/sxchnge/product/verification/store"
"git.sendico.io/tech/sxchnge/shared/database"
edgemongo "git.sendico.io/tech/sxchnge/shared/database/dependencies"
"git.sendico.io/tech/sxchnge/shared/errors"
sharedmodel "git.sendico.io/tech/sxchnge/shared/model"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go/modules/mongodb"
"go.mongodb.org/mongo-driver/v2/bson"
"go.uber.org/zap"
"net/url"
"testing"
"time"
)
func customer(login string) *customermodel.Account {
return (&customermodel.AccountData{LoginData: customermodel.LoginData{UserDataBase: customermodel.UserDataBase{Login: login}, Password: "CustomerPassword1!"}, Describable: sharedmodel.Describable{Name: "Customer"}}).ToAccount()
}
// Uses the actual copied repositories against an empty SXCHNGE database.
// There is deliberately no seed, organization, role, policy or Sendico connection.
func TestCustomerLifecycleWithoutTenancy(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
container, err := mongodb.Run(ctx, "mongo:8", mongodb.WithReplicaSet("rs"))
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, container.Terminate(context.Background())) })
uri, err := container.ConnectionString(ctx)
require.NoError(t, err)
endpoint, err := url.Parse(uri)
require.NoError(t, err)
query := endpoint.Query()
query.Set("directConnection", "true")
endpoint.RawQuery = query.Encode()
uri = endpoint.String()
factory, err := db.NewConnection(zap.NewNop(), &db.Config{Driver: db.Mongo, Settings: sharedmodel.SettingsT{"uri": uri, "database": "sxchnge_customers"}})
require.NoError(t, err)
t.Cleanup(factory.CloseConnection)
// Custom collections prove lifecycle and login storage select the same data.
config := &middleware.AuthStorageConfig{AccountsCollection: "customers", VerificationTokensCollection: "customer_verification", RefreshTokensCollection: "customer_sessions"}
svc, err := NewAccountService(zap.NewNop(), factory, &middleware.PasswordConfig{Check: middleware.PasswordChecks{MinLength: 12}}, config)
require.NoError(t, err)
first, second := customer("first@example.test"), customer("second@example.test")
firstToken, err := svc.CreateAccount(ctx, first)
require.NoError(t, err)
require.NotEmpty(t, firstToken)
require.Equal(t, customermodel.AccountPendingVerification, first.Status)
require.True(t, first.MatchPassword("CustomerPassword1!"))
_, err = svc.CreateAccount(ctx, second)
require.NoError(t, err)
require.NotEqual(t, first.ID, second.ID)
// Activation tokens cannot be used as another customer's token.
_, err = svc.vdb.Consume(ctx, second.ID, verificationmodel.PurposeAccountActivation, "", firstToken)
require.Error(t, err)
_, err = svc.vdb.Consume(ctx, first.ID, verificationmodel.PurposeAccountActivation, "", firstToken)
require.NoError(t, err)
_, err = svc.CreateAccount(ctx, customer("first@example.test"))
require.ErrorIs(t, err, merrors.ErrDataConflict)
require.NoError(t, svc.ValidateAccount(customer("validate@example.test")))
require.ErrorIs(t, svc.ValidateAccount(nil), merrors.ErrInvalidArg)
_, err = svc.CreateAccount(ctx, nil)
require.ErrorIs(t, err, merrors.ErrInvalidArg)
require.ErrorIs(t, svc.DeleteAccount(ctx, bson.NilObjectID), merrors.ErrInvalidArg)
for _, c := range []*customermodel.Account{first, second} {
require.NoError(t, svc.sessions.Create(ctx, &sessionmodel.RefreshToken{AccountRef: &c.ID, ExpiresAt: time.Now().Add(time.Hour), ClientRefreshToken: sessionmodel.ClientRefreshToken{SessionIdentifier: sessionmodel.SessionIdentifier{ClientID: "web", DeviceID: "device", SessionVersion: "v1"}, RefreshToken: c.ID.Hex()}}))
}
require.NoError(t, svc.DeleteAccount(ctx, first.ID))
var stored customermodel.Account
require.ErrorIs(t, svc.accountDB.Get(ctx, first.ID, &stored), merrors.ErrNoData)
require.NoError(t, svc.accountDB.Get(ctx, second.ID, &stored))
session := &sessionmodel.SessionIdentifier{ClientID: "web", DeviceID: "device", SessionVersion: "v1"}
_, err = svc.sessions.GetSession(ctx, first.ID, session)
require.Error(t, err)
_, err = svc.sessions.GetSession(ctx, second.ID, session)
require.NoError(t, err)
// The final local customer can be deleted; there is no sole-member restriction.
require.NoError(t, svc.DeleteAccount(ctx, second.ID))
deps, err := edgemongo.ResolveDependencies(factory)
require.NoError(t, err)
collections, err := deps.Database.ListCollectionNames(ctx, bson.D{})
require.NoError(t, err)
for _, forbidden := range []string{"organizations", "roles", "policies", "policy_assignments", "invitations", "accounts"} {
require.NotContains(t, collections, forbidden)
}
// A token issuance failure must roll back the preceding customer insert.
realVerification := svc.vdb
failure := merrors.Internal("injected verification failure")
svc.vdb = &failingVerification{DB: realVerification, failure: failure}
candidate := customer("rollback@example.test")
_, err = svc.CreateAccount(ctx, candidate)
require.ErrorIs(t, err, failure)
require.True(t, candidate.ID.IsZero())
_, err = svc.accountDB.GetByEmail(ctx, candidate.Login)
require.ErrorIs(t, err, merrors.ErrNoData)
svc.vdb = realVerification
// If an outer workflow fails after token issuance, neither write may commit.
outerFailure := merrors.Internal("injected outer failure")
_, err = factory.TransactionFactory().CreateTransaction().Execute(ctx, func(tx context.Context) (any, error) {
_, e := svc.CreateAccount(tx, customer("outer@example.test"))
if e != nil {
return nil, e
}
return nil, outerFailure
})
require.ErrorIs(t, err, outerFailure)
_, err = svc.accountDB.GetByEmail(ctx, "outer@example.test")
require.ErrorIs(t, err, merrors.ErrNoData)
count, err := deps.Database.Collection(config.VerificationTokensCollection).CountDocuments(ctx, bson.D{})
require.NoError(t, err)
require.EqualValues(t, 2, count)
}
type failingVerification struct {
verification.DB
failure error
}
func (f *failingVerification) Create(context.Context, *verification.Request) (string, error) {
return "", f.failure
}
@@ -0,0 +1,248 @@
package accountserviceimp
import (
"context"
"errors"
"fmt"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
verificationmodel "git.sendico.io/tech/sxchnge/product/verification/model"
"time"
"unicode"
"git.sendico.io/tech/sxchnge/product/auth/config"
authstorage "git.sendico.io/tech/sxchnge/product/auth/storage"
"git.sendico.io/tech/sxchnge/product/customers/store"
"git.sendico.io/tech/sxchnge/product/sessions/store"
"git.sendico.io/tech/sxchnge/product/verification/store"
"git.sendico.io/tech/sxchnge/shared/database"
"git.sendico.io/tech/sxchnge/shared/database/transaction"
"git.sendico.io/tech/sxchnge/shared/errors"
"git.sendico.io/tech/sxchnge/shared/logging"
"git.sendico.io/tech/sxchnge/shared/logging/fields"
"go.mongodb.org/mongo-driver/v2/bson"
"go.uber.org/zap"
)
type service struct {
logger mlogger.Logger
accountDB account.DB
config *middleware.PasswordConfig
vdb verification.DB
sessions refreshtokens.DB
transactions transaction.Factory
}
func validateUserRequest(u *customermodel.Account) error {
if u == nil {
return merrors.InvalidArgument("account is required")
}
if u.Name == "" {
return merrors.InvalidArgument("Name must not be empty")
}
if u.Login == "" {
return merrors.InvalidArgument("Login must not be empty")
}
if u.Password == "" {
return merrors.InvalidArgument("Password must not be empty")
}
return nil
}
func (s *service) ValidatePassword(
password string,
oldPassword *string,
) error {
var hasDigit, hasUpper, hasLower, hasSpecial bool
if oldPassword != nil {
if *oldPassword == password {
return merrors.InvalidArgument("New password cannot be the same as the old password")
}
}
if len(password) < s.config.Check.MinLength {
return merrors.InvalidArgument(fmt.Sprintf("Password must be at least %d characters long", s.config.Check.MinLength))
}
// Check for digit, uppercase, lowercase, and special character
for _, char := range password {
switch {
case unicode.IsDigit(char):
hasDigit = true
case unicode.IsUpper(char):
hasUpper = true
case unicode.IsLower(char):
hasLower = true
case unicode.IsPunct(char) || unicode.IsSymbol(char):
hasSpecial = true
}
}
if s.config.Check.Digit && !hasDigit {
return merrors.InvalidArgument("Password must contain at least one digit")
}
if s.config.Check.Upper && !hasUpper {
return merrors.InvalidArgument("Password must contain at least one uppercase letter")
}
if s.config.Check.Lower && !hasLower {
return merrors.InvalidArgument("Password must contain at least one lowercase letter")
}
if s.config.Check.Special && !hasSpecial {
return merrors.InvalidArgument("Password must contain at least one special character")
}
// If all checks pass, return nil (no error)
return nil
}
func (s *service) ValidateAccount(acct *customermodel.Account) error {
if err := validateUserRequest(acct); err != nil {
s.logger.Warn("Invalid signup account received", zap.Error(err))
return err
}
if err := s.ValidatePassword(acct.Password, nil); err != nil {
s.logger.Warn("Password validation failed", zap.Error(err), mzap.Email(acct.Login))
return err
}
if err := acct.HashPassword(); err != nil {
s.logger.Warn("Failed to hash password", zap.Error(err), mzap.Email(acct.Login))
return err
}
return nil
}
func (s *service) CreateAccount(
ctx context.Context,
acct *customermodel.Account,
) (string, error) {
if acct == nil {
return "", merrors.InvalidArgument("account is required")
}
if !acct.ID.IsZero() {
return "", merrors.InvalidArgument("new account must not have an ID")
}
candidate := acct.Copy()
if err := s.ValidateAccount(candidate); err != nil {
return "", err
}
candidate.Status = customermodel.AccountPendingVerification
// The customer and activation token either both commit or neither does.
var saved *customermodel.Account
result, err := s.transactions.CreateTransaction().Execute(ctx, func(tx context.Context) (any, error) {
saved = candidate.Copy()
if err := s.accountDB.Create(tx, saved); err != nil {
return nil, err
}
return s.VerifyAccount(tx, saved)
})
if err != nil {
if errors.Is(err, merrors.ErrDataConflict) {
s.logger.Info("Customer login already exists")
} else {
s.logger.Warn("Customer creation failed", zap.Error(err))
}
return "", err
}
token, ok := result.(string)
if !ok {
return "", merrors.Internal("unexpected account creation result")
}
*acct = *saved
s.logger.Info("Customer created pending verification", mzap.AccRef(acct.ID))
return token, nil
}
func (s *service) VerifyAccount(
ctx context.Context,
acct *customermodel.Account,
) (string, error) {
if acct == nil || acct.ID.IsZero() {
return "", merrors.InvalidArgument("customer reference is required")
}
token, err := s.vdb.Create(
ctx,
verification.NewLinkRequest(*acct.GetID(), verificationmodel.PurposeAccountActivation, "").
WithTTL(time.Hour*24),
)
if err != nil {
s.logger.Warn("Failed to create verification token for new account", zap.Error(err), mzap.StorableRef(acct))
return "", err
}
return token, nil
}
func (s *service) DeleteAccount(
ctx context.Context,
accountRef bson.ObjectID,
) error {
if accountRef.IsZero() {
return merrors.InvalidArgument("account reference is required")
}
_, err := s.transactions.CreateTransaction().Execute(ctx, func(tx context.Context) (any, error) {
if err := s.sessions.RevokeAll(tx, accountRef, ""); err != nil {
return nil, err
}
return nil, s.accountDB.Delete(tx, accountRef)
})
if err != nil {
s.logger.Warn("Customer deletion failed", zap.Error(err), mzap.AccRef(accountRef))
return err
}
s.logger.Info("Customer deleted and sessions revoked", mzap.AccRef(accountRef))
return nil
}
func (s *service) ResetPassword(
ctx context.Context,
acct *customermodel.Account,
) (string, error) {
if acct == nil || acct.ID.IsZero() {
return "", merrors.InvalidArgument("customer reference is required")
}
return s.vdb.Create(
ctx,
verification.NewOTPRequest(*acct.GetID(), verificationmodel.PurposePasswordReset, "").
WithTTL(time.Hour),
)
}
func (s *service) UpdateLogin(
ctx context.Context,
acct *customermodel.Account,
newLogin string,
) (string, error) {
if acct == nil || acct.ID.IsZero() {
return "", merrors.InvalidArgument("customer reference is required")
}
return s.vdb.Create(
ctx,
verification.NewOTPRequest(*acct.GetID(), verificationmodel.PurposeEmailChange, newLogin).
WithTTL(time.Hour),
)
}
func NewAccountService(
l mlogger.Logger,
dbf db.Factory,
config *middleware.PasswordConfig,
storageConfig *middleware.AuthStorageConfig,
) (*service, error) {
logger := l.Named("account_service")
if config == nil {
return nil, merrors.Internal("password configuration is required")
}
stores, err := authstorage.OpenStores(logger, dbf, storageConfig)
if err != nil {
return nil, err
}
return &service{logger: logger, config: config, accountDB: stores.Accounts,
vdb: stores.Verification, sessions: stores.RefreshTokens, transactions: dbf.TransactionFactory()}, nil
}
@@ -0,0 +1,245 @@
package accountserviceimp
import (
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
sharedmodel "git.sendico.io/tech/sxchnge/shared/model"
"testing"
apiconfig "git.sendico.io/tech/sxchnge/product/auth/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
)
// TestValidatePassword tests the password validation logic directly
func TestValidatePassword(t *testing.T) {
config := &apiconfig.PasswordConfig{
Check: apiconfig.PasswordChecks{
MinLength: 8,
Digit: true,
Upper: true,
Lower: true,
Special: true,
},
TokenLength: 32,
}
// Create a minimal service for testing password validation
logger := zap.NewNop() // Use no-op logger for tests
service := &service{
config: config,
logger: logger,
}
t.Run("ValidPassword", func(t *testing.T) {
err := service.ValidatePassword("TestPassword123!", nil)
assert.NoError(t, err)
})
t.Run("PasswordTooShort", func(t *testing.T) {
err := service.ValidatePassword("Test1!", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "at least 8 characters")
})
t.Run("PasswordMissingDigit", func(t *testing.T) {
err := service.ValidatePassword("TestPassword!", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "at least one digit")
})
t.Run("PasswordMissingUppercase", func(t *testing.T) {
err := service.ValidatePassword("testpassword123!", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "at least one uppercase")
})
t.Run("PasswordMissingLowercase", func(t *testing.T) {
err := service.ValidatePassword("TESTPASSWORD123!", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "at least one lowercase")
})
t.Run("PasswordMissingSpecialCharacter", func(t *testing.T) {
err := service.ValidatePassword("TestPassword123", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "at least one special character")
})
t.Run("PasswordSameAsOld", func(t *testing.T) {
oldPassword := "TestPassword123!"
err := service.ValidatePassword("TestPassword123!", &oldPassword)
assert.Error(t, err)
assert.Contains(t, err.Error(), "cannot be the same as the old password")
})
}
// TestValidateAccount tests the account validation logic directly
func TestValidateAccount(t *testing.T) {
config := &apiconfig.PasswordConfig{
Check: apiconfig.PasswordChecks{
MinLength: 8,
Digit: true,
Upper: true,
Lower: true,
Special: true,
},
TokenLength: 32,
}
logger := zap.NewNop() // Use no-op logger for tests
service := &service{
config: config,
logger: logger,
}
t.Run("ValidAccount", func(t *testing.T) {
account := &customermodel.Account{
AccountPublic: customermodel.AccountPublic{
AccountBase: customermodel.AccountBase{
Describable: sharedmodel.Describable{
Name: "Test User",
},
},
UserDataBase: customermodel.UserDataBase{
Login: "test@example.com",
},
},
Password: "TestPassword123!",
}
originalPassword := account.Password
err := service.ValidateAccount(account)
require.NoError(t, err)
// Password should be hashed after validation
assert.NotEqual(t, originalPassword, account.Password)
})
t.Run("AccountMissingName", func(t *testing.T) {
account := &customermodel.Account{
AccountPublic: customermodel.AccountPublic{
UserDataBase: customermodel.UserDataBase{
Login: "test@example.com",
},
},
Password: "TestPassword123!",
}
err := service.ValidateAccount(account)
assert.Error(t, err)
assert.Contains(t, err.Error(), "Name must not be empty")
})
t.Run("AccountMissingLogin", func(t *testing.T) {
account := &customermodel.Account{
AccountPublic: customermodel.AccountPublic{
AccountBase: customermodel.AccountBase{
Describable: sharedmodel.Describable{
Name: "Test User",
},
},
},
Password: "TestPassword123!",
}
err := service.ValidateAccount(account)
assert.Error(t, err)
assert.Contains(t, err.Error(), "Login must not be empty")
})
t.Run("AccountMissingPassword", func(t *testing.T) {
account := &customermodel.Account{
AccountPublic: customermodel.AccountPublic{
AccountBase: customermodel.AccountBase{
Describable: sharedmodel.Describable{
Name: "Test User",
},
},
UserDataBase: customermodel.UserDataBase{
Login: "test@example.com",
},
},
Password: "",
}
err := service.ValidateAccount(account)
assert.Error(t, err)
assert.Contains(t, err.Error(), "Password must not be empty")
})
t.Run("AccountInvalidPassword", func(t *testing.T) {
account := &customermodel.Account{
AccountPublic: customermodel.AccountPublic{
AccountBase: customermodel.AccountBase{
Describable: sharedmodel.Describable{
Name: "Test User",
},
},
UserDataBase: customermodel.UserDataBase{
Login: "test@example.com",
},
},
Password: "weak", // Should fail validation
}
err := service.ValidateAccount(account)
assert.Error(t, err)
// Should fail on password validation
assert.Contains(t, err.Error(), "at least 8 characters")
})
}
// TestPasswordConfiguration verifies different password rule configurations
func TestPasswordConfiguration(t *testing.T) {
t.Run("MinimalRequirements", func(t *testing.T) {
config := &apiconfig.PasswordConfig{
Check: apiconfig.PasswordChecks{
MinLength: 4,
Digit: false,
Upper: false,
Lower: false,
Special: false,
},
TokenLength: 16,
}
logger := zap.NewNop() // Use no-op logger for tests
service := &service{
config: config,
logger: logger,
}
// Should pass with minimal requirements
err := service.ValidatePassword("test", nil)
assert.NoError(t, err)
})
t.Run("StrictRequirements", func(t *testing.T) {
config := &apiconfig.PasswordConfig{
Check: apiconfig.PasswordChecks{
MinLength: 12,
Digit: true,
Upper: true,
Lower: true,
Special: true,
},
TokenLength: 64,
}
logger := zap.NewNop() // Use no-op logger for tests
service := &service{
config: config,
logger: logger,
}
// Should fail with shorter password
err := service.ValidatePassword("Test123!", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "at least 12 characters")
// Should pass with longer password
err = service.ValidatePassword("TestPassword123!", nil)
assert.NoError(t, err)
})
}
@@ -0,0 +1,70 @@
package model
import (
"git.sendico.io/tech/sxchnge/shared/database/record"
sharedmodel "git.sendico.io/tech/sxchnge/shared/model"
"git.sendico.io/tech/sxchnge/shared/service"
"golang.org/x/crypto/bcrypt"
)
type Filter int
type AccountStatus string
const (
AccountPendingVerification AccountStatus = "pending_verification"
AccountActive AccountStatus = "active"
AccountBlocked AccountStatus = "blocked"
)
type AccountBase struct {
storable.Base `bson:",inline" json:",inline"`
sharedmodel.ArchivableBase `bson:",inline" json:",inline"`
sharedmodel.Describable `bson:",inline" json:",inline"`
LastName string `bson:"lastName" json:"lastName"`
AvatarURL *string `bson:"avatarUrl,omitempty" json:"avatarUrl,omitempty"`
}
func (*AccountBase) Collection() string {
return mservice.Accounts
}
type AccountPublic struct {
AccountBase `bson:",inline" json:",inline"`
UserDataBase `bson:",inline" json:",inline"`
}
type Account struct {
AccountPublic `bson:",inline" json:",inline"`
Password string `bson:"password" json:"-"` // password hash
Status AccountStatus `bson:"status" json:"-"`
}
func (a *Account) Copy() *Account {
if a == nil {
return nil
}
copied := *a
return &copied
}
func (a *Account) IsActive() bool {
return a.Status == AccountActive
}
func (a *Account) HashPassword() error {
key, err := bcrypt.GenerateFromPassword([]byte(a.Password), bcrypt.DefaultCost)
if err == nil {
a.Password = string(key)
}
return err
}
func (a *Account) MatchPassword(password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(a.Password), []byte(password))
return err == nil
}
const AccountRefField = "accountRef"
@@ -0,0 +1,32 @@
package model
import sharedmodel "git.sendico.io/tech/sxchnge/shared/model"
type UserDataBase struct {
Login string `bson:"login" json:"login"`
Locale string `bson:"locale" json:"locale"`
}
type LoginData struct {
UserDataBase `bson:",inline" json:",inline"`
Password string ` bson:"-" json:"password"`
}
type AccountData struct {
LoginData `bson:",inline" json:",inline"`
sharedmodel.Describable `bson:",inline" json:",inline"`
LastName string `bson:"lastName" json:"lastName"`
}
func (ad *AccountData) ToAccount() *Account {
return &Account{
AccountPublic: AccountPublic{
AccountBase: AccountBase{
Describable: ad.Describable,
LastName: ad.LastName,
},
UserDataBase: ad.UserDataBase,
},
Password: ad.Password,
}
}
@@ -0,0 +1,14 @@
package account
import (
"context"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
"git.sendico.io/tech/sxchnge/shared/database/template"
)
// DB is the interface which must be implemented by all db drivers
type DB interface {
template.DB[*customermodel.Account]
GetByEmail(ctx context.Context, email string) (*customermodel.Account, error)
}
@@ -0,0 +1,42 @@
package accountdb
import (
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
"strings"
ri "git.sendico.io/tech/sxchnge/shared/database/repository/index"
"git.sendico.io/tech/sxchnge/shared/database/template"
"git.sendico.io/tech/sxchnge/shared/logging"
"git.sendico.io/tech/sxchnge/shared/service"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.uber.org/zap"
)
type AccountDB struct {
template.DBImp[*customermodel.Account]
}
func Create(logger mlogger.Logger, db *mongo.Database) (*AccountDB, error) {
return CreateWithCollection(logger, db, mservice.Accounts)
}
func CreateWithCollection(logger mlogger.Logger, db *mongo.Database, collection string) (*AccountDB, error) {
if normalized := strings.TrimSpace(collection); normalized != "" {
collection = normalized
} else {
collection = mservice.Accounts
}
p := &AccountDB{
DBImp: *template.Create[*customermodel.Account](logger, collection, db),
}
if err := p.Repository.CreateIndex(&ri.Definition{
Keys: []ri.Key{{Field: "login", Sort: ri.Asc}},
Unique: true,
}); err != nil {
p.Logger.Error("Failed to create account database", zap.Error(err), zap.String("collection", collection))
return nil, err
}
return p, nil
}
@@ -0,0 +1,13 @@
package accountdb
import (
"context"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
"git.sendico.io/tech/sxchnge/shared/database/repository"
)
func (db *AccountDB) GetByEmail(ctx context.Context, email string) (*customermodel.Account, error) {
var account customermodel.Account
return &account, db.FindOne(ctx, repository.Filter("login", email), &account)
}
+63
View File
@@ -0,0 +1,63 @@
package accountservice
import (
"context"
customermodel "git.sendico.io/tech/sxchnge/product/customers/model"
"git.sendico.io/tech/sxchnge/product/auth/config"
accountserviceimp "git.sendico.io/tech/sxchnge/product/customers/internal"
"git.sendico.io/tech/sxchnge/shared/database"
"git.sendico.io/tech/sxchnge/shared/logging"
"go.mongodb.org/mongo-driver/v2/bson"
)
// AccountService defines all account-related workflows.
type AccountService interface {
// ValidatePassword will:
// 1) check passsword conformance
ValidatePassword(
password string,
oldPassword *string,
) error
// ResetPassword will:
// 1) generate reset password token
ResetPassword(
ctx context.Context,
acct *customermodel.Account,
) (verificationToken string, err error)
// CreateAccount will:
// 1) validate and hash the password, then create the account
// 2) issue an activation token
CreateAccount(
ctx context.Context,
acct *customermodel.Account,
) (verificationToken string, err error)
VerifyAccount(
ctx context.Context,
acct *customermodel.Account,
) (verificationToken string, err error)
UpdateLogin(
ctx context.Context,
acct *customermodel.Account,
newLogin string,
) (verificationToken string, err error)
// DeleteAccount deletes the local customer account.
DeleteAccount(
ctx context.Context,
accountRef bson.ObjectID,
) error
}
func NewAccountService(
logger mlogger.Logger,
dbf db.Factory,
config *middleware.PasswordConfig,
storageConfig *middleware.AuthStorageConfig,
) (AccountService, error) {
return accountserviceimp.NewAccountService(logger, dbf, config, storageConfig)
}
+96
View File
@@ -0,0 +1,96 @@
module git.sendico.io/tech/sxchnge/product
go 1.27.0
require (
dario.cat/mergo v1.0.2 // indirect
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/containerd/errdefs v1.0.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/containerd/log v0.1.0 // indirect
github.com/containerd/platforms v0.2.1 // indirect
github.com/cpuguy83/dockercfg v0.3.2 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/docker/go-connections v0.7.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/ebitengine/purego v0.10.1 // indirect
github.com/felixge/httpsnoop v1.1.0 // indirect
github.com/go-chi/chi v1.5.4 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/goccy/go-json v0.10.3 // indirect
github.com/klauspost/compress v1.19.2 // indirect
github.com/lestrrat-go/blackmagic v1.0.3 // indirect
github.com/lestrrat-go/httpcc v1.0.1 // indirect
github.com/lestrrat-go/httprc/v3 v3.0.0-beta2 // indirect
github.com/lestrrat-go/jwx/v3 v3.0.2 // indirect
github.com/lestrrat-go/option v1.0.1 // indirect
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect
github.com/magiconair/properties v1.8.10 // indirect
github.com/mattn/go-colorable v0.1.15 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.2.0 // indirect
github.com/moby/moby/api v1.55.0 // indirect
github.com/moby/moby/client v0.5.0 // indirect
github.com/moby/patternmatcher v0.6.1 // indirect
github.com/moby/sys/sequential v0.7.0 // indirect
github.com/moby/sys/user v0.4.0 // indirect
github.com/moby/sys/userns v0.1.0 // indirect
github.com/moby/term v0.5.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.70.1 // indirect
github.com/prometheus/procfs v0.21.1 // indirect
github.com/segmentio/asm v1.2.0 // indirect
github.com/shirou/gopsutil/v4 v4.26.6 // indirect
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/tklauser/go-sysconf v0.4.0 // indirect
github.com/tklauser/numcpus v0.12.0 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.2.0 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect
go.opentelemetry.io/otel v1.44.0 // indirect
go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect
go.uber.org/multierr v1.10.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
)
require (
git.sendico.io/tech/sxchnge/shared v0.0.0
github.com/go-chi/chi/v5 v5.3.2
github.com/go-chi/cors v1.2.2
github.com/go-chi/jwtauth/v5 v5.4.0
github.com/go-chi/metrics v0.1.1
github.com/google/uuid v1.6.0
github.com/prometheus/client_golang v1.24.1
github.com/stretchr/testify v1.12.1
github.com/testcontainers/testcontainers-go v0.44.0
github.com/testcontainers/testcontainers-go/modules/mongodb v0.44.0
go.mongodb.org/mongo-driver/v2 v2.9.0
go.uber.org/zap v1.28.0
golang.org/x/crypto v0.56.0
gopkg.in/yaml.v3 v3.0.1
moul.io/chizap v1.0.3
)
replace git.sendico.io/tech/sxchnge/shared => ../shared
+287
View File
@@ -0,0 +1,287 @@
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I=
github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo=
github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A=
github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw=
github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA=
github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/go-chi/chi v1.5.4 h1:QHdzF2szwjqVV4wmByUnTcsbIg7UGaQ0tPF2t5GcAIs=
github.com/go-chi/chi v1.5.4/go.mod h1:uaf8YgoFazUOkPBG7fxPftUylNumIev9awIWOENIuEg=
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
github.com/go-chi/jwtauth/v5 v5.4.0 h1:Ieh0xMJsFvqylqJ02/mQHKzbbKO9DYNBh4DPKCwTwYI=
github.com/go-chi/jwtauth/v5 v5.4.0/go.mod h1:w6yjqUUXz1b8+oiJel64Sz1KJwduQM6qUA5QNzO5+bQ=
github.com/go-chi/metrics v0.1.1 h1:CXhbnkAVVjb0k73EBRQ6Z2YdWFnbXZgNtg1Mboguibk=
github.com/go-chi/metrics v0.1.1/go.mod h1:mcGTM1pPalP7WCtb+akNYFO/lwNwBBLCuedepqjoPn4=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lestrrat-go/blackmagic v1.0.3 h1:94HXkVLxkZO9vJI/w2u1T0DAoprShFd13xtnSINtDWs=
github.com/lestrrat-go/blackmagic v1.0.3/go.mod h1:6AWFyKNNj0zEXQYfTMPfZrAXUWUfTIZ5ECEUEJaijtw=
github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE=
github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E=
github.com/lestrrat-go/httprc/v3 v3.0.0-beta2 h1:SDxjGoH7qj0nBXVrcrxX8eD94wEnjR+EEuqqmeqQYlY=
github.com/lestrrat-go/httprc/v3 v3.0.0-beta2/go.mod h1:Nwo81sMxE0DcvTB+rJyynNhv/DUu2yZErV7sscw9pHE=
github.com/lestrrat-go/jwx/v3 v3.0.2 h1:N+XLjTJEzDZRP3S0SezclXFAfopwL+o5vaL+qg6rX1I=
github.com/lestrrat-go/jwx/v3 v3.0.2/go.mod h1:qO9w1qkQH77a0r9OXNM33YQPnV/evetKYRg58h1rBNE=
github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU=
github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I=
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak=
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE=
github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY=
github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8=
github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU=
github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc=
github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=
github.com/moby/moby/client v0.5.0 h1:5XhyPk2fuOWf6RlSFa3MkIIgDZkF25xToXW8Q/BH7cc=
github.com/moby/moby/client v0.5.0/go.mod h1:rcVpF8ncl9vo5gaIBdol6CnbEtSj1uxMvEV/UrykF/s=
github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U=
github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc=
github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8=
github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o=
github.com/moby/sys/user v0.4.0 h1:jhcMKit7SA80hivmFJcbB1vqmw//wU61Zdui2eQXuMs=
github.com/moby/sys/user v0.4.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs=
github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g=
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
github.com/pkg/diff v0.0.0-20200914180035-5b29258ca4f7/go.mod h1:zO8QMzTeZd5cpnIkz/Gn6iK0jDfGicM1nynOkkPIl28=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys=
github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs=
github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tailscale/depaware v0.0.0-20210622194025-720c4b409502/go.mod h1:p9lPsd+cx33L3H9nNoecRRxPssFKUwwI50I3pZ0yT+8=
github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI=
github.com/testcontainers/testcontainers-go v0.44.0/go.mod h1:IcnwQrYTO86xHXu5bvMaBH7ATlbS3Qn1M1QWW3c66rE=
github.com/testcontainers/testcontainers-go/modules/mongodb v0.44.0 h1:VSPDFiumAtt0CkZEVbmAkEmYVRvsJpKJy9oF3exRKYg=
github.com/testcontainers/testcontainers-go/modules/mongodb v0.44.0/go.mod h1:kHfzrY1cYP/zr9H4TdqAxbP836A1C2fyUojlHidhFGI=
github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU=
github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI=
github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4=
github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
github.com/xdg-go/scram v1.2.0 h1:bYKF2AEwG5rqd1BumT4gAnvwU/M9nBp2pTSxeZw7Wvs=
github.com/xdg-go/scram v1.2.0/go.mod h1:3dlrS0iBaWKYVt2ZfA4cj48umJZ+cAEbR6/SjLA88I8=
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.mongodb.org/mongo-driver/v2 v2.9.0 h1:e2mQdOmbkiYz+dj3faM7lVDwl7WdnRD+g5VicafMhL0=
go.mongodb.org/mongo-driver/v2 v2.9.0/go.mod h1:SHKN0IWkKmEVGHLjXnni6s4wPKX4v86FTgOeJJFuXcA=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.8.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI=
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y=
golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=
moul.io/chizap v1.0.3 h1:mliXvvuS5HVo3QP8qPXczWtRM5dQ9UmK3bBVIkZo6ek=
moul.io/chizap v1.0.3/go.mod h1:pq4R9kGLwz4XjBc4hodQYuoE7Yc9RUabLBFyyi2uErk=
pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk=
pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04=
+21
View File
@@ -0,0 +1,21 @@
// Adapted from Sendico api/edge/product/main.go; see ../PROVENANCE.md.
package main
import (
application "git.sendico.io/tech/sxchnge/product/app/process"
smain "git.sendico.io/tech/sxchnge/product/app/process/run"
"git.sendico.io/tech/sxchnge/product/app/profile"
"git.sendico.io/tech/sxchnge/product/app/server"
"git.sendico.io/tech/sxchnge/product/app/version"
"git.sendico.io/tech/sxchnge/shared/logging"
"os"
)
func factory(logger mlogger.Logger, file string, debug bool) (application.Application, error) {
return server.Create(logger, file, debug, profile.Runtime())
}
func main() {
if smain.RunServer("sxchnge.bff", appversion.Create(), factory) != nil {
os.Exit(1)
}
}
+121
View File
@@ -0,0 +1,121 @@
package browser
import (
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
"git.sendico.io/tech/sxchnge/shared/errors"
)
const (
TransportHeader = "X-Auth-Transport"
TransportCookie = "cookie"
CSRFHeader = "X-CSRF-Protection"
CSRFValue = "1"
RefreshCookie = "sxchnge_refresh"
)
func UsesCookie(r *http.Request) bool {
return r != nil && strings.EqualFold(strings.TrimSpace(r.Header.Get(TransportHeader)), TransportCookie)
}
func RefreshCredential(r *http.Request, fallback string) (string, error) {
if !UsesCookie(r) {
return strings.TrimSpace(fallback), nil
}
cookie, err := r.Cookie(RefreshCookie)
if err != nil || strings.TrimSpace(cookie.Value) == "" {
return "", merrors.Unauthorized("browser session is missing")
}
return cookie.Value, nil
}
func SetRefreshCookie(w http.ResponseWriter, r *http.Request, token string, expiresAt time.Time) {
if !UsesCookie(r) {
return
}
maxAge := int(time.Until(expiresAt).Seconds())
if maxAge < 1 {
maxAge = 1
}
http.SetCookie(w, &http.Cookie{
Name: RefreshCookie,
Value: token,
Path: cookiePath(r),
Expires: expiresAt.UTC(),
MaxAge: maxAge,
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
})
}
func ClearRefreshCookie(w http.ResponseWriter, r *http.Request) {
if !UsesCookie(r) {
return
}
http.SetCookie(w, &http.Cookie{
Name: RefreshCookie,
Value: "",
Path: cookiePath(r),
Expires: time.Unix(1, 0).UTC(),
MaxAge: -1,
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
})
}
func ValidateCSRF(r *http.Request, allowedOrigins []string) error {
if !UsesCookie(r) || isSafeMethod(r.Method) {
return nil
}
if r.Header.Get(CSRFHeader) != CSRFValue {
return merrors.PermissionDenied("browser CSRF protection header is missing")
}
origin := strings.TrimSpace(r.Header.Get("Origin"))
if origin == "" || !originAllowed(origin, allowedOrigins) {
return merrors.PermissionDenied("browser request origin is not allowed")
}
return nil
}
func cookiePath(r *http.Request) string {
const accountsSegment = "/accounts"
if apiEndpoint := strings.TrimSpace(os.Getenv("API_ENDPOINT")); apiEndpoint != "" {
return path.Join("/", apiEndpoint, accountsSegment)
}
if r != nil && r.URL != nil {
if index := strings.Index(r.URL.Path, accountsSegment); index >= 0 {
return r.URL.Path[:index+len(accountsSegment)]
}
}
return accountsSegment
}
func isSafeMethod(method string) bool {
switch method {
case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace:
return true
default:
return false
}
}
func originAllowed(origin string, allowedOrigins []string) bool {
parsed, err := url.Parse(origin)
if err != nil || parsed.Scheme == "" || parsed.Host == "" || parsed.User != nil || parsed.Path != "" {
return false
}
normalized := strings.TrimSuffix(strings.ToLower(origin), "/")
for _, allowed := range allowedOrigins {
if strings.TrimSuffix(strings.ToLower(strings.TrimSpace(allowed)), "/") == normalized {
return true
}
}
return false
}
@@ -0,0 +1,122 @@
package browser
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestSetRefreshCookieUsesHardenedHostOnlyPolicy(t *testing.T) {
t.Setenv("API_ENDPOINT", "/api/v1")
req := httptest.NewRequest(http.MethodPost, "http://app.sendico.io/api/v1/accounts/login", nil)
req.Header.Set(TransportHeader, TransportCookie)
req.Header.Set("X-Forwarded-Proto", "https")
recorder := httptest.NewRecorder()
SetRefreshCookie(recorder, req, "secret-refresh-token", time.Now().Add(time.Hour))
cookies := recorder.Result().Cookies()
require.Len(t, cookies, 1)
cookie := cookies[0]
require.Equal(t, RefreshCookie, cookie.Name)
require.Equal(t, "secret-refresh-token", cookie.Value)
require.Equal(t, "/api/v1/accounts", cookie.Path)
require.Empty(t, cookie.Domain, "an omitted Domain attribute keeps the cookie host-only")
require.True(t, cookie.HttpOnly)
require.True(t, cookie.Secure)
require.Equal(t, http.SameSiteStrictMode, cookie.SameSite)
require.Positive(t, cookie.MaxAge)
}
func TestSetRefreshCookieUsesConfiguredAPIPathOutsideAccountsRouter(t *testing.T) {
t.Setenv("API_ENDPOINT", "/gateway/v2/")
req := httptest.NewRequest(http.MethodPost, "https://app.sendico.io/gateway/v2/verification/login", nil)
req.Header.Set(TransportHeader, TransportCookie)
recorder := httptest.NewRecorder()
SetRefreshCookie(recorder, req, "refresh", time.Now().Add(time.Hour))
require.Equal(t, "/gateway/v2/accounts", recorder.Result().Cookies()[0].Path)
}
func TestRefreshCookieIsAlwaysSecure(t *testing.T) {
t.Setenv("API_ENDPOINT", "/api/v1")
tests := []struct {
name string
target string
forwardedProto string
}{
{name: "public hostname", target: "http://app.sendico.io/api/v1/accounts/login"},
{name: "localhost", target: "http://localhost:4000/api/v1/accounts/login"},
{name: "loopback IP", target: "http://127.0.0.1:4000/api/v1/accounts/login"},
{name: "private IP", target: "http://192.168.1.20:4000/api/v1/accounts/login"},
{name: "forwarded HTTP", target: "http://app.sendico.io/api/v1/accounts/login", forwardedProto: "http"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, test.target, nil)
req.Header.Set(TransportHeader, TransportCookie)
if test.forwardedProto != "" {
req.Header.Set("X-Forwarded-Proto", test.forwardedProto)
}
recorder := httptest.NewRecorder()
SetRefreshCookie(recorder, req, "refresh", time.Now().Add(time.Hour))
require.True(t, recorder.Result().Cookies()[0].Secure)
})
}
}
func TestClearRefreshCookieUsesHardenedPolicy(t *testing.T) {
t.Setenv("API_ENDPOINT", "/api/v1")
req := httptest.NewRequest(http.MethodPost, "http://192.168.1.20:4000/api/v1/accounts/logout", nil)
req.Header.Set(TransportHeader, TransportCookie)
recorder := httptest.NewRecorder()
ClearRefreshCookie(recorder, req)
cookies := recorder.Result().Cookies()
require.Len(t, cookies, 1)
cookie := cookies[0]
require.Equal(t, RefreshCookie, cookie.Name)
require.Empty(t, cookie.Value)
require.Equal(t, -1, cookie.MaxAge)
require.True(t, cookie.HttpOnly)
require.True(t, cookie.Secure)
require.Equal(t, http.SameSiteStrictMode, cookie.SameSite)
}
func TestValidateCSRFRejectsCrossSiteAndMissingHeaderRequests(t *testing.T) {
allowed := []string{"https://app.sendico.io"}
missingHeader := httptest.NewRequest(http.MethodPost, "https://app.sendico.io/api/v1/payments", nil)
missingHeader.Header.Set(TransportHeader, TransportCookie)
missingHeader.Header.Set("Origin", allowed[0])
require.Error(t, ValidateCSRF(missingHeader, allowed))
crossSite := httptest.NewRequest(http.MethodPost, "https://app.sendico.io/api/v1/payments", nil)
crossSite.Header.Set(TransportHeader, TransportCookie)
crossSite.Header.Set(CSRFHeader, CSRFValue)
crossSite.Header.Set("Origin", "https://attacker.example")
require.Error(t, ValidateCSRF(crossSite, allowed))
valid := httptest.NewRequest(http.MethodPost, "https://app.sendico.io/api/v1/payments", nil)
valid.Header.Set(TransportHeader, TransportCookie)
valid.Header.Set(CSRFHeader, CSRFValue)
valid.Header.Set("Origin", allowed[0])
require.NoError(t, ValidateCSRF(valid, allowed))
}
func TestRefreshCredentialNeverFallsBackForCookieTransport(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "https://app.sendico.io/api/v1/accounts/refresh", nil)
req.Header.Set(TransportHeader, TransportCookie)
credential, err := RefreshCredential(req, "body-token")
require.Error(t, err)
require.Empty(t, credential)
}
Loaded 100 of 382 files, more files were not shown because too many files have changed in this diff. Show more