Compare commits

..

8 Commits

8 changed files with 103 additions and 132 deletions

View File

@ -2,7 +2,6 @@ package api
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log/slog"
@ -11,6 +10,7 @@ import (
"forge.cadoles.com/cadoles/altcha-server/internal/client"
"forge.cadoles.com/cadoles/altcha-server/internal/config"
"github.com/altcha-org/altcha-lib-go"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
@ -21,9 +21,14 @@ type Server struct {
baseUrl string
port string
client client.Client
config config.Config
}
func (s *Server) Run(ctx context.Context) {
if s.config.Debug {
slog.SetLogLoggerLevel(slog.LevelDebug)
}
r := chi.NewRouter()
r.Use(middleware.Logger)
@ -36,8 +41,7 @@ func (s *Server) Run(ctx context.Context) {
})
r.Get(s.baseUrl+"/request", s.requestHandler)
r.Post(s.baseUrl+"/verify", s.submitHandler)
r.Post(s.baseUrl+"/verify-spam-filter", s.submitSpamFilterHandler)
logger.Info(ctx, "altcha server listening on port "+s.port)
if err := http.ListenAndServe(":"+s.port, r); err != nil {
logger.Error(ctx, err.Error())
@ -48,101 +52,55 @@ func (s *Server) requestHandler(w http.ResponseWriter, r *http.Request) {
challenge, err := s.client.Generate()
if err != nil {
slog.Debug("Failed to create challenge,", "error", err)
http.Error(w, fmt.Sprintf("Failed to create challenge : %s", err), http.StatusInternalServerError)
slog.Error(err.Error())
return
}
writeJSON(w, challenge)
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(challenge)
if err != nil {
slog.Debug("Failed to encode JSON", "error", err)
http.Error(w, "Failed to encode JSON", http.StatusInternalServerError)
return
}
}
func (s *Server) submitHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
formData := r.FormValue("altcha")
if formData == "" {
http.Error(w, "Atlcha payload missing", http.StatusBadRequest)
return
}
decodedPayload, err := base64.StdEncoding.DecodeString(formData)
var payload altcha.Payload
err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil {
http.Error(w, "Failed to decode Altcha payload", http.StatusBadRequest)
return
}
var payload map[string]interface{}
if err := json.Unmarshal(decodedPayload, &payload); err != nil {
slog.Debug("Failed to parse Altcha payload,", "error", err)
http.Error(w, "Failed to parse Altcha payload", http.StatusBadRequest)
return
}
verified, err := s.client.VerifySolution(payload)
if err != nil || !verified {
http.Error(w, "Invalid Altcha payload", http.StatusBadRequest)
return
}
writeJSON(w, map[string]interface{}{
"success": true,
"data": formData,
})
}
func (s *Server) submitSpamFilterHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
formData, err := formToMap(r)
if err != nil {
http.Error(w, "Cannot read form data", http.StatusBadRequest)
slog.Error(err.Error())
slog.Debug("Invalid Altcha payload", "error", err)
http.Error(w, "Invalid Altcha payload,", http.StatusBadRequest)
return
}
payload := r.FormValue("altcha")
if payload == "" {
http.Error(w, "Atlcha payload missing", http.StatusBadRequest)
if !verified && !s.config.DisableValidation {
slog.Debug("Invalid solution")
http.Error(w, "Invalid solution", http.StatusBadRequest)
return
}
verified, verificationData, err := s.client.VerifyServerSignature(payload)
if err != nil || !verified {
http.Error(w, "Invalid Altcha payload", http.StatusBadRequest)
slog.Error(err.Error())
return
}
if verificationData.Verified && verificationData.Expire > time.Now().Unix() {
if verificationData.Classification == "BAD" {
http.Error(w, "Classified as spam", http.StatusBadRequest)
return
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
"data": payload,
})
if err != nil {
if s.config.Debug {
slog.Debug("Failed to encode JSON", "error", err)
}
if verificationData.FieldsHash != "" {
verified, err := s.client.VerifyFieldsHash(formData, verificationData.Fields, verificationData.FieldsHash)
if err != nil || !verified {
http.Error(w, "Invalid fields hash", http.StatusBadRequest)
slog.Error(err.Error())
return
}
}
writeJSON(w, map[string]interface{}{
"success": true,
"data": formData,
"verificationData": verificationData,
})
http.Error(w, "Failed to encode JSON", http.StatusInternalServerError)
return
}
http.Error(w, "Invalid Altcha payload", http.StatusBadRequest)
}
func corsMiddleware(next http.Handler) http.Handler {
@ -160,21 +118,6 @@ func corsMiddleware(next http.Handler) http.Handler {
})
}
func writeJSON(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(data); err != nil {
http.Error(w, "Failed to encode JSON", http.StatusInternalServerError)
}
}
func formToMap(r *http.Request) (map[string][]string, error) {
if err := r.ParseForm(); err != nil {
return nil, err
}
return r.Form, nil
}
func NewServer(cfg config.Config) (*Server, error) {
expirationDuration, err := time.ParseDuration(cfg.Expire+"s")
if err != nil {
@ -191,5 +134,6 @@ func NewServer(cfg config.Config) (*Server, error) {
baseUrl: cfg.BaseUrl,
port: cfg.Port,
client: *client,
config: cfg,
}, nil
}

View File

@ -2,7 +2,6 @@ package command
import (
"context"
"fmt"
"os"
"sort"
@ -17,27 +16,6 @@ func Main(commands ...*cli.Command) {
Name: "altcha-server",
Usage: "create challenges and validate solutions for atlcha captcha",
Commands: commands,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "debug",
EnvVars: []string{"ALTCHA_DEBUG"},
Value: false,
},
},
}
app.ExitErrHandler = func (ctx *cli.Context, err error) {
if err == nil {
return
}
debug := ctx.Bool("debug")
if !debug {
fmt.Printf("[ERROR] %v\n", err)
} else {
fmt.Printf("%+v", err)
}
}
sort.Sort(cli.FlagsByName(app.Flags))

