divers refacto

This commit is contained in:
Valentin Carroy 2024-09-13 09:12:16 +02:00
parent 1139bfe73f
commit e90b6a57d8
6 changed files with 84 additions and 26 deletions

View File

@ -5,6 +5,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log/slog"
"net/http" "net/http"
"time" "time"
@ -34,8 +35,8 @@ func (s *Server) Run(ctx context.Context) {
w.Write([]byte("root.")) w.Write([]byte("root."))
}) })
r.Get(s.baseUrl+"/request", s.requestHandler) r.Get(s.baseUrl+"/request", s.requestHandler)
r.Get(s.baseUrl+"/verify", s.submitHandler) r.Post(s.baseUrl+"/verify", s.submitHandler)
r.Get(s.baseUrl+"/verify-spam-filter", s.submitSpamFilterHandler) r.Post(s.baseUrl+"/verify-spam-filter", s.submitSpamFilterHandler)
logger.Info(ctx, "altcha server listening on port "+s.port) logger.Info(ctx, "altcha server listening on port "+s.port)
if err := http.ListenAndServe(":"+s.port, r); err != nil { if err := http.ListenAndServe(":"+s.port, r); err != nil {
@ -48,6 +49,7 @@ func (s *Server) requestHandler(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
http.Error(w, fmt.Sprintf("Failed to create challenge : %s", err), http.StatusInternalServerError) http.Error(w, fmt.Sprintf("Failed to create challenge : %s", err), http.StatusInternalServerError)
slog.Error(err.Error())
return return
} }
@ -100,16 +102,20 @@ func (s *Server) submitSpamFilterHandler(w http.ResponseWriter, r *http.Request)
formData, err := formToMap(r) formData, err := formToMap(r)
if err != nil { if err != nil {
http.Error(w, "Cannot read form data", http.StatusBadRequest) http.Error(w, "Cannot read form data", http.StatusBadRequest)
slog.Error(err.Error())
return
} }
payload := r.FormValue("altcha") payload := r.FormValue("altcha")
if payload == "" { if payload == "" {
http.Error(w, "Atlcha payload missing", http.StatusBadRequest) http.Error(w, "Atlcha payload missing", http.StatusBadRequest)
return
} }
verified, verificationData, err := s.client.VerifyServerSignature(payload) verified, verificationData, err := s.client.VerifyServerSignature(payload)
if err != nil || !verified { if err != nil || !verified {
http.Error(w, "Invalid Altcha payload", http.StatusBadRequest) http.Error(w, "Invalid Altcha payload", http.StatusBadRequest)
slog.Error(err.Error())
return return
} }
@ -123,6 +129,7 @@ func (s *Server) submitSpamFilterHandler(w http.ResponseWriter, r *http.Request)
verified, err := s.client.VerifyFieldsHash(formData, verificationData.Fields, verificationData.FieldsHash) verified, err := s.client.VerifyFieldsHash(formData, verificationData.Fields, verificationData.FieldsHash)
if err != nil || !verified { if err != nil || !verified {
http.Error(w, "Invalid fields hash", http.StatusBadRequest) http.Error(w, "Invalid fields hash", http.StatusBadRequest)
slog.Error(err.Error())
return return
} }
} }
@ -168,12 +175,21 @@ func formToMap(r *http.Request) (map[string][]string, error) {
return r.Form, nil return r.Form, nil
} }
func NewServer(cfg config.Config) *Server { func NewServer(cfg config.Config) (*Server, error) {
client := *client.NewClient(cfg.HmacKey, cfg.MaxNumber, cfg.Algorithm, cfg.Salt, cfg.Expire, cfg.CheckExpire) expirationDuration, err := time.ParseDuration(cfg.Expire+"s")
if err != nil {
fmt.Printf("%+v\n", err)
}
client, err := client.New(cfg.HmacKey, cfg.MaxNumber, cfg.Algorithm, cfg.Salt, expirationDuration, cfg.CheckExpire)
if err != nil {
return &Server{}, err
}
return &Server { return &Server {
baseUrl: cfg.BaseUrl, baseUrl: cfg.BaseUrl,
port: cfg.Port, port: cfg.Port,
client: client, client: *client,
} }, nil
} }

View File

