aboutsummaryrefslogtreecommitdiff
path: root/weed/kms/envelope.go
blob: 60542b8a49f4f88cf983ebc28b7cf8c4ef19a086 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package kms

import (
	"encoding/json"
	"fmt"
)

// CiphertextEnvelope represents a standardized format for storing encrypted data
// along with the metadata needed for decryption. This ensures consistent API
// behavior across all KMS providers.
type CiphertextEnvelope struct {
	// Provider identifies which KMS provider was used
	Provider string `json:"provider"`

	// KeyID is the identifier of the key used for encryption
	KeyID string `json:"key_id"`

	// Ciphertext is the encrypted data (base64 encoded for JSON compatibility)
	Ciphertext string `json:"ciphertext"`

	// Version allows for future format changes
	Version int `json:"version"`

	// ProviderSpecific contains provider-specific metadata if needed
	ProviderSpecific map[string]interface{} `json:"provider_specific,omitempty"`
}

// CreateEnvelope creates a ciphertext envelope for consistent KMS provider behavior
func CreateEnvelope(provider, keyID, ciphertext string, providerSpecific map[string]interface{}) ([]byte, error) {
	// Validate required fields
	if provider == "" {
		return nil, fmt.Errorf("provider cannot be empty")
	}
	if keyID == "" {
		return nil, fmt.Errorf("keyID cannot be empty")
	}
	if ciphertext == "" {
		return nil, fmt.Errorf("ciphertext cannot be empty")
	}

	envelope := CiphertextEnvelope{
		Provider:         provider,
		KeyID:            keyID,
		Ciphertext:       ciphertext,
		Version:          1,
		ProviderSpecific: providerSpecific,
	}

	return json.Marshal(envelope)
}

// ParseEnvelope parses a ciphertext envelope to extract key information
func ParseEnvelope(ciphertextBlob []byte) (*CiphertextEnvelope, error) {
	if len(ciphertextBlob) == 0 {
		return nil, fmt.Errorf("ciphertext blob cannot be empty")
	}

	// Parse as envelope format
	var envelope CiphertextEnvelope
	if err := json.Unmarshal(ciphertextBlob, &envelope); err != nil {
		return nil, fmt.Errorf("failed to parse ciphertext envelope: %w", err)
	}

	// Validate required fields
	if envelope.Provider == "" {
		return nil, fmt.Errorf("envelope missing provider field")
	}
	if envelope.KeyID == "" {
		return nil, fmt.Errorf("envelope missing key_id field")
	}
	if envelope.Ciphertext == "" {
		return nil, fmt.Errorf("envelope missing ciphertext field")
	}
	if envelope.Version == 0 {
		envelope.Version = 1 // Default to version 1
	}

	return &envelope, nil
}