<commit_before>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package keys

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"encoding/asn1"
	"encoding/base64"
	"fmt"
	"io"
	"math/big"
	"strings"

	"github.com/google/exposure-notifications-server/internal/azurekeyvault"
	"github.com/google/exposure-notifications-server/pkg/base64util"

	"github.com/Azure/azure-sdk-for-go/services/keyvault/v7.0/keyvault"
)

// Compile-time check to verify implements interface.
var _ KeyManager = (*AzureKeyVault)(nil)
var _ crypto.Signer = (*AzureKeyVaultSigner)(nil)

// AzureKeyVault implements the keys.KeyManager interface and can be used to
// sign export files.
type AzureKeyVault struct {
	client *keyvault.BaseClient
}

type AZKeyID struct {
	Vault   string
	Key     string
	Version string
}

func ParseAZKeyID(keyID string) (*AZKeyID, error) {
	parts := strings.SplitN(keyID, "/", 3)
	if len(parts) < 3 {
		return nil, fmt.Errorf("key must include vaultName, keyName, and keyVersion: %v", keyID)
	}

	vault := fmt.Sprintf("https://%s.vault.azure.net", parts[0])
	key, version := parts[1], parts[2]

	return &AZKeyID{Vault: vault, Key: key, Version: version}, nil
}

// NewAzureKeyVault creates a new KeyVault key manager instance.
func NewAzureKeyVault(ctx context.Context) (KeyManager, error) {
	authorizer, err := azurekeyvault.GetKeyVaultAuthorizer()
	if err != nil {
		return nil, fmt.Errorf("secrets.NewAzureKeyVault: auth: %w", err)
	}

	client := keyvault.New()
	client.Authorizer = authorizer

	sm := &AzureKeyVault{
		client: &client,
	}

	return sm, nil
}

func (v *AzureKeyVault) Encrypt(ctx context.Context, keyID string, plaintext []byte, aad []byte) ([]byte, error) {
	k, err := ParseAZKeyID(keyID)
	if err != nil {
		return nil, err
	}

	// TODO(mikehelmick) - neds AEAD
	value := base64.URLEncoding.EncodeToString(plaintext)
	parameters := keyvault.KeyOperationsParameters{
		Algorithm: keyvault.RSAOAEP256,
		Value:     &value,
	}
	res, err := v.client.Encrypt(ctx, k.Vault, k.Key, k.Version, parameters)
	if err != nil {
		return nil, fmt.Errorf("unable to encrypt: %w", err)
	}

	resBytes, err := base64.URLEncoding.DecodeString(*res.Result)
	if err != nil {
		return nil, fmt.Errorf("unable to decode encrypted data: %w", err)
	}

	return resBytes, nil
}

func (v *AzureKeyVault) Decrypt(ctx context.Context, keyID string, ciphertext []byte, aad []byte) ([]byte, error) {
	k, err := ParseAZKeyID(keyID)
	if err != nil {
		return nil, err
	}

	// TODO(mikehelmick) - neds AEAD
	value := base64.URLEncoding.EncodeToString(ciphertext)
	parameters := keyvault.KeyOperationsParameters{
		Algorithm: keyvault.RSAOAEP256,
		Value:     &value,
	}
	res, err := v.client.Decrypt(ctx, k.Vault, k.Key, k.Version, parameters)
	if err != nil {
		return nil, fmt.Errorf("unable to decrypt: %w", err)
	}

	plaintext, err := base64.URLEncoding.DecodeString(*res.Result)
	if err != nil {
		return nil, fmt.Errorf("unable to decode decrypted data: %w", err)
	}

	return plaintext, nil

}

// NewSigner creates a new signer that uses a key in HashiCorp Vault's transit
// backend. The keyID in the format:
//
//     AZURE_KEY_VAULT_NAME/SECRET_NAME/SECRET_VERSION
//
// For example:
//
//     my-company-vault/api-key/1
//
// Both name and version are required.
func (v *AzureKeyVault) NewSigner(ctx context.Context, keyID string) (crypto.Signer, error) {
	k, err := ParseAZKeyID(keyID)
	if err != nil {
		return nil, err
	}
	return NewAzureKeyVaultSigner(ctx, v.client, k.Vault, k.Key, k.Version)
}

