You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

285 lines
6.8 KiB
Go

/*
Copyright 2022 CAcert Inc.
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package handler
import (
"errors"
"fmt"
"sync"
"github.com/shamaton/msgpackgen/msgpack"
"github.com/sirupsen/logrus"
"git.cacert.org/cacert-gosigner/pkg/protocol"
"git.cacert.org/cacert-gosigner/internal/health"
"git.cacert.org/cacert-gosigner/internal/x509/revoking"
"git.cacert.org/cacert-gosigner/pkg/messages"
)
// MsgPackHandler is a Handler implementation for the msgpack serialization format.
type MsgPackHandler struct {
logger *logrus.Logger
healthHandler *health.Handler
fetchCRLHandler *revoking.FetchCRLHandler
currentCommand *protocol.Command
currentResponse *protocol.Response
lock sync.Mutex
}
func (m *MsgPackHandler) HandleCommandAnnounce(frame []byte) error {
m.lock.Lock()
defer m.lock.Unlock()
var ann messages.CommandAnnounce
if err := msgpack.Unmarshal(frame, &ann); err != nil {
return fmt.Errorf("could not unmarshal command announcement: %w", err)
}
m.logger.WithField("announcement", &ann).Info("received command announcement")
m.currentCommand = &protocol.Command{Announce: &ann}
return nil
}
func (m *MsgPackHandler) HandleCommand(frame []byte) error {
m.lock.Lock()
defer m.lock.Unlock()
err := m.parseCommand(frame)
if err != nil {
m.currentResponse = m.buildErrorResponse(err.Error())
m.logCommandResponse()
return nil
}
err = m.handleCommand()
if err != nil {
m.logger.WithError(err).Error("command handling failed")
return err
}
m.logCommandResponse()
m.currentCommand = nil
return nil
}
func (m *MsgPackHandler) logCommandResponse() {
m.logger.WithField("command", m.currentCommand.Announce).Info("handled command")
m.logger.WithField(
"command",
m.currentCommand,
).WithField(
"response",
m.currentResponse,
).Debug("command and response")
}
func (m *MsgPackHandler) ResponseAnnounce() ([]byte, error) {
m.lock.Lock()
defer m.lock.Unlock()
announceData, err := msgpack.Marshal(m.currentResponse.Announce)
if err != nil {
return nil, fmt.Errorf("could not marshal response announcement: %w", err)
}
m.logger.WithField("announcement", m.currentResponse.Announce).Debug("write response announcement")
return announceData, nil
}
func (m *MsgPackHandler) ResponseData() ([]byte, error) {
m.lock.Lock()
defer m.lock.Unlock()
responseData, err := msgpack.Marshal(m.currentResponse.Response)
if err != nil {
return nil, fmt.Errorf("could not marshal response: %w", err)
}
m.logger.WithField("response", m.currentResponse.Response).Debug("write response")
return responseData, nil
}
func (m *MsgPackHandler) parseHealthCommand(frame []byte) error {
var command messages.HealthCommand
if err := msgpack.Unmarshal(frame, &command); err != nil {
m.logger.WithError(err).Error("unmarshal failed")
return errors.New("could not unmarshal health command")
}
m.currentCommand.Command = &command
return nil
}
func (m *MsgPackHandler) parseFetchCRLCommand(frame []byte) error {
var command messages.FetchCRLCommand
if err := msgpack.Unmarshal(frame, &command); err != nil {
m.logger.WithError(err).Error("unmarshal failed")
return errors.New("could not unmarshal fetch crl command")
}
m.currentCommand.Command = &command
return nil
}
func (m *MsgPackHandler) currentID() string {
return m.currentCommand.Announce.ID
}
func (m *MsgPackHandler) handleCommand() error {
var (
err error
responseData interface{}
responseCode messages.ResponseCode
)
switch m.currentCommand.Command.(type) {
case *messages.HealthCommand:
response, err := m.handleHealthCommand()
if err != nil {
return err
}
responseCode, responseData = messages.RespHealth, response
case *messages.FetchCRLCommand:
response, err := m.handleFetchCRLCommand()
if err != nil {
return err
}
responseCode, responseData = messages.RespFetchCRL, response
default:
return fmt.Errorf("unhandled command %s", m.currentCommand.Announce)
}
if err != nil {
return fmt.Errorf("error from command handler: %w", err)
}
m.currentResponse = &protocol.Response{
Announce: messages.BuildResponseAnnounce(responseCode, m.currentID()),
Response: responseData,
}
return nil
}
func (m *MsgPackHandler) buildErrorResponse(errMsg string) *protocol.Response {
return &protocol.Response{
Announce: messages.BuildResponseAnnounce(messages.RespError, m.currentID()),
Response: &messages.ErrorResponse{Message: errMsg},
}
}
func (m *MsgPackHandler) parseCommand(frame []byte) error {
switch m.currentCommand.Announce.Code {
case messages.CmdHealth:
return m.parseHealthCommand(frame)
case messages.CmdFetchCRL:
return m.parseFetchCRLCommand(frame)
default:
return fmt.Errorf("unhandled command code %s", m.currentCommand.Announce.Code)
}
}
func (m *MsgPackHandler) handleHealthCommand() (*messages.HealthResponse, error) {
res, err := m.healthHandler.CheckHealth()
if err != nil {
return nil, fmt.Errorf("could not check health: %w", err)
}
response := &messages.HealthResponse{
Version: res.Version,
Healthy: res.Healthy,
}
for _, info := range res.Info {
response.Info = append(response.Info, &messages.HealthInfo{
Source: info.Source,
Healthy: info.Healthy,
MoreInfo: info.MoreInfo,
})
}
return response, nil
}
func (m *MsgPackHandler) handleFetchCRLCommand() (*messages.FetchCRLResponse, error) {
fetchCRLPayload, ok := m.currentCommand.Command.(*messages.FetchCRLCommand)
if !ok {
return nil, fmt.Errorf("could not use payload as FetchCRLPayload")
}
res, err := m.fetchCRLHandler.FetchCRL(fetchCRLPayload.IssuerID)
if err != nil {
return nil, fmt.Errorf("could not fetch CRL: %w", err)
}
response := &messages.FetchCRLResponse{
IsDelta: false,
CRLNumber: res.Number,
CRLData: res.CRLData,
}
return response, nil
}
func New(logger *logrus.Logger, handlers ...RegisterHandler) (protocol.Handler, error) {
messages.RegisterGeneratedResolver()
h := &MsgPackHandler{
logger: logger,
}
for _, reg := range handlers {
reg(h)
}
return h, nil
}
type RegisterHandler func(handler *MsgPackHandler)
func RegisterHealthHandler(healthHandler *health.Handler) func(*MsgPackHandler) {
return func(h *MsgPackHandler) {
h.healthHandler = healthHandler
}
}
func RegisterFetchCRLHandler(fetchCRLHandler *revoking.FetchCRLHandler) func(handler *MsgPackHandler) {
return func(h *MsgPackHandler) {
h.fetchCRLHandler = fetchCRLHandler
}
}