Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTTP communication #174

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions client/coniksclient/internal/cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,11 @@ func register(cc *p.ConsistencyChecks, conf *client.Config, name string, key str
}
u, _ := url.Parse(regAddress)
switch u.Scheme {
case "https":
res, err = testutil.NewHTTPSClient(req, regAddress)
if err != nil {
return ("Error while receiving response: " + err.Error())
}
case "tcp":
res, err = testutil.NewTCPClient(req, regAddress)
if err != nil {
Expand Down Expand Up @@ -176,6 +181,11 @@ func keyLookup(cc *p.ConsistencyChecks, conf *client.Config, name string) string
var res []byte
u, _ := url.Parse(conf.Address)
switch u.Scheme {
case "https":
res, err = testutil.NewHTTPSClient(req, conf.Address)
if err != nil {
return ("Error while receiving response: " + err.Error())
}
case "tcp":
res, err = testutil.NewTCPClient(req, conf.Address)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion keyserver/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ for "read-only" requests (lookups, monitoring etc).
[policies]
...
[[addresses]]
address = "tcp://public.server.address:port"
address = "tcp://public.server.address:port" # or "https://public.server.address:port"
allow_registration = true
cert = "server.pem"
key = "server.key"
Expand Down
10 changes: 10 additions & 0 deletions keyserver/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,22 @@ import (
"bytes"
"crypto/tls"
"io"
"io/ioutil"
"net"
"net/http"
"time"

. "github.com/coniks-sys/coniks-go/protocol"
)

func (server *ConiksServer) makeHTTPSHandler(acceptableTypes map[int]bool) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body)
res, _ := server.makeHandler(acceptableTypes)(body)
w.Write(res)
}
}

