File tree Expand file tree Collapse file tree 3 files changed +15
-6
lines changed
Expand file tree Collapse file tree 3 files changed +15
-6
lines changed Original file line number Diff line number Diff line change @@ -25,7 +25,7 @@ log.Fatalf(...) // Fatal level - program will panic/exit
2525
2626// for http servers there is also
2727// access log type including user-agent, forwarded ip/proto (behind load balancer case),
28- // TLS crypto used
28+ // TLS crypto used and CN of peer certificate if any.
2929log.LogRequest (r, " some info" )
3030```
3131
Original file line number Diff line number Diff line change @@ -20,15 +20,21 @@ import (
2020 "net/http"
2121)
2222
23- // TLSInfo returns " https <cipher suite>" if the request is using TLS, or "" otherwise.
23+ // TLSInfo returns ' https <cipher suite> "<peer CN>"' if the request is using TLS
24+ // (and ' "<peer CN>"' part if mtls / a peer certificate is present) or "" otherwise.
2425func TLSInfo (r * http.Request ) string {
2526 if r .TLS == nil {
2627 return ""
2728 }
28- return fmt .Sprintf (" https %s" , tls .CipherSuiteName (r .TLS .CipherSuite ))
29+ cliCert := ""
30+ if len (r .TLS .PeerCertificates ) > 0 {
31+ cliCert = fmt .Sprintf (" %q" , r .TLS .PeerCertificates [0 ].Subject )
32+ }
33+ return fmt .Sprintf (" https %s%s" , tls .CipherSuiteName (r .TLS .CipherSuite ), cliCert )
2934}
3035
31- // LogRequest logs the incoming request, including headers when loglevel is verbose.
36+ // LogRequest logs the incoming request, TLSInfo,
37+ // including headers when loglevel is verbose.
3238//
3339//nolint:revive
3440func LogRequest (r * http.Request , msg string ) {
Original file line number Diff line number Diff line change 44 "bufio"
55 "bytes"
66 "crypto/tls"
7+ "crypto/x509"
8+ "crypto/x509/pkix"
79 "net/http"
810 "testing"
911)
@@ -17,14 +19,15 @@ func TestLogRequest(t *testing.T) {
1719 SetOutput (w )
1820 SetFlags (0 ) // remove timestamps
1921 h := http.Header {"foo" : []string {"bar" }}
20- r := & http.Request {TLS : & tls.ConnectionState {}, Header : h }
22+ cert := & x509.Certificate {Subject : pkix.Name {CommonName : "x\n yz" }} // make sure special chars are escaped
23+ r := & http.Request {TLS : & tls.ConnectionState {PeerCertificates : []* x509.Certificate {cert }}, Header : h }
2124 LogRequest (r , "test1" )
2225 r .TLS = nil
2326 r .Header = nil
2427 LogRequest (r , "test2" )
2528 w .Flush ()
2629 actual := b .String ()
27- expected := "test1: <nil> () \" \" https 0x0000\n Header Host: \n Header foo: bar\n " +
30+ expected := "test1: <nil> () \" \" https 0x0000 \" CN=x \\ nyz \" \n Header Host: \n Header foo: bar\n " +
2831 "test2: <nil> () \" \" \n Header Host: \n "
2932 if actual != expected {
3033 t .Errorf ("unexpected:\n %q\n vs:\n %q\n " , actual , expected )
You can’t perform that action at this time.
0 commit comments