threshold.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package config
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/TecharoHQ/anubis"
  6. )
  7. var (
  8. ErrNoThresholdRulesDefined = errors.New("config: no thresholds defined")
  9. ErrThresholdMustHaveName = errors.New("config.Threshold: must set name")
  10. ErrThresholdMustHaveExpression = errors.New("config.Threshold: must set expression")
  11. ErrThresholdChallengeMustHaveChallenge = errors.New("config.Threshold: a threshold with the CHALLENGE action must have challenge set")
  12. ErrThresholdCannotHaveWeighAction = errors.New("config.Threshold: a threshold cannot have the WEIGH action")
  13. DefaultThresholds = []Threshold{
  14. {
  15. Name: "legacy-anubis-behaviour",
  16. Expression: &ExpressionOrList{
  17. Expression: "weight > 0",
  18. },
  19. Action: RuleChallenge,
  20. Challenge: &ChallengeRules{
  21. Algorithm: "fast",
  22. Difficulty: anubis.DefaultDifficulty,
  23. },
  24. },
  25. }
  26. )
  27. type Threshold struct {
  28. Expression *ExpressionOrList `json:"expression" yaml:"expression"`
  29. Challenge *ChallengeRules `json:"challenge" yaml:"challenge"`
  30. Name string `json:"name" yaml:"name"`
  31. Action Rule `json:"action" yaml:"action"`
  32. }
  33. func (t Threshold) Valid() error {
  34. var errs []error
  35. if len(t.Name) == 0 {
  36. errs = append(errs, ErrThresholdMustHaveName)
  37. }
  38. if t.Expression == nil {
  39. errs = append(errs, ErrThresholdMustHaveExpression)
  40. }
  41. if t.Expression != nil {
  42. if err := t.Expression.Valid(); err != nil {
  43. errs = append(errs, err)
  44. }
  45. }
  46. if err := t.Action.Valid(); err != nil {
  47. errs = append(errs, err)
  48. }
  49. if t.Action == RuleWeigh {
  50. errs = append(errs, ErrThresholdCannotHaveWeighAction)
  51. }
  52. if t.Action == RuleChallenge && t.Challenge == nil {
  53. errs = append(errs, ErrThresholdChallengeMustHaveChallenge)
  54. }
  55. if t.Challenge != nil {
  56. if err := t.Challenge.Valid(); err != nil {
  57. errs = append(errs, err)
  58. }
  59. }
  60. if len(errs) != 0 {
  61. return fmt.Errorf("config: threshold entry for %q is not valid:\n%w", t.Name, errors.Join(errs...))
  62. }
  63. return nil
  64. }