Merge pull request #45 from letsencrypt/mvdan-lint-errcheck-fixes

Golint Error Check Fixes
This commit is contained in:
James 'J.C.' Jones 2015-03-21 08:49:05 -07:00
commit 8dc00128b6
16 changed files with 184 additions and 197 deletions

View File

@ -2,6 +2,7 @@
// This Source Code Form is subject to the terms of the Mozilla Public // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this // License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
package analysisengine package analysisengine
import ( import (
@ -19,7 +20,7 @@ type AnalysisEngine interface {
// An Analysis Engine that just logs to the JSON Logger. // An Analysis Engine that just logs to the JSON Logger.
type LoggingAnalysisEngine struct { type LoggingAnalysisEngine struct {
jsonLogger *log.JsonLogger jsonLogger *log.JSONLogger
} }
func (eng *LoggingAnalysisEngine) ProcessMessage(delivery amqp.Delivery) { func (eng *LoggingAnalysisEngine) ProcessMessage(delivery amqp.Delivery) {
@ -28,6 +29,6 @@ func (eng *LoggingAnalysisEngine) ProcessMessage(delivery amqp.Delivery) {
} }
// Construct a new Analysis Engine. // Construct a new Analysis Engine.
func NewLoggingAnalysisEngine(logger *log.JsonLogger) AnalysisEngine { func NewLoggingAnalysisEngine(logger *log.JSONLogger) AnalysisEngine {
return &LoggingAnalysisEngine{jsonLogger: logger} return &LoggingAnalysisEngine{jsonLogger: logger}
} }

View File

@ -2,16 +2,18 @@
// This Source Code Form is subject to the terms of the Mozilla Public // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this // License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
package analysisengine package analysisengine
import ( import (
"testing"
"github.com/letsencrypt/boulder/log" "github.com/letsencrypt/boulder/log"
"github.com/streadway/amqp" "github.com/streadway/amqp"
"testing"
) )
func TestNewLoggingAnalysisEngine(t *testing.T) { func TestNewLoggingAnalysisEngine(t *testing.T) {
log := log.NewJsonLogger("newEngine") log := log.NewJSONLogger("newEngine")
ae := NewLoggingAnalysisEngine(log) ae := NewLoggingAnalysisEngine(log)
// Trivially check an empty mock message // Trivially check an empty mock message

View File

@ -6,12 +6,13 @@
package main package main
import ( import (
"github.com/codegangsta/cli"
"github.com/streadway/amqp"
"log" "log"
"net/url" "net/url"
"os" "os"
"github.com/codegangsta/cli"
"github.com/streadway/amqp"
"github.com/letsencrypt/boulder/analysis" "github.com/letsencrypt/boulder/analysis"
blog "github.com/letsencrypt/boulder/log" blog "github.com/letsencrypt/boulder/log"
) )
@ -31,7 +32,7 @@ const (
AmqpImmediate = false AmqpImmediate = false
) )
func startMonitor(AmqpUrl string, logger *blog.JsonLogger) { func startMonitor(AmqpURL string, logger *blog.JSONLogger) {
ae := analysisengine.NewLoggingAnalysisEngine(logger) ae := analysisengine.NewLoggingAnalysisEngine(logger)
@ -41,16 +42,14 @@ func startMonitor(AmqpUrl string, logger *blog.JsonLogger) {
log.Fatalf("Could not determine hostname") log.Fatalf("Could not determine hostname")
} }
conn, err := amqp.Dial(AmqpUrl) conn, err := amqp.Dial(AmqpURL)
if err != nil { if err != nil {
log.Fatalf("Could not connect to AMQP server: %s", err) log.Fatalf("Could not connect to AMQP server: %s", err)
return
} }
rpcCh, err := conn.Channel() rpcCh, err := conn.Channel()
if err != nil { if err != nil {
log.Fatalf("Could not start channel: %s", err) log.Fatalf("Could not start channel: %s", err)
return
} }
err = rpcCh.ExchangeDeclare( err = rpcCh.ExchangeDeclare(
@ -63,7 +62,6 @@ func startMonitor(AmqpUrl string, logger *blog.JsonLogger) {
nil) nil)
if err != nil { if err != nil {
log.Fatalf("Could not declare exchange: %s", err) log.Fatalf("Could not declare exchange: %s", err)
return
} }
_, err = rpcCh.QueueDeclare( _, err = rpcCh.QueueDeclare(
@ -75,7 +73,6 @@ func startMonitor(AmqpUrl string, logger *blog.JsonLogger) {
nil) nil)
if err != nil { if err != nil {
log.Fatalf("Could not declare queue: %s", err) log.Fatalf("Could not declare queue: %s", err)
return
} }
err = rpcCh.QueueBind( err = rpcCh.QueueBind(
@ -86,7 +83,6 @@ func startMonitor(AmqpUrl string, logger *blog.JsonLogger) {
nil) nil)
if err != nil { if err != nil {
log.Fatalf("Could not bind queue: %s", err) log.Fatalf("Could not bind queue: %s", err)
return
} }
deliveries, err := rpcCh.Consume( deliveries, err := rpcCh.Consume(
@ -99,7 +95,6 @@ func startMonitor(AmqpUrl string, logger *blog.JsonLogger) {
nil) nil)
if err != nil { if err != nil {
log.Fatalf("Could not subscribe to queue: %s", err) log.Fatalf("Could not subscribe to queue: %s", err)
return
} }
// Run forever. // Run forever.
@ -141,7 +136,7 @@ func main() {
} }
app.Action = func(c *cli.Context) { app.Action = func(c *cli.Context) {
logger := blog.NewJsonLogger("am") logger := blog.NewJSONLogger("am")
// Parse SysLog URL if one was provided // Parse SysLog URL if one was provided
if c.GlobalString("jsonlog") == "" { if c.GlobalString("jsonlog") == "" {
@ -151,14 +146,12 @@ func main() {
syslogU, err := url.Parse(c.GlobalString("jsonlog")) syslogU, err := url.Parse(c.GlobalString("jsonlog"))
if err != nil { if err != nil {
log.Fatalf("Could not parse Syslog URL: %s", err) log.Fatalf("Could not parse Syslog URL: %s", err)
return
} }
logger.SetEndpoint(syslogU.Scheme, syslogU.Host) logger.SetEndpoint(syslogU.Scheme, syslogU.Host)
err = logger.Connect() err = logger.Connect()
if err != nil { if err != nil {
log.Fatalf("Could not open remote syslog: %s", err) log.Fatalf("Could not open remote syslog: %s", err)
return
} }
logger.EnableStdOut(c.GlobalBool("stdout")) logger.EnableStdOut(c.GlobalBool("stdout"))
@ -170,9 +163,7 @@ func main() {
startMonitor(c.GlobalString("amqp"), logger) startMonitor(c.GlobalString("amqp"), logger)
} }
err := app.Run(os.Args) if err := app.Run(os.Args); err != nil {
if err != nil {
log.Fatalf("Could not start: %s", err) log.Fatalf("Could not start: %s", err)
return
} }
} }

View File

@ -42,7 +42,7 @@ func amqpChannel(url string) (ch *amqp.Channel) {
} }
// Start the server and wait around // Start the server and wait around
func runForever(server *rpc.AmqpRpcServer) { func runForever(server *rpc.AmqpRPCServer) {
forever := make(chan bool) forever := make(chan bool)
server.Start() server.Start()
fmt.Fprintf(os.Stderr, "Server running...\n") fmt.Fprintf(os.Stderr, "Server running...\n")
@ -310,6 +310,7 @@ func main() {
authzPath := "/acme/authz/" authzPath := "/acme/authz/"
newCertPath := "/acme/new-cert" newCertPath := "/acme/new-cert"
certPath := "/acme/cert/" certPath := "/acme/cert/"
wfe.NewReg = urlBase + newRegPath wfe.NewReg = urlBase + newRegPath
wfe.RegBase = urlBase + regPath wfe.RegBase = urlBase + regPath
wfe.NewAuthz = urlBase + newAuthzPath wfe.NewAuthz = urlBase + newAuthzPath
@ -324,7 +325,8 @@ func main() {
http.HandleFunc(certPath, wfe.Certificate) http.HandleFunc(certPath, wfe.Certificate)
fmt.Fprintf(os.Stderr, "Server running, listening on %s...\n", c.String("listenAddress")) fmt.Fprintf(os.Stderr, "Server running, listening on %s...\n", c.String("listenAddress"))
http.ListenAndServe(c.String("listenAddress"), nil) err = http.ListenAndServe(c.String("listenAddress"), nil)
failOnError(err, "Error starting HTTP server")
}, },
}, },
{ {

View File

@ -20,7 +20,7 @@ func SimpleHTTPSChallenge() Challenge {
func DvsniChallenge() Challenge { func DvsniChallenge() Challenge {
nonce := make([]byte, 16) nonce := make([]byte, 16)
rand.Read(nonce) _, _ = rand.Read(nonce) // NOTE: Ignoring errors
return Challenge{ return Challenge{
Type: ChallengeTypeDVSNI, Type: ChallengeTypeDVSNI,
Status: StatusPending, Status: StatusPending,

View File

@ -26,7 +26,7 @@ const (
) )
const ( const (
ChallengeTypeSimpleHTTPS = "simpleHttps" ChallengeTypeSimpleHTTPS = "simpleHTTPS"
ChallengeTypeDVSNI = "dvsni" ChallengeTypeDVSNI = "dvsni"
ChallengeTypeDNS = "dns" ChallengeTypeDNS = "dns"
ChallengeTypeRecoveryToken = "recoveryToken" ChallengeTypeRecoveryToken = "recoveryToken"
@ -66,8 +66,7 @@ type rawCertificateRequest struct {
func (cr *CertificateRequest) UnmarshalJSON(data []byte) error { func (cr *CertificateRequest) UnmarshalJSON(data []byte) error {
var raw rawCertificateRequest var raw rawCertificateRequest
err := json.Unmarshal(data, &raw) if err := json.Unmarshal(data, &raw); err != nil {
if err != nil {
return err return err
} }
@ -135,10 +134,10 @@ type Challenge struct {
// A URI to which a response can be POSTed // A URI to which a response can be POSTed
URI AcmeURL `json:"uri"` URI AcmeURL `json:"uri"`
// Used by simpleHttps, recoveryToken, and dns challenges // Used by simpleHTTPS, recoveryToken, and dns challenges
Token string `json:"token,omitempty"` Token string `json:"token,omitempty"`
// Used by simpleHttps challenges // Used by simpleHTTPS challenges
Path string `json:"path,omitempty"` Path string `json:"path,omitempty"`
// Used by dvsni challenges // Used by dvsni challenges

View File

@ -70,7 +70,7 @@ func B64dec(x string) ([]byte, error) {
func RandomString(byteLength int) string { func RandomString(byteLength int) string {
b := make([]byte, byteLength) b := make([]byte, byteLength)
rand.Read(b) // NOTE: Ignoring errors _, _ = rand.Read(b) // NOTE: Ignoring errors
return B64enc(b) return B64enc(b)
} }
@ -82,7 +82,7 @@ func NewToken() string {
func Fingerprint256(data []byte) string { func Fingerprint256(data []byte) string {
d := sha256.New() d := sha256.New()
d.Write(data) _, _ = d.Write(data) // Never returns an error
return B64enc(d.Sum(nil)) return B64enc(d.Sum(nil))
} }
@ -104,8 +104,7 @@ func (u AcmeURL) MarshalJSON() ([]byte, error) {
func (u *AcmeURL) UnmarshalJSON(data []byte) error { func (u *AcmeURL) UnmarshalJSON(data []byte) error {
var str string var str string
err := json.Unmarshal(data, &str) if err := json.Unmarshal(data, &str); err != nil {
if err != nil {
return err return err
} }
@ -143,7 +142,7 @@ func VerifyCSR(csr *x509.CertificateRequest) error {
default: default:
return errors.New("Unsupported CSR signing algorithm") return errors.New("Unsupported CSR signing algorithm")
} }
hash.Write(csr.RawTBSCertificateRequest) _, _ = hash.Write(csr.RawTBSCertificateRequest) // Never returns an error
inputHash := hash.Sum(nil) inputHash := hash.Sum(nil)
// Verify the signature using the public key in the CSR // Verify the signature using the public key in the CSR

View File

@ -2,6 +2,7 @@
// This Source Code Form is subject to the terms of the Mozilla Public // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this // License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
package log package log
import ( import (
@ -50,7 +51,7 @@ type LogMessage struct {
} }
// Structure to hold logger details. // Structure to hold logger details.
type JsonLogger struct { type JSONLogger struct {
stdout bool // True if logging to stdout (independent of network) stdout bool // True if logging to stdout (independent of network)
online bool // True if logging to network online bool // True if logging to network
scheme string // Golang net URI scheme (tcp/udp) scheme string // Golang net URI scheme (tcp/udp)
@ -61,28 +62,28 @@ type JsonLogger struct {
program string // Defines the 'program' field in JSON program string // Defines the 'program' field in JSON
} }
func NewJsonLogger(programName string) *JsonLogger { func NewJSONLogger(programName string) *JSONLogger {
return &JsonLogger{ return &JSONLogger{
program: programName, program: programName,
level: 7, // Default to all level: 7, // Default to all
} }
} }
func (jl *JsonLogger) EnableStdOut(stdout bool) { func (jl *JSONLogger) EnableStdOut(stdout bool) {
jl.stdout = stdout jl.stdout = stdout
} }
func (jl *JsonLogger) SetLevel(level int) { func (jl *JSONLogger) SetLevel(level int) {
jl.level = level jl.level = level
} }
func (jl *JsonLogger) SetEndpoint(scheme string, host string) { func (jl *JSONLogger) SetEndpoint(scheme string, host string) {
jl.scheme = scheme jl.scheme = scheme
jl.host = host jl.host = host
jl.online = true jl.online = true
} }
func (jl *JsonLogger) Connect() error { func (jl *JSONLogger) Connect() error {
conn, err := net.Dial(jl.scheme, jl.host) conn, err := net.Dial(jl.scheme, jl.host)
if err == nil { if err == nil {
jl.conn = conn jl.conn = conn
@ -91,42 +92,42 @@ func (jl *JsonLogger) Connect() error {
} }
// Log at the Critical severity level. // Log at the Critical severity level.
func (jl *JsonLogger) Critical(messageStr string, payloadObj interface{}) { func (jl *JSONLogger) Critical(messageStr string, payloadObj interface{}) {
jl.Write(CRITICAL, messageStr, payloadObj) jl.Write(CRITICAL, messageStr, payloadObj)
} }
// Log at the Alert severity level. // Log at the Alert severity level.
func (jl *JsonLogger) Alert(messageStr string, payloadObj interface{}) { func (jl *JSONLogger) Alert(messageStr string, payloadObj interface{}) {
jl.Write(ALERT, messageStr, payloadObj) jl.Write(ALERT, messageStr, payloadObj)
} }
// Log at the Emergency severity level. // Log at the Emergency severity level.
func (jl *JsonLogger) Emergency(messageStr string, payloadObj interface{}) { func (jl *JSONLogger) Emergency(messageStr string, payloadObj interface{}) {
jl.Write(EMERGENCY, messageStr, payloadObj) jl.Write(EMERGENCY, messageStr, payloadObj)
} }
// Log at the Error severity level. // Log at the Error severity level.
func (jl *JsonLogger) Error(messageStr string, payloadObj interface{}) { func (jl *JSONLogger) Error(messageStr string, payloadObj interface{}) {
jl.Write(ERROR, messageStr, payloadObj) jl.Write(ERROR, messageStr, payloadObj)
} }
// Log at the Warning severity level. // Log at the Warning severity level.
func (jl *JsonLogger) Warning(messageStr string, payloadObj interface{}) { func (jl *JSONLogger) Warning(messageStr string, payloadObj interface{}) {
jl.Write(WARNING, messageStr, payloadObj) jl.Write(WARNING, messageStr, payloadObj)
} }
// Log at the Notice severity level. // Log at the Notice severity level.
func (jl *JsonLogger) Notice(messageStr string, payloadObj interface{}) { func (jl *JSONLogger) Notice(messageStr string, payloadObj interface{}) {
jl.Write(NOTICE, messageStr, payloadObj) jl.Write(NOTICE, messageStr, payloadObj)
} }
// Log at the Info severity level. // Log at the Info severity level.
func (jl *JsonLogger) Info(messageStr string, payloadObj interface{}) { func (jl *JSONLogger) Info(messageStr string, payloadObj interface{}) {
jl.Write(INFO, messageStr, payloadObj) jl.Write(INFO, messageStr, payloadObj)
} }
// Log at the Debug severity level. // Log at the Debug severity level.
func (jl *JsonLogger) Debug(messageStr string, payloadObj interface{}) { func (jl *JSONLogger) Debug(messageStr string, payloadObj interface{}) {
jl.Write(DEBUG, messageStr, payloadObj) jl.Write(DEBUG, messageStr, payloadObj)
} }
@ -134,7 +135,7 @@ func (jl *JsonLogger) Debug(messageStr string, payloadObj interface{}) {
// serializes it to the wire. If the send via WriteAndRetry() fails, this method // serializes it to the wire. If the send via WriteAndRetry() fails, this method
// calls log.Fatalf() which will abort the program, leaving the system to restart // calls log.Fatalf() which will abort the program, leaving the system to restart
// the process. // the process.
func (jl *JsonLogger) Write(severity int, messageStr string, payloadObj interface{}) { func (jl *JSONLogger) Write(severity int, messageStr string, payloadObj interface{}) {
if severity > jl.level { if severity > jl.level {
return return
} }
@ -164,7 +165,6 @@ func (jl *JsonLogger) Write(severity int, messageStr string, payloadObj interfac
_, err = jl.WriteAndRetry(buf.Bytes()) _, err = jl.WriteAndRetry(buf.Bytes())
if err != nil { if err != nil {
log.Fatalf("Failed to send log message, even with retry, exiting: %s\n", buf.String()) log.Fatalf("Failed to send log message, even with retry, exiting: %s\n", buf.String())
return
} }
} }
} }
@ -172,7 +172,7 @@ func (jl *JsonLogger) Write(severity int, messageStr string, payloadObj interfac
// Send the provided data on the connection; if there is an error, // Send the provided data on the connection; if there is an error,
// it will retry to connect and transmit again, once. If that fails, // it will retry to connect and transmit again, once. If that fails,
// it returns an error. // it returns an error.
func (jl *JsonLogger) WriteAndRetry(data []byte) (int, error) { func (jl *JSONLogger) WriteAndRetry(data []byte) (int, error) {
jl.mu.Lock() jl.mu.Lock()
defer jl.mu.Unlock() defer jl.mu.Unlock()

View File

@ -76,7 +76,7 @@ func TestWriteTcp(t *testing.T) {
socket, outChan := awaitMessage(t, Scheme, Address) socket, outChan := awaitMessage(t, Scheme, Address)
defer socket.Close() defer socket.Close()
log := NewJsonLogger("just a test") log := NewJSONLogger("just a test")
log.SetEndpoint(Scheme, Address) log.SetEndpoint(Scheme, Address)
msg := "Test " + Scheme + " " + Address msg := "Test " + Scheme + " " + Address
@ -88,7 +88,7 @@ func TestWriteTcp(t *testing.T) {
} }
func TestWriteNoNetwork(t *testing.T) { func TestWriteNoNetwork(t *testing.T) {
log := NewJsonLogger("just a test") log := NewJSONLogger("just a test")
log.Debug("Check", nil) log.Debug("Check", nil)
// Nothing to assert // Nothing to assert
@ -103,7 +103,7 @@ func TestWriteUnMarshallable(t *testing.T) {
socket, outChan := awaitMessage(t, Scheme, Address) socket, outChan := awaitMessage(t, Scheme, Address)
defer socket.Close() defer socket.Close()
log := NewJsonLogger("please don't work") log := NewJSONLogger("please don't work")
log.SetEndpoint(Scheme, Address) log.SetEndpoint(Scheme, Address)
log.Connect() log.Connect()
@ -120,7 +120,7 @@ func TestWriteTcpAllLevels(t *testing.T) {
socket, outChan := awaitMessage(t, Scheme, Address) socket, outChan := awaitMessage(t, Scheme, Address)
defer socket.Close() defer socket.Close()
log := NewJsonLogger("just a test") log := NewJSONLogger("just a test")
log.SetEndpoint(Scheme, Address) log.SetEndpoint(Scheme, Address)
msg := "Test " + Scheme + " " + Address msg := "Test " + Scheme + " " + Address
@ -187,7 +187,7 @@ func TestLevelMasking(t *testing.T) {
socket, outChan := awaitMessage(t, Scheme, Address) socket, outChan := awaitMessage(t, Scheme, Address)
defer socket.Close() defer socket.Close()
log := NewJsonLogger("just a test") log := NewJSONLogger("just a test")
log.SetEndpoint(Scheme, Address) log.SetEndpoint(Scheme, Address)
msg := "Test " + Scheme + " " + Address msg := "Test " + Scheme + " " + Address
@ -224,7 +224,7 @@ func TestEmbeddedNewline(t *testing.T) {
socket, outChan := awaitMessage(t, Scheme, Address) socket, outChan := awaitMessage(t, Scheme, Address)
defer socket.Close() defer socket.Close()
log := NewJsonLogger("embedded newline") log := NewJSONLogger("embedded newline")
log.SetEndpoint(Scheme, Address) log.SetEndpoint(Scheme, Address)
payload := struct { payload := struct {

View File

@ -99,8 +99,7 @@ func (ra *RegistrationAuthorityImpl) NewCertificate(req core.CertificateRequest,
// Verify the CSR // Verify the CSR
// TODO: Verify that other aspects of the CSR are appropriate // TODO: Verify that other aspects of the CSR are appropriate
csr := req.CSR csr := req.CSR
err = core.VerifyCSR(csr) if err = core.VerifyCSR(csr); err != nil {
if err != nil {
err = core.UnauthorizedError("Invalid signature on CSR") err = core.UnauthorizedError("Invalid signature on CSR")
return return
} }
@ -159,7 +158,9 @@ func (ra *RegistrationAuthorityImpl) UpdateAuthorization(base core.Authorization
authz.Challenges[challengeIndex] = authz.Challenges[challengeIndex].MergeResponse(response) authz.Challenges[challengeIndex] = authz.Challenges[challengeIndex].MergeResponse(response)
// Store the updated version // Store the updated version
ra.SA.UpdatePendingAuthorization(authz) if err = ra.SA.UpdatePendingAuthorization(authz); err != nil {
return
}
// Dispatch to the VA for service // Dispatch to the VA for service
ra.VA.UpdateValidations(authz) ra.VA.UpdateValidations(authz)
@ -191,6 +192,6 @@ func (ra *RegistrationAuthorityImpl) OnValidationUpdate(authz core.Authorization
authz.Expires = time.Now().Add(365 * 24 * time.Hour) authz.Expires = time.Now().Add(365 * 24 * time.Hour)
} }
// Finalize the authorization // Finalize the authorization (error ignored)
ra.SA.FinalizeAuthorization(authz) _ = ra.SA.FinalizeAuthorization(authz)
} }

View File

@ -168,7 +168,7 @@ func TestOnValidationUpdate(t *testing.T) {
AuthzUpdated.ID, _ = sa.NewPendingAuthorization() AuthzUpdated.ID, _ = sa.NewPendingAuthorization()
sa.UpdatePendingAuthorization(AuthzUpdated) sa.UpdatePendingAuthorization(AuthzUpdated)
// Simulate a successful simpleHttps challenge // Simulate a successful simpleHTTPS challenge
AuthzFromVA = AuthzUpdated AuthzFromVA = AuthzUpdated
AuthzFromVA.Challenges[0].Status = core.StatusValid AuthzFromVA.Challenges[0].Status = core.StatusValid

View File

@ -62,7 +62,6 @@ func amqpSubscribe(ch *amqp.Channel, name string) (msgs <-chan amqp.Delivery, er
nil) nil)
if err != nil { if err != nil {
log.Fatalf("Could not declare exchange: %s", err) log.Fatalf("Could not declare exchange: %s", err)
return
} }
q, err := ch.QueueDeclare( q, err := ch.QueueDeclare(
@ -74,7 +73,6 @@ func amqpSubscribe(ch *amqp.Channel, name string) (msgs <-chan amqp.Delivery, er
nil) nil)
if err != nil { if err != nil {
log.Fatalf("Could not declare queue: %s", err) log.Fatalf("Could not declare queue: %s", err)
return
} }
err = ch.QueueBind( err = ch.QueueBind(
@ -85,7 +83,6 @@ func amqpSubscribe(ch *amqp.Channel, name string) (msgs <-chan amqp.Delivery, er
nil) nil)
if err != nil { if err != nil {
log.Fatalf("Could not bind queue: %s", err) log.Fatalf("Could not bind queue: %s", err)
return
} }
msgs, err = ch.Consume( msgs, err = ch.Consume(
@ -98,7 +95,6 @@ func amqpSubscribe(ch *amqp.Channel, name string) (msgs <-chan amqp.Delivery, er
nil) nil)
if err != nil { if err != nil {
log.Fatalf("Could not subscribe to queue: %s", err) log.Fatalf("Could not subscribe to queue: %s", err)
return
} }
return return
@ -110,7 +106,7 @@ func amqpSubscribe(ch *amqp.Channel, name string) (msgs <-chan amqp.Delivery, er
// //
// To implement specific functionality, using code should use the Handle // To implement specific functionality, using code should use the Handle
// method to add specific actions. // method to add specific actions.
type AmqpRpcServer struct { type AmqpRPCServer struct {
serverQueue string serverQueue string
channel *amqp.Channel channel *amqp.Channel
dispatchTable map[string]func([]byte) []byte dispatchTable map[string]func([]byte) []byte
@ -119,21 +115,21 @@ type AmqpRpcServer struct {
// Create a new AMQP-RPC server on the given queue and channel. // Create a new AMQP-RPC server on the given queue and channel.
// Note that you must call Start() to actually start the server // Note that you must call Start() to actually start the server
// listening for requests. // listening for requests.
func NewAmqpRpcServer(serverQueue string, channel *amqp.Channel) *AmqpRpcServer { func NewAmqpRPCServer(serverQueue string, channel *amqp.Channel) *AmqpRPCServer {
return &AmqpRpcServer{ return &AmqpRPCServer{
serverQueue: serverQueue, serverQueue: serverQueue,
channel: channel, channel: channel,
dispatchTable: make(map[string]func([]byte) []byte), dispatchTable: make(map[string]func([]byte) []byte),
} }
} }
func (rpc *AmqpRpcServer) Handle(method string, handler func([]byte) []byte) { func (rpc *AmqpRPCServer) Handle(method string, handler func([]byte) []byte) {
rpc.dispatchTable[method] = handler rpc.dispatchTable[method] = handler
} }
// Starts the AMQP-RPC server running in a separate thread. // Starts the AMQP-RPC server running in a separate thread.
// There is currently no Stop() method. // There is currently no Stop() method.
func (rpc *AmqpRpcServer) Start() (err error) { func (rpc *AmqpRPCServer) Start() (err error) {
msgs, err := amqpSubscribe(rpc.channel, rpc.serverQueue) msgs, err := amqpSubscribe(rpc.channel, rpc.serverQueue)
if err != nil { if err != nil {
return return
@ -144,20 +140,21 @@ func (rpc *AmqpRpcServer) Start() (err error) {
// XXX-JWS: jws.Verify(body) // XXX-JWS: jws.Verify(body)
cb, present := rpc.dispatchTable[msg.Type] cb, present := rpc.dispatchTable[msg.Type]
log.Printf(" [s<] received %s(%s) [%s]", msg.Type, core.B64enc(msg.Body), msg.CorrelationId) log.Printf(" [s<] received %s(%s) [%s]", msg.Type, core.B64enc(msg.Body), msg.CorrelationId)
if present { if !present {
response := cb(msg.Body) continue
log.Printf(" [s>] sending %s(%s) [%s]", msg.Type, core.B64enc(response), msg.CorrelationId)
rpc.channel.Publish(
AmqpExchange,
msg.ReplyTo,
AmqpMandatory,
AmqpImmediate,
amqp.Publishing{
CorrelationId: msg.CorrelationId,
Type: msg.Type,
Body: response, // XXX-JWS: jws.Sign(privKey, body)
})
} }
response := cb(msg.Body)
log.Printf(" [s>] sending %s(%s) [%s]", msg.Type, core.B64enc(response), msg.CorrelationId)
rpc.channel.Publish(
AmqpExchange,
msg.ReplyTo,
AmqpMandatory,
AmqpImmediate,
amqp.Publishing{
CorrelationId: msg.CorrelationId,
Type: msg.Type,
Body: response, // XXX-JWS: jws.Sign(privKey, body)
})
} }
}() }()
return return
@ -172,7 +169,7 @@ func (rpc *AmqpRpcServer) Start() (err error) {
// //
// ``` // ```
// request = /* serialize request to []byte */ // request = /* serialize request to []byte */
// response = <-AmqpRpcClient.Dispatch(method, request) // response = <-AmqpRPCCLient.Dispatch(method, request)
// return /* deserialized response */ // return /* deserialized response */
// ``` // ```
// //
@ -181,7 +178,7 @@ func (rpc *AmqpRpcServer) Start() (err error) {
// //
// DispatchSync will manage the channel for you, and also enforce a // DispatchSync will manage the channel for you, and also enforce a
// timeout on the transaction (default 60 seconds) // timeout on the transaction (default 60 seconds)
type AmqpRpcClient struct { type AmqpRPCCLient struct {
serverQueue string serverQueue string
clientQueue string clientQueue string
channel *amqp.Channel channel *amqp.Channel
@ -189,8 +186,8 @@ type AmqpRpcClient struct {
timeout time.Duration timeout time.Duration
} }
func NewAmqpRpcClient(clientQueue, serverQueue string, channel *amqp.Channel) (rpc *AmqpRpcClient, err error) { func NewAmqpRPCCLient(clientQueue, serverQueue string, channel *amqp.Channel) (rpc *AmqpRPCCLient, err error) {
rpc = &AmqpRpcClient{ rpc = &AmqpRPCCLient{
serverQueue: serverQueue, serverQueue: serverQueue,
clientQueue: clientQueue, clientQueue: clientQueue,
channel: channel, channel: channel,
@ -211,21 +208,22 @@ func NewAmqpRpcClient(clientQueue, serverQueue string, channel *amqp.Channel) (r
responseChan, present := rpc.pending[corrID] responseChan, present := rpc.pending[corrID]
log.Printf(" [c<] received %s(%s) [%s]", msg.Type, core.B64enc(msg.Body), corrID) log.Printf(" [c<] received %s(%s) [%s]", msg.Type, core.B64enc(msg.Body), corrID)
if present { if !present {
responseChan <- msg.Body continue
delete(rpc.pending, corrID)
} }
responseChan <- msg.Body
delete(rpc.pending, corrID)
} }
}() }()
return return
} }
func (rpc *AmqpRpcClient) SetTimeout(ttl time.Duration) { func (rpc *AmqpRPCCLient) SetTimeout(ttl time.Duration) {
rpc.timeout = ttl rpc.timeout = ttl
} }
func (rpc *AmqpRpcClient) Dispatch(method string, body []byte) chan []byte { func (rpc *AmqpRPCCLient) Dispatch(method string, body []byte) chan []byte {
// Create a channel on which to direct the response // Create a channel on which to direct the response
// At least in some cases, it's important that this channel // At least in some cases, it's important that this channel
// be buffered to avoid deadlock // be buffered to avoid deadlock
@ -250,7 +248,7 @@ func (rpc *AmqpRpcClient) Dispatch(method string, body []byte) chan []byte {
return responseChan return responseChan
} }
func (rpc *AmqpRpcClient) DispatchSync(method string, body []byte) (response []byte, err error) { func (rpc *AmqpRPCCLient) DispatchSync(method string, body []byte) (response []byte, err error) {
select { select {
case response = <-rpc.Dispatch(method, body): case response = <-rpc.Dispatch(method, body):
return return
@ -261,7 +259,7 @@ func (rpc *AmqpRpcClient) DispatchSync(method string, body []byte) (response []b
} }
} }
func (rpc *AmqpRpcClient) SyncDispatchWithTimeout(method string, body []byte, ttl time.Duration) (response []byte, err error) { func (rpc *AmqpRPCCLient) SyncDispatchWithTimeout(method string, body []byte, ttl time.Duration) (response []byte, err error) {
switch { switch {
} }

View File

@ -72,8 +72,8 @@ type certificateRequest struct {
Key jose.JsonWebKey Key jose.JsonWebKey
} }
func NewRegistrationAuthorityServer(serverQueue string, channel *amqp.Channel, impl core.RegistrationAuthority) (rpc *AmqpRpcServer, err error) { func NewRegistrationAuthorityServer(serverQueue string, channel *amqp.Channel, impl core.RegistrationAuthority) (rpc *AmqpRPCServer, err error) {
rpc = NewAmqpRpcServer(serverQueue, channel) rpc = NewAmqpRPCServer(serverQueue, channel)
rpc.Handle(MethodNewRegistration, func(req []byte) (response []byte) { rpc.Handle(MethodNewRegistration, func(req []byte) (response []byte) {
var rr registrationRequest var rr registrationRequest
@ -96,46 +96,44 @@ func NewRegistrationAuthorityServer(serverQueue string, channel *amqp.Channel, i
rpc.Handle(MethodNewAuthorization, func(req []byte) (response []byte) { rpc.Handle(MethodNewAuthorization, func(req []byte) (response []byte) {
var ar authorizationRequest var ar authorizationRequest
err := json.Unmarshal(req, &ar) if err := json.Unmarshal(req, &ar); err != nil {
if err != nil { return nil
return
} }
authz, err := impl.NewAuthorization(ar.Authz, ar.Key) authz, err := impl.NewAuthorization(ar.Authz, ar.Key)
if err != nil { if err != nil {
return return nil
} }
response, err = json.Marshal(authz) response, err = json.Marshal(authz)
if err != nil { if err != nil {
response = []byte{} return nil
} }
return return response
}) })
rpc.Handle(MethodNewCertificate, func(req []byte) (response []byte) { rpc.Handle(MethodNewCertificate, func(req []byte) []byte {
log.Printf(" [.] Entering MethodNewCertificate") log.Printf(" [.] Entering MethodNewCertificate")
var cr certificateRequest var cr certificateRequest
err := json.Unmarshal(req, &cr) if err := json.Unmarshal(req, &cr); err != nil {
if err != nil {
log.Printf(" [!] Error unmarshaling certificate request: %s", err.Error()) log.Printf(" [!] Error unmarshaling certificate request: %s", err.Error())
log.Printf(" JSON data: %s", string(req)) log.Printf(" JSON data: %s", string(req))
return return nil
} }
log.Printf(" [.] No problem unmarshaling request") log.Printf(" [.] No problem unmarshaling request")
cert, err := impl.NewCertificate(cr.Req, cr.Key) cert, err := impl.NewCertificate(cr.Req, cr.Key)
if err != nil { if err != nil {
log.Printf(" [!] Error issuing new certificate: %s", err.Error()) log.Printf(" [!] Error issuing new certificate: %s", err.Error())
return return nil
} }
log.Printf(" [.] No problem issuing new cert") log.Printf(" [.] No problem issuing new cert")
response, err = json.Marshal(cert) response, err := json.Marshal(cert)
if err != nil { if err != nil {
response = []byte{} return nil
} }
return return response
}) })
rpc.Handle(MethodUpdateRegistration, func(req []byte) (response []byte) { rpc.Handle(MethodUpdateRegistration, func(req []byte) (response []byte) {
@ -172,52 +170,46 @@ func NewRegistrationAuthorityServer(serverQueue string, channel *amqp.Channel, i
newAuthz, err := impl.UpdateAuthorization(authz.Authz, authz.Index, authz.Response) newAuthz, err := impl.UpdateAuthorization(authz.Authz, authz.Index, authz.Response)
if err != nil { if err != nil {
return return nil
} }
response, err = json.Marshal(newAuthz) response, err = json.Marshal(newAuthz)
if err != nil { if err != nil {
response = []byte{} return nil
} }
return return response
}) })
rpc.Handle(MethodRevokeCertificate, func(req []byte) (response []byte) { rpc.Handle(MethodRevokeCertificate, func(req []byte) []byte {
// Nobody's listening, so it doesn't matter what we return
response = []byte{}
certs, err := x509.ParseCertificates(req) certs, err := x509.ParseCertificates(req)
if err != nil || len(certs) == 0 { if err != nil || len(certs) == 0 {
return return nil
} }
impl.RevokeCertificate(*certs[0]) // Error explicitly ignored since response is nil anyway
return _ = impl.RevokeCertificate(*certs[0])
return nil
}) })
rpc.Handle(MethodOnValidationUpdate, func(req []byte) (response []byte) { rpc.Handle(MethodOnValidationUpdate, func(req []byte) []byte {
// Nobody's listening, so it doesn't matter what we return
response = []byte{}
var authz core.Authorization var authz core.Authorization
err := json.Unmarshal(req, &authz) if err := json.Unmarshal(req, &authz); err != nil {
if err != nil { return nil
return
} }
impl.OnValidationUpdate(authz) impl.OnValidationUpdate(authz)
return return nil
}) })
return rpc, nil return rpc, nil
} }
type RegistrationAuthorityClient struct { type RegistrationAuthorityClient struct {
rpc *AmqpRpcClient rpc *AmqpRPCCLient
} }
func NewRegistrationAuthorityClient(clientQueue, serverQueue string, channel *amqp.Channel) (rac RegistrationAuthorityClient, err error) { func NewRegistrationAuthorityClient(clientQueue, serverQueue string, channel *amqp.Channel) (rac RegistrationAuthorityClient, err error) {
rpc, err := NewAmqpRpcClient(clientQueue, serverQueue, channel) rpc, err := NewAmqpRPCCLient(clientQueue, serverQueue, channel)
if err != nil { if err != nil {
return return
} }
@ -331,32 +323,29 @@ func (rac RegistrationAuthorityClient) OnValidationUpdate(authz core.Authorizati
// ValidationAuthorityClient / Server // ValidationAuthorityClient / Server
// -> UpdateValidations // -> UpdateValidations
func NewValidationAuthorityServer(serverQueue string, channel *amqp.Channel, impl core.ValidationAuthority) (rpc *AmqpRpcServer, err error) { func NewValidationAuthorityServer(serverQueue string, channel *amqp.Channel, impl core.ValidationAuthority) (rpc *AmqpRPCServer, err error) {
rpc = NewAmqpRpcServer(serverQueue, channel) rpc = NewAmqpRPCServer(serverQueue, channel)
rpc.Handle(MethodUpdateValidations, func(req []byte) []byte { rpc.Handle(MethodUpdateValidations, func(req []byte) []byte {
// Nobody's listening, so it doesn't matter what we return
zero := []byte{}
var authz core.Authorization var authz core.Authorization
err := json.Unmarshal(req, &authz) if err := json.Unmarshal(req, &authz); err != nil {
if err != nil { return nil
return zero
} }
impl.UpdateValidations(authz) // Error explicitly ignored since response is nil anyway
return zero _ = impl.UpdateValidations(authz)
return nil
}) })
return rpc, nil return rpc, nil
} }
type ValidationAuthorityClient struct { type ValidationAuthorityClient struct {
rpc *AmqpRpcClient rpc *AmqpRPCCLient
} }
func NewValidationAuthorityClient(clientQueue, serverQueue string, channel *amqp.Channel) (vac ValidationAuthorityClient, err error) { func NewValidationAuthorityClient(clientQueue, serverQueue string, channel *amqp.Channel) (vac ValidationAuthorityClient, err error) {
rpc, err := NewAmqpRpcClient(clientQueue, serverQueue, channel) rpc, err := NewAmqpRPCCLient(clientQueue, serverQueue, channel)
if err != nil { if err != nil {
return return
} }
@ -377,25 +366,23 @@ func (vac ValidationAuthorityClient) UpdateValidations(authz core.Authorization)
// CertificateAuthorityClient / Server // CertificateAuthorityClient / Server
// -> IssueCertificate // -> IssueCertificate
func NewCertificateAuthorityServer(serverQueue string, channel *amqp.Channel, impl core.CertificateAuthority) (rpc *AmqpRpcServer, err error) { func NewCertificateAuthorityServer(serverQueue string, channel *amqp.Channel, impl core.CertificateAuthority) (rpc *AmqpRPCServer, err error) {
rpc = NewAmqpRpcServer(serverQueue, channel) rpc = NewAmqpRPCServer(serverQueue, channel)
rpc.Handle(MethodIssueCertificate, func(req []byte) []byte { rpc.Handle(MethodIssueCertificate, func(req []byte) []byte {
zero := []byte{}
csr, err := x509.ParseCertificateRequest(req) csr, err := x509.ParseCertificateRequest(req)
if err != nil { if err != nil {
return zero // XXX return nil // XXX
} }
cert, err := impl.IssueCertificate(*csr) cert, err := impl.IssueCertificate(*csr)
if err != nil { if err != nil {
return zero // XXX return nil // XXX
} }
serialized, err := json.Marshal(cert) serialized, err := json.Marshal(cert)
if err != nil { if err != nil {
return zero // XXX return nil // XXX
} }
return serialized return serialized
@ -405,11 +392,11 @@ func NewCertificateAuthorityServer(serverQueue string, channel *amqp.Channel, im
} }
type CertificateAuthorityClient struct { type CertificateAuthorityClient struct {
rpc *AmqpRpcClient rpc *AmqpRPCCLient
} }
func NewCertificateAuthorityClient(clientQueue, serverQueue string, channel *amqp.Channel) (cac CertificateAuthorityClient, err error) { func NewCertificateAuthorityClient(clientQueue, serverQueue string, channel *amqp.Channel) (cac CertificateAuthorityClient, err error) {
rpc, err := NewAmqpRpcClient(clientQueue, serverQueue, channel) rpc, err := NewAmqpRPCCLient(clientQueue, serverQueue, channel)
if err != nil { if err != nil {
return return
} }
@ -429,8 +416,8 @@ func (cac CertificateAuthorityClient) IssueCertificate(csr x509.CertificateReque
return return
} }
func NewStorageAuthorityServer(serverQueue string, channel *amqp.Channel, impl core.StorageAuthority) (rpc *AmqpRpcServer) { func NewStorageAuthorityServer(serverQueue string, channel *amqp.Channel, impl core.StorageAuthority) (rpc *AmqpRPCServer) {
rpc = NewAmqpRpcServer(serverQueue, channel) rpc = NewAmqpRPCServer(serverQueue, channel)
rpc.Handle(MethodGetRegistration, func(req []byte) (response []byte) { rpc.Handle(MethodGetRegistration, func(req []byte) (response []byte) {
reg, err := impl.GetCertificate(string(req)) reg, err := impl.GetCertificate(string(req))
@ -446,25 +433,25 @@ func NewStorageAuthorityServer(serverQueue string, channel *amqp.Channel, impl c
return return
}) })
rpc.Handle(MethodGetAuthorization, func(req []byte) (response []byte) { rpc.Handle(MethodGetAuthorization, func(req []byte) []byte {
authz, err := impl.AddCertificate(req) authz, err := impl.AddCertificate(req)
if err != nil { if err != nil {
return return nil
} }
jsonAuthz, err := json.Marshal(authz) jsonAuthz, err := json.Marshal(authz)
if err == nil { if err != nil {
response = jsonAuthz return nil
} }
return return jsonAuthz
}) })
rpc.Handle(MethodAddCertificate, func(req []byte) (response []byte) { rpc.Handle(MethodAddCertificate, func(req []byte) []byte {
id, err := impl.AddCertificate(req) id, err := impl.AddCertificate(req)
if err == nil { if err != nil {
response = []byte(id) return nil
} }
return return []byte(id)
}) })
rpc.Handle(MethodNewRegistration, func(req []byte) (response []byte) { rpc.Handle(MethodNewRegistration, func(req []byte) (response []byte) {
@ -472,7 +459,7 @@ func NewStorageAuthorityServer(serverQueue string, channel *amqp.Channel, impl c
if err == nil { if err == nil {
response = []byte(id) response = []byte(id)
} }
return return []byte(id)
}) })
rpc.Handle(MethodNewPendingAuthorization, func(req []byte) (response []byte) { rpc.Handle(MethodNewPendingAuthorization, func(req []byte) (response []byte) {
@ -483,26 +470,28 @@ func NewStorageAuthorityServer(serverQueue string, channel *amqp.Channel, impl c
return return
}) })
rpc.Handle(MethodUpdatePendingAuthorization, func(req []byte) (response []byte) { rpc.Handle(MethodUpdatePendingAuthorization, func(req []byte) []byte {
var authz core.Authorization var authz core.Authorization
err := json.Unmarshal(req, authz) err := json.Unmarshal(req, authz)
if err != nil { if err != nil {
return return nil
} }
impl.UpdatePendingAuthorization(authz) // Error explicitly ignored since response is nil anyway
return _ = impl.UpdatePendingAuthorization(authz)
return nil
}) })
rpc.Handle(MethodFinalizeAuthorization, func(req []byte) (response []byte) { rpc.Handle(MethodFinalizeAuthorization, func(req []byte) []byte {
var authz core.Authorization var authz core.Authorization
err := json.Unmarshal(req, authz) err := json.Unmarshal(req, authz)
if err != nil { if err != nil {
return return nil
} }
impl.FinalizeAuthorization(authz) // Error explicitly ignored since response is nil anyway
return _ = impl.FinalizeAuthorization(authz)
return nil
}) })
rpc.Handle(MethodGetCertificate, func(req []byte) (response []byte) { rpc.Handle(MethodGetCertificate, func(req []byte) (response []byte) {
@ -517,11 +506,11 @@ func NewStorageAuthorityServer(serverQueue string, channel *amqp.Channel, impl c
} }
type StorageAuthorityClient struct { type StorageAuthorityClient struct {
rpc *AmqpRpcClient rpc *AmqpRPCCLient
} }
func NewStorageAuthorityClient(clientQueue, serverQueue string, channel *amqp.Channel) (sac StorageAuthorityClient, err error) { func NewStorageAuthorityClient(clientQueue, serverQueue string, channel *amqp.Channel) (sac StorageAuthorityClient, err error) {
rpc, err := NewAmqpRpcClient(clientQueue, serverQueue, channel) rpc, err := NewAmqpRPCCLient(clientQueue, serverQueue, channel)
if err != nil { if err != nil {
return return
} }
@ -577,7 +566,7 @@ func (cac StorageAuthorityClient) NewRegistration() (id string, err error) {
} }
func (cac StorageAuthorityClient) NewPendingAuthorization() (id string, err error) { func (cac StorageAuthorityClient) NewPendingAuthorization() (id string, err error) {
response, err := cac.rpc.DispatchSync(MethodNewPendingAuthorization, []byte{}) response, err := cac.rpc.DispatchSync(MethodNewPendingAuthorization, nil)
if err != nil || len(response) == 0 { if err != nil || len(response) == 0 {
err = errors.New("NewPendingAuthorization RPC failed") // XXX err = errors.New("NewPendingAuthorization RPC failed") // XXX
return return

View File

@ -23,7 +23,7 @@ type SQLStorageAuthority struct {
func digest256(data []byte) []byte { func digest256(data []byte) []byte {
d := sha256.New() d := sha256.New()
d.Write(data) _, _ = d.Write(data) // Never returns an error
return d.Sum(nil) return d.Sum(nil)
} }

View File

@ -87,7 +87,7 @@ func (va ValidationAuthorityImpl) validateDvsni(identifier core.AcmeIdentifier,
RS := append(R, S...) RS := append(R, S...)
sha := sha256.New() sha := sha256.New()
sha.Write(RS) _, _ = sha.Write(RS) // Never returns an error
z := make([]byte, sha.Size()) z := make([]byte, sha.Size())
sha.Sum(z) sha.Sum(z)
zName := hex.EncodeToString(z) zName := hex.EncodeToString(z)

View File

@ -9,6 +9,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log"
"net/http" "net/http"
"net/url" "net/url"
"regexp" "regexp"
@ -39,20 +40,18 @@ func NewWebFrontEndImpl() WebFrontEndImpl {
// Method implementations // Method implementations
func verifyPOST(request *http.Request) ([]byte, jose.JsonWebKey, error) { func verifyPOST(request *http.Request) ([]byte, jose.JsonWebKey, error) {
zero := []byte{}
zeroKey := jose.JsonWebKey{} zeroKey := jose.JsonWebKey{}
// Read body // Read body
body, err := ioutil.ReadAll(request.Body) body, err := ioutil.ReadAll(request.Body)
if err != nil { if err != nil {
return zero, zeroKey, err return nil, zeroKey, err
} }
// Parse as JWS // Parse as JWS
var jws jose.JsonWebSignature var jws jose.JsonWebSignature
err = json.Unmarshal(body, &jws) if err = json.Unmarshal(body, &jws); err != nil {
if err != nil { return nil, zeroKey, err
return zero, zeroKey, err
} }
// Verify JWS // Verify JWS
@ -61,9 +60,8 @@ func verifyPOST(request *http.Request) ([]byte, jose.JsonWebKey, error) {
// RA. However the WFE is the RA's only view of the outside world // RA. However the WFE is the RA's only view of the outside world
// *anyway*, so it could always lie about what key was used by faking // *anyway*, so it could always lie about what key was used by faking
// the signature itself. // the signature itself.
err = jws.Verify() if err = jws.Verify(); err != nil {
if err != nil { return nil, zeroKey, err
return zero, zeroKey, err
} }
// TODO Return JWS body // TODO Return JWS body
@ -155,8 +153,7 @@ func (wfe *WebFrontEndImpl) NewAuthorization(response http.ResponseWriter, reque
} }
var init core.Authorization var init core.Authorization
err = json.Unmarshal(body, &init) if err = json.Unmarshal(body, &init); err != nil {
if err != nil {
sendError(response, "Error unmarshaling JSON", http.StatusBadRequest) sendError(response, "Error unmarshaling JSON", http.StatusBadRequest)
return return
} }
@ -182,7 +179,9 @@ func (wfe *WebFrontEndImpl) NewAuthorization(response http.ResponseWriter, reque
response.Header().Add("Location", authzURL) response.Header().Add("Location", authzURL)
response.Header().Add("Link", link(wfe.NewCert, "next")) response.Header().Add("Link", link(wfe.NewCert, "next"))
response.WriteHeader(http.StatusCreated) response.WriteHeader(http.StatusCreated)
response.Write(responseBody) if _, err = response.Write(responseBody); err != nil {
log.Printf("Could not write response: %s", err)
}
} }
func (wfe *WebFrontEndImpl) NewCertificate(response http.ResponseWriter, request *http.Request) { func (wfe *WebFrontEndImpl) NewCertificate(response http.ResponseWriter, request *http.Request) {
@ -198,8 +197,7 @@ func (wfe *WebFrontEndImpl) NewCertificate(response http.ResponseWriter, request
} }
var init core.CertificateRequest var init core.CertificateRequest
err = json.Unmarshal(body, &init) if err = json.Unmarshal(body, &init); err != nil {
if err != nil {
sendError(response, "Error unmarshaling certificate request", http.StatusBadRequest) sendError(response, "Error unmarshaling certificate request", http.StatusBadRequest)
return return
} }
@ -219,7 +217,9 @@ func (wfe *WebFrontEndImpl) NewCertificate(response http.ResponseWriter, request
// TODO: Content negotiation for cert format // TODO: Content negotiation for cert format
response.Header().Add("Location", certURL) response.Header().Add("Location", certURL)
response.WriteHeader(http.StatusCreated) response.WriteHeader(http.StatusCreated)
response.Write(cert.DER) if _, err = response.Write(cert.DER); err != nil {
log.Printf("Could not write response: %s", err)
}
} }
func (wfe *WebFrontEndImpl) Challenge(authz core.Authorization, response http.ResponseWriter, request *http.Request) { func (wfe *WebFrontEndImpl) Challenge(authz core.Authorization, response http.ResponseWriter, request *http.Request) {
@ -255,8 +255,7 @@ func (wfe *WebFrontEndImpl) Challenge(authz core.Authorization, response http.Re
} }
var challengeResponse core.Challenge var challengeResponse core.Challenge
err = json.Unmarshal(body, &challengeResponse) if err = json.Unmarshal(body, &challengeResponse); err != nil {
if err != nil {
sendError(response, "Error unmarshaling authorization", http.StatusBadRequest) sendError(response, "Error unmarshaling authorization", http.StatusBadRequest)
return return
} }
@ -280,7 +279,9 @@ func (wfe *WebFrontEndImpl) Challenge(authz core.Authorization, response http.Re
return return
} }
response.WriteHeader(http.StatusAccepted) response.WriteHeader(http.StatusAccepted)
response.Write(jsonReply) if _, err = response.Write(jsonReply); err != nil {
log.Printf("Could not write response: %s", err)
}
} }
} }
@ -379,7 +380,9 @@ func (wfe *WebFrontEndImpl) Authorization(response http.ResponseWriter, request
return return
} }
response.WriteHeader(http.StatusOK) response.WriteHeader(http.StatusOK)
response.Write(jsonReply) if _, err = response.Write(jsonReply); err != nil {
log.Printf("Could not write response: %s", err)
}
} }
} }
@ -401,7 +404,9 @@ func (wfe *WebFrontEndImpl) Certificate(response http.ResponseWriter, request *h
// TODO: Indicate content type // TODO: Indicate content type
// TODO: Link header // TODO: Link header
response.WriteHeader(http.StatusOK) response.WriteHeader(http.StatusOK)
response.Write(cert) if _, err = response.Write(cert); err != nil {
log.Printf("Could not write response: %s", err)
}
case "POST": case "POST":
// TODO: Handle revocation in POST // TODO: Handle revocation in POST