add secure mode to graphql http server

This commit is contained in:
jangko 2021-08-02 09:42:35 +07:00
parent 5ed7fc0af1
commit 53f6e0d186
No known key found for this signature in database
GPG Key ID: 31702AE10541E6B9
4 changed files with 126 additions and 5 deletions

View File

@ -9,10 +9,12 @@
import
std/[strutils, json, tables],
chronicles, chronos, chronos/apps/http/httpserver,
chronicles, chronos, chronos/apps/http/[httpserver, shttpserver],
./graphql, ./api, ./builtin/json_respstream,
./server_common, ./graphiql, zlib/gzip
export shttpserver
type
ContentType = enum
ctGraphQl
@ -198,6 +200,43 @@ proc new*(t: typedesc[GraphqlHttpServerRef],
else:
err("Could not create HTTP server instance: " & sres.error())
proc new*(t: typedesc[GraphqlHttpServerRef],
graphql: GraphqlRef,
address: TransportAddress,
tlsPrivateKey: TLSPrivateKey,
tlsCertificate: TLSCertificate,
secureFlags: set[TLSFlags] = {},
serverIdent: string = "",
serverFlags = {HttpServerFlags.NotifyDisconnect},
socketFlags: set[ServerFlags] = {ReuseAddr},
serverUri = Uri(),
maxConnections: int = -1,
backlogSize: int = 100,
bufferSize: int = 4096,
httpHeadersTimeout = 10.seconds,
maxHeadersSize: int = 8192,
maxRequestBodySize: int = 1_048_576): GraphqlHttpResult[GraphqlHttpServerRef] =
var server = GraphqlHttpServerRef(
graphql: graphql,
savePoint: graphql.getNameCounter,
defRespHeader: HttpTable.init([("Content-Type", "application/json")])
)
proc processCallback(rf: RequestFence): Future[HttpResponseRef] =
routingRequest(server, rf)
let sres = SecureHttpServerRef.new(address, processCallback,
tlsPrivateKey, tlsCertificate, serverFlags,
socketFlags, serverUri, serverIdent, secureFlags,
maxConnections, bufferSize, backlogSize,
httpHeadersTimeout, maxHeadersSize,
maxRequestBodySize)
if sres.isOk():
server.server = sres.get()
ok(server)
else:
err("Could not create HTTP server instance: " & sres.error())
proc state*(rs: GraphqlHttpServerRef): GraphqlHttpServerState {.raises: [Defect].} =
## Returns current GraphQL server's state.
case rs.server.state
@ -211,8 +250,9 @@ proc state*(rs: GraphqlHttpServerRef): GraphqlHttpServerState {.raises: [Defect]
proc start*(rs: GraphqlHttpServerRef) =
## Starts GraphQL server.
rs.server.start()
notice "GraphQL service started", at = "http://" & $rs.server.address & "/graphql"
notice "GraphiQL UI ready", at = "http://" & $rs.server.address & "/graphql/ui"
let scheme = rs.server.baseUri.scheme
notice "GraphQL service started", at = scheme & "://" & $rs.server.address & "/graphql"
notice "GraphiQL UI ready", at = scheme & "://" & $rs.server.address & "/graphql/ui"
proc stop*(rs: GraphqlHttpServerRef) {.async.} =
## Stop GraphQL server from accepting new connections.

View File

@ -19,6 +19,7 @@ type
Configuration* = ref object
bindAddress*: TransportAddress
schema*: Schema
secure*: bool
var testConfig {.threadvar.}: Configuration
@ -54,6 +55,8 @@ proc processArguments*(): Result[Configuration, string] =
config.bindAddress = initTAddress(value)
except Exception as e:
return err(e.msg)
of "secure", "s":
config.secure = true
else:
var msg = "Unknown option " & key
if value.len > 0: msg = msg & " : " & value

View File

@ -10,7 +10,7 @@
import
std/[os, strutils], chronos, chronicles,
../graphql, ../graphql/httpserver,
./swapi, ./ethapi, ./config
./swapi, ./ethapi, ./config, ../tests/keys/keys
proc loadSchema(ctx: GraphqlRef, schema: config.Schema): GraphqlResult =
notice "loading graphql api", name = schema
@ -44,7 +44,17 @@ proc main() =
debugEcho res.error
return
let sres = GraphqlHttpServerRef.new(ctx, conf.bindAddress, socketFlags = socketFlags)
let sres = if conf.secure:
GraphqlHttpServerRef.new(ctx,
address = conf.bindAddress,
tlsPrivateKey = TLSPrivateKey.init(SecureKey),
tlsCertificate = TLSCertificate.init(SecureCrt),
socketFlags = socketFlags)
else:
GraphqlHttpServerRef.new(ctx,
address = conf.bindAddress,
socketFlags = socketFlags)
if sres.isErr():
debugEcho sres.error
return

68
tests/keys/keys.nim Normal file
View File

@ -0,0 +1,68 @@
# nim-graphql
# Copyright (c) 2021 Status Research & Development GmbH
# Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
# at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.
# To create self-signed certificate and key you can use openssl
# openssl req -new -x509 -sha256 -newkey rsa:2048 -nodes \
# -keyout example-com.key.pem -days 3650 -out example-com.cert.pem
const SecureKey* = """
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCn7tXGLKMIMzOG
tVzUixax1/ftlSLcpEAkZMORuiCCnYjtIJhGZdzRFZC8fBlfAJZpLIAOfX2L2f1J
ZuwpwDkOIvNqKMBrl5Mvkl5azPT0rtnjuwrcqN5NFtbmZPKFYvbjex2aXGqjl5MW
nQIs/ZA++DVEXmaN9oDxcZsvRMDKfrGQf9iLeoVL47Gx9KpqNqD/JLIn4LpieumV
yYidm6ukTOqHRvrWm36y6VvKW4TE97THacULmkeahtTf8zDJbbh4EO+gifgwgJ2W
BUS0+5hMcWu8111mXmanlOVlcoW8fH8RmPjL1eK1Z3j3SVHEf7oWZtIVW5gGA0jQ
nfA4K51RAgMBAAECggEANZ7/R13tWKrwouy6DWuz/WlWUtgx333atUQvZhKmWs5u
cDjeJmxUC7b1FhoSB9GqNT7uTLIpKkSaqZthgRtNnIPwcU890Zz+dEwqMJgNByvl
it+oYjjRco/+YmaNQaYN6yjelPE5Y678WlYb4b29Fz4t0/zIhj/VgEKkKH2tiXpS
TIicoM7pSOscEUfaW3yp5bS5QwNU6/AaF1wws0feBACd19ZkcdPvr52jopbhxlXw
h3XTV/vXIJd5zWGp0h/Jbd4xcD4MVo2GjfkeORKY6SjDaNzt8OGtePcKnnbUVu8b
2XlDxukhDQXqJ3g0sHz47mhvo4JeIM+FgymRm+3QmQKBgQDTawrEA3Zy9WvucaC7
Zah02oE9nuvpF12lZ7WJh7+tZ/1ss+Fm7YspEKaUiEk7nn1CAVFtem4X4YCXTBiC
Oqq/o+ipv1yTur0ae6m4pwLm5wcMWBh3H5zjfQTfrClNN8yjWv8u3/sq8KesHPnT
R92/sMAptAChPgTzQphWbxFiYwKBgQDLWFaBqXfZYVnTyUvKX8GorS6jGWc6Eh4l
lAFA+2EBWDICrUxsDPoZjEXrWCixdqLhyehaI3KEFIx2bcPv6X2c7yx3IG5lA/Gx
TZiKlY74c6jOTstkdLW9RJbg1VUHUVZMf/Owt802YmEfUI5S5v7jFmKW6VG+io+K
+5KYeHD1uwKBgQDMf53KPA82422jFwYCPjLT1QduM2q97HwIomhWv5gIg63+l4BP
rzYMYq6+vZUYthUy41OAMgyLzPQ1ZMXQMi83b7R9fTxvKRIBq9xfYCzObGnE5vHD
SDDZWvR75muM5Yxr9nkfPkgVIPMO6Hg+hiVYZf96V0LEtNjU9HWmJYkLQQKBgQCQ
ULGUdGHKtXy7AjH3/t3CiKaAupa4cANVSCVbqQy/l4hmvfdu+AbH+vXkgTzgNgKD
nHh7AI1Vj//gTSayLlQn/Nbh9PJkXtg5rYiFUn+VdQBo6yMOuIYDPZqXFtCx0Nge
kvCwisHpxwiG4PUhgS+Em259DDonsM8PJFx2OYRx4QKBgEQpGhg71Oi9MhPJshN7
dYTowaMS5eLTk2264ARaY+hAIV7fgvUa+5bgTVaWL+Cfs33hi4sMRqlEwsmfds2T
cnQiJ4cU20Euldfwa5FLnk6LaWdOyzYt/ICBJnKFRwfCUbS4Bu5rtMEM+3t0wxnJ
IgaD04WhoL9EX0Qo3DC1+0kG
-----END PRIVATE KEY-----
"""
# This SSL certificate will expire 13 October 2030.
const SecureCrt* = """
-----BEGIN CERTIFICATE-----
MIIDnzCCAoegAwIBAgIUUdcusjDd3XQi3FPM8urdFG3qI+8wDQYJKoZIhvcNAQEL
BQAwXzELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEYMBYGA1UEAwwPMTI3LjAuMC4xOjQz
ODA4MB4XDTIwMTAxMjIxNDUwMVoXDTMwMTAxMDIxNDUwMVowXzELMAkGA1UE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