feat(api): sign-in, refresh rotation and bootstrap admin (M1)
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m15s
ci / api / api (push) Successful in 1m31s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 47s
ci / ts / ts (packages + web) (push) Successful in 39s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 26s

- users, refresh_tokens and audit_log schema (migration 00002)
- argon2id passwords with rehash on login, password policy, lockout
  with exponential back-off and a per-IP rate limit in Redis
- Ed25519 JWT access tokens with kid-based key rotation; rotating
  refresh tokens with reuse detection (cookie for web, body for Android)
- bootstrap admin on first start; must_change_credentials and
  must_change_password gate every other endpoint
- /auth/login, /auth/refresh, /auth/logout(-all), /me, /me/password,
  /me/bootstrap-credentials, /me/sessions; server-info reports
  bootstrap_required
- role policy from docs/auth-and-roles.md with table tests
- problem+json errors with field errors; ru/en translations of the codes
- install.sh and update.sh generate JWT_PRIVATE_KEY

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mrleo1nidandClaude Opus 5.5 committed 2026-10-20 06:12:25 +03:00
1 parent b6def39e29
commit ed4a492dba
37 files changed
+5826 -49

No files matched your search

@@ -0,0 +1,71 @@
// Package apperr — доменные ошибки с машинным кодом для i18n. В problem+json их переводит
// единственное место — httpx.ResponseError; модули только возвращают *Error.
package apperr
import (
"fmt"
"net/http"
)
// FieldError — ошибка конкретного поля запроса.
type FieldError struct {
Field string `json:"field"`
Code string `json:"code"`
}
// Error — ошибка, которую можно показать клиенту: HTTP-статус, код и параметры для перевода.
type Error struct {
Status int
Code string
Detail string
Params map[string]any
Fields []FieldError
// RetryAfter — секунды для заголовка Retry-After (429).
RetryAfter int
}
func (e *Error) Error() string {
if e.Detail != "" {
return fmt.Sprintf("%s: %s", e.Code, e.Detail)
}
return e.Code
}
// Is сравнивает ошибки по коду: errors.Is(err, apperr.Unauthorized("auth.invalid_credentials", "")).
func (e *Error) Is(target error) bool {
t, ok := target.(*Error)
return ok && t.Code == e.Code
}
// New создаёт ошибку с произвольным статусом.
func New(status int, code, detail string) *Error {
return &Error{Status: status, Code: code, Detail: detail}
}
// Unauthorized — 401.
func Unauthorized(code, detail string) *Error { return New(http.StatusUnauthorized, code, detail) }
// Forbidden — 403.
func Forbidden(code, detail string) *Error { return New(http.StatusForbidden, code, detail) }
// NotFound — 404.
func NotFound(code, detail string) *Error { return New(http.StatusNotFound, code, detail) }
// Conflict — 409.
func Conflict(code, detail string) *Error { return New(http.StatusConflict, code, detail) }
// Validation — 422 с ошибкой одного поля.
func Validation(field, code, detail string, params map[string]any) *Error {
return &Error{
Status: http.StatusUnprocessableEntity,
Code: code,
Detail: detail,
Params: params,
Fields: []FieldError{{Field: field, Code: code}},
}
}
// TooManyRequests — 429 с Retry-After.
func TooManyRequests(code string, retryAfterSec int) *Error {
return &Error{Status: http.StatusTooManyRequests, Code: code, Detail: "rate limited", RetryAfter: retryAfterSec}
}
@@ -19,6 +19,18 @@ type API struct {
SupportedLocales []string `env:"SUPPORTED_LOCALES" envDefault:"ru,en" envSeparator:","`
MinAndroidVersionCode int `env:"MIN_ANDROID_VERSION_CODE" envDefault:"0"`
// JWTPrivateKey — Ed25519 (base64: 32-байтовый seed или 64-байтовый ключ). Пусто — случайный ключ
// на время жизни процесса: после перезапуска всем придётся обновить access-токен (refresh остаётся).
JWTPrivateKey string `env:"JWT_PRIVATE_KEY"`
// JWTPreviousKeys — прежние ключи через запятую: токены, подписанные ими, ещё принимаются.
JWTPreviousKeys []string `env:"JWT_PREVIOUS_KEYS" envSeparator:","`
AccessTokenTTL time.Duration `env:"ACCESS_TOKEN_TTL" envDefault:"15m"`
// CookieSecure — флаг Secure у refresh-cookie. Отключать только для разработки по http не на localhost.
CookieSecure bool `env:"COOKIE_SECURE" envDefault:"true"`
BootstrapAdminUsername string `env:"BOOTSTRAP_ADMIN_USERNAME" envDefault:"admin"`
BootstrapAdminPassword string `env:"BOOTSTRAP_ADMIN_PASSWORD"`
}
// StorageAgent — конфигурация внутреннего сервиса storage-agent.
+34 -12
View File
@@ -3,24 +3,49 @@ package httpx
import (
"encoding/json"
"errors"
"log/slog"
"net/http"
"strconv"
"pipu/api/internal/platform/apperr"
)
// Problem — тело ответа application/problem+json. Поле Code переводится клиентом через i18n.
type Problem struct {
Type string `json:"type"`
Status int `json:"status"`
Code string `json:"code"`
Detail string `json:"detail,omitempty"`
Params map[string]any `json:"params,omitempty"`
Type string `json:"type"`
Status int `json:"status"`
Code string `json:"code"`
Detail string `json:"detail,omitempty"`
Params map[string]any `json:"params,omitempty"`
Errors []apperr.FieldError `json:"errors,omitempty"`
}
// WriteProblem пишет ответ об ошибке.
func WriteProblem(w http.ResponseWriter, status int, code, detail string) {
writeProblem(w, Problem{Type: "about:blank", Status: status, Code: code, Detail: detail})
}
func writeProblem(w http.ResponseWriter, p Problem) {
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(Problem{Type: "about:blank", Status: status, Code: code, Detail: detail})
w.WriteHeader(p.Status)
_ = json.NewEncoder(w).Encode(p)
}
// WriteError пишет доменную ошибку *apperr.Error; любую другую — как 500 (подробности в лог).
func WriteError(log *slog.Logger, w http.ResponseWriter, r *http.Request, err error) {
var ae *apperr.Error
if !errors.As(err, &ae) {
log.ErrorContext(r.Context(), "handler failed", "path", r.URL.Path, "err", err)
WriteProblem(w, http.StatusInternalServerError, "common.internal", "internal error")
return
}
if ae.RetryAfter > 0 {
w.Header().Set("Retry-After", strconv.Itoa(ae.RetryAfter))
}
writeProblem(w, Problem{
Type: "about:blank", Status: ae.Status, Code: ae.Code, Detail: ae.Detail, Params: ae.Params, Errors: ae.Fields,
})
}
// NotFound — обработчик неизвестных путей.
@@ -38,10 +63,7 @@ func RequestError(w http.ResponseWriter, _ *http.Request, err error) {
WriteProblem(w, http.StatusBadRequest, "common.bad_request", err.Error())
}
// ResponseError — непредвиденная ошибка обработчика: детали только в лог.
// ResponseError — ошибка обработчика: доменные — как есть, прочие — 500 с деталями только в логе.
func ResponseError(log *slog.Logger) func(http.ResponseWriter, *http.Request, error) {
return func(w http.ResponseWriter, r *http.Request, err error) {
log.ErrorContext(r.Context(), "handler failed", "path", r.URL.Path, "err", err)
WriteProblem(w, http.StatusInternalServerError, "common.internal", "internal error")
}
return func(w http.ResponseWriter, r *http.Request, err error) { WriteError(log, w, r, err) }
}