requests.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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
package repo

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"sync"

	"html/template"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"senary/auth"
	"senary/common"
	"slices"
	"strings"

	"github.com/bluekeyes/go-gitdiff/gitdiff"
)

type RequestList struct {
	RequestBase
	Requests []*common.IssueRequest
}

type RequestManager struct {
	config       *common.Config
	repo         string
	ac           *auth.AuthClient
	lock         sync.Mutex
	patchHandler PatchHandler
}

type RequestBase struct {
	User     common.AuthInfo
	Repo     string
	ClientID string
	Warnings []Warning
}

type Warning struct {
	Level   Level
	Message string
}

type RequestElement struct {
	RequestBase
	Request string

	Issue common.IssueRequest
}

type RequestThread struct {
	RequestBase
	Title    string
	ID       string
	Issue    common.IssueRequest
	Elements []template.HTML
}

func NewRequestManager(config *common.Config, repo string, ac *auth.AuthClient) *RequestManager {
	return &RequestManager{config: config, repo: repo, ac: ac, patchHandler: *NewPatchHandler(config, repo)}
}

func (rm *RequestManager) errorHandler(err string, w http.ResponseWriter, r *http.Request) {
	r.AddCookie(&http.Cookie{Name: "error", Value: err})
	rm.Serve(w, r)
}

func (rm *RequestManager) ApplyPatch(w http.ResponseWriter, r *http.Request) {

	authUser := rm.ac.GetAuthInfo(rm.config, r)

	if authUser.IsMaintainer {
		idString := r.PathValue("id")
		patchHash := r.PathValue("patch")
		err := rm.patchHandler.Apply(rm.RequestIssueElement(idString, patchHash))
		if err == nil {
			err := rm.patchHandler.Upstream()
			if err != nil {
				fmt.Printf("could not upstream: %v\n", err)
			}
			err = rm.patchHandler.Rebuild()
			if err != nil {
				fmt.Printf("could not rebuild: %v\n", err)
			}
			http.Redirect(w, r, r.Header.Get("Referer"), 302)
			return
		} else {
			fmt.Printf("could not apply patch: %v\n", err)
		}
	}
	http.Redirect(w, r, "/404", 404)
}

func (rm *RequestManager) ServePatch(w http.ResponseWriter, r *http.Request) {
	idString := r.PathValue("id")
	patchHash := r.PathValue("patch")
	patchfile, err := os.Open(rm.RequestIssueElement(idString, patchHash))
	if err == nil {
		defer patchfile.Close()
		w.Header().Set("Content-Disposition", "attachment; filename="+patchHash+".patch")
		w.Header().Set("Content-Type", "text/x-diff")
		io.Copy(w, patchfile)
		return
	}
	http.Redirect(w, r, "/404", 404)
}

func (rm *RequestManager) Serve(w http.ResponseWriter, r *http.Request) {

	baseResponse := RequestList{RequestBase: RequestBase{Repo: rm.repo, User: rm.ac.GetAuthInfo(rm.config, r), ClientID: rm.config.ClientID}}

	if cookie, _ := r.Cookie("error"); cookie != nil {
		baseResponse.Warnings = append(baseResponse.Warnings, Warning{Level: WARN, Message: cookie.Value})
	}

	if strings.HasSuffix(r.URL.Path, "/new") {
		if value := r.FormValue("type"); value == "issue" {
			rm.config.Templates.ExecuteTemplate(w, "request.new.tpl.html", baseResponse)
			return
		}
		if value := r.FormValue("type"); value == "patch" {
			rm.config.Templates.ExecuteTemplate(w, "request.newpatch.tpl.html", baseResponse)
			return
		}
	}

	// assume this is an issue thread...
	if !strings.HasSuffix(r.URL.Path, "/") {
		http.Redirect(w, r, r.URL.String()+"/", http.StatusMovedPermanently)
	}

	// list all issues
	if strings.HasSuffix(r.URL.Path, "requests/") {
		authuser := rm.ac.GetAuthInfo(rm.config, r)
		rl := baseResponse

		// Get a list of issues in creation order...
		issueList := rm.LoadIssues(rm.RequestLogPath(), func(hash string) (*common.IssueRequest, error) {
			data, err := os.ReadFile(rm.RequestIssuePath(hash))
			if err == nil {
				var issue common.IssueRequest
				err := json.Unmarshal(data, &issue)
				return &issue, err
			}
			return nil, err
		},
			func(ir common.IssueRequest) bool {
				return authuser.IsMaintainer
			},
			func(level Level, warning string) {

			})
		slices.Reverse(issueList)
		rl.Requests = issueList

		err := rm.config.Templates.ExecuteTemplate(w, "request.list.tpl.html", rl)
		if err != nil {
			fmt.Printf("error %v\n", err)
		}
		return
	}

	// otherwise list a single issue...
	authuser := rm.ac.GetAuthInfo(rm.config, r)
	// otherwise...
	rt := RequestThread{RequestBase: baseResponse.RequestBase}
	issuehash := path.Base(r.URL.Path)
	// Get a list of issues in creation order...

	issueList := rm.LoadIssues(rm.RequestIssueLogPath(issuehash), func(hash string) (*common.IssueRequest, error) {
		data, err := os.ReadFile(rm.RequestIssueElement(issuehash, hash))
		if err == nil {
			var issue common.IssueRequest
			err := json.Unmarshal(data, &issue)
			return &issue, err
		}
		return nil, err
	},
		func(ir common.IssueRequest) bool {
			return ir.RequestType == common.RequestInit || authuser.IsMaintainer
		},

		func(level Level, warning string) {

			rt.Warnings = append(rt.Warnings, Warning{Level: level, Message: warning})

		})

	for _, issue := range issueList {

		if issue.RequestType == common.RequestInit {
			rt.Title = issue.Summary
			rt.ID = issue.ID
			rt.Issue = *issue
		}

		var doc bytes.Buffer
		rm.config.Templates.ExecuteTemplate(&doc, "request.element.tpl.html", RequestElement{Issue: *issue, Request: issuehash, RequestBase: rt.RequestBase})
		rt.Elements = append(rt.Elements, template.HTML(doc.String()))
	}

	err := rm.config.Templates.ExecuteTemplate(w, "request.thread.tpl.html", rt)
	if err != nil {
		fmt.Printf("error %v\n", err)
	}
}

