|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "bytes" |
| 6 | + "encoding/hex" |
| 7 | + "errors" |
| 8 | + "flag" |
| 9 | + "fmt" |
| 10 | + "io" |
| 11 | + "log" |
| 12 | + "os" |
| 13 | +) |
| 14 | + |
| 15 | +var version = "undefined" |
| 16 | + |
| 17 | +const ( |
| 18 | + envKeySecret = "BASIC_AUTH_HMAC_SECRET" |
| 19 | +) |
| 20 | + |
| 21 | +var ( |
| 22 | + hexSecret = flag.String("secret", "", "hex-encoded HMAC secret value") |
| 23 | + hexSecretFile = flag.String("secret-file", "", "file containing single line with hex-encoded secret") |
| 24 | + showVersion = flag.Bool("version", false, "show program version and exit") |
| 25 | +) |
| 26 | + |
| 27 | +func run() int { |
| 28 | + var err error |
| 29 | + |
| 30 | + flag.Parse() |
| 31 | + if *showVersion { |
| 32 | + fmt.Println(version) |
| 33 | + return 0 |
| 34 | + } |
| 35 | + |
| 36 | + if *hexSecret != "" && *hexSecretFile != "" { |
| 37 | + log.Print("Options \"-secret\" and \"-secret-file\" are mutually exclusive. Exiting...") |
| 38 | + return 2 |
| 39 | + } |
| 40 | + |
| 41 | + hs := os.Getenv(envKeySecret) |
| 42 | + if *hexSecret != "" { |
| 43 | + hs = *hexSecret |
| 44 | + } |
| 45 | + if *hexSecretFile != "" { |
| 46 | + r, err := readSecretFromFile(*hexSecretFile) |
| 47 | + if err != nil { |
| 48 | + log.Printf("read of secret from file %q failed: %v", *hexSecretFile, err) |
| 49 | + return 1 |
| 50 | + } |
| 51 | + hs = r |
| 52 | + } |
| 53 | + |
| 54 | + if hs == "" { |
| 55 | + log.Print(`secret is not specified! Please set "-secret" or "-secret-file"`+ |
| 56 | + ` command line options or `+envKeySecret+` environment variable.`) |
| 57 | + return 2 |
| 58 | + } |
| 59 | + |
| 60 | + secret, err := hex.DecodeString(hs) |
| 61 | + if err != nil { |
| 62 | + log.Printf("unable to hex-decode secret: %v", err) |
| 63 | + return 3 |
| 64 | + } |
| 65 | + |
| 66 | + log.Printf("secret=%x\n", secret) |
| 67 | + |
| 68 | + return 0 |
| 69 | +} |
| 70 | + |
| 71 | +func readSecretFromFile(filename string) (string, error) { |
| 72 | + f, err := os.Open(filename) |
| 73 | + if err != nil { |
| 74 | + return "", fmt.Errorf("unable to open secret file for reading: %w", err) |
| 75 | + } |
| 76 | + defer f.Close() |
| 77 | + |
| 78 | + rd := bufio.NewReader(f) |
| 79 | + buf, err := rd.ReadBytes('\n') |
| 80 | + if err != nil && !errors.Is(err, io.EOF) { |
| 81 | + return "", fmt.Errorf("secret file reading failed: %w", err) |
| 82 | + } |
| 83 | + |
| 84 | + buf = bytes.TrimSpace(buf) |
| 85 | + return string(buf), nil |
| 86 | +} |
| 87 | + |
| 88 | +func main() { |
| 89 | + log.Default().SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile) |
| 90 | + os.Exit(run()) |
| 91 | +} |
0 commit comments