summaryrefslogtreecommitdiff
path: root/pkg/rest/mailbox.go
blob: 7526e4b99dc7861d2546f41eefb5e3aca7881dcc (plain)
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// This file is part of taler-mailbox, the Taler Mailbox implementation.
// Copyright (C) 2022 Martin Schanzenbach
//
// Taler-mailbox is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Taler-mailbox is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL3.0-or-later

package mailbox

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	gnunetutil "git.gnunet.org/gnunet-go.git/pkg/util"
	"github.com/gorilla/mux"
	"gopkg.in/ini.v1"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"taler.net/taler-go.git/pkg/merchant"
	tos "taler.net/taler-go.git/pkg/rest"
	talerutil "taler.net/taler-go.git/pkg/util"
)

// Mailbox is the primary object of the Mailbox service
type Mailbox struct {

	// The main router
	Router *mux.Router

	// The main DB handle
	Db *gorm.DB

	// Our configuration from the config.json
	Cfg *ini.File

	// Merchant object
	Merchant merchant.Merchant
}

type identityMessage struct {
	// Public DH key used to encrypt the body. Must be fresh
	// and only used once (ephemeral).
	EphemeralKey string `json:"ephemeral_key"`

	// Encrypted message. Must be exactly 256-32 bytes long.
	Body string

	// Order ID, if the client recently paid for this message.
	//order_id?: string;
}

// VersionResponse is the JSON response of the /config enpoint
type VersionResponse struct {
	// libtool-style representation of the Merchant protocol version, see
	// https://www.gnu.org/software/libtool/manual/html_node/Versioning.html#Versioning
	// The format is "current:revision:age".
	Version string `json:"version"`

	// Name of the protocol.
	Name string `json:"name"` // "taler-mailbox"

	// fee for one month of registration
	MessageFee string `json:"message_fee"`

	// How long will the service store a message
	// before giving up
	DeliveryPeriod uint64 `josn:"delivery_period"`
}

// MailboxRateLimitedResponse is the JSON response when a rate limit is hit
type MailboxRateLimitedResponse struct {

	// Taler error code, TALER_EC_mailbox_REGISTER_RATE_LIMITED.
	Code int `json:"code"`

	// When the client should retry. Currently: In microseconds
	RetryDelay int64 `json:"retry_delay"`

	// The human readable error message.
	Hint string `json:"hint"`
}

type inboxEntry struct {
	// ORM
	gorm.Model `json:"-"`

	// and only used once (ephemeral).
	EphemeralKey string `json:"ephemeral_key"`

	// Encrypted message. Must be exactly 256-32 bytes long.
	Body string

	// Hash of the inbox for this entry
	HMailbox string

	// Order ID
	OrderID string

	// Read flag
	Read bool
}

func (m *Mailbox) configResponse(w http.ResponseWriter, r *http.Request) {
	dpStr := m.Cfg.Section("mailbox").Key("delivery_period").MustString("1w")
	dp, err := time.ParseDuration(dpStr)
	if err != nil {
		log.Fatal(err)
	}

	cfg := VersionResponse{
		Version:        "0:0:0",
		Name:           "taler-mailbox",
		MessageFee:     m.Cfg.Section("mailbox").Key("message_fee").MustString("KUDOS:1"),
		DeliveryPeriod: uint64(dp.Microseconds()),
	}
	w.Header().Set("Content-Type", "application/json")
	response, _ := json.Marshal(cfg)
	w.Write(response)
}

func (m *Mailbox) getMessagesResponse(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	//to, toSet := vars["timeout_ms"]
	var entries []inboxEntry
	// FIXME rate limit
	// FIXME timeout
	// FIXME possibly limit results here
	err := m.Db.Where("h_mailbox = ? AND read = ?", vars["h_mailbox"], false).Find(&entries).Error
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	if len(entries) == 0 {
		w.WriteHeader(http.StatusNoContent)
		return
	}
	for _, entry := range entries {
		eph, err := gnunetutil.DecodeStringToBinary(entry.EphemeralKey, 32)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		body, err := gnunetutil.DecodeStringToBinary(entry.Body, 256-32)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		entry.Read = true
		w.Write(eph)
		w.Write(body)
	}
	m.Db.Save(&entries)
	w.WriteHeader(http.StatusOK)
}

