aboutsummaryrefslogtreecommitdiff
path: root/internal/modules/handler.go
blob: c01f716f197a64536980a4e942ab4a0c8da57a68 (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
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
package modules

import (
	"encoding/json"
	"fmt"
	"log/slog"
	"net/http"
	"net/url"
	"path/filepath"
	"strings"

	"git.ofmax.li/go-git-server/internal/admin"
	"github.com/go-chi/chi/v5"
)

// ModuleHandler handles Go module proxy requests and go-import metadata
type ModuleHandler struct {
	reposDir   string
	serverHost string
}

// normalizeImportPath creates a properly formatted full import path
func (h *ModuleHandler) normalizeImportPath(modulePath string) (string, error) {
	if h.serverHost == "" {
		return "", fmt.Errorf("serverHost cannot be empty")
	}
	if modulePath == "" {
		return "", fmt.Errorf("modulePath cannot be empty")
	}
	if strings.Contains(modulePath, "..") {
		return "", fmt.Errorf("modulePath cannot contain '..'")
	}

	// Clean the inputs
	host := strings.TrimRight(h.serverHost, "/")
	module := strings.Trim(modulePath, "/")

	// Validate that module path doesn't contain invalid characters
	if strings.ContainsAny(module, " \t\n\r") {
		return "", fmt.Errorf("modulePath cannot contain whitespace characters")
	}

	return host + "/" + module, nil
}

// buildRepoURL creates a proper repository URL
func (h *ModuleHandler) buildRepoURL(modulePath string) (string, error) {
	_, err := h.normalizeImportPath(modulePath)
	if err != nil {
		return "", err
	}

	// Use proper URL building to ensure valid URLs
	repoURL := &url.URL{
		Scheme: "https",
		Host:   h.serverHost,
		Path:   "/" + strings.Trim(modulePath, "/"),
	}

	return repoURL.String(), nil
}

// generateGoImportHTML creates the HTML response for go-import requests
func (h *ModuleHandler) generateGoImportHTML(modulePath string) (string, error) {
	fullImportPath, err := h.normalizeImportPath(modulePath)
	if err != nil {
		return "", fmt.Errorf("failed to normalize import path: %w", err)
	}

	repoURL, err := h.buildRepoURL(modulePath)
	if err != nil {
		return "", fmt.Errorf("failed to build repository URL: %w", err)
	}

	return fmt.Sprintf(`<!DOCTYPE html>
<html>
<head>
	<meta name="go-import" content="%s git %s">
	<meta name="go-source" content="%s %s %s/tree/{/dir} %s/blob/{/dir}/{file}#L{line}">
</head>
<body>
	go get %s
</body>
</html>`,
		fullImportPath, repoURL,
		fullImportPath, repoURL, repoURL, repoURL,
		fullImportPath), nil
}

// NewModuleHandler creates a new module handler with explicit routes for known repos
func NewModuleHandler(reposDir, serverHost string, config *admin.ServerRepos) http.Handler {
	handler := &ModuleHandler{
		reposDir:   reposDir,
		serverHost: serverHost,
	}

	r := chi.NewRouter()

	if config == nil {
		slog.Warn("no server config provided, falling back to catch-all routing")
		r.Get("/*", handler.handleAllRequests)
		return r
	}

	// Register explicit routes only for repositories configured as Go modules
	for _, repo := range config.Repos {
		if !repo.GoModule {
			slog.Debug("skipping non-Go module repo", "repo", repo.Name)
			continue
		}

		// Use repo name as module path
		modulePath := repo.Name

		r.Get("/"+modulePath+"/@v/list", handler.createVersionListHandler(modulePath))
		r.Get("/"+modulePath+"/@v/*", handler.createGenericVersionHandler(modulePath))
		r.Get("/"+modulePath+"/@latest", handler.createLatestVersionHandler(modulePath))
		r.Get("/"+modulePath, handler.createGoImportHandler(modulePath))
		r.Get("/"+modulePath+"/", handler.createGoImportHandler(modulePath))

		slog.Debug("registered Go module routes", "module", modulePath)
	}

	return r
}

// Handler creators that capture the module path
func (h *ModuleHandler) createVersionListHandler(modulePath string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		h.handleVersionListForModule(w, r, modulePath)
	}
}