type Level int

const (
	WARN = Level(iota)
	INFO
)

func (rm *RequestManager) LoadIssues(logpath string, loadfn func(hash string) (*common.IssueRequest, error), approve func(common.IssueRequest) bool, warningCallback func(Level, string)) []*common.IssueRequest {

	issueMap := make(map[string]*common.IssueRequest)

	common.LogIer(logpath, func(le common.LogEntry) {
		//isFirst := issuehash == le.Hash
		if le.Type == common.LOG_APPROVED {
			issueMap[le.Hash].Approved = true
			issueMap[le.Hash].Moderated = false
		} else if le.Type == common.LOG_DELETED {
			issueMap[le.Hash].Approved = false
			issueMap[le.Hash].Moderated = false
		} else {

			issue, err := loadfn(le.Hash)
			if err == nil {

				issueMap[le.Hash] = issue
				issueMap[le.Hash].Moderated = true
				issueMap[le.Hash].Approved = approve(*issue)

				if issue.PatchRef != "" {
					// NOTE: this currently takes advantage of the fact that patches can only be associated with a top
					// level issue, this is not the ideal long term...
					patchfile, err := os.Open(rm.RequestIssueElement(le.Hash, issue.PatchRef))
					if err == nil {
						files, prelude, err := gitdiff.Parse(patchfile)
						if err == nil {

							header, err := gitdiff.ParsePatchHeader(prelude)
							if err == nil {
								patchSummary := common.PatchInfo{}
								patchSummary.Title = header.Title
								if header.Author != nil {
									patchSummary.Author = header.Author.String()
								}

								var doc bytes.Buffer
								rm.config.Templates.ExecuteTemplate(&doc, "diffstat.tpl.html", files)
								patchSummary.Body = template.HTML(doc.String())
								issue.PatchInfo = patchSummary

								if _, err := rm.patchHandler.CheckApplied(rm.RequestIssueElement(le.Hash, issue.PatchRef)); err == nil {
									warningCallback(INFO, "This Patch Has Been Applied")
								} else {
									if _, err := rm.patchHandler.CheckApply(rm.RequestIssueElement(le.Hash, issue.PatchRef)); err != nil {
										warningCallback(WARN, "This Patch Does Not Apply To The Current Repository")
									} else {
										warningCallback(INFO, "This Patch Can Be Applied To The Current Repository")
										issue.PatchInfo.CanBeApplied = true
									}
								}

							}
						}
					}
				}

			}
		}
	})

	issueList := []*common.IssueRequest{}

	for _, issue := range issueMap {
		if issue.Approved {
			issueList = append(issueList, issue)
		}
	}

	if len(issueList) > 0 {
		if issueList[0].Moderated {
			warningCallback(INFO, "Public Listing of this Request Is Pending Review By A Maintainer")
		}
	}

	slices.SortFunc(issueList, func(a *common.IssueRequest, b *common.IssueRequest) int {
		return a.Created.Compare(b.Created)
	})

	return issueList
}

func (rm *RequestManager) RequestLogPath() string {
	return filepath.Join(rm.config.RequestsDir, rm.repo, "log")
}

