9
9
"github.com/st2projects/ssh-sentinel-server/crypto"
10
10
"github.com/st2projects/ssh-sentinel-server/helper"
11
11
"github.com/st2projects/ssh-sentinel-server/sql"
12
- "io/ioutil "
12
+ "io"
13
13
"net/http"
14
14
"time"
15
15
)
@@ -18,41 +18,56 @@ func AuthenticationHandler(next http.Handler) http.Handler {
18
18
fn := func (w http.ResponseWriter , r * http.Request ) {
19
19
w .Header ().Set (contentTypeKey , jsonContentType )
20
20
21
- body , err := ioutil .ReadAll (r .Body )
21
+ body , err := io .ReadAll (r .Body )
22
22
23
23
if err != nil {
24
24
panic (helper .NewError ("Failed to marshall request %s" , err ))
25
25
}
26
26
27
27
signRequest , err := MarshallSigningRequest (bytes .NewReader (body ))
28
28
29
- r .Body = ioutil .NopCloser (bytes .NewBuffer (body ))
29
+ r .Body = io .NopCloser (bytes .NewBuffer (body ))
30
30
31
31
if err != nil {
32
32
panic (helper .NewError ("Failed to marshall request %s" , err ))
33
33
}
34
34
35
- user := sql .GetUserByUsername (signRequest .Username )
35
+ user , err := sql .GetUserByUsername (signRequest .Username )
36
+
37
+ if err != nil {
38
+ authorisationFailed (w , "No such user %s" , helper .Sanitize (signRequest .Username ))
39
+ }
36
40
37
41
hasValidAPIKey , err := crypto .Validate (signRequest .APIKey , user .APIKey .Key )
38
42
39
43
if ! hasValidAPIKey {
40
- w .WriteHeader (http .StatusUnauthorized )
41
- panic (helper .NewError ("Unauthorised key" ))
44
+ authorisationFailed (w , "Invalid API key for user %s" , helper .Sanitize (signRequest .Username ))
42
45
}
43
46
44
47
hasValidPrincipals := CheckPrincipals (user .Principals , signRequest .Principals )
45
48
46
49
if ! hasValidPrincipals {
47
- panic (helper .NewError ("One or more unauthorised principals requested %v" , signRequest .Principals ))
50
+ // Sanitize the principals for logging
51
+ helper .SanitizeStringSlice (signRequest .Principals )
52
+ authorisationFailed (w , "One or more unauthorised principals requested %v" , signRequest .Principals )
48
53
}
49
54
55
+ log .Infof ("User %s is authenticated" , helper .Sanitize (signRequest .Username ))
56
+
50
57
next .ServeHTTP (w , r )
51
58
}
52
59
53
60
return http .HandlerFunc (fn )
54
61
}
55
62
63
+ func authorisationFailed (w http.ResponseWriter , msg string , args ... any ) {
64
+ w .WriteHeader (http .StatusUnauthorized )
65
+
66
+ log .Errorf (msg , args ... )
67
+
68
+ panic (helper .NewError ("Authentication failed" ))
69
+ }
70
+
56
71
func LoggingHandler (next http.Handler ) http.Handler {
57
72
fn := func (w http.ResponseWriter , r * http.Request ) {
58
73
t1 := time .Now ()
0 commit comments