@ -1,6 +1,7 @@
package client package client
import ( import (
"errors"
"time" "time"
"github.com/altcha-org/altcha-lib-go" "github.com/altcha-org/altcha-lib-go"
@ -11,13 +12,13 @@ type Client struct {
maxNumber int64 maxNumber int64
algorithm altcha.Algorithm algorithm altcha.Algorithm
salt string salt string
expire string expire time.Duration
checkExpire bool checkExpire bool
} }
func NewClient(hmacKey string, maxNumber int64, algorithm string, salt string, expire string, checkExpire bool) *Client { func New(hmacKey string, maxNumber int64, algorithm string, salt string, expire time.Duration, checkExpire bool) (*Client, error) {
if len(hmacKey) == 0 { if len(hmacKey) == 0 {
panic("HMAC key not found in env") return &Client{}, errors.New("HMAC key not found")
} }
return &Client { return &Client {
hmacKey: hmacKey, hmacKey: hmacKey,
@ -26,12 +27,11 @@ func NewClient(hmacKey string, maxNumber int64, algorithm string, salt string, e
salt: salt, salt: salt,
expire: expire, expire: expire,
checkExpire: checkExpire, checkExpire: checkExpire,
} }, nil
} }
func (c *Client) Generate() (altcha.Challenge, error) { func (c *Client) Generate() (altcha.Challenge, error) {
expirationDuration, _ := time.ParseDuration(c.expire+"s") expiration := time.Now().Add(c.expire)
expiration := time.Now().Add(expirationDuration)
options := altcha.ChallengeOptions{ options := altcha.ChallengeOptions{
HMACKey: c.hmacKey, HMACKey: c.hmacKey,

View File

@ -2,6 +2,7 @@ package command
import ( import (
"fmt" "fmt"
"time"
"forge.cadoles.com/cadoles/altcha-server/internal/client" "forge.cadoles.com/cadoles/altcha-server/internal/client"
"forge.cadoles.com/cadoles/altcha-server/internal/command/common" "forge.cadoles.com/cadoles/altcha-server/internal/command/common"
@ -21,12 +22,23 @@ func GenerateCommand() *cli.Command {
Action: func(ctx *cli.Context) error { Action: func(ctx *cli.Context) error {
cfg := config.Config{} cfg := config.Config{}
if err := env.Parse(&cfg); err != nil { if err := env.Parse(&cfg); err != nil {
fmt.Printf("%+v\n", err) logger.Error(ctx.Context, err.Error())
return err
} }
c := client.NewClient(cfg.HmacKey, cfg.MaxNumber, cfg.Algorithm, cfg.Salt, cfg.Expire, cfg.CheckExpire) expirationDuration, err := time.ParseDuration(cfg.Expire+"s")
if err != nil {
logger.Error(ctx.Context, err.Error())
return err
}
challenge, err := c.Generate() client, err := client.New(cfg.HmacKey, cfg.MaxNumber, cfg.Algorithm, cfg.Salt, expirationDuration, cfg.CheckExpire)
if err != nil {
logger.Error(ctx.Context, err.Error())
return err
}
challenge, err := client.Generate()
if err != nil { if err != nil {
logger.Error(ctx.Context, err.Error()) logger.Error(ctx.Context, err.Error())
return err return err

View File

@ -1,13 +1,12 @@
package command package command
import ( import (
"fmt"
"forge.cadoles.com/cadoles/altcha-server/internal/api" "forge.cadoles.com/cadoles/altcha-server/internal/api"
"forge.cadoles.com/cadoles/altcha-server/internal/command/common" "forge.cadoles.com/cadoles/altcha-server/internal/command/common"
"forge.cadoles.com/cadoles/altcha-server/internal/config" "forge.cadoles.com/cadoles/altcha-server/internal/config"
"github.com/caarlos0/env/v11" "github.com/caarlos0/env/v11"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"gitlab.com/wpetit/goweb/logger"
) )
func RunCommand() *cli.Command { func RunCommand() *cli.Command {
@ -20,10 +19,16 @@ func RunCommand() *cli.Command {
Action: func(ctx *cli.Context) error { Action: func(ctx *cli.Context) error {
cfg := config.Config{} cfg := config.Config{}
if err := env.Parse(&cfg); err != nil { if err := env.Parse(&cfg); err != nil {
fmt.Printf("%+v\n", err) logger.Error(ctx.Context, err.Error())
return err
}
server, err := api.NewServer(cfg)
if err != nil {
logger.Error(ctx.Context, err.Error())
return err
} }
api.NewServer(cfg).Run(ctx.Context) server.Run(ctx.Context)
return nil return nil
}, },
} }

View File

@ -2,6 +2,7 @@ package command
import ( import (
"fmt" "fmt"
"time"
"forge.cadoles.com/cadoles/altcha-server/internal/client" "forge.cadoles.com/cadoles/altcha-server/internal/client"
"forge.cadoles.com/cadoles/altcha-server/internal/command/common" "forge.cadoles.com/cadoles/altcha-server/internal/command/common"
@ -23,16 +24,26 @@ func SolveCommand() *cli.Command {
Action: func(ctx *cli.Context) error { Action: func(ctx *cli.Context) error {
cfg := config.Config{} cfg := config.Config{}
if err := env.Parse(&cfg); err != nil { if err := env.Parse(&cfg); err != nil {
fmt.Printf("%+v\n", err) logger.Error(ctx.Context, err.Error())
return err
} }
challenge := ctx.Args().Get(0) challenge := ctx.Args().Get(0)
salt := ctx.Args().Get(1) salt := ctx.Args().Get(1)
c := client.NewClient(cfg.HmacKey, cfg.MaxNumber, cfg.Algorithm, salt, cfg.Expire, cfg.CheckExpire) expirationDuration, err := time.ParseDuration(cfg.Expire+"s")
if err != nil {
logger.Error(ctx.Context, err.Error())
return err
}
client, err := client.New(cfg.HmacKey, cfg.MaxNumber, cfg.Algorithm, salt, expirationDuration, cfg.CheckExpire)
if err != nil {
logger.Error(ctx.Context, err.Error())
return err
}
solution, err := c.Solve(challenge) solution, err := client.Solve(challenge)
if err != nil { if err != nil {
logger.Error(ctx.Context, err.Error()) logger.Error(ctx.Context, err.Error())

View File

@ -3,6 +3,7 @@ package command
import ( import (
"fmt" "fmt"
"strconv" "strconv"
"time"
"forge.cadoles.com/cadoles/altcha-server/internal/client" "forge.cadoles.com/cadoles/altcha-server/internal/client"
"forge.cadoles.com/cadoles/altcha-server/internal/command/common" "forge.cadoles.com/cadoles/altcha-server/internal/command/common"
@ -10,6 +11,7 @@ import (
"github.com/altcha-org/altcha-lib-go" "github.com/altcha-org/altcha-lib-go"
"github.com/caarlos0/env/v11" "github.com/caarlos0/env/v11"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"gitlab.com/wpetit/goweb/logger"
) )
func VerifyCommand() *cli.Command { func VerifyCommand() *cli.Command {
@ -24,7 +26,8 @@ func VerifyCommand() *cli.Command {
Action: func(ctx *cli.Context) error { Action: func(ctx *cli.Context) error {
cfg := config.Config{} cfg := config.Config{}
if err := env.Parse(&cfg); err != nil { if err := env.Parse(&cfg); err != nil {
fmt.Printf("%+v\n", err) logger.Error(ctx.Context, err.Error())
return err
} }
challenge := ctx.Args().Get(0) challenge := ctx.Args().Get(0)
@ -32,7 +35,17 @@ func VerifyCommand() *cli.Command {
signature := ctx.Args().Get(2) signature := ctx.Args().Get(2)
solution, _ := strconv.ParseInt(ctx.Args().Get(3), 10, 64) solution, _ := strconv.ParseInt(ctx.Args().Get(3), 10, 64)
c := client.NewClient(cfg.HmacKey, cfg.MaxNumber, cfg.Algorithm, cfg.Salt, cfg.Expire, cfg.CheckExpire) expirationDuration, err := time.ParseDuration(cfg.Expire+"s")
if err != nil {
logger.Error(ctx.Context, err.Error())
return err
}
client, err := client.New(cfg.HmacKey, cfg.MaxNumber, cfg.Algorithm, cfg.Salt, expirationDuration, cfg.CheckExpire)
if err != nil {
logger.Error(ctx.Context, err.Error())
return err
}
payload := altcha.Payload{ payload := altcha.Payload{
Algorithm: cfg.Algorithm, Algorithm: cfg.Algorithm,
@ -42,9 +55,10 @@ func VerifyCommand() *cli.Command {
Signature: signature, Signature: signature,
} }
verified, err := c.VerifySolution(payload) verified, err := client.VerifySolution(payload)
if err != nil { if err != nil {
logger.Error(ctx.Context, err.Error())
return err return err
} }