~alazarte/uploader

ref: 0453a720e18ccf0d340e1d8c545874aca495a9d9 uploader/main.go -rw-r--r-- 3.0 KiB
0453a720 — Alejandro Lazarte allow secret rotation after each upload instead of timeout 7 months ago
                                                                                
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
package main

import (
	"encoding/csv"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"time"
)

var (
	outputPath      string
	secretsFilepath string
	port            string
	interval        uint

	// secret things
	secretOriginal string
	secrets        []string
	secretCurrent  string
	secretIndex    int
	rot            rotator
)

type rotator struct {
	rotate func()
}

func upload(w http.ResponseWriter, r *http.Request) {
	// upload only 10 Mb
	if err := r.ParseMultipartForm(10 << 20); err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	if secret, ok := r.MultipartForm.Value["secret"]; !ok || secret[0] != secretCurrent {
		log.Println("invalid secret:", secret[0], ", current is:", secretCurrent)
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	files, ok := r.MultipartForm.File["file"]
	if !ok {
		log.Println("no file found")
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	log.Println(len(files), "files found")
	for _, v := range files {
		f, err := v.Open()
		if err != nil {
			log.Println(err)
			continue
		}

		b := make([]byte, v.Size)
		f.Read(b)

		l, err := os.OpenFile(fmt.Sprintf("%s/%s", outputPath, v.Filename), os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			log.Println(err)
			return
		}
		defer l.Close()

		n, err := l.Write(b)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		log.Println("save file, size:", n)

		rot.rotate()
	}
}

func init() {
	flag.StringVar(&outputPath, "output", "", "path to where store uploaded files")
	flag.StringVar(&secretsFilepath, "secrets", "", "file with the secrets stored separated with ,: secret1,secret2...")
	flag.StringVar(&port, "port", "8080", "listening port")
	flag.UintVar(&interval, "interval", 0, "if bigger than zero, use as interval between secret rotation in minutes")
	flag.Parse()

	if outputPath == "" || secretsFilepath == "" {
		fmt.Println("either missimg output path or secrets filepath")
		fmt.Println("usage:")
		flag.PrintDefaults()
		os.Exit(1)
	}

	outputPath = filepath.Clean(outputPath)

	f, err := os.Open(secretsFilepath)
	if err != nil {
		fmt.Println("couldn't read secrets file:", err)
		os.Exit(2)
	}
	defer f.Close()

	// just read a single record of values
	secrets, err := csv.NewReader(f).Read()
	if err != nil {
		fmt.Println("failed to load secrets values:", err)
		os.Exit(2)
	}
	fmt.Println("secrets are:", secrets)

	i := 0
	if interval > 0 {
		go func() {
			for {
				if i == len(secrets) {
					i = 0
				}
				secretCurrent = secrets[i]
				log.Println("current secret:", secretCurrent)
				time.Sleep(time.Duration(interval) * time.Minute)
				i += 1
			}
		}()
		rot.rotate = func() {
			log.Println("fake rotator, current secret is:", secretCurrent)
		}
	} else {
		rot.rotate = func() {
			secretCurrent = secrets[secretIndex]
			log.Println("current secret:", secretCurrent)
			secretIndex++
		}
	}
	rot.rotate()
}

func main() {
	log.Printf("listening on port %s\n", port)
	http.HandleFunc("/", upload)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}