public_view.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. package handler
  2. import (
  3. "fmt"
  4. "html"
  5. "io"
  6. "log"
  7. "net/http"
  8. "path/filepath"
  9. "strings"
  10. "aws-sts-mock/internal/kvdb"
  11. "aws-sts-mock/internal/storage"
  12. )
  13. // PublicViewHandler handles public viewing of S3 bucket contents
  14. type PublicViewHandler struct {
  15. storage *storage.UserAwareStorage
  16. db kvdb.KVDB
  17. }
  18. // NewPublicViewHandler creates a new public view handler
  19. func NewPublicViewHandler(storage *storage.UserAwareStorage, db kvdb.KVDB) *PublicViewHandler {
  20. return &PublicViewHandler{
  21. storage: storage,
  22. db: db,
  23. }
  24. }
  25. // Handle processes public view requests
  26. // URL format: /{bucketName}/{key...}
  27. func (h *PublicViewHandler) Handle(w http.ResponseWriter, r *http.Request) {
  28. // Parse path: /{bucketName}/{key...}
  29. path := strings.TrimPrefix(r.URL.Path, "/")
  30. if path == "" {
  31. http.Error(w, "Invalid path format. Expected: /{bucketName}/{key}", http.StatusBadRequest)
  32. return
  33. }
  34. parts := strings.SplitN(path, "/", 2)
  35. bucketName := parts[0]
  36. key := ""
  37. if len(parts) > 1 {
  38. key = parts[1]
  39. }
  40. // Resolve bucket name to accountID and bucketID
  41. accountID, bucketID, err := h.db.ResolveBucketName(bucketName)
  42. if err != nil {
  43. log.Printf("Failed to resolve bucket name %s: %v", bucketName, err)
  44. http.Error(w, "Bucket not found", http.StatusNotFound)
  45. return
  46. }
  47. // Check if bucket has public viewing enabled
  48. config, err := h.db.GetBucketConfig(accountID, bucketID)
  49. if err != nil {
  50. log.Printf("Bucket config not found for %s:%s", accountID, bucketID)
  51. http.Error(w, "Bucket not found or not configured for public access", http.StatusNotFound)
  52. return
  53. }
  54. if !config.PublicViewing {
  55. http.Error(w, "Public viewing not enabled for this bucket", http.StatusForbidden)
  56. return
  57. }
  58. // If no key specified, show bucket listing
  59. if key == "" {
  60. h.handleBucketListing(w, r, accountID, bucketID, config)
  61. return
  62. }
  63. // Serve the file
  64. h.handleFileDownload(w, r, accountID, bucketID, bucketName, key)
  65. }
  66. func (h *PublicViewHandler) handleBucketListing(w http.ResponseWriter, r *http.Request, accountID, bucketID string, config *kvdb.BucketConfig) {
  67. // List all objects in the bucket
  68. objects, err := h.storage.ListObjectsByBucketIDForUser(accountID, bucketID)
  69. if err != nil {
  70. log.Printf("Error listing objects: %v", err)
  71. http.Error(w, "Error listing bucket contents", http.StatusInternalServerError)
  72. return
  73. }
  74. // Generate HTML page
  75. htmlContent := h.generateBucketListingHTML(config.BucketName, objects)
  76. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  77. w.WriteHeader(http.StatusOK)
  78. w.Write([]byte(htmlContent))
  79. }
  80. func (h *PublicViewHandler) handleFileDownload(w http.ResponseWriter, r *http.Request, accountID, bucketID, bucketName, key string) {
  81. // Get the file
  82. file, info, err := h.storage.GetObjectByBucketIDForUser(accountID, bucketID, key)
  83. if err != nil {
  84. if err == storage.ErrObjectNotFound {
  85. http.Error(w, "File not found", http.StatusNotFound)
  86. return
  87. }
  88. log.Printf("Error getting object: %v", err)
  89. http.Error(w, "Error retrieving file", http.StatusInternalServerError)
  90. return
  91. }
  92. defer file.Close()
  93. // Set headers
  94. w.Header().Set("Content-Type", getContentType(key))
  95. w.Header().Set("Content-Length", fmt.Sprintf("%d", info.Size))
  96. w.Header().Set("Last-Modified", info.LastModified.UTC().Format(http.TimeFormat))
  97. w.Header().Set("ETag", fmt.Sprintf("\"%s\"", info.ETag))
  98. // If it's an image, set inline disposition, otherwise attachment
  99. ext := strings.ToLower(filepath.Ext(key))
  100. if isImage(ext) || isText(ext) || ext == ".pdf" {
  101. w.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=\"%s\"", filepath.Base(key)))
  102. } else {
  103. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filepath.Base(key)))
  104. }
  105. w.WriteHeader(http.StatusOK)
  106. // Stream the file
  107. http.ServeContent(w, r, filepath.Base(key), info.LastModified, file.(io.ReadSeeker))
  108. }
  109. func (h *PublicViewHandler) generateBucketListingHTML(bucketName string, objects []storage.ObjectInfo) string {
  110. var sb strings.Builder
  111. sb.WriteString(`<!DOCTYPE html>
  112. <html lang="en">
  113. <head>
  114. <meta charset="UTF-8">
  115. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  116. <title>`)
  117. sb.WriteString(html.EscapeString(bucketName))
  118. sb.WriteString(` - Public Bucket</title>
  119. <style>
  120. * { margin: 0; padding: 0; box-sizing: border-box; }
  121. body {
  122. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
  123. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  124. min-height: 100vh;
  125. padding: 20px;
  126. }
  127. .container {
  128. max-width: 1200px;
  129. margin: 0 auto;
  130. background: white;
  131. border-radius: 12px;
  132. box-shadow: 0 20px 60px rgba(0,0,0,0.3);
  133. overflow: hidden;
  134. }
  135. .header {
  136. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  137. color: white;
  138. padding: 30px;
  139. text-align: center;
  140. }
  141. .header h1 {
  142. font-size: 2em;
  143. margin-bottom: 10px;
  144. }
  145. .header p {
  146. opacity: 0.9;
  147. font-size: 0.9em;
  148. }
  149. .stats {
  150. display: flex;
  151. justify-content: space-around;
  152. padding: 20px;
  153. background: #f8f9fa;
  154. border-bottom: 1px solid #e9ecef;
  155. }
  156. .stat {
  157. text-align: center;
  158. }
  159. .stat-value {
  160. font-size: 2em;
  161. font-weight: bold;
  162. color: #667eea;
  163. }
  164. .stat-label {
  165. font-size: 0.9em;
  166. color: #6c757d;
  167. margin-top: 5px;
  168. }
  169. .file-list {
  170. padding: 20px;
  171. }
  172. .file-item {
  173. display: flex;
  174. align-items: center;
  175. padding: 15px;
  176. border-bottom: 1px solid #e9ecef;
  177. transition: background 0.2s;
  178. text-decoration: none;
  179. color: inherit;
  180. }
  181. .file-item:hover {
  182. background: #f8f9fa;
  183. }
  184. .file-item:last-child {
  185. border-bottom: none;
  186. }
  187. .file-icon {
  188. width: 40px;
  189. height: 40px;
  190. margin-right: 15px;
  191. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  192. border-radius: 8px;
  193. display: flex;
  194. align-items: center;
  195. justify-content: center;
  196. color: white;
  197. font-weight: bold;
  198. font-size: 0.8em;
  199. flex-shrink: 0;
  200. }
  201. .file-info {
  202. flex: 1;
  203. }
  204. .file-name {
  205. font-weight: 500;
  206. color: #212529;
  207. margin-bottom: 4px;
  208. word-break: break-all;
  209. }
  210. .file-meta {
  211. font-size: 0.85em;
  212. color: #6c757d;
  213. }
  214. .empty-state {
  215. text-align: center;
  216. padding: 60px 20px;
  217. color: #6c757d;
  218. }
  219. .empty-state svg {
  220. width: 100px;
  221. height: 100px;
  222. margin-bottom: 20px;
  223. opacity: 0.3;
  224. }
  225. .footer {
  226. text-align: center;
  227. padding: 20px;
  228. background: #f8f9fa;
  229. color: #6c757d;
  230. font-size: 0.85em;
  231. }
  232. @media (max-width: 768px) {
  233. .stats { flex-direction: column; gap: 15px; }
  234. .file-icon { width: 35px; height: 35px; }
  235. }
  236. </style>
  237. </head>
  238. <body>
  239. <div class="container">
  240. <div class="header">
  241. <h1>🗂️ `)
  242. sb.WriteString(html.EscapeString(bucketName))
  243. sb.WriteString(`</h1>
  244. <p>Public Bucket Contents</p>
  245. </div>
  246. <div class="stats">
  247. <div class="stat">
  248. <div class="stat-value">`)
  249. sb.WriteString(fmt.Sprintf("%d", len(objects)))
  250. sb.WriteString(`</div>
  251. <div class="stat-label">Files</div>
  252. </div>
  253. <div class="stat">
  254. <div class="stat-value">`)
  255. totalSize := int64(0)
  256. for _, obj := range objects {
  257. totalSize += obj.Size
  258. }
  259. sb.WriteString(formatBytes(totalSize))
  260. sb.WriteString(`</div>
  261. <div class="stat-label">Total Size</div>
  262. </div>
  263. </div>
  264. <div class="file-list">`)
  265. if len(objects) == 0 {
  266. sb.WriteString(`
  267. <div class="empty-state">
  268. <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
  269. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
  270. </svg>
  271. <p>This bucket is empty</p>
  272. </div>`)
  273. } else {
  274. for _, obj := range objects {
  275. ext := strings.ToLower(filepath.Ext(obj.Key))
  276. icon := getFileIcon(ext)
  277. sb.WriteString(fmt.Sprintf(`
  278. <a href="/%s/%s" class="file-item">
  279. <div class="file-icon">%s</div>
  280. <div class="file-info">
  281. <div class="file-name">%s</div>
  282. <div class="file-meta">%s • %s</div>
  283. </div>
  284. </a>`,
  285. bucketName,
  286. obj.Key,
  287. icon,
  288. html.EscapeString(obj.Key),
  289. formatBytes(obj.Size),
  290. obj.LastModified.Format("Jan 02, 2006 15:04"),
  291. ))
  292. }
  293. }
  294. sb.WriteString(`
  295. </div>
  296. <div class="footer">
  297. <p>Powered by AWS S3 Mock Server</p>
  298. </div>
  299. </div>
  300. </html>`)
  301. return sb.String()
  302. }
  303. func formatBytes(bytes int64) string {
  304. const unit = 1024
  305. if bytes < unit {
  306. return fmt.Sprintf("%d B", bytes)
  307. }
  308. div, exp := int64(unit), 0
  309. for n := bytes / unit; n >= unit; n /= unit {
  310. div *= unit
  311. exp++
  312. }
  313. return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
  314. }
  315. func getFileIcon(ext string) string {
  316. switch ext {
  317. case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg":
  318. return "🖼️"
  319. case ".pdf":
  320. return "📄"
  321. case ".doc", ".docx":
  322. return "📝"
  323. case ".xls", ".xlsx":
  324. return "📊"
  325. case ".zip", ".tar", ".gz", ".rar":
  326. return "📦"
  327. case ".mp4", ".avi", ".mov", ".mkv":
  328. return "🎬"
  329. case ".mp3", ".wav", ".flac":
  330. return "🎵"
  331. case ".txt", ".md":
  332. return "📃"
  333. case ".js", ".ts", ".go", ".py", ".java":
  334. return "💻"
  335. default:
  336. return "📁"
  337. }
  338. }
  339. func getContentType(filename string) string {
  340. ext := strings.ToLower(filepath.Ext(filename))
  341. switch ext {
  342. case ".jpg", ".jpeg":
  343. return "image/jpeg"
  344. case ".png":
  345. return "image/png"
  346. case ".gif":
  347. return "image/gif"
  348. case ".webp":
  349. return "image/webp"
  350. case ".svg":
  351. return "image/svg+xml"
  352. case ".pdf":
  353. return "application/pdf"
  354. case ".json":
  355. return "application/json"
  356. case ".xml":
  357. return "application/xml"
  358. case ".txt":
  359. return "text/plain"
  360. case ".html":
  361. return "text/html"
  362. case ".css":
  363. return "text/css"
  364. case ".js":
  365. return "application/javascript"
  366. case ".mp4":
  367. return "video/mp4"
  368. case ".mp3":
  369. return "audio/mpeg"
  370. default:
  371. return "application/octet-stream"
  372. }
  373. }
  374. func isImage(ext string) bool {
  375. switch ext {
  376. case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg", ".bmp":
  377. return true
  378. }
  379. return false
  380. }
  381. func isText(ext string) bool {
  382. switch ext {
  383. case ".txt", ".md", ".html", ".css", ".js", ".json", ".xml", ".csv":
  384. return true
  385. }
  386. return false
  387. }