func (rm *RequestManager) RequestIssuePath(issuehash string) string {
	return filepath.Join(rm.config.RequestsDir, rm.repo, issuehash, issuehash)
}

func (rm *RequestManager) RequestIssueElement(issuehash string, subhash string) string {
	return filepath.Join(rm.config.RequestsDir, rm.repo, issuehash, subhash)
}

func (rm *RequestManager) RequestIssueLogPath(issuehash string) string {
	return filepath.Join(rm.config.RequestsDir, rm.repo, issuehash, "log")
}

func (rm *RequestManager) handleApprove(w http.ResponseWriter, r *http.Request) {

	if rm.ac.GetAuthInfo(rm.config, r).IsMaintainer {
		id := r.FormValue("requestid")
		eid := r.FormValue("elementid")

		if len(eid) == 0 {
			// approving a top-level
			err := rm.updateLog(rm.RequestLogPath(), id, common.LOG_APPROVED)
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}

			// approving the top-level sub-level
			err = rm.updateLog(rm.RequestIssueLogPath(id), id, common.LOG_APPROVED)
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}

		} else {

			// approving a sub-level
			err := rm.updateLog(rm.RequestIssueLogPath(id), eid, common.LOG_APPROVED)
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}
		}
	}
	http.Redirect(w, r, r.Header.Get("Referer"), 302)
}

func (rm *RequestManager) handleTombstone(w http.ResponseWriter, r *http.Request) {

	if rm.ac.GetAuthInfo(rm.config, r).IsMaintainer {
		id := r.FormValue("requestid")
		eid := r.FormValue("elementid")

		if len(eid) == 0 {
			// approving a top-level
			err := rm.updateLog(rm.RequestLogPath(), id, common.LOG_DELETED)
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}
		} else {
			// approving a sub-level
			err := rm.updateLog(rm.RequestIssueLogPath(id), eid, common.LOG_DELETED)
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}
		}
	}
	http.Redirect(w, r, r.Header.Get("Referer"), 302)
}

// thread safe logging (note: currently this means a global lock per repo for threads, this is likely fine for the target of smaller sites)
// as the locks are only used when recording hashes for new files/approvals/deletions
// TODO: in the future, break this down further to a lock per log?
func (rm *RequestManager) updateLog(logpath string, hash string, status common.LogType) error {
	rm.lock.Lock()
	defer rm.lock.Unlock()
	return common.WriteToLog(logpath, hash, status)
}

func (rm *RequestManager) handlePatch(w http.ResponseWriter, r *http.Request) {

	r.ParseMultipartForm(1024 * 1024 * int64(rm.config.MaxPatchSizeMB))
	file, _, err := r.FormFile("patchfile")
	if err != nil {
		rm.errorHandler("Could Not Create Patch Request", w, r)
		return
	}
	defer file.Close()

	id, err := common.RandomIdent(24)
	if err != nil {
		rm.errorHandler("Could Not Create Patch Request", w, r)
		return
	}

	fileBytes, err := io.ReadAll(file)
	if err != nil {
		rm.errorHandler("Could Not Create Patch Request", w, r)
		return
	}

	// TODO check that this is a patch file...
	buf := bytes.NewBuffer(fileBytes)
	_, description, err := gitdiff.Parse(buf)
	if err != nil {
		rm.errorHandler("Could Not Create Patch Request", w, r)
		return
	}
	if _, err := gitdiff.ParsePatchHeader(description); err != nil {
		rm.errorHandler("Could Not Create Patch Request", w, r)
		return
	}

	summary := r.FormValue("summary")
	issueRequest, err := common.NewIssueRequest(summary, description, rm.ac.GetAuthInfo(rm.config, r))
	if err != nil {
		rm.errorHandler("Could Not Create Patch Request", w, r)
		return
	}
	issueRequest.PatchRef = id

	patchRef := filepath.Join(rm.config.RequestsDir, rm.repo, issueRequest.ID, issueRequest.PatchRef)
	os.MkdirAll(filepath.Dir(patchRef), 0755)
	patchFile, _ := os.Create(patchRef)
	defer patchFile.Close()
	// write this byte array to our temporary file
	patchFile.Write(fileBytes)

	rm.SaveIssue(&issueRequest, w, r)

	http.Redirect(w, r, path.Join("/repos", rm.repo, "requests", issueRequest.ID), http.StatusTemporaryRedirect)
}

