cacert-gosigner/internal/hsm/context.go

107 lines
2.2 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 hsm
import (
"fmt"
"github.com/ThalesIgnite/crypto11"
"git.cacert.org/cacert-gosigner/internal/config"
)
type ConfigOption func(a *Access)
func CADirectoryOption(path string) func(a *Access) {
return func(a *Access) {
a.caDirectory = path
}
}
func CaConfigOption(signerConfig *config.SignerConfig) func(a *Access) {
return func(a *Access) {
a.signerConfig = signerConfig
}
}
func SetupModeOption() func(a *Access) {
return func(a *Access) {
a.setupMode = true
}
}
func VerboseLoggingOption() func(a *Access) {
return func(a *Access) {
a.verbose = true
}
}
// setupContext sets global context for HSM operations.
func (a *Access) setupContext(options ...ConfigOption) {
a.p11Contexts = make(map[string]*crypto11.Context)
for _, opt := range options {
opt(a)
}
}
func (a *Access) GetSignerConfig() *config.SignerConfig {
return a.signerConfig
}
func (a *Access) IsSetupMode() bool {
return a.setupMode
}
func (a *Access) IsVerbose() bool {
return a.verbose
}
func (a *Access) GetP11Context(entry *config.CaCertificateEntry) (*crypto11.Context, error) {
if p11Context, ok := a.p11Contexts[entry.Storage]; ok {
return p11Context, nil
}
p11Context, err := a.prepareCrypto11Context(entry.Storage)
if err != nil {
return nil, err
}
a.p11Contexts[entry.Storage] = p11Context
return p11Context, nil
}
func (a *Access) CloseP11Contexts() error {
seen := make(map[*crypto11.Context]struct{}, 0)
for _, p11Context := range a.p11Contexts {
if _, ok := seen[p11Context]; ok {
continue
}
seen[p11Context] = struct{}{}
err := p11Context.Close()
if err != nil {
return fmt.Errorf("could not close context: %w", err)
}
}
return nil
}