2024-04-24 20:00:06 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2024-05-22 21:18:40 +02:00
|
|
|
"context"
|
2024-04-24 20:00:06 +02:00
|
|
|
"crypto/aes"
|
|
|
|
"crypto/cipher"
|
|
|
|
"crypto/rand"
|
|
|
|
"database/sql"
|
|
|
|
"encoding/hex"
|
2024-05-10 11:00:34 +02:00
|
|
|
"encoding/json"
|
2024-04-24 20:00:06 +02:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
2024-05-22 21:18:40 +02:00
|
|
|
"time"
|
2024-04-24 20:00:06 +02:00
|
|
|
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
_ "github.com/lib/pq"
|
|
|
|
"github.com/rs/cors"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
maxUploadSize = 10 * 1024 * 1024 // 10 MB
|
|
|
|
keySize = 32
|
|
|
|
nonceSize = 12
|
|
|
|
)
|
|
|
|
|
|
|
|
var db *sql.DB
|
|
|
|
|
|
|
|
func main() {
|
2024-05-22 21:18:40 +02:00
|
|
|
var err error
|
|
|
|
db, err = initDB()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2024-04-24 20:00:06 +02:00
|
|
|
defer db.Close()
|
|
|
|
|
|
|
|
router := mux.NewRouter()
|
|
|
|
router.HandleFunc("/upload", handleUpload).Methods("POST")
|
|
|
|
router.HandleFunc("/download/{id}", handleDownload).Methods("GET")
|
2024-05-10 11:00:34 +02:00
|
|
|
router.HandleFunc("/get/{id}", handleGetFileInfo).Methods("GET")
|
2024-04-24 20:00:06 +02:00
|
|
|
|
|
|
|
handler := cors.New(cors.Options{
|
|
|
|
AllowedOrigins: []string{"*"},
|
|
|
|
AllowedMethods: []string{"GET", "POST"},
|
|
|
|
AllowedHeaders: []string{"*"},
|
|
|
|
}).Handler(router)
|
|
|
|
|
|
|
|
http.ListenAndServe(":8080", handler)
|
|
|
|
}
|
|
|
|
|
2024-05-22 21:18:40 +02:00
|
|
|
func initDB() (*sql.DB, error) {
|
2024-04-24 20:00:06 +02:00
|
|
|
db, err := sql.Open("postgres", "postgres://file:password@localhost/filedb?sslmode=disable")
|
|
|
|
if err != nil {
|
2024-05-22 21:18:40 +02:00
|
|
|
return nil, err
|
2024-04-24 20:00:06 +02:00
|
|
|
}
|
2024-05-22 21:18:40 +02:00
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
if err := createFilesTable(ctx, db); err != nil {
|
|
|
|
return nil, err
|
2024-04-24 20:00:06 +02:00
|
|
|
}
|
2024-05-22 21:18:40 +02:00
|
|
|
|
|
|
|
return db, nil
|
2024-04-24 20:00:06 +02:00
|
|
|
}
|
|
|
|
|
2024-05-22 21:18:40 +02:00
|
|
|
func createFilesTable(ctx context.Context, db *sql.DB) error {
|
|
|
|
_, err := db.ExecContext(ctx, `
|
2024-04-24 20:00:06 +02:00
|
|
|
CREATE TABLE IF NOT EXISTS files (
|
|
|
|
id TEXT PRIMARY KEY,
|
|
|
|
name TEXT,
|
|
|
|
data BYTEA
|
|
|
|
);
|
|
|
|
`)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func handleUpload(w http.ResponseWriter, r *http.Request) {
|
2024-05-22 21:18:40 +02:00
|
|
|
if err := r.ParseMultipartForm(maxUploadSize); err != nil {
|
|
|
|
handleError(w, fmt.Errorf("error parsing multipart form: %v", err), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
2024-04-24 20:00:06 +02:00
|
|
|
|
|
|
|
key, err := generateRandomKey()
|
|
|
|
if err != nil {
|
2024-05-22 21:18:40 +02:00
|
|
|
handleError(w, fmt.Errorf("error generating encryption key: %v", err), http.StatusInternalServerError)
|
2024-04-24 20:00:06 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
file, handler, err := r.FormFile("file")
|
|
|
|
if err != nil {
|
2024-05-22 21:18:40 +02:00
|
|
|
handleError(w, fmt.Errorf("error getting form file: %v", err), http.StatusBadRequest)
|
2024-04-24 20:00:06 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
id := generateID()
|
|
|
|
|
|
|
|
encryptedData, err := encryptFile(file, key)
|
|
|
|
if err != nil {
|
2024-05-22 21:18:40 +02:00
|
|
|
handleError(w, fmt.Errorf("error encrypting file: %v", err), http.StatusInternalServerError)
|
2024-04-24 20:00:06 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-05-22 21:18:40 +02:00
|
|
|
if err := storeFileInDB(r.Context(), id, handler.Filename, encryptedData); err != nil {
|
|
|
|
handleError(w, fmt.Errorf("error storing file in database: %v", err), http.StatusInternalServerError)
|
2024-04-24 20:00:06 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
encodedKey := hex.EncodeToString(key)
|
2024-06-02 18:04:04 +02:00
|
|
|
|
|
|
|
type UploadResponse struct {
|
|
|
|
ID string `json:"id"`
|
|
|
|
Key string `json:"key"`
|
|
|
|
}
|
|
|
|
|
|
|
|
response := UploadResponse{
|
|
|
|
ID: id,
|
|
|
|
Key: encodedKey,
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
if err := json.NewEncoder(w).Encode(response); err != nil {
|
|
|
|
handleError(w, fmt.Errorf("error encoding response: %v", err), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
2024-04-24 20:00:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func handleDownload(w http.ResponseWriter, r *http.Request) {
|
2024-05-22 21:18:40 +02:00
|
|
|
id := mux.Vars(r)["id"]
|
2024-04-24 20:00:06 +02:00
|
|
|
keyHex := r.URL.Query().Get("key")
|
2024-05-22 21:18:40 +02:00
|
|
|
|
2024-04-24 20:00:06 +02:00
|
|
|
key, err := hex.DecodeString(keyHex)
|
|
|
|
if err != nil {
|
2024-05-22 21:18:40 +02:00
|
|
|
handleError(w, fmt.Errorf("invalid key: %v", err), http.StatusBadRequest)
|
2024-04-24 20:00:06 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-05-22 21:18:40 +02:00
|
|
|
fileName, encryptedData, err := getFileFromDB(r.Context(), id)
|
2024-04-24 20:00:06 +02:00
|
|
|
if err != nil {
|
2024-05-22 21:18:40 +02:00
|
|
|
handleError(w, fmt.Errorf("error getting file from database: %v", err), http.StatusInternalServerError)
|
2024-04-24 20:00:06 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
|
|
|
|
|
2024-05-22 21:18:40 +02:00
|
|
|
err = decryptAndStreamFile(w, encryptedData, key)
|
2024-04-24 20:00:06 +02:00
|
|
|
if err != nil {
|
2024-05-22 21:18:40 +02:00
|
|
|
handleError(w, fmt.Errorf("error decrypting and streaming file: %v", err), http.StatusInternalServerError)
|
2024-04-24 20:00:06 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-10 11:00:34 +02:00
|
|
|
func handleGetFileInfo(w http.ResponseWriter, r *http.Request) {
|
2024-05-22 21:18:40 +02:00
|
|
|
id := mux.Vars(r)["id"]
|
2024-05-10 11:00:34 +02:00
|
|
|
keyHex := r.URL.Query().Get("key")
|
2024-05-22 21:18:40 +02:00
|
|
|
|
2024-05-10 11:00:34 +02:00
|
|
|
key, err := hex.DecodeString(keyHex)
|
|
|
|
if err != nil {
|
2024-05-22 21:18:40 +02:00
|
|
|
handleError(w, fmt.Errorf("invalid key: %v", err), http.StatusBadRequest)
|
2024-05-10 11:00:34 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-05-22 21:18:40 +02:00
|
|
|
fileName, encryptedData, err := getFileFromDB(r.Context(), id)
|
2024-05-10 11:00:34 +02:00
|
|
|
if err != nil {
|
2024-05-22 21:18:40 +02:00
|
|
|
handleError(w, fmt.Errorf("error getting file from database: %v", err), http.StatusInternalServerError)
|
2024-05-10 11:00:34 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
plaintext, err := decryptFile(encryptedData, key)
|
|
|
|
if err != nil {
|
2024-05-22 21:18:40 +02:00
|
|
|
handleError(w, fmt.Errorf("error decrypting file: %v", err), http.StatusInternalServerError)
|
2024-05-10 11:00:34 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
fileSizeBytes := len(plaintext)
|
|
|
|
var fileSize string
|
|
|
|
if fileSizeBytes >= 1024*1024 {
|
|
|
|
fileSize = fmt.Sprintf("%.2f MB", float64(fileSizeBytes)/(1024*1024))
|
|
|
|
} else {
|
|
|
|
fileSize = fmt.Sprintf("%.2f KB", float64(fileSizeBytes)/1024)
|
|
|
|
}
|
|
|
|
|
|
|
|
fileInfo := struct {
|
|
|
|
FileName string `json:"fileName"`
|
|
|
|
FileSize string `json:"fileSize"`
|
|
|
|
}{
|
|
|
|
FileName: fileName,
|
|
|
|
FileSize: fileSize,
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
2024-06-02 18:06:31 +02:00
|
|
|
if err := json.NewEncoder(w).Encode(fileInfo); err != nil {
|
|
|
|
handleError(w, fmt.Errorf("error encoding response: %v", err), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
2024-05-10 11:00:34 +02:00
|
|
|
}
|
|
|
|
|
2024-05-22 21:18:40 +02:00
|
|
|
func storeFileInDB(ctx context.Context, id, fileName string, encryptedData []byte) error {
|
|
|
|
tx, err := db.BeginTx(ctx, nil)
|
2024-04-24 20:00:06 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer tx.Rollback()
|
|
|
|
|
2024-05-22 21:18:40 +02:00
|
|
|
_, err = tx.ExecContext(ctx, "INSERT INTO files (id, name, data) VALUES ($1, $2, $3)", id, fileName, encryptedData)
|
2024-04-24 20:00:06 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return tx.Commit()
|
|
|
|
}
|
|
|
|
|
2024-05-22 21:18:40 +02:00
|
|
|
func getFileFromDB(ctx context.Context, id string) (fileName string, encryptedData []byte, err error) {
|
|
|
|
err = db.QueryRowContext(ctx, "SELECT name, data FROM files WHERE id = $1", id).Scan(&fileName, &encryptedData)
|
2024-04-24 20:00:06 +02:00
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
return "", nil, errors.New("file not found")
|
|
|
|
}
|
|
|
|
return fileName, encryptedData, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func handleError(w http.ResponseWriter, err error, code int) {
|
|
|
|
http.Error(w, err.Error(), code)
|
|
|
|
}
|
|
|
|
|
|
|
|
func encryptFile(in io.Reader, key []byte) ([]byte, error) {
|
|
|
|
block, err := aes.NewCipher(key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
aesgcm, err := cipher.NewGCM(block)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
nonce := make([]byte, nonceSize)
|
|
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
plaintext, err := io.ReadAll(in)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
|
|
|
|
return append(nonce, ciphertext...), nil
|
|
|
|
}
|
|
|
|
|
2024-05-22 21:18:40 +02:00
|
|
|
func decryptAndStreamFile(w io.Writer, encryptedData []byte, key []byte) error {
|
|
|
|
if len(encryptedData) < nonceSize {
|
|
|
|
return errors.New("ciphertext too short")
|
|
|
|
}
|
|
|
|
|
2024-04-24 20:00:06 +02:00
|
|
|
block, err := aes.NewCipher(key)
|
|
|
|
if err != nil {
|
2024-05-22 21:18:40 +02:00
|
|
|
return err
|
2024-04-24 20:00:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
aesgcm, err := cipher.NewGCM(block)
|
|
|
|
if err != nil {
|
2024-05-22 21:18:40 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
nonce, ciphertext := encryptedData[:nonceSize], encryptedData[nonceSize:]
|
|
|
|
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2024-04-24 20:00:06 +02:00
|
|
|
}
|
|
|
|
|
2024-05-22 21:18:40 +02:00
|
|
|
_, err = w.Write(plaintext)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func decryptFile(encryptedData []byte, key []byte) ([]byte, error) {
|
2024-04-24 20:00:06 +02:00
|
|
|
if len(encryptedData) < nonceSize {
|
|
|
|
return nil, errors.New("ciphertext too short")
|
|
|
|
}
|
|
|
|
|
2024-05-22 21:18:40 +02:00
|
|
|
block, err := aes.NewCipher(key)
|
2024-04-24 20:00:06 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2024-05-22 21:18:40 +02:00
|
|
|
aesgcm, err := cipher.NewGCM(block)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
nonce, ciphertext := encryptedData[:nonceSize], encryptedData[nonceSize:]
|
|
|
|
return aesgcm.Open(nil, nonce, ciphertext, nil)
|
2024-04-24 20:00:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func generateRandomKey() ([]byte, error) {
|
|
|
|
key := make([]byte, keySize)
|
|
|
|
_, err := rand.Read(key)
|
|
|
|
return key, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func generateID() string {
|
|
|
|
b := make([]byte, 16)
|
|
|
|
if _, err := rand.Read(b); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return hex.EncodeToString(b)
|
|
|
|
}
|