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.

96 lines
2.0 KiB
Go

package hsm
import (
"context"
"github.com/ThalesIgnite/crypto11"
"git.cacert.org/cacert-gosigner/pkg/config"
)
type ctxKey int
const (
ctxP11Contexts ctxKey = iota
ctxSetupMode
ctxSignerConfig
ctxVerboseLogging
)
type ConfigOption func(ctx context.Context) context.Context
func CaConfigOption(signerConfig *config.SignerConfig) func(context.Context) context.Context {
return func(ctx context.Context) context.Context {
return context.WithValue(ctx, ctxSignerConfig, signerConfig)
}
}
func SetupModeOption() func(context.Context) context.Context {
return func(ctx context.Context) context.Context {
return context.WithValue(ctx, ctxSetupMode, true)
}
}
func VerboseLoggingOption() func(ctx context.Context) context.Context {
return func(ctx context.Context) context.Context {
return context.WithValue(ctx, ctxVerboseLogging, true)
}
}
// SetupContext sets global context for HSM operations.
func SetupContext(options ...ConfigOption) context.Context {
ctx := context.Background()
ctx = context.WithValue(ctx, ctxP11Contexts, make(map[string]*crypto11.Context))
for _, opt := range options {
ctx = opt(ctx)
}
return ctx
}
func GetSignerConfig(ctx context.Context) *config.SignerConfig {
signerConfig, ok := ctx.Value(ctxSignerConfig).(*config.SignerConfig)
if !ok {
return nil
}
return signerConfig
}
func IsSetupMode(ctx context.Context) bool {
setupMode, ok := ctx.Value(ctxSetupMode).(bool)
if !ok {
return false
}
return setupMode
}
func IsVerbose(ctx context.Context) bool {
verbose, ok := ctx.Value(ctxVerboseLogging).(bool)
if !ok {
return false
}
return verbose
}
func GetP11Context(ctx context.Context, entry *config.CaCertificateEntry) (*crypto11.Context, error) {
contexts := ctx.Value(ctxP11Contexts).(map[string]*crypto11.Context)
if p11Context, ok := contexts[entry.Storage]; ok {
return p11Context, nil
}
p11Context, err := prepareCrypto11Context(ctx, entry.Storage)
if err != nil {
return nil, err
}
contexts[entry.Storage] = p11Context
return p11Context, nil
}