func (m *Mailbox) sendMessageResponse(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	var msg identityMessage
	var entry inboxEntry
	if r.Body == nil {
		http.Error(w, "No request body", 400)
		return
	}
	err := json.NewDecoder(r.Body).Decode(&msg)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	tx := m.Db.Where("h_mailbox = ?", vars["h_mailbox"])
	// FIXME max messages from config
	// FIXME unclear if this is how the API is defined
	if tx.RowsAffected > 10 {
		w.WriteHeader(http.StatusTooManyRequests)
		return
	}
	err = m.Db.First(&entry, "h_mailbox = ? AND ephemeral_key = ? AND body = ?", vars["h_mailbox"], msg.EphemeralKey, msg.Body).Error
	// FIXME
	cost, _ := talerutil.ParseAmount("KUDOS:1")
	if err != nil {
		entry.HMailbox = vars["h_mailbox"]
		entry.EphemeralKey = msg.EphemeralKey
		entry.Body = msg.Body
		entry.Read = false
	}
	if len(entry.OrderID) == 0 {
		// Add new order for new entry
		orderID, newOrderErr := m.Merchant.AddNewOrder(*cost)
		if newOrderErr != nil {
			fmt.Println(newOrderErr)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		entry.OrderID = orderID
	}
	// Check if order paid.
	payto, paytoErr := m.Merchant.IsOrderPaid(entry.OrderID)
	if paytoErr != nil {
		fmt.Println(paytoErr)
		w.WriteHeader(http.StatusInternalServerError)
		log.Println(paytoErr)
		return
	}
	if len(payto) != 0 {
		m.Db.Save(&entry)
		w.WriteHeader(http.StatusPaymentRequired)
		w.Header().Set("Taler", payto)
		return
	}
	// In this case, this order was paid
	m.Db.Save(&entry)
	w.WriteHeader(http.StatusNoContent)
}

func (m *Mailbox) termsResponse(w http.ResponseWriter, r *http.Request) {
	tos.ServiceTermsResponse(m.Cfg.Section("mailbox"), w, r)
}

func (m *Mailbox) privacyResponse(w http.ResponseWriter, r *http.Request) {
	tos.PrivacyPolicyResponse(m.Cfg.Section("mailbox"), w, r)
}

func (m *Mailbox) setupHandlers() {
	m.Router = mux.NewRouter().StrictSlash(true)

	/* ToS API */
	m.Router.HandleFunc("/terms", m.termsResponse).Methods("GET")
	m.Router.HandleFunc("/privacy", m.privacyResponse).Methods("GET")

	/* Config API */
	m.Router.HandleFunc("/config", m.configResponse).Methods("GET")

	/* Mailbox API */
	m.Router.HandleFunc("/{h_mailbox}", m.sendMessageResponse).Methods("POST")
	m.Router.HandleFunc("/{h_mailbox}", m.getMessagesResponse).Methods("GET")
}

// Initialize the Mailbox instance with cfgfile
func (m *Mailbox) Initialize(cfgfile string) {
	_cfg, err := ini.Load(cfgfile)
	if err != nil {
		fmt.Printf("Failed to read config: %v", err)
		os.Exit(1)
	}
	m.Cfg = _cfg
	if m.Cfg.Section("mailbox").Key("production").MustBool(false) {
		fmt.Println("Production mode enabled")
	}

	psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		m.Cfg.Section("mailbox-pq").Key("host").MustString("localhost"),
		m.Cfg.Section("mailbox-pq").Key("port").MustInt64(5432),
		m.Cfg.Section("mailbox-pq").Key("user").MustString("taler-mailbox"),
		m.Cfg.Section("mailbox-pq").Key("password").MustString("secret"),
		m.Cfg.Section("mailbox-pq").Key("db_name").MustString("taler-mailbox"))
	_db, err := gorm.Open(postgres.Open(psqlconn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Silent),
	})
	if err != nil {
		panic(err)
	}
	m.Db = _db
	if err := m.Db.AutoMigrate(&inboxEntry{}); err != nil {
		panic(err)
	}

	merchURL := m.Cfg.Section("mailbox").Key("merchant_baseurl_private").MustString("http://merchant.mailbox/instances/myInstance")
	merchToken := m.Cfg.Section("mailbox").Key("merchant_token").MustString("secretAccessToken")
	m.Merchant = merchant.NewMerchant(merchURL, merchToken)
	m.setupHandlers()
}