snapshot of https://github.com/ory/kratos.git (master, 2026-09-15; blobs > 131072B omitted)
Some checks failed
CI / Run tests and lints (push) Failing after 29s
CI / Build CLI docs (push) Has been skipped
CI / Run Playwright end-to-end tests (mysql) (push) Failing after 3s
CI / Run Playwright end-to-end tests (postgres) (push) Failing after 2s
CI / Run Playwright end-to-end tests (sqlite) (push) Failing after 3s
CodeQL / Analyze (go) (push) Failing after 4s
CodeQL / Analyze (javascript) (push) Failing after 3s
Docker Image Scanners / scanners (push) Failing after 4s
Synchronize Issue Labels / Synchronize Issue Labels (push) Has been skipped
CI / Run end-to-end tests (postgres) (push) Failing after 19s
CI / Run end-to-end tests (sqlite) (push) Failing after 2s
CI / Run Playwright end-to-end tests (cockroach) (push) Failing after 2s
CI / Draft newsletter (push) Has been skipped
CI / Generate release (push) Has been skipped
CI / Pending approval Slack notification (push) Has been skipped
CI / Send newsletter (push) Has been skipped

This commit is contained in:
upstream-mirror
2026-09-15 21:19:12 +05:00
commit c60cc7ca75
8092 changed files with 394160 additions and 0 deletions

84
cipher/aes.go Normal file
View File

@@ -0,0 +1,84 @@
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package cipher
import (
"context"
"crypto/aes"
stdcipher "crypto/cipher"
"encoding/hex"
"github.com/pkg/errors"
"github.com/ory/herodot"
)
type AES struct {
c SecretsProvider
}
func NewCryptAES(c SecretsProvider) *AES {
return &AES{c: c}
}
// aesGCM returns an AES-256-GCM AEAD that generates a random nonce internally
// and prepends it to the ciphertext (nonce | ciphertext | tag).
func aesGCM(key *[32]byte) (stdcipher.AEAD, error) {
block, err := aes.NewCipher(key[:])
if err != nil {
return nil, errors.WithStack(err)
}
gcm, err := stdcipher.NewGCMWithRandomNonce(block)
if err != nil {
return nil, errors.WithStack(err)
}
return gcm, nil
}
// Encrypt returns the AES-256-GCM encryption of plaintext.
func (a *AES) Encrypt(ctx context.Context, message []byte) (string, error) {
if len(message) == 0 {
return "", nil
}
if len(a.c.SecretsCipher(ctx)) == 0 {
return "", errors.WithStack(herodot.ErrMisconfiguration().WithReason("Unable to encrypt message because no cipher secrets were configured."))
}
gcm, err := aesGCM(&a.c.SecretsCipher(ctx)[0])
if err != nil {
return "", errors.WithStack(herodot.ErrForbidden().WithWrap(err))
}
return hex.EncodeToString(gcm.Seal(nil, nil, message, nil)), nil
}
// Decrypt returns the decrypted AES data.
func (a *AES) Decrypt(ctx context.Context, ciphertext string) ([]byte, error) {
if len(ciphertext) == 0 {
return nil, nil
}
secrets := a.c.SecretsCipher(ctx)
if len(secrets) == 0 {
return nil, errors.WithStack(herodot.ErrMisconfiguration().WithReason("Unable to decipher the encrypted message because no AES secrets were configured."))
}
decode, err := hex.DecodeString(ciphertext)
if err != nil {
return nil, errors.WithStack(herodot.ErrBadRequest().WithWrap(err))
}
for i := range secrets {
gcm, err := aesGCM(&secrets[i])
if err != nil {
continue
}
if plaintext, err := gcm.Open(nil, nil, decode, nil); err == nil {
return plaintext, nil
}
}
return nil, errors.WithStack(herodot.ErrForbidden().WithReason("Unable to decipher the encrypted message."))
}

94
cipher/chacha20.go Normal file
View File

