2021-02-26 07:15:45 +05:30
package di
import (
2024-02-01 16:41:39 +05:30
"crypto/rand"
"crypto/rsa"
2021-02-26 07:15:45 +05:30
"crypto/x509"
"encoding/pem"
2024-03-05 18:25:31 +05:30
"errors"
"log/slog"
2021-02-26 07:15:45 +05:30
2024-03-05 18:25:31 +05:30
"ely.by/chrly/internal/client/signer"
2024-02-01 12:42:34 +05:30
"ely.by/chrly/internal/http"
2024-02-01 16:41:39 +05:30
"ely.by/chrly/internal/security"
2024-02-01 12:28:26 +05:30
2023-12-13 21:59:12 +05:30
"github.com/defval/di"
2021-02-26 07:15:45 +05:30
"github.com/spf13/viper"
)
2024-02-01 16:41:39 +05:30
var securityDiOptions = di . Options (
2024-03-05 17:37:54 +05:30
di . Provide ( newSigner ,
di . As ( new ( http . Signer ) ) ,
2024-03-05 18:25:31 +05:30
di . As ( new ( signer . Signer ) ) ,
2021-02-26 07:15:45 +05:30
) ,
2024-03-05 17:37:54 +05:30
di . Provide ( newSignerService ) ,
2021-02-26 07:15:45 +05:30
)
2024-03-05 17:37:54 +05:30
func newSigner ( config * viper . Viper ) ( * security . Signer , error ) {
2024-03-05 18:25:31 +05:30
var privateKey * rsa . PrivateKey
var err error
2021-02-27 07:07:59 +05:30
keyStr := config . GetString ( "chrly.signing.key" )
2021-02-26 07:15:45 +05:30
if keyStr == "" {
2024-03-05 18:25:31 +05:30
privateKey , err = rsa . GenerateKey ( rand . Reader , 2048 )
2024-02-01 16:41:39 +05:30
if err != nil {
return nil , err
}
2024-03-05 18:25:31 +05:30
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 07:15:45 +05:30
2024-03-05 18:25:31 +05:30
privateKey , err = x509 . ParsePKCS1PrivateKey ( rawPem . Bytes )
2021-02-26 07:15:45 +05:30
if err != nil {
return nil , err
}
}
2024-02-01 16:41:39 +05:30
return security . NewSigner ( privateKey ) , nil
2021-02-26 07:15:45 +05:30
}
2024-03-05 17:37:54 +05:30
2024-03-05 18:25:31 +05:30
func newSignerService ( s signer . Signer ) http . SignerService {
return & signer . LocalSigner {
Signer : s ,
2024-03-05 17:37:54 +05:30
}
}