1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2024-12-12 10:55:20 +02:00
sap-jenkins-library/pkg/github/secret.go
Jordi van Liempt e3935ca088
feat(vault): Vault secret rotation for GH Actions (#4280)
* rotate Vault secret on GH Actions

* test alternative sodium package

* try doing it without libsodium

* disable validity check for testing purposes

* basic unit test

* re-enable secret validity check

* tidy

* tidy parameters

* forgot to update param names in code

* apply review feedback

* improve error logging

* update step metadata

* apply metadata suggestion from review

Co-authored-by: Christopher Fenner <26137398+CCFenner@users.noreply.github.com>

* align githubToken param

* Fix secretStore

* Add alias for githubToken

* Move logic to separate file

---------

Co-authored-by: I557621 <jordi.van.liempt@sap.com>
Co-authored-by: Christopher Fenner <26137398+CCFenner@users.noreply.github.com>
Co-authored-by: Vyacheslav Starostin <vyacheslav.starostin@sap.com>
2023-04-17 08:35:13 +02:00

40 lines
1.2 KiB
Go

package github
import (
"crypto/rand"
"encoding/base64"
"github.com/google/go-github/v45/github"
"golang.org/x/crypto/nacl/box"
"github.com/SAP/jenkins-library/pkg/log"
)
// CreateEncryptedSecret creates an encrypted secret using a public key from a GitHub repository, which can be sent through the GitHub API
// https://github.com/google/go-github/blob/master/example/newreposecretwithxcrypto/main.go
func CreateEncryptedSecret(secretName, secretValue string, publicKey *github.PublicKey) (*github.EncryptedSecret, error) {
decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey.GetKey())
if err != nil {
log.Entry().Warn("Could not decode public key from base64")
return nil, err
}
var boxKey [32]byte
copy(boxKey[:], decodedPublicKey)
secretBytes := []byte(secretValue)
encryptedSecretBytes, err := box.SealAnonymous([]byte{}, secretBytes, &boxKey, rand.Reader)
if err != nil {
log.Entry().Warn("Could not encrypt secret using public key")
return nil, err
}
encryptedSecretString := base64.StdEncoding.EncodeToString(encryptedSecretBytes)
githubSecret := &github.EncryptedSecret{
Name: secretName,
KeyID: publicKey.GetKeyID(),
EncryptedValue: encryptedSecretString,
}
return githubSecret, nil
}