func (h *ModuleHandler) createLatestVersionHandler(modulePath string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		h.handleLatestVersionForModule(w, r, modulePath)
	}
}

func (h *ModuleHandler) createGoImportHandler(modulePath string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		h.handleGoImportForModule(w, r, modulePath)
	}
}

func (h *ModuleHandler) createGenericVersionHandler(modulePath string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		path := r.URL.Path

		if strings.HasSuffix(path, ".info") {
			version := ExtractVersion(path)
			h.handleVersionInfoForModule(w, r, modulePath, version)
		} else if strings.HasSuffix(path, ".mod") {
			version := ExtractVersion(path)
			h.handleModFileForModule(w, r, modulePath, version)
		} else if strings.HasSuffix(path, ".zip") {
			version := ExtractVersion(path)
			h.handleModuleZipForModule(w, r, modulePath, version)
		} else {
			http.NotFound(w, r)
		}
	}
}

// handleAllRequests routes to the appropriate handler based on the URL path
func (h *ModuleHandler) handleAllRequests(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path

	// Route to specific handlers based on path patterns
	if strings.HasSuffix(path, "/@v/list") {
		h.handleVersionList(w, r)
		return
	}

	if strings.HasSuffix(path, "/@latest") {
		h.handleLatestVersion(w, r)
		return
	}

	if strings.Contains(path, "/@v/") {
		if strings.HasSuffix(path, ".info") {
			h.handleVersionInfo(w, r)
			return
		}
		if strings.HasSuffix(path, ".mod") {
			h.handleModFile(w, r)
			return
		}
		if strings.HasSuffix(path, ".zip") {
			h.handleModuleZip(w, r)
			return
		}
	}

	// Default to go-import handler for all other requests
	h.handleGoImport(w, r)
}

