Debian Codegraph @

internal/config/types/secret.go

raw
1 package types
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "os"
8 "strings"
9 )
10
11 // Secret represents a secret value that can be a plain string or a file path.
12 // If the value starts with "file://", it is treated as a file path, and the secret value is read from the file.
13 // The "file://" syntax supports environment variables.
14 // For example, "file://$HOME/my_secret.txt" would read the secret from the "my_secret.txt" file in the user's home directory.
15 type Secret string
16
17 // String reassembles the Secret into a valid string.
18 //
19 //goland:noinspection GoMixedReceiverTypes
20 func (s Secret) String() string {
21 return string(s)
22 }
23
24 // MarshalText implements [encoding.TextMarshaler] interface for Secret
25 //
26 //goland:noinspection GoMixedReceiverTypes
27 func (s Secret) MarshalText() ([]byte, error) {
28 return []byte(s), nil
29 }
30
31 // UnmarshalText implements the [encoding.TextUnmarshaler] interface for Secret
32 //
33 //goland:noinspection GoMixedReceiverTypes
34 func (s *Secret) UnmarshalText(text []byte) error {
35 stringText := string(text)
36
37 switch {
38 case strings.HasPrefix(stringText, "file://"):
39 filePath := os.ExpandEnv(strings.TrimPrefix(stringText, "file://"))
40
41 body, err := os.ReadFile(filePath)
42 if err != nil {
43 return fmt.Errorf("unable read secret %s: %w", filePath, err)
44 }
45
46 body = bytes.TrimSpace(body)
47
48 *s = Secret(body)
49 default:
50 *s = Secret(stringText)
51 }
52
53 return nil
54 }
55
56 // MarshalJSON implements the [json.Marshaler] interface.
57 //
58 //goland:noinspection GoMixedReceiverTypes
59 func (s Secret) MarshalJSON() ([]byte, error) {
60 if len(s) == 0 {
61 return json.Marshal("") //nolint:wrapcheck
62 }
63
64 return json.Marshal("***") //nolint:wrapcheck
65 }