From 585f47378647658f55475bfa7e6ad40498ae504d Mon Sep 17 00:00:00 2001 From: Gustavo Ocanto Date: Wed, 2 Jul 2025 15:07:57 +0800 Subject: [PATCH 1/2] read secrets if any --- boost/factory.go | 6 +++--- env/env.go | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/boost/factory.go b/boost/factory.go index a1fddf32..2bee9713 100644 --- a/boost/factory.go +++ b/boost/factory.go @@ -72,9 +72,9 @@ func MakeEnv(validate *pkg.Validator) *env.Environment { } db := env.DBEnvironment{ - UserName: env.GetEnvVar("ENV_DB_USER_NAME"), - UserPassword: env.GetEnvVar("ENV_DB_USER_PASSWORD"), - DatabaseName: env.GetEnvVar("ENV_DB_DATABASE_NAME"), + UserName: env.GetSecretOrEnv("postgres_user", "ENV_DB_USER_NAME"), + UserPassword: env.GetSecretOrEnv("postgres_password", "ENV_DB_USER_PASSWORD"), + DatabaseName: env.GetSecretOrEnv("postgres_db", "ENV_DB_DATABASE_NAME"), Port: port, Host: env.GetEnvVar("ENV_DB_HOST"), DriverName: database.DriverName, diff --git a/env/env.go b/env/env.go index 6bb4c657..f3772c28 100644 --- a/env/env.go +++ b/env/env.go @@ -16,3 +16,20 @@ type Environment struct { func GetEnvVar(key string) string { return strings.TrimSpace(os.Getenv(key)) } + +func GetSecretOrEnv(secretName string, envVarName string) string { + secretPath := "/run/secrets/" + secretName + + // Try to read the secret file first. + content, err := os.ReadFile(secretPath) + if err == nil { + return strings.TrimSpace(string(content)) + } + + // If the file does not exist, fall back to the environment variable. + if os.IsNotExist(err) { + return GetEnvVar(envVarName) // Use your existing function here + } + + return GetEnvVar(envVarName) +} From 98e09e50ba78de159347f948bdc3276536019d0a Mon Sep 17 00:00:00 2001 From: Gustavo Ocanto Date: Wed, 2 Jul 2025 15:11:05 +0800 Subject: [PATCH 2/2] add secrets to the api service too --- docker-compose.yml | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index c3ba8864..690708fb 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -73,12 +73,6 @@ services: env_file: - .env environment: - # --- These variables inject the database credentials directly into the - # API container at runtime. This ensures the Go application uses the - # same secure credentials that the 'api-db' service is configured with. - ENV_DB_USER_NAME: ${ENV_DB_USER_NAME} - ENV_DB_USER_PASSWORD: ${ENV_DB_USER_PASSWORD} - ENV_DB_DATABASE_NAME: ${ENV_DB_DATABASE_NAME} # --- This ensures the Go web server listens for connections from other # containers (like Caddy), not just from within itself. ENV_DB_HOST: api-db @@ -93,6 +87,10 @@ services: - APP_GROUP=${ENV_DOCKER_USER_GROUP} container_name: oullin_api restart: unless-stopped + secrets: + - postgres_user + - postgres_password + - postgres_db depends_on: api-db: condition: service_healthy