View File

@ -2,7 +2,6 @@ package command
import (
"forge.cadoles.com/cadoles/altcha-server/internal/api"
"forge.cadoles.com/cadoles/altcha-server/internal/command/common"
"forge.cadoles.com/cadoles/altcha-server/internal/config"
"github.com/caarlos0/env/v11"
"github.com/urfave/cli/v2"
@ -10,12 +9,9 @@ import (
)
func RunCommand() *cli.Command {
flags := common.Flags()
return &cli.Command{
Name: "run",
Usage: "run the atlcha api server",
Flags: flags,
Action: func(ctx *cli.Context) error {
cfg := config.Config{}
if err := env.Parse(&cfg); err != nil {

View File

@ -5,7 +5,6 @@ import (
"time"
"forge.cadoles.com/cadoles/altcha-server/internal/client"
"forge.cadoles.com/cadoles/altcha-server/internal/command/common"
"forge.cadoles.com/cadoles/altcha-server/internal/config"
"github.com/caarlos0/env/v11"
"github.com/urfave/cli/v2"
@ -13,12 +12,9 @@ import (
)
func SolveCommand() *cli.Command {
flags := common.Flags()
return &cli.Command{
Name: "solve",
Usage: "solve the challenge and return the solution",
Flags: flags,
Args: true,
ArgsUsage: "[CHALLENGE] [SALT]",
Action: func(ctx *cli.Context) error {

View File

@ -6,7 +6,6 @@ import (
"time"
"forge.cadoles.com/cadoles/altcha-server/internal/client"
"forge.cadoles.com/cadoles/altcha-server/internal/command/common"
"forge.cadoles.com/cadoles/altcha-server/internal/config"
"github.com/altcha-org/altcha-lib-go"
"github.com/caarlos0/env/v11"
@ -15,12 +14,9 @@ import (
)
func VerifyCommand() *cli.Command {
flags := common.Flags()
return &cli.Command{
Name: "verify",
Usage: "verify the solution",
Flags: flags,
Args: true,
ArgsUsage: "[challenge] [salt] [signature] [solution]",
Action: func(ctx *cli.Context) error {

View File

@ -1,12 +1,14 @@
package config
type Config struct {
BaseUrl string `env:"ALTCHA_BASE_URL" envDefault:""`
Port string `env:"ALTCHA_PORT" envDefault:"3333"`
HmacKey string `env:"ALTCHA_HMAC_KEY"`
MaxNumber int64 `env:"ALTCHA_MAX_NUMBER" envDefault:"1000000"`
Algorithm string `env:"ALTCHA_ALGORITHM" envDefault:"SHA-256"`
Salt string `env:"ALTCHA_SALT"`
Expire string `env:"ALTCHA_EXPIRE" envDefault:"600"`
CheckExpire bool `env:"ALTCHA_CHECK_EXPIRE" envDefault:"1"`
BaseUrl string `env:"ALTCHA_BASE_URL" envDefault:""`
Port string `env:"ALTCHA_PORT" envDefault:"3333"`
HmacKey string `env:"ALTCHA_HMAC_KEY"`
MaxNumber int64 `env:"ALTCHA_MAX_NUMBER" envDefault:"1000000"`
Algorithm string `env:"ALTCHA_ALGORITHM" envDefault:"SHA-256"`
Salt string `env:"ALTCHA_SALT"`
Expire string `env:"ALTCHA_EXPIRE" envDefault:"600"`
CheckExpire bool `env:"ALTCHA_CHECK_EXPIRE" envDefault:"1"`
Debug bool `env:"ALTCHA_DEBUG" envDefault:"false"`
DisableValidation bool `env:"ALTCHA_DISABLE_VALIDATION" envDefault:"false"`
}

9
misc/k6/README.md Normal file
View File

@ -0,0 +1,9 @@
# K6 - Load Test
Very basic load testing script for [k6](https://k6.io/).
## How to run
```shell
k6 run -e LOAD_TEST_URL={altcha-api-url} TestChallenge.js
```

50
misc/k6/TestChallenge.js Normal file
View File

@ -0,0 +1,50 @@
import { check, group } from 'k6';
import http from 'k6/http'
export const options = {
scenarios: {
load: {
vus: 10,
iterations: 10,
executor: 'per-vu-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
}
};
http.setResponseCallback(
http.expectedStatuses(200)
);
export default function () {
let response;
group('Request challenge', function () {
response = http.get(`${__ENV.LOAD_TEST_URL}request`);
check(response, {
'is status 200': (r) => r.status === 200,
'Contenu souhaité': r => r.body.includes('algorithm') && r.body.includes('challenge') && r.body.includes('maxNumber') && r.body.includes('salt') && r.body.includes('signature'),
});
})
group('Verify challenge', function () {
const data = {"challenge":"d5656d52c5eadce5117024fbcafc706aad397c7befa17804d73c992d966012a8","salt":"8ec1b7ed694331baeb7416d9?expires=1727963398","signature":"781014d0a7ace7e7ae9d12e2d5c0204b60a8dbf42daa352ab40ab582b03a9dc6","number":219718,};
response = http.post(`${__ENV.LOAD_TEST_URL}verify`, JSON.stringify(data),
{
headers: { 'Content-Type': 'application/json' },
});
check(response, {
'is status 200': (r) => r.status === 200,
'Challenge verified': (r) => r.body.includes('true'),
});
})
}