phase 2 testing complete

This commit is contained in:
2026-05-07 00:09:50 +02:00
parent 57991e5406
commit 5d8662595c
27 changed files with 1150 additions and 112 deletions
+66
View File
@@ -0,0 +1,66 @@
package middleware
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"net/http"
)
const csrfCookieName = "fb_csrf"
const csrfHeaderName = "X-CSRF-Token"
// NewCSRFToken generates a cryptographically random CSRF token, sets it as a
// non-HttpOnly cookie (so the SPA can read it), and returns the token value.
func NewCSRFToken(w http.ResponseWriter, secure bool) (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
token := base64.RawURLEncoding.EncodeToString(b)
http.SetCookie(w, &http.Cookie{
Name: csrfCookieName,
Value: token,
Path: "/",
HttpOnly: false, // must be readable by JS for the double-submit pattern
Secure: secure,
SameSite: http.SameSiteLaxMode,
})
return token, nil
}
// CSRF is a middleware that enforces the double-submit cookie pattern for all
// state-mutating requests (POST, PUT, PATCH, DELETE). Safe methods are passed
// through unchanged.
func CSRF(secure bool) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace:
// Safe method — no CSRF validation needed, just pass through.
next.ServeHTTP(w, r)
return
}
cookie, err := r.Cookie(csrfCookieName)
if err != nil || cookie.Value == "" {
http.Error(w, `{"error":"CSRF cookie missing"}`, http.StatusForbidden)
return
}
headerToken := r.Header.Get(csrfHeaderName)
if headerToken == "" {
http.Error(w, `{"error":"X-CSRF-Token header missing"}`, http.StatusForbidden)
return
}
// Constant-time compare prevents timing attacks.
if subtle.ConstantTimeCompare([]byte(cookie.Value), []byte(headerToken)) != 1 {
http.Error(w, `{"error":"CSRF validation failed"}`, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
}
+47 -51
View File
@@ -1,13 +1,13 @@
package api
import (
"encoding/json"
"io/fs"
"net/http"
"github.com/go-chi/chi/v5"
chimiddleware "github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
gcsrf "github.com/gorilla/csrf"
"github.com/gorilla/sessions"
"xorm.io/xorm"
@@ -30,15 +30,7 @@ func New(cfg *config.Config, engine *xorm.Engine, store sessions.Store, staticFi
MaxAge: 300,
}))
csrfMiddleware := gcsrf.Protect(
[]byte(cfg.CSRFSecret),
gcsrf.Secure(!cfg.Debug),
gcsrf.SameSite(gcsrf.SameSiteLaxMode),
gcsrf.ErrorHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, `{"error":"CSRF validation failed"}`, http.StatusForbidden)
})),
)
csrf := middleware.CSRF(!cfg.Debug)
auth := middleware.NewAuth(store)
repoH := handlers.NewRepoHandler(engine, cfg)
@@ -47,57 +39,61 @@ func New(cfg *config.Config, engine *xorm.Engine, store sessions.Store, staticFi
pipeH := handlers.NewPipelineHandler(engine)
wsH := handlers.NewWSHandler()
// Health — no auth, no CSRF
r.Get("/api/v1/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status":"ok"}`))
})
r.Route("/api/v1", func(r chi.Router) {
// CSRF token bootstrap for SPA
r.With(csrfMiddleware).Get("/api/v1/csrf", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-CSRF-Token", gcsrf.Token(r))
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"ok":true}`))
})
// ── Public ────────────────────────────────────────────────────────────
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status":"ok"}`))
})
// Auth (CSRF protected, no session required)
r.With(csrfMiddleware).Route("/api/v1/auth", func(r chi.Router) {
r.Post("/login", userH.Login)
r.Post("/logout", userH.Logout)
r.Post("/register", userH.Register)
})
// Generates a CSRF token + cookie. SPA calls this once on load.
r.Get("/csrf", func(w http.ResponseWriter, r *http.Request) {
token, err := middleware.NewCSRFToken(w, !cfg.Debug)
if err != nil {
http.Error(w, `{"error":"could not generate CSRF token"}`, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"token": token})
})
// Authenticated API
r.With(csrfMiddleware).With(auth.Require).Route("/api/v1", func(r chi.Router) {
r.Get("/me", userH.Me)
// ── Auth (CSRF validated, no session required) ─────────────────────────
r.With(csrf).Post("/auth/register", userH.Register)
r.With(csrf).Post("/auth/login", userH.Login)
r.With(csrf).Post("/auth/logout", userH.Logout)
r.Route("/repos", func(r chi.Router) {
r.Get("/", repoH.List)
r.Post("/", repoH.Create)
r.Route("/{owner}/{repo}", func(r chi.Router) {
r.Get("/", repoH.Get)
r.Get("/tree", repoH.Tree)
r.Get("/blob", repoH.Blob)
r.Get("/commits", repoH.Commits)
r.Route("/pulls", func(r chi.Router) {
r.Get("/", prH.List)
r.Post("/", prH.Create)
r.Get("/{prID}", prH.Get)
r.Post("/{prID}/merge", prH.Merge)
r.Post("/{prID}/close", prH.Close)
})
r.Route("/pipelines", func(r chi.Router) {
r.Get("/", pipeH.List)
r.Get("/{runID}", pipeH.Get)
// ── Protected (session + CSRF for mutations) ──────────────────────────
r.Group(func(r chi.Router) {
r.Use(auth.Require)
r.Get("/me", userH.Me)
r.Route("/repos", func(r chi.Router) {
r.Get("/", repoH.List)
r.With(csrf).Post("/", repoH.Create)
r.Route("/{owner}/{repo}", func(r chi.Router) {
r.Get("/", repoH.Get)
r.Get("/tree", repoH.Tree)
r.Get("/blob", repoH.Blob)
r.Get("/commits", repoH.Commits)
r.Route("/pulls", func(r chi.Router) {
r.Get("/", prH.List)
r.With(csrf).Post("/", prH.Create)
r.Get("/{prID}", prH.Get)
r.With(csrf).Post("/{prID}/merge", prH.Merge)
r.With(csrf).Post("/{prID}/close", prH.Close)
})
r.Route("/pipelines", func(r chi.Router) {
r.Get("/", pipeH.List)
r.Get("/{runID}", pipeH.Get)
})
})
})
})
})
// WebSocket — session auth only, no CSRF needed for WS upgrades
r.With(auth.Optional).Get("/ws", wsH.Hub)
// SPA fallback
r.Handle("/*", spaHandler(staticFiles))
return r
+9 -9
View File
@@ -3,13 +3,13 @@ package models
import "time"
type FederationActor struct {
ID int64 `xorm:"pk autoincr" json:"id"`
UserID int64 `xorm:"notnull unique index" json:"userId"`
APID string `xorm:"notnull unique varchar(500)" json:"apId"`
InboxURL string `xorm:"notnull varchar(500)" json:"inboxUrl"`
OutboxURL string `xorm:"notnull varchar(500)" json:"outboxUrl"`
PublicKey string `xorm:"text notnull" json:"publicKey"`
PrivateKey string `xorm:"text notnull" json:"-"`
CreatedAt time.Time `xorm:"created" json:"createdAt"`
UpdatedAt time.Time `xorm:"updated" json:"updatedAt"`
ID int64 `xorm:"'id' pk autoincr" json:"id"`
UserID int64 `xorm:"'user_id' notnull unique index" json:"userId"`
APID string `xorm:"'ap_id' notnull unique varchar(500)" json:"apId"`
InboxURL string `xorm:"'inbox_url' notnull varchar(500)" json:"inboxUrl"`
OutboxURL string `xorm:"'outbox_url' notnull varchar(500)" json:"outboxUrl"`
PublicKey string `xorm:"'public_key' text notnull" json:"publicKey"`
PrivateKey string `xorm:"'private_key' text notnull" json:"-"`
CreatedAt time.Time `xorm:"'created_at' created" json:"createdAt"`
UpdatedAt time.Time `xorm:"'updated_at' updated" json:"updatedAt"`
}
+10 -10
View File
@@ -11,14 +11,14 @@ const (
)
type PullRequest struct {
ID int64 `xorm:"pk autoincr" json:"id"`
RepoID int64 `xorm:"notnull index" json:"repoId"`
AuthorID int64 `xorm:"notnull index" json:"authorId"`
Title string `xorm:"notnull varchar(255)" json:"title"`
Body string `xorm:"text" json:"body"`
SourceBranch string `xorm:"notnull varchar(255)" json:"sourceBranch"`
TargetBranch string `xorm:"default 'main' varchar(255)" json:"targetBranch"`
Status PRStatus `xorm:"default 'open' varchar(16)" json:"status"`
CreatedAt time.Time `xorm:"created" json:"createdAt"`
UpdatedAt time.Time `xorm:"updated" json:"updatedAt"`
ID int64 `xorm:"'id' pk autoincr" json:"id"`
RepoID int64 `xorm:"'repo_id' notnull index" json:"repoId"`
AuthorID int64 `xorm:"'author_id' notnull index" json:"authorId"`
Title string `xorm:"'title' notnull varchar(255)" json:"title"`
Body string `xorm:"'body' text" json:"body"`
SourceBranch string `xorm:"'source_branch' notnull varchar(255)" json:"sourceBranch"`
TargetBranch string `xorm:"'target_branch' default 'main' varchar(255)" json:"targetBranch"`
Status PRStatus `xorm:"'status' default 'open' varchar(16)" json:"status"`
CreatedAt time.Time `xorm:"'created_at' created" json:"createdAt"`
UpdatedAt time.Time `xorm:"'updated_at' updated" json:"updatedAt"`
}
+9 -9
View File
@@ -3,13 +3,13 @@ package models
import "time"
type Repository struct {
ID int64 `xorm:"pk autoincr" json:"id"`
OwnerID int64 `xorm:"notnull index" json:"ownerId"`
Name string `xorm:"notnull varchar(100)" json:"name"`
Description string `xorm:"varchar(500)" json:"description"`
IsPrivate bool `xorm:"default false" json:"isPrivate"`
DefaultBranch string `xorm:"default 'main' varchar(255)" json:"defaultBranch"`
DiskPath string `xorm:"notnull" json:"-"`
CreatedAt time.Time `xorm:"created" json:"createdAt"`
UpdatedAt time.Time `xorm:"updated" json:"updatedAt"`
ID int64 `xorm:"'id' pk autoincr" json:"id"`
OwnerID int64 `xorm:"'owner_id' notnull index" json:"ownerId"`
Name string `xorm:"'name' notnull varchar(100)" json:"name"`
Description string `xorm:"'description' varchar(500)" json:"description"`
IsPrivate bool `xorm:"'is_private' default false" json:"isPrivate"`
DefaultBranch string `xorm:"'default_branch' default 'main' varchar(255)" json:"defaultBranch"`
DiskPath string `xorm:"'disk_path' notnull" json:"-"`
CreatedAt time.Time `xorm:"'created_at' created" json:"createdAt"`
UpdatedAt time.Time `xorm:"'updated_at' updated" json:"updatedAt"`
}
+8 -8
View File
@@ -3,12 +3,12 @@ package models
import "time"
type User struct {
ID int64 `xorm:"pk autoincr" json:"id"`
Username string `xorm:"unique notnull varchar(64)" json:"username"`
Email string `xorm:"unique notnull varchar(255)" json:"email"`
PasswordHash string `xorm:"notnull" json:"-"`
AvatarURL string `xorm:"varchar(500)"`
IsAdmin bool `xorm:"default false" json:"isAdmin"`
CreatedAt time.Time `xorm:"created" json:"createdAt"`
UpdatedAt time.Time `xorm:"updated" json:"updatedAt"`
ID int64 `xorm:"'id' pk autoincr" json:"id"`
Username string `xorm:"'username' unique notnull varchar(64)" json:"username"`
Email string `xorm:"'email' unique notnull varchar(255)" json:"email"`
PasswordHash string `xorm:"'password_hash' notnull" json:"-"`
AvatarURL string `xorm:"'avatar_url' varchar(500)" json:"avatarUrl"`
IsAdmin bool `xorm:"'is_admin' default false" json:"isAdmin"`
CreatedAt time.Time `xorm:"'created_at' created" json:"createdAt"`
UpdatedAt time.Time `xorm:"'updated_at' updated" json:"updatedAt"`
}