-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
228 lines (204 loc) · 6.86 KB
/
main.go
File metadata and controls
228 lines (204 loc) · 6.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package main
import (
"context"
"crypto/subtle"
"crypto/tls"
"encoding/json"
"io"
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"golang.org/x/crypto/acme/autocert"
"ws-codingame-insalgo/internal/realtime"
)
// TODO: Déploiement du site ; Lien avec le bot discord pour pouvoir maj depuis le discord
// securityHeaders ajoute des en-têtes de sécurité standard.
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Referrer-Policy", "no-referrer")
// CSP très permissif pour ce POC; à durcir selon besoins
w.Header().Set("Content-Security-Policy", "default-src 'self'; connect-src 'self' wss:; style-src 'self' 'unsafe-inline'; script-src 'self'")
w.Header().Set("Permissions-Policy", "geolocation=(), microphone=(), camera=()")
// HSTS seulement en HTTPS (voir plus bas)
next.ServeHTTP(w, r)
})
}
// allowedHostsMiddleware limite les hosts servis si ALLOWED_HOSTS est défini (liste séparée par virgules).
func allowedHostsMiddleware(next http.Handler) http.Handler {
allowed := strings.Split(strings.TrimSpace(os.Getenv("ALLOWED_HOSTS")), ",")
set := make(map[string]struct{})
for _, h := range allowed {
h = strings.TrimSpace(h)
if h != "" {
set[strings.ToLower(h)] = struct{}{}
}
}
if len(set) == 0 {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
host := strings.ToLower(r.Host)
if _, ok := set[host]; !ok {
http.Error(w, "Host non autorisé", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
func broadcastHandler(hub *realtime.Hub, apiKey string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Méthode non autorisée", http.StatusMethodNotAllowed)
return
}
if strings.TrimSpace(apiKey) == "" {
http.Error(w, "API non configurée", http.StatusInternalServerError)
return
}
key := r.Header.Get("X-Api-Key")
if key == "" {
auth := r.Header.Get("Authorization")
const prefix = "Bearer "
if strings.HasPrefix(auth, prefix) {
key = strings.TrimSpace(auth[len(prefix):])
}
}
if subtle.ConstantTimeCompare([]byte(key), []byte(apiKey)) != 1 {
http.Error(w, "Non autorisé", http.StatusUnauthorized)
return
}
var payload struct {
Content string `json:"content"`
}
ct := r.Header.Get("Content-Type")
if strings.Contains(ct, "application/json") {
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, "JSON invalide", http.StatusBadRequest)
return
}
} else {
b, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Lecture corps requête échouée", http.StatusBadRequest)
return
}
payload.Content = string(b)
}
_ = r.Body.Close()
content := strings.TrimSpace(payload.Content)
if content == "" {
http.Error(w, "content vide", http.StatusBadRequest)
return
}
hub.Broadcast(realtime.Message{Content: content})
w.WriteHeader(http.StatusNoContent)
}
}
func main() {
// Hub WebSocket
hub := realtime.NewHub()
// Origines autorisées pour WS via env ALLOWED_ORIGINS (schéma+host+port)
var allowedOrigins []string
if v := strings.TrimSpace(os.Getenv("ALLOWED_ORIGINS")); v != "" {
for _, item := range strings.Split(v, ",") {
item = strings.TrimSpace(item)
if item != "" {
allowedOrigins = append(allowedOrigins, item)
}
}
}
apiKey := strings.TrimSpace(os.Getenv("BROADCAST_API_KEY"))
mux := http.NewServeMux()
mux.HandleFunc("/ws", hub.Handler(allowedOrigins))
mux.HandleFunc("/api/broadcast", broadcastHandler(hub, apiKey))
mux.Handle("/", http.FileServer(http.Dir("static")))
// Wrap middlewares
handler := securityHeaders(allowedHostsMiddleware(mux))
// Lecture du terminal et diffusion
// go func() {
// scanner := bufio.NewScanner(os.Stdin)
// fmt.Println("Tapez vos messages ci-dessous et appuyez sur Entrée pour les envoyer aux clients...")
// for scanner.Scan() {
// line := scanner.Text()
// hub.Broadcast(realtime.Message{Content: line})
// }
// if err := scanner.Err(); err != nil {
// log.Printf("Erreur de lecture depuis le terminal: %v", err)
// }
// }()
// Choisir HTTP ou HTTPS
addrHTTP := ":8080"
addrHTTPS := ":8443" // par défaut local; 443 en prod
certFile := strings.TrimSpace(os.Getenv("TLS_CERT_FILE"))
keyFile := strings.TrimSpace(os.Getenv("TLS_KEY_FILE"))
domain := strings.TrimSpace(os.Getenv("DOMAIN"))
srv := &http.Server{
Addr: addrHTTP,
Handler: handler,
}
// Arrêt gracieux
shutdownCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
<-shutdownCtx.Done()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = srv.Shutdown(ctx)
}()
// Si certs fournis, servir en HTTPS
if certFile != "" && keyFile != "" {
srv.Addr = addrHTTPS
// HSTS en HTTPS
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload")
securityHeaders(allowedHostsMiddleware(mux)).ServeHTTP(w, r)
})
srv.Handler = handler
log.Printf("Serveur démarré en HTTPS sur https://localhost%s", addrHTTPS)
log.Printf("WebSocket disponible sur wss://localhost%s/ws", addrHTTPS)
if err := srv.ListenAndServeTLS(certFile, keyFile); err != nil && err != http.ErrServerClosed {
log.Fatalf("Erreur serveur HTTPS: %v", err)
}
return
}
// Sinon si un domaine est fourni, tenter autocert (Let’s Encrypt)
if domain != "" {
m := &autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(domain),
Cache: autocert.DirCache(".cert-cache"),
}
// HTTP-01 challenge sur :80
go func() {
httpSrv := &http.Server{Addr: ":80", Handler: m.HTTPHandler(nil)}
log.Printf("Serveur challenge HTTP démarré sur :80 pour %s", domain)
if err := httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Printf("Erreur challenge HTTP: %v", err)
}
}()
// Serveur HTTPS principal sur :443
httpsSrv := &http.Server{
Addr: ":443",
Handler: handler,
TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
}
log.Printf("Serveur démarré en HTTPS sur https://%s", domain)
log.Printf("WebSocket disponible sur wss://%s/ws", domain)
if err := httpsSrv.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
log.Fatalf("Erreur serveur HTTPS (autocert): %v", err)
}
return
}
// Fallback: HTTP
log.Printf("Serveur démarré sur http://localhost%s", addrHTTP)
log.Printf("WebSocket disponible sur ws://localhost%s/ws", addrHTTP)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Erreur serveur HTTP: %v", err)
}
}