package main import ( "crypto/sha256" "crypto/subtle" "encoding/json" "errors" "io" "net/http" ) const ( tokenEnvVar = "IISHKO_MODERATION_TOKEN" authHeader = "X-Moderation-Token" maxBodyBytes = 65536 ) const ( msgUnauthorized = "Неавторизованный запрос." msgInvalidJSON = "Некорректный JSON в запросе." msgTrailingData = "Лишние данные после JSON-объекта." msgInternalFailure = "Внутренняя ошибка сервера." ) type errorResponse struct { Error string `json:"error"` } // newHandler builds the complete loopback policy API. The token is injected // once at startup and is never logged. func newHandler(token string) http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /healthz", handleHealthz) mux.HandleFunc("POST /v1/plan", func(w http.ResponseWriter, r *http.Request) { handlePlan(w, r, token) }) return mux } func handleHealthz(w http.ResponseWriter, _ *http.Request) { writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) } func handlePlan(w http.ResponseWriter, r *http.Request, token string) { if !authorized(r, token) { writeJSON(w, http.StatusUnauthorized, errorResponse{Error: msgUnauthorized}) return } body := http.MaxBytesReader(w, r.Body, maxBodyBytes) defer body.Close() decoder := json.NewDecoder(body) decoder.DisallowUnknownFields() var req Request if err := decoder.Decode(&req); err != nil { writeJSON(w, requestErrorStatus(err), errorResponse{Error: msgInvalidJSON}) return } var extra any if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) { writeJSON(w, requestErrorStatus(err), errorResponse{Error: msgTrailingData}) return } response, err := Plan(req) if err != nil { var policyErr *PolicyError if errors.As(err, &policyErr) { writeJSON(w, policyErr.Status, errorResponse{Error: policyErr.Message}) return } writeJSON(w, http.StatusInternalServerError, errorResponse{Error: msgInternalFailure}) return } writeJSON(w, http.StatusOK, response) } // authorized accepts exactly one X-Moderation-Token header whose value matches // the configured token. Both values are hashed so the comparison is // constant-time even when the supplied token has a different length. func authorized(r *http.Request, token string) bool { values := r.Header.Values(authHeader) if len(values) != 1 { return false } provided := sha256.Sum256([]byte(values[0])) expected := sha256.Sum256([]byte(token)) return subtle.ConstantTimeCompare(provided[:], expected[:]) == 1 } func requestErrorStatus(err error) int { var tooLarge *http.MaxBytesError if errors.As(err, &tooLarge) { return http.StatusRequestEntityTooLarge } return http.StatusBadRequest } func writeJSON(w http.ResponseWriter, status int, value any) { payload, err := json.Marshal(value) if err != nil { http.Error(w, "", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Cache-Control", "no-store") w.Header().Set("X-Content-Type-Options", "nosniff") w.WriteHeader(status) _, _ = w.Write(append(payload, '\n')) }