~gbmor/getwtxt

ref: 24e86fbcc7d8c4332290428959228d1df23f8872 getwtxt/registry/fetch_test.go -rw-r--r-- 6.3 KiB
24e86fbcBen Morrison conditionally parsing datestamp as either rfc3339Nano or rfc3339 1 year, 1 month 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
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
/*
Copyright (c) 2019 Ben Morrison (gbmor)

This file is part of Registry.

Registry is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Registry 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with Registry.  If not, see <https://www.gnu.org/licenses/>.
*/

package registry

import (
	"bufio"
	"fmt"
	"net/http"
	"os"
	"strings"
	"testing"
	"time"
)

func constructTwtxt() []byte {
	registry := initTestEnv()
	var resp []byte
	// iterates through each mock user's mock statuses
	for _, v := range registry.Users {
		for _, e := range v.Status {
			split := strings.Split(e, "\t")
			status := []byte(split[2] + "\t" + split[3] + "\n")
			resp = append(resp, status...)
		}
	}
	return resp
}

// this is just dumping all the mock statuses.
// it'll be served under fake paths as
// "remote" twtxt.txt files
func twtxtHandler(w http.ResponseWriter, _ *http.Request) {
	// prepare the response
	resp := constructTwtxt()
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	n, err := w.Write(resp)
	if err != nil || n == 0 {
		fmt.Printf("Got error or wrote zero bytes: %v bytes, %v\n", n, err)
	}
}

var getTwtxtCases = []struct {
	name      string
	url       string
	wantErr   bool
	localOnly bool
}{
	{
		name:      "Constructed Local twtxt.txt",
		url:       "http://localhost:8080/twtxt.txt",
		wantErr:   false,
		localOnly: true,
	},
	{
		name:      "Inaccessible Site With twtxt.txt",
		url:       "https://example33333333333.com/twtxt.txt",
		wantErr:   true,
		localOnly: false,
	},
	{
		name:      "Inaccessible Site Without twtxt.txt",
		url:       "https://example333333333333.com",
		wantErr:   true,
		localOnly: false,
	},
	{
		name:      "Local File Inclusion 1",
		url:       "file://init_test.go",
		wantErr:   true,
		localOnly: false,
	},
	{
		name:      "Local File Inclusion 2",
		url:       "/etc/passwd",
		wantErr:   true,
		localOnly: false,
	},
	{
		name:      "Remote File Inclusion",
		url:       "https://example.com/file.cgi",
		wantErr:   true,
		localOnly: false,
	},
	{
		name:      "Remote Registry",
		url:       "https://twtxt.tilde.institute/api/plain/tweets/",
		wantErr:   false,
		localOnly: false,
	},
	{
		name:      "Garbage Data",
		url:       "this will be replaced with garbage data",
		wantErr:   true,
		localOnly: true,
	},
}

// Test the function that yoinks the /twtxt.txt file
// for a given user.
func Test_GetTwtxt(t *testing.T) {
	var buf = make([]byte, 256)
	// read random data into case 4
	rando, _ := os.Open("/dev/random")
	reader := bufio.NewReader(rando)
	n, err := reader.Read(buf)
	if err != nil || n == 0 {
		t.Errorf("Couldn't set up test: %v\n", err)
	}
	getTwtxtCases[7].url = string(buf)

	if !getTwtxtCases[0].localOnly {
		http.Handle("/twtxt.txt", http.HandlerFunc(twtxtHandler))
		go fmt.Println(http.ListenAndServe(":8080", nil))
	}

	for _, tt := range getTwtxtCases {
		t.Run(tt.name, func(t *testing.T) {
			if tt.localOnly {
				t.Skipf("Local-only test. Skipping ... \n")
			}
			out, _, err := GetTwtxt(tt.url, nil)
			if tt.wantErr && err == nil {
				t.Errorf("Expected error: %v\n", tt.url)
			}
			if !tt.wantErr && err != nil {
				t.Errorf("Unexpected error: %v %v\n", tt.url, err)
			}
			if !tt.wantErr && out == nil {
				t.Errorf("Incorrect data received: %v\n", out)
			}
		})
	}

}

// running the benchmarks separately for each case
// as they have different properties (allocs, time)
func Benchmark_GetTwtxt(b *testing.B) {

	for i := 0; i < b.N; i++ {
		_, _, err := GetTwtxt("https://gbmor.dev/twtxt.txt", nil)
		if err != nil {
			continue
		}
	}
}

var parseTwtxtCases = []struct {
	name      string
	data      []byte
	wantErr   bool
	localOnly bool
}{
	{
		name:      "Constructed twtxt file",
		data:      constructTwtxt(),
		wantErr:   false,
		localOnly: false,
	},
	{
		name:      "Incorrectly formatted date",
		data:      []byte("2019 April 23rd\tI love twtxt!!!11"),
		wantErr:   true,
		localOnly: false,
	},
	{
		name:      "No data",
		data:      []byte{},
		wantErr:   true,
		localOnly: false,
	},
	{
		name:      "Variant rfc3339 datestamp",
		data:      []byte("2020-02-04T21:28:21.868659+00:00\tWill this work?"),
		wantErr:   false,
		localOnly: false,
	},
	{
		name:      "Random/garbage data",
		wantErr:   true,
		localOnly: true,
	},
}

// See if we can break ParseTwtxt or get it
// to throw an unexpected error
func Test_ParseUserTwtxt(t *testing.T) {
	var buf = make([]byte, 256)
	// read random data into case 4
	rando, _ := os.Open("/dev/random")
	reader := bufio.NewReader(rando)
	n, err := reader.Read(buf)
	if err != nil || n == 0 {
		t.Errorf("Couldn't set up test: %v\n", err)
	}
	parseTwtxtCases[4].data = buf

	for _, tt := range parseTwtxtCases {
		if tt.localOnly {
			t.Skipf("Local-only test: Skipping ... \n")
		}
		t.Run(tt.name, func(t *testing.T) {
			timemap, errs := ParseUserTwtxt(tt.data, "testuser", "testurl")
			if errs == nil && tt.wantErr {
				t.Errorf("Expected error(s), received none.\n")
			}

			if !tt.wantErr {
				if errs != nil {
					t.Errorf("Unexpected error: %v\n", errs)
				}

				for k, v := range timemap {
					if k == (time.Time{}) || v == "" {
						t.Errorf("Empty status or empty timestamp: %v, %v\n", k, v)
					}
				}
			}
		})
	}
}

func Benchmark_ParseUserTwtxt(b *testing.B) {
	var buf = make([]byte, 256)
	// read random data into case 4
	rando, _ := os.Open("/dev/random")
	reader := bufio.NewReader(rando)
	n, err := reader.Read(buf)
	if err != nil || n == 0 {
		b.Errorf("Couldn't set up benchmark: %v\n", err)
	}
	parseTwtxtCases[3].data = buf

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		for _, tt := range parseTwtxtCases {
			_, _ = ParseUserTwtxt(tt.data, "testuser", "testurl")
		}
	}
}

var timestampCases = []struct {
	name     string
	orig     string
	expected string
}{
	{
		name:     "Timezone appended",
		orig:     "2020-01-13T16:08:25.544735+00:00",
		expected: "2020-01-13T16:08:25.544735Z",
	},
	{
		name:     "It's fine already",
		orig:     "2020-01-14T00:19:45.092344Z",
		expected: "2020-01-14T00:19:45.092344Z",
	},
}