/
uncopier.go
228 lines (214 loc) · 7.75 KB
/
uncopier.go
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 (
"crypto/tls"
"fmt"
"github.com/gin-contrib/cors"
"github.com/nanmu42/gzip"
//"github.com/gin-contrib/gzip"
"github.com/gin-contrib/static"
"github.com/gin-gonic/autotls"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"github.com/uncopied/uncopier/api"
"github.com/uncopied/uncopier/api/v1.0/middleware"
"github.com/uncopied/uncopier/certificates"
"github.com/uncopied/uncopier/database"
"github.com/uncopied/uncopier/upload"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"time"
)
// direct call to IPFS, http://127.0.0.1:8080/ipfs/QmYZ8w9v86HHUcxM8Yi1sBKNPgqNoL3jcitNUEtyWp5muP
// proxied call to IPDS http://127.0.0.1:8081/ipfs/QmYZ8w9v86HHUcxM8Yi1sBKNPgqNoL3jcitNUEtyWp5muP
// IPFS node should be configured with disabling of subdomains
// "PublicGateways": {
// "localhost": {
// "Paths": ["/ipfs"],
// "UseSubdomains": false
// },
// "127.0.0.1": {
// "Paths": ["/ipfs"],
// "UseSubdomains": false
// }
// }
func ReverseProxyIPFS() gin.HandlerFunc {
localIPFSHost:=os.Getenv("LOCAL_IPFS_HOST")
localIPFSPort:=os.Getenv("LOCAL_IPFS_PORT")
target := localIPFSHost+":"+localIPFSPort
targetUrl,err := url.Parse("http://"+target)
if err!=nil {
log.Fatal(err)
}
proxy := httputil.NewSingleHostReverseProxy(targetUrl)
return func(c *gin.Context) {
proxy.ServeHTTP(c.Writer, c.Request)
}
}
// https://github.com/gin-gonic/gin/issues/1543
func headersByRequestURI() gin.HandlerFunc {
return func(c *gin.Context) {
serverTls := os.Getenv("SERVER_TLS")
if serverTls == "https" {
serverHost := os.Getenv("SERVER_HOST")
// https://blog.bracebin.com/achieving-perfect-ssl-labs-score-with-go
//'https://www.paypal.com/xoplatform
//"https://www.sandbox.paypal.com/xoplatform/logger/api/logger' because it violates the
c.Header("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
c.Header("Content-Security-Policy", "base-uri 'self'; "+
"default-src 'self' https://"+serverHost+"; "+
"font-src 'self' data: https://pro.fontawesome.com https://cdn.jsdelivr.net https://fonts.googleapis.com; " +
"connect-src 'self' https://www.google-analytics.com https://www.paypal.com/ https://www.sandbox.paypal.com ; "+
"img-src 'self' data: https://user-images.githubusercontent.com/ http://www.w3.org https://t.paypal.com/; "+
"script-src 'self' 'unsafe-inline' https://www.googletagmanager.com https://www.paypal.com/; "+
"frame-src 'self' https://www.paypal.com/ https://www.sandbox.paypal.com; "+
"style-src 'self' 'unsafe-inline' https://pro.fontawesome.com https://fonts.googleapis.com https://cdn.jsdelivr.net;")
// This below is no longer necessary, should be
// c.Header("X-Frame-Options","SAMEORIGIN")
// INLINE_RUNTIME_CHUNK=false
}
if strings.HasPrefix(c.Request.RequestURI, "/static/") ||
strings.HasPrefix(c.Request.RequestURI, "/assets/") ||
strings.HasPrefix(c.Request.RequestURI, "/docs/") {
// 10 days
c.Header("Cache-Control", "max-age=864000")
//c.Header("Content-Description", "File Transfer")
//c.Header("Content-Type", "application/octet-stream")
//c.Header("Content-Transfer-Encoding", "binary")
} else if !strings.HasPrefix(c.Request.RequestURI, "/api/") {
// default : one day
c.Header("Cache-Control", "max-age=86400")
}
}
}
func main() {
fmt.Println("odotenv.Load()")
err := godotenv.Load()
if err != nil {
panic(err)
}
// initializes database
db, _ := database.Initialize()
db.Debug()
router := gin.Default()
// gzip as per https://www.webpagetest.org/ reco
// but the default gzip middleware caused net::ERR_HTTP2_PROTOCOL_ERROR errors
//router.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedExtensions([]string{
// ".png", ".gif", ".jpeg", ".jpg",
// ".pdf",
// })))
router.Use(gzip.DefaultHandler().Gin)
// max-age or expires
// https://github.com/gin-gonic/gin/issues/1543
router.Use(headersByRequestURI())
// CORS for https://foo.com and https://github.com origins, allowing:
// - PUT and PATCH methods
// - Origin header
// - Credentials share
// - Preflight requests cached for 12 hours
// TODO : tune this for prod
// Also beware there is a bug when calling http://localhost:8081/api/v1.0/src (redirect 307 not working with CORS)
// so need to call http://localhost:8081/api/v1.0/src/ to avoid redirects
router.Use(cors.New(cors.Config{
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"},
AllowHeaders: []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
AllowCredentials: false,
MaxAge: 12 * time.Hour,
AllowFiles: true,
AllowAllOrigins: true,
}))
router.Use(static.ServeRoot("/", "./public")) // static files have higher priority over dynamic routes
router.LoadHTMLGlob("templates/*")
//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "Main website",
"artistName": "Mary Stone",
})
})
// proxy for IPFS requests
router.GET("/ipfs/:hash", ReverseProxyIPFS())
router.Use(database.Inject(db))
router.Use(middleware.JWTMiddleware())
// apply api router
api.ApplyRoutes(router)
// apply certificates router
certificates.ApplyRoutes(router)
// ipfs upload
upload.ApplyRoutes(router)
// todo : add https://prometheus.io/
// good checklist here
// https://github.com/fiorix/freegeoip
// add no route to redirect to / : catch all route for React
router.NoRoute(func(c *gin.Context) {
// https://stackoverflow.com/questions/27928372/react-router-urls-dont-work-when-refreshing-or-writing-manually
c.Redirect(http.StatusMovedPermanently, "/")
})
tlsKind := os.Getenv("SERVER_TLS")
serverHost := os.Getenv("SERVER_HOST")
fmt.Printf("Serving with tlsMod %s\n", tlsKind)
if tlsKind =="http" {
// needs redirecting 80 port to 8081
httpPort:=os.Getenv("SERVER_HTTP_PORT")
err = router.Run(serverHost+":"+httpPort)
if err!=nil {
log.Fatal(err)
}
} else if tlsKind =="https" {
// needs redirecting 443 port to 8443
httpsPort:=os.Getenv("SERVER_HTTPS_PORT")
fullChain:=os.Getenv("SERVER_HTTPS_FULLCHAIN")
privKey:=os.Getenv("SERVER_HTTPS_PRIVKEY")
addr:=serverHost+":"+httpsPort
server := &http.Server{
Addr: addr,
Handler: router,
TLSConfig: &tls.Config{
PreferServerCipherSuites: true,
CurvePreferences: []tls.CurveID{
tls.CurveP256,
tls.X25519,
},
MinVersion: tls.VersionTLS12,
},
ReadTimeout: 30 * time.Second,
ReadHeaderTimeout: 30 * time.Second,
WriteTimeout: 120 * time.Second,
}
err := server.ListenAndServeTLS(fullChain, privKey)
// err = http.ListenAndServeTLS(addr, fullChain, privKey, router)
//err = router.RunTLS(addr,fullChain,privKey) // listen and serve on 0.0.0.0:8443
if err!=nil {
log.Fatal(err)
}
// to monitor files open lsof -p [PID_ID]
// TODO: set limits ulimit -n 65535
// https://medium.com/@muhammadtriwibowo/set-permanently-ulimit-n-open-files-in-ubuntu-4d61064429a
httpPort:=os.Getenv("SERVER_HTTP_PORT")
addr2:=serverHost+":"+httpPort
// https://blog.cloudflare.com/exposing-go-on-the-internet/
srv := &http.Server{
Addr: addr2,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Connection", "close")
reqUrl := "https://" + req.Host + req.URL.String()
http.Redirect(w, req, reqUrl, http.StatusMovedPermanently)
}),
}
go func() { log.Fatal(srv.ListenAndServe()) }( )
} else if tlsKind =="autocert" {
// needs root priviledge to run on 443
domain1:=os.Getenv("SERVER_DOMAIN1")
domain2:=os.Getenv("SERVER_DOMAIN2")
err = autotls.Run(router, domain1, domain2)
if err!=nil {
log.Fatal(err)
}
}
}