// New handler methods that accept module path as parameter
func (h *ModuleHandler) handleVersionListForModule(w http.ResponseWriter, r *http.Request, modulePath string) {
	repoPath := filepath.Join(h.reposDir, modulePath+".git")

	versions, err := h.getVersions(repoPath)
	if err != nil {
		slog.Error("failed to get versions", "module", modulePath, "error", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(http.StatusOK)

	for _, version := range versions {
		fmt.Fprintln(w, version)
	}

	slog.Debug("served version list", "module", modulePath, "count", len(versions))
}

func (h *ModuleHandler) handleLatestVersionForModule(w http.ResponseWriter, r *http.Request, modulePath string) {
	repoPath := filepath.Join(h.reposDir, modulePath+".git")

	version, err := h.getLatestVersion(repoPath)
	if err != nil {
		slog.Error("failed to get latest version", "module", modulePath, "error", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	timestamp, err := h.getVersionTimestamp(repoPath, version)
	if err != nil {
		slog.Error("failed to get version timestamp", "module", modulePath, "version", version, "error", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	info := VersionInfo{
		Version: version,
		Time:    timestamp,
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(info); err != nil {
		slog.Error("failed to encode JSON response", "error", err)
	}

	slog.Debug("served latest version", "module", modulePath, "version", version)
}

func (h *ModuleHandler) handleVersionInfoForModule(w http.ResponseWriter, r *http.Request, modulePath, version string) {
	repoPath := filepath.Join(h.reposDir, modulePath+".git")

	timestamp, err := h.getVersionTimestamp(repoPath, version)
	if err != nil {
		slog.Error("failed to get version timestamp", "module", modulePath, "version", version, "error", err)
		// Check if it's a repository access issue (500) vs version not found (404)
		if strings.Contains(err.Error(), "repository does not exist") || strings.Contains(err.Error(), "failed to open repository") {
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		} else {
			http.Error(w, "Not Found", http.StatusNotFound)
		}
		return
	}

	info := VersionInfo{
		Version: version,
		Time:    timestamp,
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(info); err != nil {
		slog.Error("failed to encode JSON response", "error", err)
	}

	slog.Debug("served version info", "module", modulePath, "version", version)
}

func (h *ModuleHandler) handleModFileForModule(w http.ResponseWriter, r *http.Request, modulePath, version string) {
	repoPath := filepath.Join(h.reposDir, modulePath+".git")

	modContent, err := h.getModFile(repoPath, version)
	if err != nil {
		slog.Error("failed to get mod file", "module", modulePath, "version", version, "error", err)
		// Check if it's a repository access issue (500) vs version not found (404)
		if strings.Contains(err.Error(), "repository does not exist") || strings.Contains(err.Error(), "failed to open repository") {
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		} else {
			http.Error(w, "Not Found", http.StatusNotFound)
		}
		return
	}

	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	if _, err := w.Write(modContent); err != nil {
		slog.Error("failed to write mod file response", "error", err)
	}

	slog.Debug("served mod file", "module", modulePath, "version", version)
}

func (h *ModuleHandler) handleModuleZipForModule(w http.ResponseWriter, r *http.Request, modulePath, version string) {
	repoPath := filepath.Join(h.reposDir, modulePath+".git")

	zipData, err := h.getModuleZip(repoPath, version)
	if err != nil {
		slog.Error("failed to get module zip", "module", modulePath, "version", version, "error", err)
		// Check if it's a repository access issue (500) vs version not found (404)
		if strings.Contains(err.Error(), "repository does not exist") || strings.Contains(err.Error(), "failed to open repository") {
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		} else {
			http.Error(w, "Not Found", http.StatusNotFound)
		}
		return
	}

	w.Header().Set("Content-Type", "application/zip")
	w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s@%s.zip",
		strings.ReplaceAll(modulePath, "/", "-"), version))
	w.WriteHeader(http.StatusOK)
	if _, err := w.Write(zipData); err != nil {
		slog.Error("failed to write zip response", "error", err)
	}

	slog.Debug("served module zip", "module", modulePath, "version", version, "size", len(zipData))
}

func (h *ModuleHandler) handleGoImportForModule(w http.ResponseWriter, r *http.Request, modulePath string) {
	// Only handle if go-get=1 parameter is present
	if r.URL.Query().Get("go-get") != "1" {
		http.NotFound(w, r)
		return
	}

	// Generate HTML with go-import meta tag
	html, err := h.generateGoImportHTML(modulePath)
	if err != nil {
		slog.Error("failed to generate go-import HTML", "module", modulePath, "error", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	if _, err := w.Write([]byte(html)); err != nil {
		slog.Error("failed to write go-import response", "error", err)
	}

	slog.Debug("served go-import", "module", modulePath)
}

// handleGoImport serves the go-import meta tag for module discovery
func (h *ModuleHandler) handleGoImport(w http.ResponseWriter, r *http.Request) {
	// Only handle if go-get=1 parameter is present
	if r.URL.Query().Get("go-get") != "1" {
		http.NotFound(w, r)
		return
	}

	modulePath := ExtractModulePath(r.URL.Path)

	// Generate HTML with go-import meta tag
	html, err := h.generateGoImportHTML(modulePath)
	if err != nil {
		slog.Error("failed to generate go-import HTML", "module", modulePath, "error", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	if _, err := w.Write([]byte(html)); err != nil {
		slog.Error("failed to write go-import response", "error", err)
	}

	slog.Debug("served go-import", "module", modulePath)
}

// handleVersionList returns a list of available versions
func (h *ModuleHandler) handleVersionList(w http.ResponseWriter, r *http.Request) {
	modulePath := ExtractModulePath(r.URL.Path)
	repoPath := filepath.Join(h.reposDir, modulePath+".git")

	versions, err := h.getVersions(repoPath)
	if err != nil {
		slog.Error("failed to get versions", "module", modulePath, "error", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(http.StatusOK)

	for _, version := range versions {
		fmt.Fprintln(w, version)
	}

	slog.Debug("served version list", "module", modulePath, "count", len(versions))
}

// handleLatestVersion returns the latest version information
func (h *ModuleHandler) handleLatestVersion(w http.ResponseWriter, r *http.Request) {
	modulePath := ExtractModulePath(r.URL.Path)
	repoPath := filepath.Join(h.reposDir, modulePath+".git")

	version, err := h.getLatestVersion(repoPath)
	if err != nil {
		slog.Error("failed to get latest version", "module", modulePath, "error", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	timestamp, err := h.getVersionTimestamp(repoPath, version)
	if err != nil {
		slog.Error("failed to get version timestamp", "module", modulePath, "version", version, "error", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	info := VersionInfo{
		Version: version,
		Time:    timestamp,
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(info); err != nil {
		slog.Error("failed to encode JSON response", "error", err)
	}

	slog.Debug("served latest version", "module", modulePath, "version", version)
}

// handleVersionInfo returns version metadata
func (h *ModuleHandler) handleVersionInfo(w http.ResponseWriter, r *http.Request) {
	modulePath := ExtractModulePath(r.URL.Path)
	version := ExtractVersion(r.URL.Path)
	repoPath := filepath.Join(h.reposDir, modulePath+".git")

	timestamp, err := h.getVersionTimestamp(repoPath, version)
	if err != nil {
		slog.Error("failed to get version timestamp", "module", modulePath, "version", version, "error", err)
		// Check if it's a repository access issue (500) vs version not found (404)
		if strings.Contains(err.Error(), "repository does not exist") || strings.Contains(err.Error(), "failed to open repository") {
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		} else {
			http.Error(w, "Not Found", http.StatusNotFound)
		}
		return
	}

	info := VersionInfo{
		Version: version,
		Time:    timestamp,
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(info); err != nil {
		slog.Error("failed to encode JSON response", "error", err)
	}

	slog.Debug("served version info", "module", modulePath, "version", version)
}

// handleModFile returns the go.mod file for a specific version
func (h *ModuleHandler) handleModFile(w http.ResponseWriter, r *http.Request) {
	modulePath := ExtractModulePath(r.URL.Path)
	version := ExtractVersion(r.URL.Path)
	repoPath := filepath.Join(h.reposDir, modulePath+".git")

	modContent, err := h.getModFile(repoPath, version)
	if err != nil {
		slog.Error("failed to get mod file", "module", modulePath, "version", version, "error", err)
		// Check if it's a repository access issue (500) vs version not found (404)
		if strings.Contains(err.Error(), "repository does not exist") || strings.Contains(err.Error(), "failed to open repository") {
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		} else {
			http.Error(w, "Not Found", http.StatusNotFound)
		}
		return
	}

	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	if _, err := w.Write(modContent); err != nil {
		slog.Error("failed to write mod file response", "error", err)
	}

	slog.Debug("served mod file", "module", modulePath, "version", version)
}

// handleModuleZip returns a zip archive of the module source
func (h *ModuleHandler) handleModuleZip(w http.ResponseWriter, r *http.Request) {
	modulePath := ExtractModulePath(r.URL.Path)
	version := ExtractVersion(r.URL.Path)
	repoPath := filepath.Join(h.reposDir, modulePath+".git")

	zipData, err := h.getModuleZip(repoPath, version)
	if err != nil {
		slog.Error("failed to get module zip", "module", modulePath, "version", version, "error", err)
		// Check if it's a repository access issue (500) vs version not found (404)
		if strings.Contains(err.Error(), "repository does not exist") || strings.Contains(err.Error(), "failed to open repository") {
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		} else {
			http.Error(w, "Not Found", http.StatusNotFound)
		}
		return
	}

	w.Header().Set("Content-Type", "application/zip")
	w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s@%s.zip",
		strings.ReplaceAll(modulePath, "/", "-"), version))
	w.WriteHeader(http.StatusOK)
	if _, err := w.Write(zipData); err != nil {
		slog.Error("failed to write zip response", "error", err)
	}

	slog.Debug("served module zip", "module", modulePath, "version", version, "size", len(zipData))
}

// VersionInfo represents module version metadata
type VersionInfo struct {
	Version string `json:"Version"`
	Time    string `json:"Time"`
}