Debian Codegraph @

secrets/secrets.go

raw
1 // Copyright 2019 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package secrets provides an easy and portable way to encrypt and decrypt
16 // messages. Subpackages contain driver implementations of
17 // secrets for supported services.
18 //
19 // See https://gocloud.dev/howto/secrets/ for a detailed how-to guide.
20 //
21 // # OpenTelemetry Integration
22 //
23 // OpenTelemetry supports tracing and metric collection for multiple languages and
24 // backend providers. See https://opentelemetry.io.
25 //
26 // This API collects OpenTelemetry traces and metrics for the following methods:
27 // - Encrypt
28 // - Decrypt
29 //
30 // All trace and metric names begin with the package import path.
31 // The traces add the method name.
32 // For example, "gocloud.dev/secrets/Encrypt".
33 // The metrics are "completed_calls", a count of completed method calls by driver,
34 // method and status (error code); and "latency", a distribution of method latency
35 // by driver and method.
36 // For example, "gocloud.dev/secrets/latency".
37 //
38 // To enable trace collection in your application, see the OpenTelemetry documentation at
39 // https://opentelemetry.io/docs/instrumentation/go/getting-started/.
40 package secrets // import "gocloud.dev/secrets"
41
42 import (
43 "context"
44 "net/url"
45 "sync"
46
47 "gocloud.dev/internal/gcerr"
48 "gocloud.dev/internal/openurl"
49 gcdkotel "gocloud.dev/internal/otel"
50 "gocloud.dev/secrets/driver"
51 )
52
53 // Keeper does encryption and decryption. To create a Keeper, use constructors
54 // found in driver subpackages.
55 type Keeper struct {
56 k driver.Keeper
57 tracer *gcdkotel.Tracer
58
59 // mu protects the closed variable.
60 // Read locks are kept to allow holding a read lock for long-running calls,
61 // and thereby prevent closing until a call finishes.
62 mu sync.RWMutex
63 closed bool
64 }
65
66 // NewKeeper is intended for use by drivers only. Do not use in application code.
67 var NewKeeper = newKeeper
68
69 // newKeeper creates a Keeper.
70 func newKeeper(k driver.Keeper) *Keeper {
71 return &Keeper{
72 k: k,
73 tracer: gcdkotel.NewTracer(pkgName, gcdkotel.ProviderName(k)),
74 }
75 }
76
77 const pkgName = "gocloud.dev/secrets"
78
79 var (
80
81 // OpenTelemetryViews are predefined views for OpenTelemetry metrics.
82 // The views include counts and latency distributions for API method calls.
83 // See the explanations at https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for usage.
84 OpenTelemetryViews = gcdkotel.Views(pkgName)
85 )
86
87 // Encrypt encrypts the plaintext and returns the cipher message.
88 func (k *Keeper) Encrypt(ctx context.Context, plaintext []byte) (ciphertext []byte, err error) {
89 ctx, span := k.tracer.Start(ctx, "Encrypt")
90 defer func() { k.tracer.End(ctx, span, err) }()
91
92 k.mu.RLock()
93 defer k.mu.RUnlock()
94 if k.closed {
95 return nil, errClosed
96 }
97
98 b, err := k.k.Encrypt(ctx, plaintext)
99 if err != nil {
100 return nil, wrapError(k, err)
101 }
102 return b, nil
103 }
104
105 // Decrypt decrypts the ciphertext and returns the plaintext.
106 func (k *Keeper) Decrypt(ctx context.Context, ciphertext []byte) (plaintext []byte, err error) {
107 ctx, span := k.tracer.Start(ctx, "Decrypt")
108 defer func() { k.tracer.End(ctx, span, err) }()
109
110 k.mu.RLock()
111 defer k.mu.RUnlock()
112 if k.closed {
113 return nil, errClosed
114 }
115
116 b, err := k.k.Decrypt(ctx, ciphertext)
117 if err != nil {
118 return nil, wrapError(k, err)
119 }
120 return b, nil
121 }
122
123 var errClosed = gcerr.Newf(gcerr.FailedPrecondition, nil, "secrets: Keeper has been closed")
124
125 // Close releases any resources used for the Keeper.
126 func (k *Keeper) Close() error {
127 k.mu.Lock()
128 prev := k.closed
129 k.closed = true
130 k.mu.Unlock()
131 if prev {
132 return errClosed
133 }
134 return wrapError(k, k.k.Close())
135 }
136
137 // ErrorAs converts i to driver-specific types. See
138 // https://gocloud.dev/concepts/as/ for background information and the
139 // driver package documentation for the specific types supported for
140 // that driver.
141 //
142 // ErrorAs panics if i is nil or not a pointer.
143 // ErrorAs returns false if err == nil.
144 func (k *Keeper) ErrorAs(err error, i any) bool {
145 return gcerr.ErrorAs(err, i, k.k.ErrorAs)
146 }
147
148 func wrapError(k *Keeper, err error) error {
149 if err == nil {
150 return nil
151 }
152 if gcerr.DoNotWrap(err) {
153 return err
154 }
155 return gcerr.New(k.k.ErrorCode(err), err, 2, "secrets")
156 }
157
158 // KeeperURLOpener represents types that can open Keepers based on a URL.
159 // The opener must not modify the URL argument. OpenKeeperURL must be safe to
160 // call from multiple goroutines.
161 //
162 // This interface is generally implemented by types in driver packages.
163 type KeeperURLOpener interface {
164 OpenKeeperURL(ctx context.Context, u *url.URL) (*Keeper, error)
165 }
166
167 // URLMux is a URL opener multiplexer. It matches the scheme of the URLs
168 // against a set of registered schemes and calls the opener that matches the
169 // URL's scheme.
170 // See https://gocloud.dev/concepts/urls/ for more information.
171 //
172 // The zero value is a multiplexer with no registered schemes.
173 type URLMux struct {
174 schemes openurl.SchemeMap
175 }
176
177 // KeeperSchemes returns a sorted slice of the registered Keeper schemes.
178 func (mux *URLMux) KeeperSchemes() []string { return mux.schemes.Schemes() }
179
180 // ValidKeeperScheme returns true iff scheme has been registered for Keepers.
181 func (mux *URLMux) ValidKeeperScheme(scheme string) bool { return mux.schemes.ValidScheme(scheme) }
182
183 // RegisterKeeper registers the opener with the given scheme. If an opener
184 // already exists for the scheme, RegisterKeeper panics.
185 func (mux *URLMux) RegisterKeeper(scheme string, opener KeeperURLOpener) {
186 mux.schemes.Register("secrets", "Keeper", scheme, opener)
187 }
188
189 // OpenKeeper calls OpenKeeperURL with the URL parsed from urlstr.
190 // OpenKeeper is safe to call from multiple goroutines.
191 func (mux *URLMux) OpenKeeper(ctx context.Context, urlstr string) (*Keeper, error) {
192 opener, u, err := mux.schemes.FromString("Keeper", urlstr)
193 if err != nil {
194 return nil, err
195 }
196 return opener.(KeeperURLOpener).OpenKeeperURL(ctx, u)
197 }
198
199 // OpenKeeperURL dispatches the URL to the opener that is registered with the
200 // URL's scheme. OpenKeeperURL is safe to call from multiple goroutines.
201 func (mux *URLMux) OpenKeeperURL(ctx context.Context, u *url.URL) (*Keeper, error) {
202 opener, err := mux.schemes.FromURL("Keeper", u)
203 if err != nil {
204 return nil, err
205 }
206 return opener.(KeeperURLOpener).OpenKeeperURL(ctx, u)
207 }
208
209 var defaultURLMux = new(URLMux)
210
211 // DefaultURLMux returns the URLMux used by OpenKeeper.
212 //
213 // Driver packages can use this to register their KeeperURLOpener on the mux.
214 func DefaultURLMux() *URLMux {
215 return defaultURLMux
216 }
217
218 // OpenKeeper opens the Keeper identified by the URL given.
219 // See the URLOpener documentation in driver subpackages for
220 // details on supported URL formats, and https://gocloud.dev/concepts/urls
221 // for more information.
222 func OpenKeeper(ctx context.Context, urlstr string) (*Keeper, error) {
223 return defaultURLMux.OpenKeeper(ctx, urlstr)
224 }