Skip to content

Commit 80632eb

Browse files
authored
fix: replace hardcoded JWT/session/CSRF/DB/MinIO/Redis secrets with env vars (#189)
* fix: replace hardcoded JWT/session/CSRF/DB/MinIO/Redis secrets with env vars Remove CWE-798 hardcoded credentials across 3 demos: - hertz_jwt: JWT signing key "secret key" -> JWT_SECRET_KEY env - hertz_session: session/CSRF secrets + DB "gorm:gorm" -> env vars - tiktok_demo: DB "douyin:douyin123" + MinIO + Redis creds -> env vars * fix: replace hardcoded JWT key "tiktok secret key" in tiktok_demo Use JWT_SECRET_KEY env var with fatal exit if unset.
1 parent 1c20b40 commit 80632eb

10 files changed

Lines changed: 138 additions & 32 deletions

File tree

bizdemo/hertz_jwt/biz/mw/jwt.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ package mw
1919
import (
2020
"context"
2121
"errors"
22+
"fmt"
2223
"net/http"
24+
"os"
2325
"time"
2426

2527
"github.com/cloudwego/hertz-examples/bizdemo/hertz_jwt/biz/dal/mysql"
@@ -36,11 +38,20 @@ var (
3638
IdentityKey = "identity"
3739
)
3840

41+
func getJWTKey() []byte {
42+
key := os.Getenv("JWT_SECRET_KEY")
43+
if key == "" {
44+
fmt.Fprintf(os.Stderr, "fatal: JWT_SECRET_KEY is not set. Generate one with: openssl rand -base64 32\n")
45+
os.Exit(1)
46+
}
47+
return []byte(key)
48+
}
49+
3950
func InitJwt() {
4051
var err error
4152
JwtMiddleware, err = jwt.New(&jwt.HertzJWTMiddleware{
4253
Realm: "test zone",
43-
Key: []byte("secret key"),
54+
Key: getJWTKey(),
4455
Timeout: time.Hour,
4556
MaxRefresh: time.Hour,
4657
TokenLookup: "header: Authorization, query: token, cookie: jwt",

bizdemo/hertz_session/biz/dal/mysql/init.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ var DB *gorm.DB
2727

2828
func Init() {
2929
var err error
30-
DB, err = gorm.Open(mysql.Open(consts.MySQLDefaultDSN), &gorm.Config{
30+
DB, err = gorm.Open(mysql.Open(consts.GetMySQLDSN()), &gorm.Config{
3131
SkipDefaultTransaction: true,
3232
PrepareStmt: true,
3333
Logger: logger.Default.LogMode(logger.Info),

bizdemo/hertz_session/biz/mw/csrf.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import (
3030

3131
func InitCSRF(h *server.Hertz) {
3232
h.Use(csrf.New(
33-
csrf.WithSecret(consts.CSRFSecretKey),
33+
csrf.WithSecret(consts.GetCSRFSecret()),
3434
csrf.WithKeyLookUp(consts.CSRFKeyLookUp),
3535
csrf.WithNext(utils.IsLogout),
3636
csrf.WithErrorFunc(func(ctx context.Context, c *app.RequestContext) {

bizdemo/hertz_session/biz/mw/session.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import (
2424
)
2525

2626
func InitSession(h *server.Hertz) {
27-
store, err := redis.NewStore(consts.MaxIdleNum, consts.TCP, consts.RedisAddr, consts.RedisPasswd, []byte(consts.SessionSecretKey))
27+
store, err := redis.NewStore(consts.MaxIdleNum, consts.TCP, consts.RedisAddr, consts.RedisPasswd, consts.GetSessionSecret())
2828
if err != nil {
2929
panic(err)
3030
}

bizdemo/hertz_session/pkg/consts/consts.go

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,51 @@
1616

1717
package consts
1818

19+
import (
20+
"fmt"
21+
"os"
22+
)
23+
24+
// getSessionSecret retrieves the session secret from env, with fatal exit if unset.
25+
func GetSessionSecret() []byte {
26+
key := os.Getenv("SESSION_SECRET")
27+
if key == "" {
28+
fmt.Fprintf(os.Stderr, "fatal: SESSION_SECRET is not set. Generate one with: openssl rand -base64 32\n")
29+
os.Exit(1)
30+
}
31+
return []byte(key)
32+
}
33+
34+
// GetCSRFSecret retrieves the CSRF secret from env, with fatal exit if unset.
35+
func GetCSRFSecret() string {
36+
key := os.Getenv("CSRF_SECRET")
37+
if key == "" {
38+
fmt.Fprintf(os.Stderr, "fatal: CSRF_SECRET is not set. Generate one with: openssl rand -base64 32\n")
39+
os.Exit(1)
40+
}
41+
return key
42+
}
43+
44+
// GetMySQLDSN retrieves the MySQL DSN from env, with fatal exit if unset.
45+
func GetMySQLDSN() string {
46+
dsn := os.Getenv("DB_DSN")
47+
if dsn == "" {
48+
fmt.Fprintf(os.Stderr, "fatal: DB_DSN is not set\n")
49+
os.Exit(1)
50+
}
51+
return dsn
52+
}
53+
1954
// constants
2055
const (
21-
TCP = "tcp"
22-
UserTableName = "users"
23-
RedisAddr = "127.0.0.1:6379"
24-
MaxIdleNum = 10
25-
RedisPasswd = ""
26-
SessionSecretKey = "session-secret"
27-
CSRFSecretKey = "csrf-secret"
28-
CSRFKeyLookUp = "form:csrf"
29-
Username = "username"
30-
HertzSession = "HERTZ-SESSION"
31-
MySQLDefaultDSN = "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local"
56+
TCP = "tcp"
57+
UserTableName = "users"
58+
RedisAddr = "127.0.0.1:6379"
59+
MaxIdleNum = 10
60+
RedisPasswd = ""
61+
CSRFKeyLookUp = "form:csrf"
62+
Username = "username"
63+
HertzSession = "HERTZ-SESSION"
3264
)
3365

3466
// error msg

bizdemo/tiktok_demo/biz/dal/db/init.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ var DB *gorm.DB
2929
// Init init DB
3030
func Init() {
3131
var err error
32-
DB, err = gorm.Open(mysql.Open(constants.MySQLDefaultDSN),
32+
DB, err = gorm.Open(mysql.Open(constants.GetMySQLDSN()),
3333
&gorm.Config{
3434
PrepareStmt: true,
3535
SkipDefaultTransaction: true,

bizdemo/tiktok_demo/biz/mw/jwt/jwt.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ package jwt
1818

1919
import (
2020
"context"
21+
"fmt"
22+
"os"
2123
"time"
2224

2325
"github.com/cloudwego/hertz/pkg/app"
@@ -37,9 +39,18 @@ var (
3739
identity = "user_id"
3840
)
3941

42+
func getJWTKey() []byte {
43+
key := os.Getenv("JWT_SECRET_KEY")
44+
if key == "" {
45+
fmt.Fprintf(os.Stderr, "fatal: JWT_SECRET_KEY is not set. Generate one with: openssl rand -base64 32\n")
46+
os.Exit(1)
47+
}
48+
return []byte(key)
49+
}
50+
4051
func Init() {
4152
JwtMiddleware, _ = jwt.New(&jwt.HertzJWTMiddleware{
42-
Key: []byte("tiktok secret key"),
53+
Key: getJWTKey(),
4354
TokenLookup: "query:token,form:token",
4455
Timeout: 24 * time.Hour,
4556
IdentityKey: identity,

bizdemo/tiktok_demo/biz/mw/minio/minio.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,8 @@ func PutToBucketByFilePath(ctx context.Context, bucketName, filename, filepath s
8383

8484
func Init() {
8585
ctx := context.Background()
86-
Client, err = minio.New(constants.MinioEndPoint, &minio.Options{
87-
Creds: credentials.NewStaticV4(constants.MinioAccessKeyID, constants.MinioSecretAccessKey, ""),
86+
Client, err = minio.New(constants.GetMinioEndpoint(), &minio.Options{
87+
Creds: credentials.NewStaticV4(constants.GetMinioAccessKeyID(), constants.GetMinioSecretAccessKey(), ""),
8888
Secure: constants.MiniouseSSL,
8989
})
9090
if err != nil {

bizdemo/tiktok_demo/biz/mw/redis/redis.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,13 @@ var (
3232

3333
func InitRedis() {
3434
rdbFollows = redis.NewClient(&redis.Options{
35-
Addr: constants.RedisAddr,
36-
Password: constants.RedisPassword,
35+
Addr: constants.GetRedisAddr(),
36+
Password: constants.GetRedisPassword(),
3737
DB: 0,
3838
})
3939
rdbFavorite = redis.NewClient(&redis.Options{
40-
Addr: constants.RedisAddr,
41-
Password: constants.RedisPassword,
40+
Addr: constants.GetRedisAddr(),
41+
Password: constants.GetRedisPassword(),
4242
DB: 1,
4343
})
4444
}

bizdemo/tiktok_demo/pkg/constants/constant.go

Lines changed: 61 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,69 @@
1616

1717
package constants
1818

19-
// connection information
20-
const (
21-
MySQLDefaultDSN = "douyin:douyin123@tcp(127.0.0.1:18000)/douyin?charset=utf8&parseTime=True&loc=Local"
19+
import (
20+
"fmt"
21+
"os"
22+
)
23+
24+
// GetMySQLDSN retrieves the MySQL DSN from env, with fatal exit if unset.
25+
func GetMySQLDSN() string {
26+
dsn := os.Getenv("DB_DSN")
27+
if dsn == "" {
28+
fmt.Fprintf(os.Stderr, "fatal: DB_DSN is not set\n")
29+
os.Exit(1)
30+
}
31+
return dsn
32+
}
33+
34+
// GetMinioEndpoint retrieves the MinIO endpoint from env, with fatal exit if unset.
35+
func GetMinioEndpoint() string {
36+
ep := os.Getenv("MINIO_ENDPOINT")
37+
if ep == "" {
38+
fmt.Fprintf(os.Stderr, "fatal: MINIO_ENDPOINT is not set\n")
39+
os.Exit(1)
40+
}
41+
return ep
42+
}
2243

23-
MinioEndPoint = "localhost:18001"
24-
MinioAccessKeyID = "douyin"
25-
MinioSecretAccessKey = "douyin123"
26-
MiniouseSSL = false
44+
// GetMinioAccessKeyID retrieves the MinIO access key from env, with fatal exit if unset.
45+
func GetMinioAccessKeyID() string {
46+
key := os.Getenv("MINIO_ACCESS_KEY_ID")
47+
if key == "" {
48+
fmt.Fprintf(os.Stderr, "fatal: MINIO_ACCESS_KEY_ID is not set\n")
49+
os.Exit(1)
50+
}
51+
return key
52+
}
2753

28-
RedisAddr = "localhost:18003"
29-
RedisPassword = "douyin123"
54+
// GetMinioSecretAccessKey retrieves the MinIO secret key from env, with fatal exit if unset.
55+
func GetMinioSecretAccessKey() string {
56+
key := os.Getenv("MINIO_SECRET_ACCESS_KEY")
57+
if key == "" {
58+
fmt.Fprintf(os.Stderr, "fatal: MINIO_SECRET_ACCESS_KEY is not set\n")
59+
os.Exit(1)
60+
}
61+
return key
62+
}
63+
64+
// GetRedisAddr retrieves the Redis address from env, with fatal exit if unset.
65+
func GetRedisAddr() string {
66+
addr := os.Getenv("REDIS_ADDR")
67+
if addr == "" {
68+
fmt.Fprintf(os.Stderr, "fatal: REDIS_ADDR is not set\n")
69+
os.Exit(1)
70+
}
71+
return addr
72+
}
73+
74+
// GetRedisPassword retrieves the Redis password from env, with fatal exit if unset.
75+
func GetRedisPassword() string {
76+
return os.Getenv("REDIS_PASSWORD")
77+
}
78+
79+
// connection information
80+
const (
81+
MiniouseSSL = false
3082
)
3183

3284
// constants in the project

0 commit comments

Comments
 (0)