2021-02-26 02:45:45 +01:00
package di
import (
2024-02-01 12:11:39 +01:00
"crypto/rand"
"crypto/rsa"
2021-02-26 02:45:45 +01:00
"crypto/x509"
"encoding/pem"
2024-03-05 13:55:31 +01:00
"errors"
"log/slog"
2021-02-26 02:45:45 +01:00
2024-03-05 13:55:31 +01:00
"ely.by/chrly/internal/client/signer"
2024-02-01 08:12:34 +01:00
"ely.by/chrly/internal/http"
2024-02-01 12:11:39 +01:00
"ely.by/chrly/internal/security"
2024-02-01 07:58:26 +01:00
2023-12-13 17:29:12 +01:00
"github.com/defval/di"
2021-02-26 02:45:45 +01:00
"github.com/spf13/viper"
)
2024-02-01 12:11:39 +01:00
var securityDiOptions = di . Options (
2024-03-05 13:07:54 +01:00
di . Provide ( newSigner ,
di . As ( new ( http . Signer ) ) ,
2024-03-05 13:55:31 +01:00
di . As ( new ( signer . Signer ) ) ,
2021-02-26 02:45:45 +01:00
) ,
2024-03-05 13:07:54 +01:00
di . Provide ( newSignerService ) ,
2021-02-26 02:45:45 +01:00
)
2024-03-05 13:07:54 +01:00
func newSigner ( config * viper . Viper ) ( * security . Signer , error ) {
2024-03-05 13:55:31 +01:00
var privateKey * rsa . PrivateKey
var err error
2021-02-27 02:37:59 +01:00
keyStr := config . GetString ( "chrly.signing.key" )
2021-02-26 02:45:45 +01:00
if keyStr == "" {
2024-03-05 13:55:31 +01:00
privateKey , err = rsa . GenerateKey ( rand . Reader , 2048 )
2024-02-01 12:11:39 +01:00
if err != nil {
return nil , err
}
2024-03-05 13:55:31 +01:00
slog . Warn ( "A private signing key has been generated. To make it permanent, specify the valid RSA private key in the config parameter chrly.signing.key" )
} else {
keyBytes := [ ] byte ( keyStr )
rawPem , _ := pem . Decode ( keyBytes )
if rawPem == nil {
return nil , errors . New ( "unable to decode pem key" )
}
2021-02-26 02:45:45 +01:00
2024-03-05 13:55:31 +01:00
privateKey , err = x509 . ParsePKCS1PrivateKey ( rawPem . Bytes )
2021-02-26 02:45:45 +01:00
if err != nil {
return nil , err
}
}
2024-02-01 12:11:39 +01:00
return security . NewSigner ( privateKey ) , nil
2021-02-26 02:45:45 +01:00
}
2024-03-05 13:07:54 +01:00
2024-03-05 13:55:31 +01:00
func newSignerService ( s signer . Signer ) http . SignerService {
return & signer . LocalSigner {
Signer : s ,
2024-03-05 13:07:54 +01:00
}
}