IISHKO: Telegram bot, Mini App and gateway
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled

Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 21:51:30 +03:00
co-authored by Claude Opus 5.5
commit 0ee6fb843b
179 changed files with 59173 additions and 0 deletions
+143
View File
@@ -0,0 +1,143 @@
package main
import (
"errors"
"strconv"
)
const (
// DefaultMuteDuration is one hour, used when /mute has a target but no duration.
DefaultMuteDuration int64 = 3600
// MinDuration is the shortest accepted mute duration.
MinDuration int64 = 30
// MaxDuration is the longest accepted mute duration: 365 days.
MaxDuration int64 = 365 * 24 * 60 * 60
)
var (
errDurationFormat = errors.New("Некорректная длительность. Используйте, например: 30s, 10m, 2h, 1d, 1h30m.")
errDurationRange = errors.New("Длительность должна быть от 30 секунд до 365 дней.")
)
// ParseDuration parses a mute duration. Unit suffixes are s, m, h, d and w;
// components may be combined (1h30m). A bare number is interpreted as minutes.
func ParseDuration(raw string) (int64, error) {
if raw == "" {
return 0, errDurationFormat
}
if isDigits(raw) {
minutes, err := strconv.ParseInt(raw, 10, 64)
if err != nil || minutes > MaxDuration/60 {
return 0, errDurationRange
}
seconds := minutes * 60
if seconds < MinDuration {
return 0, errDurationRange
}
return seconds, nil
}
if !isDurationLike(raw) {
return 0, errDurationFormat
}
var total int64
for i := 0; i < len(raw); {
j := i
for j < len(raw) && raw[j] >= '0' && raw[j] <= '9' {
j++
}
if j == i {
return 0, errDurationFormat
}
amount, err := strconv.ParseInt(raw[i:j], 10, 64)
if err != nil {
return 0, errDurationRange
}
if j >= len(raw) {
return 0, errDurationFormat
}
multiplier, ok := durationUnit(raw[j])
if !ok {
return 0, errDurationFormat
}
if amount > MaxDuration/multiplier {
return 0, errDurationRange
}
component := amount * multiplier
if component > MaxDuration-total {
return 0, errDurationRange
}
total += component
i = j + 1
}
if total < MinDuration || total > MaxDuration {
return 0, errDurationRange
}
return total, nil
}
func durationUnit(value byte) (int64, bool) {
switch value {
case 's', 'S':
return 1, true
case 'm', 'M':
return 60, true
case 'h', 'H':
return 3600, true
case 'd', 'D':
return 86400, true
case 'w', 'W':
return 604800, true
default:
return 0, false
}
}
// isDurationLike reports whether value has the lexical shape of a duration:
// either a bare number (minutes) or one or more number+unit components.
func isDurationLike(value string) bool {
if value == "" {
return false
}
if isDigits(value) {
return true
}
for i := 0; i < len(value); {
if value[i] < '0' || value[i] > '9' {
return false
}
j := i
for j < len(value) && value[j] >= '0' && value[j] <= '9' {
j++
}
if j >= len(value) {
return false
}
if _, ok := durationUnit(value[j]); !ok {
return false
}
i = j + 1
}
return true
}
func isDigits(value string) bool {
if value == "" {
return false
}
for i := range len(value) {
if value[i] < '0' || value[i] > '9' {
return false
}
}
return true
}
func isSignedDigits(value string) bool {
if value == "" {
return false
}
if value[0] == '-' || value[0] == '+' {
return len(value) > 1 && isDigits(value[1:])
}
return isDigits(value)
}
+73
View File
@@ -0,0 +1,73 @@
package main
import (
"errors"
"fmt"
"testing"
)
func TestParseDuration(t *testing.T) {
tests := []struct {
raw string
want int64
wantErr error
}{
{"30s", 30, nil},
{"30S", 30, nil},
{"29s", 0, errDurationRange},
{"1m", 60, nil},
{"10m", 600, nil},
{"1h", 3600, nil},
{"1H", 3600, nil},
{"1h30m", 5400, nil},
{"1m30s", 90, nil},
{"1d", 86400, nil},
{"1w", 604800, nil},
{"1D2H", 93600, nil},
{"365d", MaxDuration, nil},
{"365d1s", 0, errDurationRange},
{"366d", 0, errDurationRange},
{"0s", 0, errDurationRange},
{"30m0s", 1800, nil},
{"1", 60, nil},
{"29", 1740, nil},
{"0", 0, errDurationRange},
{"525600", MaxDuration, nil},
{"525601", 0, errDurationRange},
{"", 0, errDurationFormat},
{"abc", 0, errDurationFormat},
{"1x", 0, errDurationFormat},
{"h", 0, errDurationFormat},
{"1h30", 0, errDurationFormat},
{"-5m", 0, errDurationFormat},
{"1.5h", 0, errDurationFormat},
{" 5m", 0, errDurationFormat},
{"5m ", 0, errDurationFormat},
{"5 s", 0, errDurationFormat},
{"m5", 0, errDurationFormat},
{"999999999999999999999999h", 0, errDurationRange},
}
for _, test := range tests {
t.Run(fmt.Sprintf("%q", test.raw), func(t *testing.T) {
got, err := ParseDuration(test.raw)
if !errors.Is(err, test.wantErr) {
t.Fatalf("ParseDuration(%q) error = %v, want %v", test.raw, err, test.wantErr)
}
if got != test.want {
t.Fatalf("ParseDuration(%q) = %d, want %d", test.raw, got, test.want)
}
})
}
}
func TestParseDurationBounds(t *testing.T) {
if seconds, err := ParseDuration("30s"); err != nil || seconds != MinDuration {
t.Fatalf("minimum duration = %d, %v; want %d", seconds, err, MinDuration)
}
if seconds, err := ParseDuration("365d"); err != nil || seconds != MaxDuration {
t.Fatalf("maximum duration = %d, %v; want %d", seconds, err, MaxDuration)
}
if _, err := ParseDuration("365d1m"); !errors.Is(err, errDurationRange) {
t.Fatalf("one minute above maximum: error = %v, want range error", err)
}
}
+3
View File
@@ -0,0 +1,3 @@
module iishko/moderation
go 1.23
+110
View File
@@ -0,0 +1,110 @@
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'))
}
+291
View File
@@ -0,0 +1,291 @@
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
const testToken = "0123456789abcdef0123456789abcdef" // gitleaks:allow
func newTestHandler() http.Handler {
return newHandler(testToken)
}
func perform(handler http.Handler, method, path, token, body string) *httptest.ResponseRecorder {
request := httptest.NewRequest(method, path, strings.NewReader(body))
if token != "" {
request.Header.Set(authHeader, token)
}
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
return recorder
}
func validPlanBody(action string) string {
return `{"action":"` + action + `","args":["@alice"],"reply_uid":0,"candidates":[{"uid":101,"username":"alice"}],"actor_allowed":true,"bot_allowed":true,"chat_type":"supergroup","protected_uids":[],"bot_username":"iishkogatewaybot"}`
}
func errorMessage(t *testing.T, recorder *httptest.ResponseRecorder) string {
t.Helper()
var payload map[string]string
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatalf("error body is not JSON: %v (%q)", err, recorder.Body.String())
}
if len(payload) != 1 {
t.Fatalf("error body keys = %d, want 1 (%q)", len(payload), recorder.Body.String())
}
message, ok := payload["error"]
if !ok || message == "" {
t.Fatalf("error body = %q", recorder.Body.String())
}
return message
}
func TestHealthz(t *testing.T) {
recorder := perform(newTestHandler(), http.MethodGet, "/healthz", "", "")
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", recorder.Code)
}
if body := strings.TrimSpace(recorder.Body.String()); body != `{"status":"ok"}` {
t.Fatalf("body = %q", body)
}
if contentType := recorder.Header().Get("Content-Type"); contentType != "application/json; charset=utf-8" {
t.Fatalf("content type = %q", contentType)
}
recorder = perform(newTestHandler(), http.MethodPost, "/healthz", "", "")
if recorder.Code != http.StatusMethodNotAllowed {
t.Fatalf("POST /healthz status = %d, want 405", recorder.Code)
}
}
func TestPlanAuth(t *testing.T) {
handler := newTestHandler()
tests := []struct {
name string
token string
}{
{"missing", ""},
{"empty header", ""},
{"wrong", "fedcba9876543210fedcba9876543210"},
{"prefix", testToken[:len(testToken)-1]},
{"longer", testToken + "x"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
recorder := perform(handler, http.MethodPost, "/v1/plan", test.token, validPlanBody(ActionBan))
if recorder.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401 (%q)", recorder.Code, recorder.Body.String())
}
message := errorMessage(t, recorder)
if strings.Contains(message, testToken) {
t.Fatal("error response echoed the token")
}
})
}
request := httptest.NewRequest(http.MethodPost, "/v1/plan", strings.NewReader(validPlanBody(ActionBan)))
request.Header.Add(authHeader, testToken)
request.Header.Add(authHeader, testToken)
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusUnauthorized {
t.Fatalf("duplicate header status = %d, want 401", recorder.Code)
}
recorder = perform(handler, http.MethodPost, "/v1/plan", testToken+","+testToken, validPlanBody(ActionBan))
if recorder.Code != http.StatusUnauthorized {
t.Fatalf("combined header status = %d, want 401", recorder.Code)
}
recorder = perform(handler, http.MethodPost, "/v1/plan", "", `{"action":`)
if recorder.Code != http.StatusUnauthorized {
t.Fatalf("auth must run before body parsing, status = %d", recorder.Code)
}
}
func TestPlanSuccess(t *testing.T) {
recorder := perform(newTestHandler(), http.MethodPost, "/v1/plan", testToken, validPlanBody(ActionBan))
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (%q)", recorder.Code, recorder.Body.String())
}
if contentType := recorder.Header().Get("Content-Type"); contentType != "application/json; charset=utf-8" {
t.Fatalf("content type = %q", contentType)
}
if cacheControl := recorder.Header().Get("Cache-Control"); cacheControl != "no-store" {
t.Fatalf("cache control = %q", cacheControl)
}
if options := recorder.Header().Get("X-Content-Type-Options"); options != "nosniff" {
t.Fatalf("content type options = %q", options)
}
var response Response
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
t.Fatalf("decode response: %v", err)
}
if response.Action != ActionBan || response.TargetUID != 101 {
t.Fatalf("response = %+v", response)
}
if response.DurationSeconds != 0 || response.Mode != "" || response.Reason != "" {
t.Fatalf("unexpected optional fields: %+v", response)
}
var raw map[string]json.RawMessage
if err := json.Unmarshal(recorder.Body.Bytes(), &raw); err != nil {
t.Fatalf("decode raw response: %v", err)
}
for _, key := range []string{"action", "target_uid", "duration_seconds", "mode", "reason"} {
if _, ok := raw[key]; !ok {
t.Fatalf("response is missing key %q: %s", key, recorder.Body.String())
}
}
if len(raw) != 5 {
t.Fatalf("response has %d keys, want 5: %s", len(raw), recorder.Body.String())
}
}
func TestPlanRouting(t *testing.T) {
handler := newTestHandler()
cases := []struct {
method string
path string
token string
want int
}{
{http.MethodGet, "/v1/plan", testToken, http.StatusMethodNotAllowed},
{http.MethodOptions, "/v1/plan", testToken, http.StatusMethodNotAllowed},
{http.MethodPost, "/v1/plans", testToken, http.StatusNotFound},
{http.MethodGet, "/v1/plan/", testToken, http.StatusNotFound},
{http.MethodGet, "/healthz/", "", http.StatusNotFound},
{http.MethodGet, "/", "", http.StatusNotFound},
}
for _, test := range cases {
t.Run(test.method+" "+test.path, func(t *testing.T) {
recorder := perform(handler, test.method, test.path, test.token, validPlanBody(ActionBan))
if recorder.Code != test.want {
t.Fatalf("status = %d, want %d (%q)", recorder.Code, test.want, recorder.Body.String())
}
})
}
}
func TestPlanJSONErrors(t *testing.T) {
handler := newTestHandler()
tests := []struct {
name string
body string
}{
{"empty", ""},
{"whitespace", " \n"},
{"truncated", `{"action":`},
{"syntax", `{"action":"resolve",}`},
{"top level array", `[]`},
{"top level null", `null`},
{"wrong type", `{"action":"resolve","reply_uid":"101"}`},
{"unknown field", `{"action":"resolve","reply_uid":101,"extra":true}`},
{"unknown nested field", `{"action":"resolve","candidates":[{"uid":1,"username":"a","extra":true}]}`},
{"trailing true", `{"action":"resolve","reply_uid":101} true`},
{"trailing object", `{"action":"resolve","reply_uid":101}{"action":"resolve"}`},
{"trailing junk", `{"action":"resolve","reply_uid":101}x`},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
recorder := perform(handler, http.MethodPost, "/v1/plan", testToken, test.body)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400 (%q)", recorder.Code, recorder.Body.String())
}
errorMessage(t, recorder)
})
}
}
func TestPlanTrailingDataMessage(t *testing.T) {
recorder := perform(newTestHandler(), http.MethodPost, "/v1/plan", testToken,
`{"action":"resolve","reply_uid":101} true`)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400", recorder.Code)
}
if message := errorMessage(t, recorder); message != msgTrailingData {
t.Fatalf("message = %q, want %q", message, msgTrailingData)
}
}
func TestPlanPolicyErrorStatus(t *testing.T) {
body := `{"action":"ban","args":["@alice"],"reply_uid":0,"candidates":[{"uid":101,"username":"alice"}],"actor_allowed":false,"bot_allowed":true,"chat_type":"supergroup","protected_uids":[],"bot_username":"iishkogatewaybot"}`
recorder := perform(newTestHandler(), http.MethodPost, "/v1/plan", testToken, body)
if recorder.Code != http.StatusForbidden {
t.Fatalf("status = %d, want 403 (%q)", recorder.Code, recorder.Body.String())
}
if message := errorMessage(t, recorder); message != msgPermissions {
t.Fatalf("message = %q, want %q", message, msgPermissions)
}
}
func TestPlanBodyLimit(t *testing.T) {
handler := newTestHandler()
base := `{"action":"resolve","reply_uid":101}`
if len(base) > maxBodyBytes {
t.Fatalf("base body %d exceeds limit %d", len(base), maxBodyBytes)
}
exactBody := base + strings.Repeat(" ", maxBodyBytes-len(base))
if len(exactBody) != maxBodyBytes {
t.Fatalf("body length = %d, want %d", len(exactBody), maxBodyBytes)
}
recorder := perform(handler, http.MethodPost, "/v1/plan", testToken, exactBody)
if recorder.Code != http.StatusOK {
t.Fatalf("exact limit status = %d, want 200 (%q)", recorder.Code, recorder.Body.String())
}
tooLarge := exactBody + " "
recorder = perform(handler, http.MethodPost, "/v1/plan", testToken, tooLarge)
if recorder.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("over limit status = %d, want 413 (%q)", recorder.Code, recorder.Body.String())
}
errorMessage(t, recorder)
}
func TestLoadToken(t *testing.T) {
valid := strings.Repeat("a", minTokenLength)
t.Setenv(tokenEnvVar, valid)
token, err := loadToken()
if err != nil || token != valid {
t.Fatalf("loadToken() = %q, %v", token, err)
}
for _, value := range []string{"", strings.Repeat("a", minTokenLength-1)} {
t.Setenv(tokenEnvVar, value)
if _, err := loadToken(); err == nil {
t.Fatalf("loadToken accepted %d characters", len(value))
}
}
}
func TestValidateAddr(t *testing.T) {
valid := []string{"127.0.0.1:48003", "127.0.0.2:1", "[::1]:48003"}
for _, addr := range valid {
if err := validateAddr(addr); err != nil {
t.Fatalf("validateAddr(%q) = %v", addr, err)
}
}
invalid := []string{
"",
"127.0.0.1",
":48003",
"localhost:48003",
"0.0.0.0:48003",
"[::]:48003",
"8.8.8.8:48003",
"127.0.0.1:0",
"127.0.0.1:65536",
"127.0.0.1:abc",
"::1:48003",
}
for _, addr := range invalid {
if err := validateAddr(addr); err == nil {
t.Fatalf("validateAddr(%q) = nil, want error", addr)
}
}
}
+110
View File
@@ -0,0 +1,110 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
)
const (
defaultAddr = "127.0.0.1:48003"
minTokenLength = 32
)
func main() {
if err := run(); err != nil {
log.Printf("moderation: %v", err)
os.Exit(1)
}
}
func run() error {
token, err := loadToken()
if err != nil {
return err
}
addr := flag.String("addr", defaultAddr, "loopback IP and port to listen on")
flag.Parse()
if err := validateAddr(*addr); err != nil {
return err
}
listener, err := net.Listen("tcp", *addr)
if err != nil {
return fmt.Errorf("listen: %w", err)
}
server := &http.Server{
Handler: newHandler(token),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 16 << 10,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
serveErr := make(chan error, 1)
go func() {
serveErr <- server.Serve(listener)
}()
log.Printf("moderation listening on http://%s", listener.Addr().String())
select {
case err := <-serveErr:
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return fmt.Errorf("serve: %w", err)
case <-ctx.Done():
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
_ = server.Close()
return fmt.Errorf("shutdown: %w", err)
}
return nil
}
// loadToken reads the required shared secret. Errors deliberately name the
// variable but never echo its value.
func loadToken() (string, error) {
token := os.Getenv(tokenEnvVar)
if len(token) < minTokenLength {
return "", fmt.Errorf("%s must be at least %d characters", tokenEnvVar, minTokenLength)
}
return token, nil
}
// validateAddr accepts only a literal loopback IP with an explicit port, so a
// misconfiguration can never expose the service on a public interface.
func validateAddr(addr string) error {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return fmt.Errorf("invalid -addr: %w", err)
}
if host == "" {
return errors.New("-addr must contain a loopback IP")
}
ip := net.ParseIP(host)
if ip == nil || !ip.IsLoopback() {
return fmt.Errorf("-addr host %q is not a loopback IP", host)
}
number, err := strconv.Atoi(port)
if err != nil || number < 1 || number > 65535 {
return fmt.Errorf("-addr port %q is invalid", port)
}
return nil
}
+410
View File
@@ -0,0 +1,410 @@
package main
import (
"errors"
"fmt"
"net/http"
"strconv"
"strings"
)
const (
ActionBan = "ban"
ActionUnban = "unban"
ActionMute = "mute"
ActionUnmute = "unmute"
ActionKick = "kick"
ActionResolve = "resolve"
ActionSetup = "setup"
ActionChatMode = "chatmode"
)
const (
msgMissingTarget = "Укажите получателя или ответьте на сообщение."
msgTargetConflict = "Укажите либо получателя, либо ответ на сообщение, но не оба."
msgEmptyArgument = "Пустой аргумент."
msgTooManyArguments = "Слишком много аргументов."
msgPermissions = "Недостаточно прав для выполнения команды."
msgSupergroupOnly = "Команда доступна только в супергруппе."
msgProtectedTarget = "Этот участник защищён от ограничений."
msgUnknownAction = "Неизвестное действие."
msgInvalidReplyID = "Некорректный ID ответа."
msgInvalidCandidate = "Некорректный ID кандидата."
msgInvalidProtected = "Некорректный ID защищённого участника."
msgInvalidUserID = "Некорректный ID пользователя."
msgNonPositiveUserID = "ID пользователя должен быть больше нуля."
msgUserIDRange = "ID пользователя вне допустимого диапазона."
msgInvalidUsername = "Некорректное имя пользователя."
msgTooManyModeArgs = "Укажите режим чата: quiet, mentions или replies."
msgInvalidMode = "Режим должен быть quiet, mentions или replies."
msgSetupArguments = "Команда setup не принимает аргументов."
)
// Candidate is a username-to-ID mapping supplied by the Python bridge for the
// current chat. The policy service never performs Telegram lookups itself.
type Candidate struct {
UID int64 `json:"uid"`
Username string `json:"username"`
}
// Request is the policy request produced by the Python bridge. Permission
// flags are the result of live Telegram checks and are trusted as provided.
type Request struct {
Action string `json:"action"`
Args []string `json:"args"`
ReplyUID int64 `json:"reply_uid"`
Candidates []Candidate `json:"candidates"`
ActorAllowed bool `json:"actor_allowed"`
BotAllowed bool `json:"bot_allowed"`
ChatType string `json:"chat_type"`
ProtectedUIDs []int64 `json:"protected_uids"`
BotUsername string `json:"bot_username"`
}
// Response is the resolved policy decision. Every field is always emitted.
type Response struct {
Action string `json:"action"`
TargetUID int64 `json:"target_uid"`
DurationSeconds int64 `json:"duration_seconds"`
Mode string `json:"mode"`
Reason string `json:"reason"`
}
// PolicyError carries a Russian user-facing message and the HTTP status the
// bridge should map the rejection to.
type PolicyError struct {
Status int
Message string
}
func (e *PolicyError) Error() string {
return e.Message
}
func policyError(status int, message string) *PolicyError {
return &PolicyError{Status: status, Message: message}
}
func badRequest(format string, args ...any) *PolicyError {
return policyError(http.StatusBadRequest, fmt.Sprintf(format, args...))
}
func protectedError() *PolicyError {
return policyError(http.StatusForbidden, msgProtectedTarget)
}
func durationPolicyError(err error) *PolicyError {
return badRequest("%s", err.Error())
}
// Plan resolves a single moderation command. It is pure and stateless: the
// bridge supplies candidates, chat kind, protection list and live permission
// booleans; Plan never touches Telegram, a database or the filesystem.
func Plan(req Request) (Response, error) {
if err := validateRequest(req); err != nil {
return Response{}, err
}
action := canonicalAction(req.Action)
if action == "" {
return Response{}, badRequest("%s", msgUnknownAction)
}
req.Action = action
switch action {
case ActionResolve:
// The shared legacy resolver must stay usable while permissions are
// still being computed by the caller.
return planResolve(req)
case ActionSetup:
if err := requireRights(req); err != nil {
return Response{}, err
}
if len(req.Args) != 0 {
return Response{}, badRequest("%s", msgSetupArguments)
}
return Response{Action: ActionSetup}, nil
case ActionChatMode:
if err := requireRights(req); err != nil {
return Response{}, err
}
return planChatMode(req)
case ActionBan, ActionUnban, ActionKick:
if err := requireRights(req); err != nil {
return Response{}, err
}
targetUID, err := resolveSingleTarget(req)
if err != nil {
return Response{}, err
}
if action != ActionUnban && isProtected(req.ProtectedUIDs, targetUID) {
return Response{}, protectedError()
}
return Response{Action: action, TargetUID: targetUID}, nil
case ActionMute, ActionUnmute:
if err := requireRights(req); err != nil {
return Response{}, err
}
if !strings.EqualFold(req.ChatType, "supergroup") {
return Response{}, badRequest("%s", msgSupergroupOnly)
}
if action == ActionMute {
return planMute(req)
}
targetUID, err := resolveSingleTarget(req)
if err != nil {
return Response{}, err
}
return Response{Action: ActionUnmute, TargetUID: targetUID}, nil
default:
return Response{}, badRequest("%s", msgUnknownAction)
}
}
func validateRequest(req Request) error {
if req.ReplyUID < 0 {
return badRequest("%s", msgInvalidReplyID)
}
for _, candidate := range req.Candidates {
if candidate.UID <= 0 {
return badRequest("%s", msgInvalidCandidate)
}
}
for _, uid := range req.ProtectedUIDs {
if uid <= 0 {
return badRequest("%s", msgInvalidProtected)
}
}
return nil
}
func canonicalAction(raw string) string {
switch strings.ToLower(strings.TrimSpace(raw)) {
case ActionBan:
return ActionBan
case ActionUnban:
return ActionUnban
case ActionMute:
return ActionMute
case ActionUnmute:
return ActionUnmute
case ActionKick:
return ActionKick
case ActionResolve:
return ActionResolve
case ActionSetup:
return ActionSetup
case ActionChatMode:
return ActionChatMode
default:
return ""
}
}
func requireRights(req Request) error {
if !req.ActorAllowed || !req.BotAllowed {
return policyError(http.StatusForbidden, msgPermissions)
}
return nil
}
func planResolve(req Request) (Response, error) {
targetUID, err := resolveSingleTarget(req)
if err != nil {
return Response{}, err
}
return Response{Action: ActionResolve, TargetUID: targetUID}, nil
}
func planChatMode(req Request) (Response, error) {
if len(req.Args) == 0 {
return Response{}, badRequest("%s", msgTooManyModeArgs)
}
if len(req.Args) > 1 {
return Response{}, badRequest("%s", msgTooManyArguments)
}
mode := asciiLower(strings.TrimSpace(req.Args[0]))
switch mode {
case "quiet", "mentions", "replies":
return Response{Action: ActionChatMode, Mode: mode}, nil
default:
return Response{}, badRequest("%s", msgInvalidMode)
}
}
// resolveSingleTarget handles commands that take exactly one target: an
// explicit ID/username or, when no explicit target is present, the replied
// message author.
func resolveSingleTarget(req Request) (int64, error) {
if len(req.Args) > 1 {
return 0, badRequest("%s", msgTooManyArguments)
}
if len(req.Args) == 1 {
if req.ReplyUID > 0 {
return 0, badRequest("%s", msgTargetConflict)
}
return parseTargetToken(req.Args[0], req.Candidates)
}
if req.ReplyUID <= 0 {
return 0, badRequest("%s", msgMissingTarget)
}
return req.ReplyUID, nil
}
// planMute resolves the extra duration rules for /mute:
// - /mute with a reply uses the replied author and one hour;
// - /mute 2h with a reply keeps the replied author, two hours;
// - /mute @name 2h uses an explicit target and duration;
// - a bare number is minutes only when a target is already unambiguous,
// otherwise it is an explicit user ID.
func planMute(req Request) (Response, error) {
switch len(req.Args) {
case 0:
if req.ReplyUID <= 0 {
return Response{}, badRequest("%s", msgMissingTarget)
}
return muteResponse(req, req.ReplyUID, DefaultMuteDuration)
case 1:
token := req.Args[0]
if token == "" {
return Response{}, badRequest("%s", msgEmptyArgument)
}
if req.ReplyUID > 0 {
if isDurationLike(token) {
duration, err := ParseDuration(token)
if err != nil {
return Response{}, durationPolicyError(err)
}
return muteResponse(req, req.ReplyUID, duration)
}
if isSignedDigits(token) {
if _, err := parseUserID(token); err != nil {
return Response{}, err
}
}
return Response{}, badRequest("%s", msgTargetConflict)
}
if isSignedDigits(token) {
uid, err := parseUserID(token)
if err != nil {
return Response{}, err
}
return muteResponse(req, uid, DefaultMuteDuration)
}
if isDurationLike(token) {
return Response{}, badRequest("%s", msgMissingTarget)
}
uid, err := resolveUsername(strings.TrimPrefix(token, "@"), req.Candidates)
if err != nil {
return Response{}, err
}
return muteResponse(req, uid, DefaultMuteDuration)
case 2:
if req.ReplyUID > 0 {
return Response{}, badRequest("%s", msgTargetConflict)
}
first, second := req.Args[0], req.Args[1]
if first == "" || second == "" {
return Response{}, badRequest("%s", msgEmptyArgument)
}
uid, err := parseTargetToken(first, req.Candidates)
if err != nil {
return Response{}, err
}
duration, err := ParseDuration(second)
if err != nil {
return Response{}, durationPolicyError(err)
}
return muteResponse(req, uid, duration)
default:
return Response{}, badRequest("%s", msgTooManyArguments)
}
}
func muteResponse(req Request, uid, duration int64) (Response, error) {
if isProtected(req.ProtectedUIDs, uid) {
return Response{}, protectedError()
}
return Response{Action: ActionMute, TargetUID: uid, DurationSeconds: duration}, nil
}
func parseTargetToken(token string, candidates []Candidate) (int64, error) {
if token == "" {
return 0, badRequest("%s", msgEmptyArgument)
}
if isSignedDigits(token) {
return parseUserID(token)
}
name := strings.TrimPrefix(token, "@")
if name == "" {
return 0, badRequest("%s", msgInvalidUsername)
}
return resolveUsername(name, candidates)
}
func parseUserID(token string) (int64, error) {
uid, err := strconv.ParseInt(token, 10, 64)
if err != nil {
if errors.Is(err, strconv.ErrRange) {
return 0, badRequest("%s", msgUserIDRange)
}
return 0, badRequest("%s", msgInvalidUserID)
}
if uid <= 0 {
return 0, badRequest("%s", msgNonPositiveUserID)
}
return uid, nil
}
func resolveUsername(raw string, candidates []Candidate) (int64, error) {
if raw == "" {
return 0, badRequest("%s", msgInvalidUsername)
}
wanted := asciiLower(raw)
var found int64
matches := 0
for _, candidate := range candidates {
name := strings.TrimPrefix(candidate.Username, "@")
if name == "" {
continue
}
if asciiLower(name) != wanted {
continue
}
matches++
found = candidate.UID
if matches > 1 {
return 0, badRequest("Несколько пользователей с именем @%s. Укажите ID.", raw)
}
}
if matches == 0 {
return 0, badRequest("Пользователь @%s не найден.", raw)
}
return found, nil
}
func isProtected(protected []int64, uid int64) bool {
for _, candidate := range protected {
if candidate == uid {
return true
}
}
return false
}
// asciiLower lowercases ASCII letters only. Telegram usernames are ASCII, so
// Unicode case folding is deliberately not applied.
func asciiLower(value string) string {
buffer := []byte(value)
changed := false
for i, b := range buffer {
if b < 'A' || b > 'Z' {
continue
}
buffer[i] = b + ('a' - 'A')
changed = true
}
if !changed {
return value
}
return string(buffer)
}
+386
View File
@@ -0,0 +1,386 @@
package main
import (
"errors"
"net/http"
"strings"
"testing"
)
func baseRequest(action string) Request {
return Request{
Action: action,
ChatType: "supergroup",
BotUsername: "iishkogatewaybot",
ActorAllowed: true,
BotAllowed: true,
}
}
func requestWith(action string, args ...string) Request {
request := baseRequest(action)
request.Args = args
return request
}
func TestPlanPermissions(t *testing.T) {
requests := []Request{
requestWith(ActionBan, "101"),
requestWith(ActionUnban, "101"),
requestWith(ActionKick, "101"),
requestWith(ActionMute, "101"),
requestWith(ActionUnmute, "101"),
requestWith(ActionSetup),
requestWith(ActionChatMode, "quiet"),
}
flags := []struct {
name string
actorAllowed bool
botAllowed bool
}{
{"actor denied", false, true},
{"bot denied", true, false},
{"both denied", false, false},
}
for _, request := range requests {
for _, flag := range flags {
t.Run(request.Action+"/"+flag.name, func(t *testing.T) {
request.ActorAllowed = flag.actorAllowed
request.BotAllowed = flag.botAllowed
_, err := Plan(request)
assertPolicyStatus(t, err, http.StatusForbidden)
})
}
}
}
func TestPlanResolveWithoutRights(t *testing.T) {
request := requestWith(ActionResolve)
request.ReplyUID = 101
request.ActorAllowed = false
request.BotAllowed = false
request.ChatType = "private"
response, err := Plan(request)
if err != nil {
t.Fatalf("resolve without rights: %v", err)
}
if response.Action != ActionResolve || response.TargetUID != 101 {
t.Fatalf("resolve response = %+v", response)
}
}
func TestPlanResolveTargets(t *testing.T) {
candidates := []Candidate{{UID: 101, Username: "Alice"}, {UID: 202, Username: "bob"}}
ambiguous := []Candidate{{UID: 1, Username: "alice"}, {UID: 2, Username: "ALICE"}}
named := requestWith(ActionResolve, "@alice")
named.Candidates = candidates
bareName := requestWith(ActionResolve, "ALICE")
bareName.Candidates = candidates
plainNumeric := requestWith(ActionResolve, "101")
plusNumeric := requestWith(ActionResolve, "+101")
reply := requestWith(ActionResolve)
reply.ReplyUID = 303
unknownName := requestWith(ActionResolve, "@carol")
unknownName.Candidates = candidates
ambiguousName := requestWith(ActionResolve, "alice")
ambiguousName.Candidates = ambiguous
tests := []struct {
name string
request Request
wantTarget int64
wantStatus int
}{
{"numeric", plainNumeric, 101, http.StatusOK},
{"signed numeric", plusNumeric, 101, http.StatusOK},
{"at username", named, 101, http.StatusOK},
{"bare username", bareName, 101, http.StatusOK},
{"reply only", reply, 303, http.StatusOK},
{"unknown username", unknownName, 0, http.StatusBadRequest},
{"ambiguous username", ambiguousName, 0, http.StatusBadRequest},
{"missing target", requestWith(ActionResolve), 0, http.StatusBadRequest},
{"zero id", requestWith(ActionResolve, "0"), 0, http.StatusBadRequest},
{"negative id", requestWith(ActionResolve, "-101"), 0, http.StatusBadRequest},
{"overflow id", requestWith(ActionResolve, "9223372036854775808"), 0, http.StatusBadRequest},
{"empty argument", requestWith(ActionResolve, ""), 0, http.StatusBadRequest},
{"empty username", requestWith(ActionResolve, "@"), 0, http.StatusBadRequest},
{"too many arguments", requestWith(ActionResolve, "101", "202"), 0, http.StatusBadRequest},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
response, err := Plan(test.request)
if test.wantStatus == http.StatusOK {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if response.Action != ActionResolve || response.TargetUID != test.wantTarget {
t.Fatalf("response = %+v, want target %d", response, test.wantTarget)
}
return
}
assertPolicyStatus(t, err, test.wantStatus)
})
}
}
func TestPlanTargetConflict(t *testing.T) {
cases := []Request{
func() Request {
request := requestWith(ActionResolve, "101")
request.ReplyUID = 202
return request
}(),
func() Request {
request := requestWith(ActionResolve, "@alice")
request.ReplyUID = 202
request.Candidates = []Candidate{{UID: 101, Username: "alice"}}
return request
}(),
func() Request {
request := requestWith(ActionBan, "101")
request.ReplyUID = 202
return request
}(),
}
for _, request := range cases {
_, err := Plan(request)
assertPolicyStatus(t, err, http.StatusBadRequest)
}
}
func TestPlanValidatesSuppliedIDs(t *testing.T) {
badCandidate := requestWith(ActionResolve, "alice")
badCandidate.Candidates = []Candidate{{UID: 0, Username: "alice"}}
badProtected := requestWith(ActionResolve, "101")
badProtected.ProtectedUIDs = []int64{-1}
badReply := requestWith(ActionResolve)
badReply.ReplyUID = -7
for _, request := range []Request{badCandidate, badProtected, badReply} {
_, err := Plan(request)
assertPolicyStatus(t, err, http.StatusBadRequest)
}
}
func TestPlanProtectedTargets(t *testing.T) {
protected := []int64{101}
for _, action := range []string{ActionBan, ActionKick} {
request := requestWith(action, "101")
request.ProtectedUIDs = protected
_, err := Plan(request)
assertPolicyStatus(t, err, http.StatusForbidden)
}
for _, action := range []string{ActionUnban, ActionUnmute} {
request := requestWith(action, "101")
request.ProtectedUIDs = protected
response, err := Plan(request)
if err != nil {
t.Fatalf("%s protected target should be allowed: %v", action, err)
}
if response.TargetUID != 101 {
t.Fatalf("%s target = %d, want 101", action, response.TargetUID)
}
}
muteRequest := requestWith(ActionMute, "101", "2h")
muteRequest.ProtectedUIDs = protected
_, err := Plan(muteRequest)
assertPolicyStatus(t, err, http.StatusForbidden)
unprotected := requestWith(ActionBan, "102")
unprotected.ProtectedUIDs = protected
response, err := Plan(unprotected)
if err != nil {
t.Fatalf("unprotected target: %v", err)
}
if response.TargetUID != 102 {
t.Fatalf("unprotected target = %d, want 102", response.TargetUID)
}
}
func TestPlanMuteRequiresSupergroup(t *testing.T) {
for _, action := range []string{ActionMute, ActionUnmute} {
for _, chatType := range []string{"group", "private", "channel", ""} {
request := requestWith(action, "101")
request.ChatType = chatType
_, err := Plan(request)
assertPolicyStatus(t, err, http.StatusBadRequest)
}
}
request := requestWith(ActionMute, "101")
request.ChatType = "SUPERGROUP"
response, err := Plan(request)
if err != nil {
t.Fatalf("case-insensitive supergroup: %v", err)
}
if response.DurationSeconds != DefaultMuteDuration {
t.Fatalf("duration = %d, want %d", response.DurationSeconds, DefaultMuteDuration)
}
}
func TestPlanMuteDurations(t *testing.T) {
muteReply := func(uid int64, args ...string) Request {
request := requestWith(ActionMute, args...)
request.ReplyUID = uid
return request
}
candidates := []Candidate{{UID: 101, Username: "Alice"}, {UID: 202, Username: "bob"}}
namedExplicit := requestWith(ActionMute, "@alice", "2h")
namedExplicit.Candidates = candidates
bareNamed := requestWith(ActionMute, "alice")
bareNamed.Candidates = candidates
namedReplyDuration := muteReply(303, "1h30m")
tests := []struct {
name string
request Request
wantTarget int64
wantDur int64
wantStatus int
}{
{"reply default", muteReply(101), 101, DefaultMuteDuration, http.StatusOK},
{"reply duration", muteReply(101, "2h"), 101, 7200, http.StatusOK},
{"reply bare minutes", muteReply(101, "90"), 101, 5400, http.StatusOK},
{"reply compound", namedReplyDuration, 303, 5400, http.StatusOK},
{"reply two minutes", muteReply(101, "2"), 101, 120, http.StatusOK},
{"explicit duration", requestWith(ActionMute, "101", "45m"), 101, 2700, http.StatusOK},
{"explicit compound", requestWith(ActionMute, "101", "1h30m"), 101, 5400, http.StatusOK},
{"explicit bare minutes", requestWith(ActionMute, "101", "5"), 101, 300, http.StatusOK},
{"explicit username", namedExplicit, 101, 7200, http.StatusOK},
{"bare username default", bareNamed, 101, DefaultMuteDuration, http.StatusOK},
{"numeric target default", requestWith(ActionMute, "202"), 202, DefaultMuteDuration, http.StatusOK},
{"max duration", requestWith(ActionMute, "101", "365d"), 101, MaxDuration, http.StatusOK},
{"min duration", requestWith(ActionMute, "101", "30s"), 101, 30, http.StatusOK},
{"duration only", requestWith(ActionMute, "2h"), 0, 0, http.StatusBadRequest},
{"missing everything", requestWith(ActionMute), 0, 0, http.StatusBadRequest},
{"reply plus name", muteReply(101, "@alice"), 0, 0, http.StatusBadRequest},
{"reply plus numeric duration", muteReply(101, "202"), 101, 12120, http.StatusOK},
{"reply plus bad name", muteReply(101, "alice"), 0, 0, http.StatusBadRequest},
{"two numbers explicit", requestWith(ActionMute, "101", "202"), 101, 12120, http.StatusOK},
{"two targets with reply", muteReply(101, "202", "2h"), 0, 0, http.StatusBadRequest},
{"too many", requestWith(ActionMute, "101", "2h", "extra"), 0, 0, http.StatusBadRequest},
{"malformed duration", requestWith(ActionMute, "101", "1x"), 0, 0, http.StatusBadRequest},
{"malformed reply duration", muteReply(101, "1x"), 0, 0, http.StatusBadRequest},
{"zero reply duration", muteReply(101, "0"), 0, 0, http.StatusBadRequest},
{"zero target", requestWith(ActionMute, "0"), 0, 0, http.StatusBadRequest},
{"negative target", requestWith(ActionMute, "-101"), 0, 0, http.StatusBadRequest},
{"zero duration", requestWith(ActionMute, "101", "0s"), 0, 0, http.StatusBadRequest},
{"short duration", requestWith(ActionMute, "101", "29s"), 0, 0, http.StatusBadRequest},
{"long duration", requestWith(ActionMute, "101", "366d"), 0, 0, http.StatusBadRequest},
{"unknown username", requestWith(ActionMute, "@carol", "1h"), 0, 0, http.StatusBadRequest},
{"empty argument", requestWith(ActionMute, ""), 0, 0, http.StatusBadRequest},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
response, err := Plan(test.request)
if test.wantStatus != http.StatusOK {
assertPolicyStatus(t, err, test.wantStatus)
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if response.Action != ActionMute || response.TargetUID != test.wantTarget || response.DurationSeconds != test.wantDur {
t.Fatalf("response = %+v, want target %d duration %d", response, test.wantTarget, test.wantDur)
}
})
}
}
func TestPlanSetup(t *testing.T) {
response, err := Plan(requestWith(ActionSetup))
if err != nil {
t.Fatalf("setup: %v", err)
}
if response.Action != ActionSetup || response.TargetUID != 0 || response.DurationSeconds != 0 || response.Mode != "" {
t.Fatalf("setup response = %+v", response)
}
_, err = Plan(requestWith(ActionSetup, "extra"))
assertPolicyStatus(t, err, http.StatusBadRequest)
}
func TestPlanChatMode(t *testing.T) {
for _, mode := range []string{"quiet", "mentions", "replies", "QUIET", " Mentions "} {
response, err := Plan(requestWith(ActionChatMode, mode))
if err != nil {
t.Fatalf("chatmode %q: %v", mode, err)
}
want := asciiLower(strings.TrimSpace(mode))
if response.Action != ActionChatMode || response.Mode != want || response.TargetUID != 0 {
t.Fatalf("chatmode %q response = %+v, want %q", mode, response, want)
}
}
for _, request := range []Request{
requestWith(ActionChatMode),
requestWith(ActionChatMode, "silent"),
requestWith(ActionChatMode, "quiet", "mentions"),
requestWith(ActionChatMode, ""),
} {
_, err := Plan(request)
assertPolicyStatus(t, err, http.StatusBadRequest)
}
}
func TestPlanActionNormalization(t *testing.T) {
request := requestWith(" BAN ", "101")
response, err := Plan(request)
if err != nil {
t.Fatalf("uppercase action: %v", err)
}
if response.Action != ActionBan || response.TargetUID != 101 {
t.Fatalf("uppercase action response = %+v", response)
}
for _, action := range []string{"", "nope", "mute "} {
if action == "mute " {
request = requestWith(action, "101")
response, err = Plan(request)
if err != nil {
t.Fatalf("padded mute: %v", err)
}
if response.Action != ActionMute {
t.Fatalf("padded mute response = %+v", response)
}
continue
}
_, err = Plan(requestWith(action, "101"))
assertPolicyStatus(t, err, http.StatusBadRequest)
}
}
func TestPlanBanAndUnbanResponses(t *testing.T) {
for _, action := range []string{ActionBan, ActionUnban, ActionKick, ActionUnmute} {
response, err := Plan(requestWith(action, "101"))
if err != nil {
t.Fatalf("%s: %v", action, err)
}
if response.Action != action || response.TargetUID != 101 || response.DurationSeconds != 0 || response.Mode != "" || response.Reason != "" {
t.Fatalf("%s response = %+v", action, response)
}
}
}
func assertPolicyStatus(t *testing.T, err error, status int) {
t.Helper()
if err == nil {
t.Fatalf("error = nil, want status %d", status)
}
var policyErr *PolicyError
if !errors.As(err, &policyErr) {
t.Fatalf("error type = %T, want *PolicyError (%v)", err, err)
}
if policyErr.Status != status {
t.Fatalf("status = %d, want %d (message %q)", policyErr.Status, status, policyErr.Message)
}
if policyErr.Message == "" {
t.Fatal("empty Russian error message")
}
}