2022-09-12 14:38:15 +02:00
|
|
|
package signer
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-09-12 22:05:06 +02:00
|
|
|
"errors"
|
2022-09-12 14:38:15 +02:00
|
|
|
"os"
|
2022-09-12 22:05:06 +02:00
|
|
|
"strings"
|
2022-09-12 14:38:15 +02:00
|
|
|
|
|
|
|
"git.front.kjuulh.io/kjuulh/curre"
|
2022-09-12 22:05:06 +02:00
|
|
|
"github.com/ProtonMail/go-crypto/openpgp"
|
2022-09-12 14:38:15 +02:00
|
|
|
"go.uber.org/zap"
|
|
|
|
)
|
|
|
|
|
|
|
|
type OpenPGP struct {
|
2022-09-12 22:05:06 +02:00
|
|
|
logger *zap.Logger
|
|
|
|
SigningKey *openpgp.Entity
|
|
|
|
config *OpenPgpConfig
|
2022-09-12 14:38:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type OpenPgpConfig struct {
|
|
|
|
PrivateKeyFilePath string
|
|
|
|
PrivateKeyPassword string
|
2022-09-12 22:05:06 +02:00
|
|
|
PrivateKeyIdentity string
|
2022-09-12 14:38:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewOpenPGP(logger *zap.Logger, config *OpenPgpConfig) *OpenPGP {
|
|
|
|
return &OpenPGP{
|
|
|
|
logger: logger,
|
|
|
|
config: config,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewOpenPGPApp(openPGP *OpenPGP) curre.Component {
|
|
|
|
return curre.NewFunctionalComponent(&curre.FunctionalComponent{
|
2022-09-12 22:05:06 +02:00
|
|
|
InitFunc: func(_ *curre.FunctionalComponent, ctx context.Context) error {
|
|
|
|
keyring, err := buildKeyring(ctx, openPGP)
|
2022-09-12 14:38:15 +02:00
|
|
|
if err != nil {
|
2022-09-12 22:05:06 +02:00
|
|
|
openPGP.logger.Panic("could not build keyring", zap.Error(err))
|
2022-09-12 14:38:15 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-09-12 22:05:06 +02:00
|
|
|
openPGP.SigningKey = keyring
|
2022-09-12 14:38:15 +02:00
|
|
|
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
StartFunc: func(fc *curre.FunctionalComponent, ctx context.Context) error {
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
StopFunc: func(fc *curre.FunctionalComponent, ctx context.Context) error {
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
})
|
2022-09-12 22:05:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func buildKeyring(_ context.Context, openPGP *OpenPGP) (*openpgp.Entity, error) {
|
|
|
|
content, err := os.ReadFile(openPGP.config.PrivateKeyFilePath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
reader := strings.NewReader(string(content))
|
|
|
|
|
|
|
|
es, err := openpgp.ReadArmoredKeyRing(reader)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, key := range es {
|
|
|
|
for k := range key.Identities {
|
|
|
|
if strings.Contains(k, openPGP.config.PrivateKeyIdentity) {
|
|
|
|
err = key.PrivateKey.Decrypt([]byte(openPGP.config.PrivateKeyPassword))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return key, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, errors.New("could not find key matching identity")
|
2022-09-12 14:38:15 +02:00
|
|
|
|
|
|
|
}
|