ci / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 48s
ci / api (push) Successful in 51s
ci / recommender (push) Canceled after 2s
ci / ts (packages + web) (push) Canceled after 0s
ci / docker (образы собираются — их сервер собирает сам при обновлении) (apps/web/Dockerfile, web, ) (push) Canceled after 0s
ci / docker (образы собираются — их сервер собирает сам при обновлении) (services/api/Dockerfile, api, api) (push) Canceled after 0s
ci / docker (образы собираются — их сервер собирает сам при обновлении) (services/api/Dockerfile, storage-agent, storage-agent) (push) Canceled after 0s
ci / docker (образы собираются — их сервер собирает сам при обновлении) (services/recommender/Dockerfile, recommender, ) (push) Canceled after 0s
ci / mobile (Metro-бандл Android) (push) Canceled after 0s
Security and robustness: - storage-agent rejects an empty INTERNAL_TOKEN (config notEmpty + middleware) - api takes the client IP only from X-Real-IP (chi RealIP trusted True-Client-IP) - /readyz reports ok/fail and logs the cause; checks run in parallel with a timeout - storage-agent shuts down gracefully; shared httpx.NewServer/Serve with IdleTimeout - goose migrations take a Postgres advisory lock - recommender readyz: per-check timeout, redis socket timeouts Clients: - Android release allows cleartext HTTP for LAN servers (expo-build-properties) - checkServer times out after 10s; connect button is disabled while checking Deploy and CI: - install.sh hands cache/uploads/updates/models to the non-root service users - update.sh refuses downgrades unless PIPU_ALLOW_DOWNGRADE=1 - recommender/analyzer get only the env they need; required secrets fail fast - nginx security headers and CSP; strip True-Client-IP - dev compose binds ports to 127.0.0.1; postgres/redis images pinned - version.mjs fails on a malformed explicit tag instead of releasing 0.0.0-dev - contract check catches untracked generated files - final releases fail without a release keystore; changelog skips rc tags Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
87 lines
2.8 KiB
Go
87 lines
2.8 KiB
Go
// Package storageagent — внутренний сервис монтирования хранилищ (см. docs/library-and-storage.md).
|
|
// В M0 — каркас: проверка здоровья, аутентификация межсервисных запросов, список точек монтирования.
|
|
package storageagent
|
|
|
|
import (
|
|
"crypto/subtle"
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"pipu/api/internal/platform/httpx"
|
|
)
|
|
|
|
// Mount — состояние точки монтирования источника.
|
|
type Mount struct {
|
|
SourceID string `json:"source_id"`
|
|
Path string `json:"path"`
|
|
}
|
|
|
|
// NewRouter возвращает роутер агента. token — общий секрет INTERNAL_TOKEN;
|
|
// при пустом token все запросы к /internal отклоняются.
|
|
func NewRouter(log *slog.Logger, token, libraryRoot string) http.Handler {
|
|
if log == nil {
|
|
log = slog.New(slog.DiscardHandler)
|
|
}
|
|
r := chi.NewRouter()
|
|
r.NotFound(httpx.NotFound)
|
|
r.Get("/healthz", func(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
|
})
|
|
r.Route("/internal", func(r chi.Router) {
|
|
r.Use(requireToken(token))
|
|
r.Get("/mounts", func(w http.ResponseWriter, r *http.Request) {
|
|
mounts, err := listMounts(libraryRoot)
|
|
if err != nil {
|
|
log.ErrorContext(r.Context(), "list mounts", "err", err)
|
|
httpx.WriteProblem(w, http.StatusInternalServerError, "storage.list_failed", "cannot list mounts")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"mounts": mounts})
|
|
})
|
|
})
|
|
return r
|
|
}
|
|
|
|
func requireToken(token string) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
|
if !ok || token == "" || subtle.ConstantTimeCompare([]byte(got), []byte(token)) != 1 {
|
|
httpx.WriteProblem(w, http.StatusUnauthorized, "auth.invalid_internal_token", "invalid internal token")
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|
|
|
|
// listMounts перечисляет подкаталоги корня библиотеки (каждый — точка монтирования источника).
|
|
func listMounts(root string) ([]Mount, error) {
|
|
entries, err := os.ReadDir(root)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return []Mount{}, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
mounts := make([]Mount, 0, len(entries))
|
|
for _, e := range entries {
|
|
if e.IsDir() {
|
|
mounts = append(mounts, Mount{SourceID: e.Name(), Path: filepath.Join(root, e.Name())})
|
|
}
|
|
}
|
|
return mounts, nil
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|