336 lines
9.8 KiB
Go
336 lines
9.8 KiB
Go
package httpserver
|
|
|
|
import (
|
|
"encoding/json"
|
|
"go/ast"
|
|
"go/parser"
|
|
"go/token"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
|
|
"Rezina-Backend/docs"
|
|
openapiswag "github.com/go-openapi/swag"
|
|
)
|
|
|
|
type documentedParameter struct {
|
|
Name string `json:"name"`
|
|
In string `json:"in"`
|
|
Required bool `json:"required"`
|
|
Type string `json:"type"`
|
|
Schema map[string]any `json:"schema"`
|
|
}
|
|
type documentedOperation struct {
|
|
Summary string `json:"summary"`
|
|
Parameters []documentedParameter `json:"parameters"`
|
|
Responses map[string]json.RawMessage `json:"responses"`
|
|
Security []map[string][]string `json:"security"`
|
|
}
|
|
type swaggerRouteContract struct {
|
|
Method, Path, Handler string
|
|
Bearer, WebSocket bool
|
|
}
|
|
|
|
var fiberPathParameter = regexp.MustCompile(`:(\w+)(?:<[^>]+>)?`)
|
|
var swaggerPathParameter = regexp.MustCompile(`\{([^}]+)\}`)
|
|
|
|
func registeredSwaggerContracts(t *testing.T) []swaggerRouteContract {
|
|
t.Helper()
|
|
var result []swaggerRouteContract
|
|
for _, audience := range []string{"admin", "client", "integration"} {
|
|
file, err := parser.ParseFile(token.NewFileSet(), "routes_"+audience+".go", nil, 0)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
ast.Inspect(file, func(node ast.Node) bool {
|
|
call, ok := node.(*ast.CallExpr)
|
|
if !ok {
|
|
return true
|
|
}
|
|
selector, ok := call.Fun.(*ast.SelectorExpr)
|
|
if !ok {
|
|
return true
|
|
}
|
|
receiver, ok := selector.X.(*ast.Ident)
|
|
if !ok || receiver.Name != "api" {
|
|
return true
|
|
}
|
|
method := strings.ToLower(selector.Sel.Name)
|
|
switch method {
|
|
case "get", "post", "put", "patch", "delete":
|
|
default:
|
|
return true
|
|
}
|
|
literal, ok := call.Args[0].(*ast.BasicLit)
|
|
if !ok {
|
|
t.Fatal("API route must use a string literal")
|
|
}
|
|
path, err := strconv.Unquote(literal.Value)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
prefix := "/api/v1"
|
|
if audience == "admin" {
|
|
prefix += "/admin"
|
|
}
|
|
contract := swaggerRouteContract{Method: method, Path: prefix + fiberPathParameter.ReplaceAllString(path, "{$1}")}
|
|
for _, argument := range call.Args[1:] {
|
|
member, ok := argument.(*ast.SelectorExpr)
|
|
if !ok {
|
|
if factory, ok := argument.(*ast.CallExpr); ok {
|
|
member, _ = factory.Fun.(*ast.SelectorExpr)
|
|
}
|
|
}
|
|
if member == nil {
|
|
continue
|
|
}
|
|
if strings.HasSuffix(member.Sel.Name, "WebsocketAuthMiddleware") {
|
|
contract.WebSocket = true
|
|
}
|
|
if member.Sel.Name == "adminAuthMiddleware" || member.Sel.Name == "clientAuthMiddleware" {
|
|
contract.Bearer = true
|
|
}
|
|
if owner, ok := member.X.(*ast.Ident); ok && (owner.Name == "h" || owner.Name == "handlers") {
|
|
contract.Handler = member.Sel.Name
|
|
}
|
|
}
|
|
result = append(result, contract)
|
|
return true
|
|
})
|
|
}
|
|
result = append(result, swaggerRouteContract{Method: "get", Path: "/payment/success", Handler: "HandleChapaSuccessPage"})
|
|
result = append(result, swaggerRouteContract{Method: "get", Path: "/", Handler: "documentServiceInfo"})
|
|
result = append(result, swaggerRouteContract{Method: "get", Path: "/api/v1/", Handler: "documentAPIIndex"})
|
|
return result
|
|
}
|
|
|
|
func TestSwaggerMatchesRegisteredRoutes(t *testing.T) {
|
|
var spec struct {
|
|
Paths map[string]map[string]documentedOperation `json:"paths"`
|
|
SecurityDefinitions map[string]any `json:"securityDefinitions"`
|
|
}
|
|
if err := json.Unmarshal([]byte(docs.SwaggerInfo.ReadDoc()), &spec); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
expected := map[string]bool{}
|
|
for _, route := range registeredSwaggerContracts(t) {
|
|
key := strings.ToUpper(route.Method) + " " + route.Path
|
|
expected[key] = true
|
|
t.Run(key, func(t *testing.T) {
|
|
operation, ok := spec.Paths[route.Path][route.Method]
|
|
if !ok {
|
|
t.Fatal("registered operation is missing from Swagger")
|
|
}
|
|
if operation.Summary == "" {
|
|
t.Error("operation has no summary")
|
|
}
|
|
if len(operation.Responses) == 0 {
|
|
t.Error("operation has no responses")
|
|
}
|
|
success := false
|
|
for code := range operation.Responses {
|
|
if strings.HasPrefix(code, "2") || code == "101" || strings.HasPrefix(code, "3") {
|
|
success = true
|
|
}
|
|
}
|
|
if !success {
|
|
t.Error("operation has no documented success response")
|
|
}
|
|
bearer := false
|
|
for _, requirement := range operation.Security {
|
|
for scheme := range requirement {
|
|
if _, exists := spec.SecurityDefinitions[scheme]; !exists {
|
|
t.Errorf("unknown security scheme %s", scheme)
|
|
}
|
|
}
|
|
if _, ok := requirement["Bearer"]; ok {
|
|
bearer = true
|
|
}
|
|
}
|
|
if bearer != route.Bearer {
|
|
t.Errorf("Bearer security=%v; route requires=%v", bearer, route.Bearer)
|
|
}
|
|
actual := map[string]bool{}
|
|
for _, parameter := range operation.Parameters {
|
|
if parameter.In == "path" {
|
|
if !parameter.Required {
|
|
t.Errorf("path parameter %s is optional", parameter.Name)
|
|
}
|
|
if parameter.Type == "" {
|
|
t.Errorf("path parameter %s has no type", parameter.Name)
|
|
}
|
|
actual[parameter.Name] = true
|
|
}
|
|
if parameter.In == "body" && len(parameter.Schema) == 0 {
|
|
t.Error("body parameter has no schema")
|
|
}
|
|
}
|
|
for _, match := range swaggerPathParameter.FindAllStringSubmatch(route.Path, -1) {
|
|
if !actual[match[1]] {
|
|
t.Errorf("missing path parameter %s", match[1])
|
|
}
|
|
delete(actual, match[1])
|
|
}
|
|
for name := range actual {
|
|
t.Errorf("documented path parameter %s does not exist in route", name)
|
|
}
|
|
if route.WebSocket {
|
|
found := false
|
|
for _, parameter := range operation.Parameters {
|
|
if parameter.Name == "token" && parameter.In == "query" && parameter.Required {
|
|
found = true
|
|
}
|
|
}
|
|
if !found {
|
|
t.Error("WebSocket query-token authentication is undocumented")
|
|
}
|
|
if _, exists := operation.Responses["101"]; !exists {
|
|
t.Error("WebSocket upgrade response is undocumented")
|
|
}
|
|
}
|
|
})
|
|
}
|
|
for path, operations := range spec.Paths {
|
|
for method := range operations {
|
|
if !expected[strings.ToUpper(method)+" "+path] {
|
|
t.Errorf("Swagger documents an unregistered operation: %s %s", method, path)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestSwaggerDocumentsParsedRequestBodies(t *testing.T) {
|
|
parsedBodies := map[string]bool{"HandleChapaWebhook": true, "SendSingleEmail": true, "SendBulkEmail": true}
|
|
files, err := filepath.Glob(filepath.Join("handlers", "*.go"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, name := range files {
|
|
if strings.HasSuffix(name, "_test.go") {
|
|
continue
|
|
}
|
|
file, err := parser.ParseFile(token.NewFileSet(), name, nil, 0)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, declaration := range file.Decls {
|
|
fn, ok := declaration.(*ast.FuncDecl)
|
|
if !ok || fn.Recv == nil || fn.Body == nil {
|
|
continue
|
|
}
|
|
ast.Inspect(fn.Body, func(node ast.Node) bool {
|
|
if call, ok := node.(*ast.CallExpr); ok {
|
|
if member, ok := call.Fun.(*ast.SelectorExpr); ok && member.Sel.Name == "BodyParser" {
|
|
parsedBodies[fn.Name.Name] = true
|
|
}
|
|
}
|
|
return true
|
|
})
|
|
}
|
|
}
|
|
var spec struct {
|
|
Paths map[string]map[string]documentedOperation `json:"paths"`
|
|
}
|
|
if err := json.Unmarshal([]byte(docs.SwaggerInfo.ReadDoc()), &spec); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, route := range registeredSwaggerContracts(t) {
|
|
if !parsedBodies[route.Handler] {
|
|
continue
|
|
}
|
|
operation := spec.Paths[route.Path][route.Method]
|
|
found := false
|
|
for _, parameter := range operation.Parameters {
|
|
if parameter.In == "body" || parameter.In == "formData" {
|
|
found = true
|
|
}
|
|
}
|
|
if !found {
|
|
t.Errorf("%s %s parses a request body but documents no body or form fields", route.Method, route.Path)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestGeneratedSwaggerArtifactsStayInSync(t *testing.T) {
|
|
var runtimeDoc map[string]any
|
|
if err := json.Unmarshal([]byte(docs.SwaggerInfo.ReadDoc()), &runtimeDoc); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, name := range []string{"swagger.json", "swagger.yaml"} {
|
|
raw, err := os.ReadFile(filepath.Join("..", "..", "docs", name))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if strings.HasSuffix(name, ".yaml") {
|
|
document, err := openapiswag.BytesToYAMLDoc(raw)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
raw, err = openapiswag.YAMLToJSON(document)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
var exported map[string]any
|
|
if err := json.Unmarshal(raw, &exported); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// Runtime host/scheme placeholders may be omitted in the static exports.
|
|
for _, section := range []string{"swagger", "info", "paths", "definitions", "securityDefinitions"} {
|
|
runtimeJSON, _ := json.Marshal(runtimeDoc[section])
|
|
exportedJSON, _ := json.Marshal(exported[section])
|
|
if string(runtimeJSON) != string(exportedJSON) {
|
|
t.Errorf("%s section %s differs from docs.go; run make swagger", name, section)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func assertSwaggerReferences(t *testing.T, document map[string]any) {
|
|
t.Helper()
|
|
var visit func(any)
|
|
visit = func(value any) {
|
|
switch node := value.(type) {
|
|
case map[string]any:
|
|
if reference, ok := node["$ref"].(string); ok {
|
|
if !strings.HasPrefix(reference, "#/") {
|
|
t.Errorf("unexpected external schema reference: %s", reference)
|
|
} else {
|
|
var current any = document
|
|
for _, segment := range strings.Split(strings.TrimPrefix(reference, "#/"), "/") {
|
|
segment = strings.ReplaceAll(strings.ReplaceAll(segment, "~1", "/"), "~0", "~")
|
|
object, ok := current.(map[string]any)
|
|
if !ok {
|
|
current = nil
|
|
break
|
|
}
|
|
current = object[segment]
|
|
}
|
|
if current == nil {
|
|
t.Errorf("unresolved schema reference: %s", reference)
|
|
}
|
|
}
|
|
}
|
|
for _, child := range node {
|
|
visit(child)
|
|
}
|
|
case []any:
|
|
for _, child := range node {
|
|
visit(child)
|
|
}
|
|
}
|
|
}
|
|
visit(document)
|
|
}
|
|
|
|
func TestSwaggerSchemaReferences(t *testing.T) {
|
|
var document map[string]any
|
|
if err := json.Unmarshal([]byte(docs.SwaggerInfo.ReadDoc()), &document); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
assertSwaggerReferences(t, document)
|
|
}
|