feat(t229): load ERP credentials from dotenv

This commit is contained in:
QiuSW
2026-07-29 10:25:56 +08:00
parent d75a7d8dc0
commit f0fbdbaddc
12 changed files with 396 additions and 26 deletions
+146
View File
@@ -0,0 +1,146 @@
package config
import (
"errors"
"io"
"os"
"strings"
"unicode/utf8"
)
const (
DefaultERPEnvironmentFile = ".env"
maximumERPEnvironmentFileBytes = 32 << 10
maximumERPEnvironmentLineBytes = 4 << 10
)
var (
errERPEnvironmentFileInvalid = errors.New("ERP .env file is invalid")
errERPEnvironmentLookup = errors.New("ERP .env lookup is required")
)
// WithERPEnvironmentFile returns a lookup that uses the process environment
// first and only falls back to approved ERP values from path.
func WithERPEnvironmentFile(
path string,
parent LookupEnvironment,
) (LookupEnvironment, error) {
if parent == nil {
return nil, errERPEnvironmentLookup
}
values, err := readERPEnvironmentFile(path)
if err != nil {
return nil, err
}
return func(name string) (string, bool) {
if value, exists := parent(name); exists {
return value, true
}
value, exists := values[name]
return value, exists
}, nil
}
func readERPEnvironmentFile(path string) (map[string]string, error) {
values := make(map[string]string)
if path == "" {
return nil, errERPEnvironmentFileInvalid
}
file, err := os.Open(path)
if errors.Is(err, os.ErrNotExist) {
return values, nil
}
if err != nil {
return nil, errors.New("ERP .env file cannot be read")
}
defer file.Close()
contents, err := io.ReadAll(io.LimitReader(
file,
maximumERPEnvironmentFileBytes+1,
))
if err != nil || len(contents) > maximumERPEnvironmentFileBytes ||
!utf8.Valid(contents) || strings.IndexByte(string(contents), 0) >= 0 {
return nil, errERPEnvironmentFileInvalid
}
for _, rawLine := range strings.Split(string(contents), "\n") {
line := strings.TrimSuffix(rawLine, "\r")
if len(line) > maximumERPEnvironmentLineBytes {
return nil, errERPEnvironmentFileInvalid
}
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
if strings.HasPrefix(line, "export ") {
line = strings.TrimSpace(strings.TrimPrefix(line, "export "))
}
name, rawValue, found := strings.Cut(line, "=")
name = strings.TrimSpace(name)
if !found || !validEnvironmentName(name) {
return nil, errERPEnvironmentFileInvalid
}
if !isERPEnvironmentName(name) {
if strings.HasPrefix(name, "CMROUBAO_") {
return nil, errERPEnvironmentFileInvalid
}
continue
}
if _, exists := values[name]; exists {
return nil, errERPEnvironmentFileInvalid
}
value, err := dotenvValue(rawValue)
if err != nil {
return nil, errERPEnvironmentFileInvalid
}
values[name] = value
}
return values, nil
}
func dotenvValue(rawValue string) (string, error) {
value := strings.TrimSpace(rawValue)
if value == "" {
return value, nil
}
quote := value[0]
if quote == '\'' || quote == '"' {
if len(value) < 2 || value[len(value)-1] != quote {
return "", errERPEnvironmentFileInvalid
}
return value[1 : len(value)-1], nil
}
if strings.HasSuffix(value, "\"") || strings.HasSuffix(value, "'") {
return "", errERPEnvironmentFileInvalid
}
return value, nil
}
func isERPEnvironmentName(name string) bool {
switch name {
case ShunyunbaoURLEnvironment,
ShunyunbaoUsernameEnvironment,
ShunyunbaoPasswordEnvironment:
return true
default:
return false
}
}
func validEnvironmentName(name string) bool {
if name == "" {
return false
}
for index := 0; index < len(name); index++ {
character := name[index]
if (character >= 'A' && character <= 'Z') ||
(character >= '0' && character <= '9' && index > 0) ||
character == '_' {
continue
}
return false
}
return true
}
+136
View File
@@ -0,0 +1,136 @@
package config
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestWithERPEnvironmentFileUsesApprovedFallbackValues(t *testing.T) {
path := writeERPEnvironmentFile(t, strings.Join([]string{
"OTHER_TOOL_TOKEN=ignored",
"CMROUBAO_SHUNYUNBAO_URL=https://erp.example.test",
"CMROUBAO_SHUNYUNBAO_USERNAME=dotenv-user",
"CMROUBAO_SHUNYUNBAO_PASSWORD='dotenv password #1'",
}, "\n"))
lookup, err := WithERPEnvironmentFile(path, func(string) (string, bool) {
return "", false
})
if err != nil {
t.Fatalf("WithERPEnvironmentFile() error = %v", err)
}
cfg, err := Load(lookup)
if err != nil {
t.Fatalf("Load() error = %v", err)
}
if cfg.ShunyunbaoURL != "https://erp.example.test" ||
cfg.ShunyunbaoUsername != "dotenv-user" ||
cfg.ShunyunbaoPassword != "dotenv password #1" {
t.Fatalf(
"ERP config = %#v",
struct {
URL string
Username string
Password string
}{cfg.ShunyunbaoURL, cfg.ShunyunbaoUsername, cfg.ShunyunbaoPassword},
)
}
if _, exists := lookup("OTHER_TOOL_TOKEN"); exists {
t.Fatal("unapproved .env value was exposed")
}
}
func TestWithERPEnvironmentFileProcessEnvironmentTakesPriority(t *testing.T) {
path := writeERPEnvironmentFile(t, strings.Join([]string{
"CMROUBAO_SHUNYUNBAO_URL=https://dotenv.example.test",
"CMROUBAO_SHUNYUNBAO_USERNAME=dotenv-user",
"CMROUBAO_SHUNYUNBAO_PASSWORD=dotenv-password",
}, "\n"))
process := map[string]string{
ShunyunbaoURLEnvironment: "https://process.example.test",
ShunyunbaoUsernameEnvironment: "process-user",
ShunyunbaoPasswordEnvironment: "process-password",
}
lookup, err := WithERPEnvironmentFile(path, lookupMap(process))
if err != nil {
t.Fatalf("WithERPEnvironmentFile() error = %v", err)
}
cfg, err := Load(lookup)
if err != nil {
t.Fatalf("Load() error = %v", err)
}
if cfg.ShunyunbaoURL != process[ShunyunbaoURLEnvironment] ||
cfg.ShunyunbaoUsername != process[ShunyunbaoUsernameEnvironment] ||
cfg.ShunyunbaoPassword != process[ShunyunbaoPasswordEnvironment] {
t.Fatalf("process values did not override .env values")
}
}
func TestWithERPEnvironmentFileAllowsMissingFile(t *testing.T) {
lookup, err := WithERPEnvironmentFile(
filepath.Join(t.TempDir(), "missing.env"),
lookupMap(nil),
)
if err != nil {
t.Fatalf("WithERPEnvironmentFile() error = %v", err)
}
if _, exists := lookup(ShunyunbaoUsernameEnvironment); exists {
t.Fatal("missing file provided a value")
}
}
func TestWithERPEnvironmentFileRejectsInvalidContentWithoutLeakingValues(t *testing.T) {
const secret = "must-not-appear-in-error"
testCases := map[string]string{
"invalid name": "not a name=" + secret,
"duplicate": strings.Join([]string{
"CMROUBAO_SHUNYUNBAO_USERNAME=" + secret,
"CMROUBAO_SHUNYUNBAO_USERNAME=another",
}, "\n"),
"unknown app config": "CMROUBAO_AUTH_PASSWORD=" + secret,
"unmatched quote": "CMROUBAO_SHUNYUNBAO_PASSWORD='" + secret,
"nul": "CMROUBAO_SHUNYUNBAO_PASSWORD=" + secret + "\x00",
}
for name, contents := range testCases {
t.Run(name, func(t *testing.T) {
path := writeERPEnvironmentFile(t, contents)
_, err := WithERPEnvironmentFile(path, lookupMap(nil))
if err == nil {
t.Fatal("WithERPEnvironmentFile() error = nil")
}
if strings.Contains(err.Error(), secret) {
t.Fatalf("error leaked .env content: %v", err)
}
})
}
}
func TestWithERPEnvironmentFileRejectsOversizedFile(t *testing.T) {
path := writeERPEnvironmentFile(
t,
"CMROUBAO_SHUNYUNBAO_USERNAME="+
strings.Repeat("x", maximumERPEnvironmentFileBytes),
)
_, err := WithERPEnvironmentFile(path, lookupMap(nil))
if err == nil {
t.Fatal("WithERPEnvironmentFile() error = nil")
}
}
func writeERPEnvironmentFile(t *testing.T, contents string) string {
t.Helper()
path := filepath.Join(t.TempDir(), ".env")
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
t.Fatalf("os.WriteFile() error = %v", err)
}
return path
}
func lookupMap(values map[string]string) LookupEnvironment {
return func(name string) (string, bool) {
value, exists := values[name]
return value, exists
}
}