-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathfirebase.go
178 lines (161 loc) · 4.7 KB
/
firebase.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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/netip"
"os"
"strings"
"sync"
"time"
"cloud.google.com/go/firestore"
firebase "firebase.google.com/go"
"google.golang.org/api/option"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const maxShareSize = 10 * 1024 // 10kB max size of the JSON blob (might need to be increased in the future)
var (
firebaseStarted sync.Once
firestoreClient *firestore.Client
)
func initFirebase() {
firebaseStarted.Do(func() {
ctx := context.Background()
var app *firebase.App
var err error
if firebaseCredentials != "" {
// running locally
sa := option.WithCredentialsFile(firebaseCredentials)
cfg := &firebase.Config{}
app, err = firebase.NewApp(ctx, cfg, sa)
} else {
// running on Google Cloud
app, err = firebase.NewApp(ctx, nil)
}
if err != nil {
log.Fatalln(err)
}
firestoreClient, err = app.Firestore(ctx)
if err != nil {
log.Fatalln(err)
}
})
}
func handleShare(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == "GET" {
id := r.FormValue("id")
if id == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("no ID supplied"))
return
}
initFirebase()
ctx := context.Background()
doc, err := firestoreClient.Collection("shared").Doc(id).Get(ctx)
if status.Code(err) == codes.NotFound {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("ID not found"))
return
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("could not fetch shared data"))
fmt.Fprintln(os.Stderr, "could not fetch data:", err)
return
}
data, err := json.Marshal(map[string]any{
"data": doc.Data()["data"],
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("could not serialize shared data"))
fmt.Fprintln(os.Stderr, "could not serialize data:", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
} else if r.Method == "POST" {
if r.Header.Get("Content-Type") != "application/json" {
w.WriteHeader(http.StatusUnsupportedMediaType)
w.Write([]byte("expected application/json data"))
return
}
// Read the data from the POST request.
var data any
err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxShareSize)).Decode(&data)
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
w.Write([]byte("could not parse JSON"))
return
}
initFirebase()
ctx := context.Background()
// Use a RFC3339 formatted timestamp, rounded to a single minute.
timestamp := time.Now().UTC().Round(time.Minute)
// Read IP address, but make it less precise.
obfuscatedIP, err := getObfuscatedIP(r)
if err != nil {
log.Fatalln(err)
}
ref, _, err := firestoreClient.Collection("shared").Add(ctx, map[string]interface{}{
"time": timestamp,
"ip": obfuscatedIP,
"data": data,
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("could not store data"))
fmt.Fprintln(os.Stderr, "could not store data:", err)
return
}
// Return a JSON object. Not because we need it right now (we're just
// returning an ID), but it makes the API extensible in the future.
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"id": ref.ID,
})
}
}
// Obtain an obfuscated IP address, with the last bits removed to preserve
// privacy.
func getObfuscatedIP(r *http.Request) (string, error) {
var address netip.Addr
if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
// Running inside Google Cloud Run (or behind a reverse proxy anyway).
// Parse the last IP address in the comma-separated list, because that's
// the one that's added by Google Cloud Run.
parts := strings.Split(forwarded, ",")
var err error
address, err = netip.ParseAddr(strings.TrimSpace(parts[len(parts)-1]))
if err != nil {
return "", fmt.Errorf("could not parse X-Forwarded-For header: %w", err)
}
} else {
// Running locally.
addrport, err := netip.ParseAddrPort(r.RemoteAddr)
if err != nil {
return "", fmt.Errorf("could not parse r.RemoteAddr: %w", err)
}
address = addrport.Addr()
}
if address.Is4() {
// clear last octet
ip := address.As4()
ip[3] = 0
return netip.AddrFrom4(ip).String() + "/24", nil
} else { // IPv6
// Zero all but the first 3 octets, to make it a /48 address.
// We might want to consider redacting the address a bit more, since
// this still identifies a single ISP customer.
ip := address.As16()
for i := 6; i < 16; i++ {
ip[i] = 0
}
return netip.AddrFrom16(ip).String() + "/48", nil
}
}