func (rm *RequestManager) SaveIssue(issueRequest *common.IssueRequest, w http.ResponseWriter, r *http.Request) {
	requestName := filepath.Join(rm.config.RequestsDir, rm.repo, issueRequest.ID, issueRequest.ID)
	os.MkdirAll(filepath.Dir(requestName), 0755)
	err := os.WriteFile(requestName, issueRequest.Serialize(), 0644)
	if err != nil {
		rm.errorHandler(err.Error(), w, r)
		return
	}

	// create the parent entry of the requests log
	err = rm.updateLog(filepath.Join(rm.config.RequestsDir, rm.repo, issueRequest.ID, "log"), issueRequest.ID, common.LOG_CREATED)
	if err != nil {
		rm.errorHandler(err.Error(), w, r)
		return
	}

	// finally write to our main requests log
	err = rm.updateLog(filepath.Join(rm.config.RequestsDir, rm.repo, "log"), issueRequest.ID, common.LOG_CREATED)
	if err != nil {
		rm.errorHandler(err.Error(), w, r)
		return
	}

	if issueRequest.User.IsMaintainer {
		// Auth Approve Maintainer Created Issues
		err = rm.updateLog(filepath.Join(rm.config.RequestsDir, rm.repo, "log"), issueRequest.ID, common.LOG_APPROVED)
		if err != nil {
			rm.errorHandler(err.Error(), w, r)
			return
		}

		// Auto Approve Maintainer Top Level Issue
		err = rm.updateLog(filepath.Join(rm.config.RequestsDir, rm.repo, issueRequest.ID, "log"), issueRequest.ID, common.LOG_APPROVED)
		if err != nil {
			rm.errorHandler(err.Error(), w, r)
			return
		}

	}

}

func (rm *RequestManager) handleNew(w http.ResponseWriter, r *http.Request) {
	if r.Response != nil {
		fmt.Printf("now here....\n")
		rm.Serve(w, r)
		return
	}

	summary := r.FormValue("summary")
	description := r.FormValue("description")
	replyto := r.FormValue("replyto")
	newtype := r.FormValue("type")
	if replyto == "" {

		if newtype == "issue" {
			if len(summary) == 0 || len(summary) > rm.config.MaxCommentLength {
				rm.errorHandler(fmt.Errorf("summary was empty, or too long").Error(), w, r)
				return
			}

			if len(description) == 0 || len(description) > rm.config.MaxCommentLength {
				rm.errorHandler(fmt.Errorf("description was empty, or too long").Error(), w, r)
				return
			}

			issueRequest, err := common.NewIssueRequest(summary, description, rm.ac.GetAuthInfo(rm.config, r))
			if err != nil {
				rm.errorHandler(err.Error(), w, r)
				return
			}

			rm.SaveIssue(&issueRequest, w, r)
			http.Redirect(w, r, path.Join("/repos", rm.repo, "requests", issueRequest.ID), http.StatusTemporaryRedirect)
		} else if newtype == "patch" {
			if len(summary) == 0 {
				rm.Serve(w, r)
				return
			}
			rm.handlePatch(w, r)
		}
	} else {
		// we are replying to an issue....
		if len(description) == 0 || len(description) > rm.config.MaxCommentLength {
			rm.errorHandler(fmt.Errorf("description was empty, or too long").Error(), w, r)
			return
		}
		issueRequest, err := common.NewIssueRequest(summary, description, rm.ac.GetAuthInfo(rm.config, r))
		if err != nil {
			rm.errorHandler(err.Error(), w, r)
			return
		}
		issueRequest.RequestType = common.RequestReply

		requestName := filepath.Join(rm.config.RequestsDir, rm.repo, replyto, issueRequest.ID)
		err = os.WriteFile(requestName, issueRequest.Serialize(), 0644)
		if err != nil {
			rm.errorHandler(err.Error(), w, r)
			return
		}

		// create the parent entry of the requests log
		err = rm.updateLog(rm.RequestIssueLogPath(replyto), issueRequest.ID, common.LOG_CREATED)
		if err != nil {
			rm.errorHandler(err.Error(), w, r)
			return
		}

		if issueRequest.User.IsMaintainer {
			// Auth Approve Maintainer Created Issues
			err = rm.updateLog(rm.RequestIssueLogPath(replyto), issueRequest.ID, common.LOG_APPROVED)
			if err != nil {
				rm.errorHandler(err.Error(), w, r)
				return
			}

		}

		http.Redirect(w, r, path.Join("/repos", rm.repo, "requests", replyto)+"/", http.StatusTemporaryRedirect)
		return
	}
}

func (rm *RequestManager) Submit(w http.ResponseWriter, r *http.Request) {

	if strings.HasSuffix(r.URL.Path, "/approve") {
		rm.handleApprove(w, r)
		return
	}

	if strings.HasSuffix(r.URL.Path, "/tombstone") {
		rm.handleTombstone(w, r)
		return
	}

	if strings.HasSuffix(r.URL.Path, "/new") {
		rm.handleNew(w, r)
		return
	}

	http.Redirect(w, r, "/404", 404)
}