type AzureKeyVaultSigner struct {
	client  *keyvault.BaseClient<commit_msg>Use RawURLEncoding instead of URLEncoding for encrypt and decrypt operations (#885)<commit_after>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package keys

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"encoding/asn1"
	"encoding/base64"
	"fmt"
	"io"
	"math/big"
	"strings"

	"github.com/google/exposure-notifications-server/internal/azurekeyvault"
	"github.com/google/exposure-notifications-server/pkg/base64util"

	"github.com/Azure/azure-sdk-for-go/services/keyvault/v7.0/keyvault"
)

// Compile-time check to verify implements interface.
var _ KeyManager = (*AzureKeyVault)(nil)
var _ crypto.Signer = (*AzureKeyVaultSigner)(nil)

// AzureKeyVault implements the keys.KeyManager interface and can be used to
// sign export files.
type AzureKeyVault struct {
	client *keyvault.BaseClient
}

type AZKeyID struct {
	Vault   string
	Key     string
	Version string
}

func ParseAZKeyID(keyID string) (*AZKeyID, error) {
	parts := strings.SplitN(keyID, "/", 3)
	if len(parts) < 3 {
		return nil, fmt.Errorf("key must include vaultName, keyName, and keyVersion: %v", keyID)
	}

	vault := fmt.Sprintf("https://%s.vault.azure.net", parts[0])
	key, version := parts[1], parts[2]

	return &AZKeyID{Vault: vault, Key: key, Version: version}, nil
}

// NewAzureKeyVault creates a new KeyVault key manager instance.
func NewAzureKeyVault(ctx context.Context) (KeyManager, error) {
	authorizer, err := azurekeyvault.GetKeyVaultAuthorizer()
	if err != nil {
		return nil, fmt.Errorf("secrets.NewAzureKeyVault: auth: %w", err)
	}

	client := keyvault.New()
	client.Authorizer = authorizer

	sm := &AzureKeyVault{
		client: &client,
	}

	return sm, nil
}

func (v *AzureKeyVault) Encrypt(ctx context.Context, keyID string, plaintext []byte, aad []byte) ([]byte, error) {
	k, err := ParseAZKeyID(keyID)
	if err != nil {
		return nil, err
	}

	// TODO(mikehelmick) - neds AEAD
	value := base64.URLEncoding.EncodeToString(plaintext)
	parameters := keyvault.KeyOperationsParameters{
		Algorithm: keyvault.RSAOAEP256,
		Value:     &value,
	}
	res, err := v.client.Encrypt(ctx, k.Vault, k.Key, k.Version, parameters)
	if err != nil {
		return nil, fmt.Errorf("unable to encrypt: %w", err)
	}

	resBytes, err := base64.RawURLEncoding.DecodeString(*res.Result)
	if err != nil {
		return nil, fmt.Errorf("unable to decode encrypted data: %w", err)
	}

	return resBytes, nil
}

func (v *AzureKeyVault) Decrypt(ctx context.Context, keyID string, ciphertext []byte, aad []byte) ([]byte, error) {
	k, err := ParseAZKeyID(keyID)
	if err != nil {
		return nil, err
	}

	// TODO(mikehelmick) - neds AEAD
	value := base64.URLEncoding.EncodeToString(ciphertext)
	parameters := keyvault.KeyOperationsParameters{
		Algorithm: keyvault.RSAOAEP256,
		Value:     &value,
	}
	res, err := v.client.Decrypt(ctx, k.Vault, k.Key, k.Version, parameters)
	if err != nil {
		return nil, fmt.Errorf("unable to decrypt: %w", err)
	}

	plaintext, err := base64.RawURLEncoding.DecodeString(*res.Result)
	if err != nil {
		return nil, fmt.Errorf("unable to decode decrypted data: %w", err)
	}

	return plaintext, nil

}

// NewSigner creates a new signer that uses a key in HashiCorp Vault's transit
// backend. The keyID in the format:
//
//     AZURE_KEY_VAULT_NAME/SECRET_NAME/SECRET_VERSION
//
// For example:
//
//     my-company-vault/api-key/1
//
// Both name and version are required.
func (v *AzureKeyVault) NewSigner(ctx context.Context, keyID string) (crypto.Signer, error) {
	k, err := ParseAZKeyID(keyID)
	if err != nil {
		return nil, err
	}
	return NewAzureKeyVaultSigner(ctx, v.client, k.Vault, k.Key, k.Version)
}

type AzureKeyVaultSigner struct {
	client  *keyvault.BaseClient
{'fraction_non_alphanumeric': 0.1270088750299832, 'fraction_numerical': 0.008755097145598465, 'mean_word_length': 4.057004244996968, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '210707', 'n_tokens_mistral': 3018, 'n_tokens_neox': 2883, 'n_words': 819}