@@ -0,0 +1,94 @@
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package cipher
import (
"context"
"crypto/rand"
"encoding/hex"
"io"
"math"
"github.com/pkg/errors"
"golang.org/x/crypto/chacha20poly1305"
"github.com/ory/herodot"
)
type XChaCha20Poly1305 struct {
c SecretsProvider
}
func NewCryptChaCha20(c SecretsProvider) *XChaCha20Poly1305 {
return &XChaCha20Poly1305{c: c}
}
// Encrypt returns a ChaCha encryption of plaintext
func (c *XChaCha20Poly1305) Encrypt(ctx context.Context, message []byte) (string, error) {
if len(message) == 0 {
return "", nil
}
if len(c.c.SecretsCipher(ctx)) == 0 {
return "", errors.WithStack(herodot.ErrMisconfiguration().WithReason("Unable to encrypt message because no cipher secrets were configured."))
}
aead, err := chacha20poly1305.NewX(c.c.SecretsCipher(ctx)[0][:])
if err != nil {
return "", herodot.ErrInternalServerError().WithWrap(err).WithReason("Unable to generate key")
}
// Make sure the size calculation does not overflow.
if len(message) > math.MaxInt-aead.NonceSize()-aead.Overhead() {
return "", errors.WithStack(herodot.ErrInternalServerError().WithReason("plaintext too large"))
}
nonce := make([]byte, aead.NonceSize(), aead.NonceSize()+len(message)+aead.Overhead())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
return "", errors.WithStack(herodot.ErrInternalServerError().WithWrap(err).WithReason("Unable to generate nonce"))
}
encryptedMsg := aead.Seal(nonce, nonce, message, nil)
return hex.EncodeToString(encryptedMsg), nil
}
// Decrypt decrypts data using 256 bit key
func (c *XChaCha20Poly1305) Decrypt(ctx context.Context, ciphertext string) ([]byte, error) {
if len(ciphertext) == 0 {
return nil, nil
}
secrets := c.c.SecretsCipher(ctx)
if len(secrets) == 0 {
return nil, errors.WithStack(herodot.ErrMisconfiguration().WithReason("Unable to decipher the encrypted message because no cipher secrets were configured."))
}
rawCiphertext, err := hex.DecodeString(ciphertext)
if err != nil {
return nil, errors.WithStack(herodot.ErrBadRequest().WithWrap(err).WithReason("Unable to decode hex encrypted string"))
}
for i := range secrets {
aead, err := chacha20poly1305.NewX(secrets[i][:])
if err != nil {
return nil, errors.WithStack(herodot.ErrInternalServerError().WithWrap(err).WithReason("Unable to instantiate chacha20"))
}
// Guard the DECODED length, not the hex string length: a hex string of
// 24+ chars passes a hex-length check while decoding to fewer than
// NonceSize bytes, and the slice below would then panic.
if len(rawCiphertext) < aead.NonceSize() {
return nil, errors.WithStack(herodot.ErrBadRequest().WithReason("cipher text too short"))
}
nonce, ciphertext := rawCiphertext[:aead.NonceSize()], rawCiphertext[aead.NonceSize():]
plaintext, err := aead.Open(nil, nonce, ciphertext, nil)
if err == nil {
return plaintext, nil
}
}
return nil, errors.WithStack(herodot.ErrForbidden().WithReason("Unable to decrypt string"))
}

29
cipher/cipher.go Normal file
View File

@@ -0,0 +1,29 @@
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package cipher
import "context"
// Cipher provides methods for encrypt and decrypt string
type Cipher interface {
// Encrypt encrypts the (binary) message and returns a hex-encoded binary ciphertext
// or an error if the encryption failed.
//
// If the message is empty, the ciphertext is also empty and no error is returned.
Encrypt(ctx context.Context, message []byte) (string, error)
// Decrypt takes a hex-encoded binary ciphertext and decrypts it or returns an error if the decryption
// failed.
//
// If the ciphertext is empty a nil byte slice is returned.
Decrypt(ctx context.Context, encrypted string) ([]byte, error)
}
type Provider interface {
Cipher(ctx context.Context) Cipher
}
type SecretsProvider interface {
SecretsCipher(ctx context.Context) [][32]byte
}

136
cipher/cipher_test.go Normal file
View File

