- Refuse non-GET requests whose Origin (or Sec-Fetch-Site) is not the apex or www. SameSite=Lax lets sibling subdomains such as radar. and git. send the auth cookies. The WebSocket check shares the helper and no longer accepts localhost in production. - Take the admin flag from the user row the token check already loads, so a demotion applies on the next request, not on token expiry. - Cut the refresh token lifetime from 365 to 90 days; refreshes renew it. - Docs: fix the stale revocation notes in backend/README.md and the Cloudflare Access comment in routes.caddy. Co-Authored-By: Claude Opus 5.5 <[email protected]>
188 lines
6.9 KiB
Go
188 lines
6.9 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/99designs/gqlgen/graphql/handler"
|
|
"github.com/99designs/gqlgen/graphql/handler/extension"
|
|
"github.com/99designs/gqlgen/graphql/handler/lru"
|
|
"github.com/99designs/gqlgen/graphql/handler/transport"
|
|
"github.com/99designs/gqlgen/graphql/playground"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/vektah/gqlparser/v2/ast"
|
|
|
|
"adam-french.co.uk/backend/graph"
|
|
"adam-french.co.uk/backend/handlers"
|
|
"adam-french.co.uk/backend/services"
|
|
)
|
|
|
|
// Command backend is the site's Go API. GraphQL is guarded by schema
|
|
// directives, not middleware; see backend/README.md.
|
|
func main() {
|
|
logsDir := "/backend/logs"
|
|
logFile, err := os.OpenFile(logsDir+"/go.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
gin.DefaultWriter = io.MultiWriter(os.Stdout, logFile)
|
|
|
|
if os.Getenv("DEV_MODE") != "true" {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
}
|
|
|
|
r := gin.New()
|
|
r.Use(gin.LoggerWithFormatter(services.TrafficLogFormatter))
|
|
r.Use(gin.Recovery())
|
|
|
|
// Only the Docker network may set X-Forwarded-For, or clients could spoof
|
|
// their IP past the login rate limiter. Must match docker-compose.yml.
|
|
err = r.SetTrustedProxies([]string{"172.28.0.0/16"})
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
dbUser := os.Getenv("POSTGRES_USER")
|
|
dbPassword := os.Getenv("POSTGRES_PASSWORD")
|
|
dbName := os.Getenv("POSTGRES_DB")
|
|
dbHost := os.Getenv("POSTGRES_HOST")
|
|
dbPort := os.Getenv("POSTGRES_PORT")
|
|
dbConfig := services.SQLConfig{User: dbUser, Password: dbPassword, DBName: dbName, Host: dbHost, Port: dbPort}
|
|
db, err := services.InitDatabase(&dbConfig)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
if os.Getenv("SEED_DB") == "true" {
|
|
services.SeedDatabase(db)
|
|
}
|
|
// Used for both the WebSocket origin check and the cookie domain.
|
|
domainName := os.Getenv("DOMAIN")
|
|
services.InitWebSocket(db, domainName)
|
|
r.Use(services.RequireSameOrigin(domainName))
|
|
|
|
spotifyRedirectURL := os.Getenv("SPOTIFY_REDIRECT_URI")
|
|
spotifyClientID := os.Getenv("SPOTIFY_CLIENT_ID")
|
|
spotifyClientSecret := os.Getenv("SPOTIFY_CLIENT_SECRET")
|
|
spotifyConfig := services.SpotifyConfig{RedirectURL: spotifyRedirectURL, ClientID: spotifyClientID, ClientSecret: spotifyClientSecret}
|
|
spotifyAuth, spotifyClient := services.InitSpotifyAuth(&spotifyConfig)
|
|
|
|
authSecret := os.Getenv("BACKEND_SECRET")
|
|
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
|
|
accessTokenLifetime := 7 * 24 * time.Hour
|
|
// Sliding: every refresh, including the gates', mints a new one.
|
|
refreshTokenLifetime := 90 * 24 * time.Hour
|
|
authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint}
|
|
auth := services.InitAuth(&authConfig)
|
|
|
|
notesDir := "/backend/notes"
|
|
notesConfig := services.NotesConfig{Dir: notesDir}
|
|
notes := services.InitNotes(¬esConfig)
|
|
|
|
giteaHost := os.Getenv("GITEA_HOST")
|
|
giteaPort := os.Getenv("GITEA_PORT")
|
|
|
|
steamAPIKey := os.Getenv("STEAM_API_KEY")
|
|
steamID := os.Getenv("STEAM_ID")
|
|
|
|
// Called over the Docker network, not through Caddy.
|
|
pythonHost := os.Getenv("PYTHON_HOST")
|
|
if pythonHost == "" {
|
|
pythonHost = "python"
|
|
}
|
|
pythonPort := os.Getenv("PYTHON_PORT")
|
|
if pythonPort == "" {
|
|
pythonPort = "8000"
|
|
}
|
|
pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort)
|
|
|
|
// Defaults match stpcore's garage/garage.toml and garage/bootstrap.sh.
|
|
s3Region := os.Getenv("S3_REGION")
|
|
if s3Region == "" {
|
|
s3Region = "garage"
|
|
}
|
|
s3Bucket := os.Getenv("S3_BUCKET")
|
|
if s3Bucket == "" {
|
|
s3Bucket = "uploads"
|
|
}
|
|
s3Config := services.S3Config{Endpoint: os.Getenv("S3_ENDPOINT"), Region: s3Region, Bucket: s3Bucket, AccessKeyID: os.Getenv("S3_ACCESS_KEY_ID"), SecretAccessKey: os.Getenv("S3_SECRET_ACCESS_KEY")}
|
|
uploads := services.NewUploads(s3Config, "/backend/uploads/", "/backend/uploads/private/")
|
|
|
|
// Shared by REST and GraphQL login, on top of Caddy's limit.
|
|
loginLimiter := services.NewRateLimiter(5, time.Minute)
|
|
|
|
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, Uploads: uploads}
|
|
|
|
// Caddy strips /api before proxying.
|
|
protected := r.Group("/", store.AuthMiddleware)
|
|
admin := r.Group("/", store.AuthMiddleware, store.AdminMiddleware)
|
|
|
|
r.GET("/rowing", store.GetRowing)
|
|
admin.POST("/rowing", store.CreateRowing)
|
|
|
|
r.POST("/auth/login", store.Login)
|
|
r.POST("/auth/refresh", store.RefreshToken)
|
|
r.GET("/auth/check", store.CheckToken)
|
|
r.POST("/auth/logout", store.Logout)
|
|
r.GET("/auth/validate-admin", store.ValidateAdmin)
|
|
r.GET("/auth/validate/:permission", store.ValidatePermission)
|
|
|
|
// The callback is open (Spotify redirects a logged-out browser) and is
|
|
// protected by the state nonce that only the admin-only start mints.
|
|
r.GET("/spotify/callback", store.CompleteSpotifyAuth)
|
|
admin.GET("/spotify/auth", store.StartSpotifyAuth)
|
|
r.GET("/spotify/listening", store.ListeningTo)
|
|
r.GET("/spotify/recent", store.RecentlyPlayed)
|
|
|
|
admin.POST("/radio/upload", store.UploadRadioSong)
|
|
admin.GET("/radio/songs", store.ListRadioSongs)
|
|
admin.DELETE("/radio/songs/:filename", store.DeleteRadioSong)
|
|
admin.PATCH("/radio/songs/:filename/disable", store.DisableRadioSong)
|
|
admin.PATCH("/radio/songs/:filename/enable", store.EnableRadioSong)
|
|
|
|
// Public: the handler reads the cookies itself for admin privileges.
|
|
r.GET("/ws", store.ConnectWebSocket)
|
|
protected.POST("/uploads", store.Upload)
|
|
admin.GET("/uploads", store.ListUploads)
|
|
|
|
admin.GET("/notes/*path", store.GetNoteFile)
|
|
|
|
// One unguarded POST route: authorisation is the schema's @admin and
|
|
// @signedIn directives, so a field with neither is public. gqlgen fails
|
|
// closed if Directives is dropped.
|
|
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
|
|
Resolvers: &graph.Resolver{Store: &store},
|
|
Directives: graph.Directives(),
|
|
}))
|
|
gqlSrv.AddTransport(transport.Options{})
|
|
gqlSrv.AddTransport(transport.POST{})
|
|
gqlSrv.AddTransport(transport.MultipartForm{})
|
|
gqlSrv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
|
|
gqlSrv.Use(extension.FixedComplexityLimit(200))
|
|
// Production never publishes its schema.
|
|
devMode := os.Getenv("DEV_MODE") == "true"
|
|
if devMode && os.Getenv("GQL_INTROSPECTION") == "true" {
|
|
gqlSrv.Use(extension.Introspection{})
|
|
}
|
|
r.POST("/graphql", graph.AuthContextMiddleware(auth, db), func(c *gin.Context) {
|
|
gqlSrv.ServeHTTP(c.Writer, c.Request)
|
|
})
|
|
if devMode && os.Getenv("GQL_PLAYGROUND") == "true" {
|
|
r.GET("/graphql", func(c *gin.Context) {
|
|
playground.Handler("GraphQL Playground", "/graphql").ServeHTTP(c.Writer, c.Request)
|
|
})
|
|
}
|
|
|
|
r.GET("/", func(c *gin.Context) {
|
|
c.JSON(200, gin.H{"message": "Hello World"})
|
|
})
|
|
|
|
port := os.Getenv("BACKEND_PORT")
|
|
// Exit non-zero so Docker doesn't report a port clash as success.
|
|
if err := r.Run(fmt.Sprintf(":%s", port)); err != nil {
|
|
log.Fatalf("http server stopped: %v", err)
|
|
}
|
|
}
|