func (server *ConiksServer) handleRequests(ln net.Listener, tlsConfig *tls.Config,
handler func(msg []byte) ([]byte, error)) {
defer ln.Close()
Expand Down
80 changes: 60 additions & 20 deletions keyserver/server.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package keyserver

import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"os/signal"
Expand Down Expand Up @@ -93,6 +95,7 @@ type ConiksServer struct {
configFilePath string
reloadChan chan os.Signal
epochTimer *time.Timer
httpServer *http.Server
}

// LoadServerConfig loads the ServerConfig for the server from the
Expand Down Expand Up @@ -171,22 +174,42 @@ func (server *ConiksServer) Run(addrs []*Address) {
server.epochUpdate()
server.waitStop.Done()
}()

hasRegistrationPerm := false
for i := 0; i < len(addrs); i++ {
addr := addrs[i]
perms := updatePerms(addr)
hasRegistrationPerm = hasRegistrationPerm || addr.AllowRegistration
ln, tlsConfig, perms := resolveAndListen(addr)
server.waitStop.Add(1)
go func() {
verb := "Listening"
if addr.AllowRegistration {
verb = "Accepting registrations"
u, err := url.Parse(addr.Address)
if err != nil {
panic(err)
}
switch u.Scheme {
case "https":
mux := http.NewServeMux()
mux.HandleFunc("/", server.makeHTTPSHandler(perms))
ln, tlsConfig := resolveAndListen(addr)
httpSrv := &http.Server{
Addr: u.Host,
Handler: mux,
TLSConfig: tlsConfig,
}
server.logger.Info(verb, "address", addr.Address)
server.handleRequests(ln, tlsConfig, server.makeHandler(perms))
server.waitStop.Done()
}()
server.httpServer = httpSrv
go func() {
httpSrv.Serve(ln)
}()
case "tcp", "unix":
ln, tlsConfig := resolveAndListen(addr)
server.waitStop.Add(1)
go func() {
server.handleRequests(ln, tlsConfig, server.makeHandler(perms))
server.waitStop.Done()
}()
}
verb := "Listening"
if addr.AllowRegistration {
verb = "Accepting registrations"
}
server.logger.Info(verb, "address", addr.Address)
}

if !hasRegistrationPerm {
Expand Down Expand Up @@ -236,20 +259,23 @@ func (server *ConiksServer) updatePolicies() {
}
}

func resolveAndListen(addr *Address) (ln net.Listener,
tlsConfig *tls.Config,
perms map[int]bool) {
perms = make(map[int]bool)
perms[protocol.KeyLookupType] = true
perms[protocol.KeyLookupInEpochType] = true
perms[protocol.MonitoringType] = true
perms[protocol.RegistrationType] = addr.AllowRegistration

func resolveAndListen(addr *Address) (ln net.Listener, tlsConfig *tls.Config) {
u, err := url.Parse(addr.Address)
if err != nil {
panic(err)
}
switch u.Scheme {
case "https":
cer, err := tls.LoadX509KeyPair(addr.TLSCertPath, addr.TLSKeyPath)
if err != nil {
panic(err)
}
tlsConfig = &tls.Config{Certificates: []tls.Certificate{cer}}
ln, err = tls.Listen("tcp", u.Host, tlsConfig)
if err != nil {
panic(err)
}
return
case "tcp":
// force to use TLS
cer, err := tls.LoadX509KeyPair(addr.TLSCertPath, addr.TLSKeyPath)
Expand Down Expand Up @@ -281,9 +307,23 @@ func resolveAndListen(addr *Address) (ln net.Listener,
}
}

func updatePerms(addr *Address) map[int]bool {
perms := make(map[int]bool)
perms[protocol.KeyLookupType] = true
perms[protocol.KeyLookupInEpochType] = true
perms[protocol.MonitoringType] = true
perms[protocol.RegistrationType] = addr.AllowRegistration
return perms
}

// Shutdown closes all of the server's connections and shuts down the server.
func (server *ConiksServer) Shutdown() error {
close(server.stop)
if server.httpServer != nil {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move this scope to line 199 (https://github.com/coast-team/coniks-go/blob/92c82f41423983acc2e0d2e60fb0858527b5e6e2/keyserver/server.go#L199) as

go func() {
  <-server.stop
  // shutdown httpServer [...]
}()

and remove httpServer from ConiksServer?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it is definitely a better solution !

defer cancel()
server.httpServer.Shutdown(ctx)
}
server.waitStop.Wait()
return nil
}
100 changes: 92 additions & 8 deletions keyserver/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ var registrationMsg = `
}
}
`

var keylookupMsg = `
{
"type": 1,
Expand All @@ -48,7 +47,6 @@ func startServer(t *testing.T, epDeadline Timestamp, useBot bool, policiesPath s
if err != nil {
t.Fatal(err)
}

addrs := []*Address{
&Address{
Address: testutil.PublicConnection,
Expand All @@ -57,6 +55,12 @@ func startServer(t *testing.T, epDeadline Timestamp, useBot bool, policiesPath s
AllowRegistration: !useBot,
},
}
addrs = append(addrs, &Address{
Address: testutil.PublicHTTPSConnection,
TLSCertPath: path.Join(dir, "server.pem"),
TLSKeyPath: path.Join(dir, "server.key"),
AllowRegistration: !useBot,
})
if useBot {
addrs = append(addrs, &Address{
Address: testutil.LocalConnection,
Expand All @@ -77,7 +81,6 @@ func startServer(t *testing.T, epDeadline Timestamp, useBot bool, policiesPath s
Path: path.Join(dir, "coniksserver.log"),
},
}

server := NewConiksServer(conf)
server.Run(conf.Addresses)
return server, func() {
Expand All @@ -101,7 +104,8 @@ func TestResolveAddresses(t *testing.T) {
TLSCertPath: path.Join(dir, "server.pem"),
TLSKeyPath: path.Join(dir, "server.key"),
}
ln, _, perms := resolveAndListen(addr)
perms := updatePerms(addr)
ln, _ := resolveAndListen(addr)
defer ln.Close()
if perms[RegistrationType] != false {
t.Error("Expect disallowing registration permission.")
Expand All @@ -112,7 +116,8 @@ func TestResolveAddresses(t *testing.T) {
Address: testutil.LocalConnection,
AllowRegistration: true,
}
ln, _, perms = resolveAndListen(addr)
perms = updatePerms(addr)
ln, _ = resolveAndListen(addr)
defer ln.Close()
if perms[RegistrationType] != true {
t.Error("Expect allowing registration permission.")
Expand Down Expand Up @@ -142,7 +147,7 @@ func TestServerReloadPoliciesWithError(t *testing.T) {
<-timer.C
}

func TestAcceptOutsideRegistrationRequests(t *testing.T) {
func TestAcceptOutsideRegistrationTCPRequests(t *testing.T) {
_, teardown := startServer(t, 60, false, "")
defer teardown()
rev, err := testutil.NewTCPClientDefault([]byte(registrationMsg))
Expand All @@ -160,6 +165,24 @@ func TestAcceptOutsideRegistrationRequests(t *testing.T) {
}
}

func TestAcceptOutsideRegistrationHTTPSRequests(t *testing.T) {
_, teardown := startServer(t, 60, false, "")
defer teardown()
rev, err := testutil.NewHTTPSClientDefault([]byte(registrationMsg))
if err != nil {
t.Error(err)
}
var response testutil.ExpectingDirProofResponse
err = json.Unmarshal(rev, &response)
if err != nil {
t.Log(string(rev))
t.Error(err)
}
if response.Error != ReqSuccess {
t.Error("Expect a successful registration", "got", response.Error)
}
}

func TestBotSendsRegistration(t *testing.T) {
_, teardown := startServer(t, 60, true, "")
defer teardown()
Expand All @@ -180,7 +203,7 @@ func TestBotSendsRegistration(t *testing.T) {
}
}

func TestSendsRegistrationFromOutside(t *testing.T) {
func TestSendsTCPRegistrationFromOutside(t *testing.T) {
_, teardown := startServer(t, 60, true, "")
defer teardown()

Expand All @@ -198,6 +221,24 @@ func TestSendsRegistrationFromOutside(t *testing.T) {
}
}

func TestSendsHTTPSRegistrationFromOutside(t *testing.T) {
_, teardown := startServer(t, 60, true, "")
defer teardown()

rev, err := testutil.NewHTTPSClientDefault([]byte(registrationMsg))
if err != nil {
t.Fatal(err)
}
var response Response
err = json.Unmarshal(rev, &response)
if err != nil {
t.Fatal(err)
}
if response.Error != ErrMalformedClientMessage {
t.Fatalf("Expect error code %d", ErrMalformedClientMessage)
}
}

func TestUpdateDirectory(t *testing.T) {
server, teardown := startServer(t, 1, true, "")
defer teardown()
Expand Down Expand Up @@ -349,7 +390,7 @@ func TestRegisterAndLookupInTheSameEpoch(t *testing.T) {
}
}

func TestRegisterAndLookup(t *testing.T) {
func TestRegisterAndTCPLookup(t *testing.T) {
server, teardown := startServer(t, 1, true, "")
defer teardown()

Expand Down Expand Up @@ -392,6 +433,49 @@ func TestRegisterAndLookup(t *testing.T) {
}
}

func TestRegisterAndHTTPSLookup(t *testing.T) {
server, teardown := startServer(t, 1, true, "")
defer teardown()

_, err := testutil.NewUnixClientDefault([]byte(registrationMsg))
if err != nil {
t.Fatal(err)
}

server.dir.Update()
rev, err := testutil.NewHTTPSClientDefault([]byte(keylookupMsg))
if err != nil {
t.Fatal(err)
}

var res testutil.ExpectingDirProofResponse
err = json.Unmarshal(rev, &res)
if err != nil {
t.Fatal(err)
}
if res.Error != ReqSuccess {
t.Fatal("Expect no error", "got", res.Error)
}
if res.DirectoryResponse.STR == nil {
t.Fatal("Expect the latets STR")
}

var str testutil.ExpectingSTR
err = json.Unmarshal(res.DirectoryResponse.STR, &str)
if err != nil {
t.Fatal(err)
}
if str.Epoch == 0 {
t.Fatal("Expect STR with epoch > 0")
}
if res.DirectoryResponse.AP == nil {
t.Fatal("Expect a proof of inclusion")
}
if res.DirectoryResponse.TB != nil {
t.Fatal("Expect returned TB is nil")
}
}

func TestKeyLookup(t *testing.T) {
server, teardown := startServer(t, 60, true, "")
defer teardown()
Expand Down
Loading