@@ -0,0 +1,136 @@
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package cipher_test
import (
"context"
"encoding/hex"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ory/herodot"
"github.com/ory/kratos/cipher"
"github.com/ory/kratos/driver/config"
"github.com/ory/kratos/pkg"
"github.com/ory/x/configx"
"github.com/ory/x/contextx"
)
var goodSecret = []string{"secret-thirty-two-character-long"}
func TestCipher(t *testing.T) {
ctx := context.Background()
_, reg := pkg.NewFastRegistryWithMocks(t, configx.WithValue(config.ViperKeySecretsDefault, goodSecret))
ciphers := []cipher.Cipher{
cipher.NewCryptAES(reg.Config()),
cipher.NewCryptChaCha20(reg.Config()),
}
for _, c := range ciphers {
t.Run(fmt.Sprintf("cipher=%T", c), func(t *testing.T) {
t.Parallel()
t.Run("case=all_work", func(t *testing.T) {
t.Parallel()
testAllWork(ctx, t, c)
})
t.Run("case=encryption_failed", func(t *testing.T) {
t.Parallel()
ctx := contextx.WithConfigValue(ctx, config.ViperKeySecretsCipher, []string{""})
// secret have to be set
_, err := c.Encrypt(ctx, []byte("not-empty"))
require.Error(t, err)
var hErr *herodot.DefaultError
require.ErrorAs(t, err, &hErr)
assert.Equal(t, "Unable to encrypt message because no cipher secrets were configured.", hErr.Reason())
ctx = contextx.WithConfigValue(ctx, config.ViperKeySecretsCipher, []string{"bad-length"})
// bad secret length
_, err = c.Encrypt(ctx, []byte("not-empty"))
require.ErrorAs(t, err, &hErr)
assert.Equal(t, "Unable to encrypt message because no cipher secrets were configured.", hErr.Reason())
})
t.Run("case=decryption_failed", func(t *testing.T) {
t.Parallel()
_, err := c.Decrypt(ctx, hex.EncodeToString([]byte("bad-data")))
require.Error(t, err)
_, err = c.Decrypt(ctx, "not-empty")
require.Error(t, err)
_, err = c.Decrypt(contextx.WithConfigValue(ctx, config.ViperKeySecretsCipher, []string{""}), "not-empty")
require.Error(t, err)
// Valid hex that decodes to fewer bytes than the AEAD nonce must be
// a clean error, not a panic: a corrupt or truncated stored
// ciphertext must never crash the caller. 16 bytes (32 hex chars)
// clears the hex-length check but is shorter than XChaCha20's
// 24-byte nonce.
_, err = c.Decrypt(ctx, hex.EncodeToString([]byte("sixteen-bytes!!!")))
require.Error(t, err)
})
})
}
c := cipher.NewNoop()
t.Run(fmt.Sprintf("cipher=%T", c), func(t *testing.T) {
t.Parallel()
testAllWork(ctx, t, c)
})
}
func TestAESBackwardsCompatibility(t *testing.T) {
t.Parallel()
// Ciphertext produced by the previous implementation
// (github.com/gtank/cryptopasta: caller-generated GCM nonce). The new
// stdlib NewGCMWithRandomNonce implementation must keep decrypting it.
// Key (32 bytes): the literal config secret below.
// Plaintext: "fixture: encrypted with caller-supplied nonce".
const legacyCiphertext = "74756223e46170ef0579f207af41b7ed435d649ae94f22bd57934398e9861870e58feba1e949d28f18dfdda6395eabf4d2d31fdeb2b07c4c428e9829509470f6d8e23c17708f1368b6"
ctx := t.Context()
_, reg := pkg.NewFastRegistryWithMocks(t, configx.WithValue(config.ViperKeySecretsCipher, []string{"change this password to a secret"}))
c := cipher.NewCryptAES(reg.Config())
plain, err := c.Decrypt(ctx, legacyCiphertext)
require.NoError(t, err)
assert.Equal(t, "fixture: encrypted with caller-supplied nonce", string(plain))
// Round-trip with the current implementation.
out, err := c.Encrypt(ctx, []byte("fixture: encrypted with caller-supplied nonce"))
require.NoError(t, err)
plain2, err := c.Decrypt(ctx, out)
require.NoError(t, err)
assert.Equal(t, "fixture: encrypted with caller-supplied nonce", string(plain2))
}
func testAllWork(ctx context.Context, t *testing.T, c cipher.Cipher) {
message := "my secret message!"
encryptedSecret, err := c.Encrypt(ctx, []byte(message))
require.NoError(t, err)
decryptedSecret, err := c.Decrypt(ctx, encryptedSecret)
require.NoError(t, err, "encrypted", encryptedSecret)
assert.Equal(t, message, string(decryptedSecret))
// data to encrypt return blank result
_, err = c.Encrypt(ctx, []byte(""))
require.NoError(t, err)
// empty encrypted data return blank
_, err = c.Decrypt(ctx, "")
require.NoError(t, err)
}

26
cipher/noop.go Normal file
View File

@@ -0,0 +1,26 @@
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package cipher
import (
"context"
"encoding/hex"
)
// Noop is default cipher implementation witch does not do encryption
type Noop struct{}
func NewNoop() *Noop {
return &Noop{}
}
// Encrypt encode message to hex
func (*Noop) Encrypt(_ context.Context, message []byte) (string, error) {
return hex.EncodeToString(message), nil
}
// Decrypt decode the hex message
func (*Noop) Decrypt(_ context.Context, ciphertext string) ([]byte, error) {
return hex.DecodeString(ciphertext)
}