-
Notifications
You must be signed in to change notification settings - Fork 7
/
server.go
133 lines (110 loc) · 2.48 KB
/
server.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"strconv"
"text/template"
"github.com/AndrewBurian/powermux"
)
type server struct {
config configuration
authenticator authenticator
router *powermux.ServeMux
}
func newServer(c configuration, a authenticator) server {
return server{
config: c,
authenticator: a,
router: powermux.NewServeMux(),
}
}
const (
DefaultExpiry = 9
)
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}
func (s *server) rootHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
loader, err := readFile(s.config.LoaderScript)
if err != nil {
log(err)
setErrorResponse(500, w)
return
}
tmpl, err := template.New("loader").Parse(loader)
if err != nil {
log(err)
setErrorResponse(500, w)
return
}
expiry := DefaultExpiry
if expiryParam := powermux.PathParam(r, "expiry"); expiryParam != "" {
expiry, _ = strconv.Atoi(expiryParam)
}
keyURL := fmt.Sprintf("%s/key", s.config.PublicURL)
expirySeconds := expiry * 3600
templateParams := struct {
URL string
Expiry int
}{keyURL, expirySeconds}
tmpl.Execute(w, templateParams)
}
}
func (s *server) keyHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
username, password, _ := r.BasicAuth()
authenticated, err := s.authenticator.authenticate(username, password)
if err != nil {
log(err)
setErrorResponse(503, w)
return
}
if !authenticated {
set401Response(w)
return
}
data, err := readFile(s.config.PrivateKey)
if err != nil {
log(err)
setErrorResponse(500, w)
return
}
fmt.Fprintf(w, (data))
}
}
func (s *server) pubKeyHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cmd := exec.Command("ssh-keygen", "-y", "-f", s.config.PrivateKey)
pubkey, err := cmd.Output()
if err != nil {
if e, ok := err.(*exec.ExitError); ok {
log(string(e.Stderr))
} else {
log(e)
}
setErrorResponse(500, w)
return
}
fmt.Fprintf(w, string(pubkey))
}
}
func set401Response(w http.ResponseWriter) {
w.Header().Add("Authenticate", "KeyGuard")
w.WriteHeader(401)
}
func setErrorResponse(code int, w http.ResponseWriter) {
w.WriteHeader(code)
}
func readFile(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
data, _ := ioutil.ReadAll(f)
return string(data), nil
}