cacert-gosigner/pkg/hsm/context.go

57 lines
1.2 KiB
Go
Raw Normal View History

package hsm
import (
"context"
"github.com/ThalesIgnite/crypto11"
"git.cacert.org/cacert-gosigner/pkg/config"
)
type ctxKey int
const (
ctxP11Contexts ctxKey = iota
ctxSetupMode
ctxSignerConfig
)
// SetupContext sets global context for HSM operations.
func SetupContext(
signerConfig *config.SignerConfig,
setupMode bool,
) context.Context {
ctx := context.Background()
ctx = context.WithValue(ctx, ctxP11Contexts, make(map[string]*crypto11.Context))
ctx = context.WithValue(ctx, ctxSignerConfig, signerConfig)
ctx = context.WithValue(ctx, ctxSetupMode, setupMode)
return ctx
}
func GetSignerConfig(ctx context.Context) *config.SignerConfig {
return ctx.Value(ctxSignerConfig).(*config.SignerConfig)
}
func IsSetupMode(ctx context.Context) bool {
return ctx.Value(ctxSetupMode).(bool)
}
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
}