Skip to content

Commit

Permalink
Allow to use own secret key & move the secret key file to ../
Browse files Browse the repository at this point in the history
  • Loading branch information
thomiceli committed Oct 29, 2024
1 parent d0b4815 commit 7fb30f0
Show file tree
Hide file tree
Showing 7 changed files with 97 additions and 10 deletions.
3 changes: 3 additions & 0 deletions config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ external-url:
# Directory where Opengist will store its data. Default: ~/.opengist/
opengist-home:

# Secret key used for session store & encrypt MFA data on database. Default: <randomized 32 bytes>
secret-key:

# URI of the database. Default: opengist.db (SQLite)
# SQLite: file name
# PostgreSQL: postgres://user:password@host:port/database
Expand Down
1 change: 1 addition & 0 deletions docs/configuration/cheat-sheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ aside: false
| log-output | OG_LOG_OUTPUT | `stdout,file` | Set the log output to one or more of the following: `stdout`, `file`. |
| external-url | OG_EXTERNAL_URL | none | Public URL to access to Opengist. |
| opengist-home | OG_OPENGIST_HOME | home directory | Path to the directory where Opengist stores its data. |
| secret-key | OG_SECRET_KEY | randomized 32 bytes | Secret key used for session store & encrypt MFA data on database. |
| db-filename | OG_DB_FILENAME | `opengist.db` | Name of the SQLite database file. |
| index.enabled | OG_INDEX_ENABLED | `true` | Enable or disable the code search index (`true` or `false`) |
| index.dirname | OG_INDEX_DIRNAME | `opengist.index` | Name of the directory where the code search index is stored. |
Expand Down
23 changes: 22 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ var SecretKey []byte
// Not using nested structs because the library
// doesn't support dot notation in this case sadly
type config struct {
SecretKey string `yaml:"secret-key" env:"OG_SECRET_KEY"`

LogLevel string `yaml:"log-level" env:"OG_LOG_LEVEL"`
LogOutput string `yaml:"log-output" env:"OG_LOG_OUTPUT"`
ExternalUrl string `yaml:"external-url" env:"OG_EXTERNAL_URL"`
Expand Down Expand Up @@ -82,6 +84,8 @@ type StaticLink struct {
func configWithDefaults() (*config, error) {
c := &config{}

c.SecretKey = ""

c.LogLevel = "warn"
c.LogOutput = "stdout,file"
c.OpengistHome = ""
Expand Down Expand Up @@ -138,7 +142,24 @@ func InitConfig(configPath string, out io.Writer) error {

C = c

// SecretKey = utils.GenerateSecretKey(filepath.Join(GetHomeDir(), "opengist-secret.key"))
if err = migrateConfig(); err != nil {
return err
}

if c.SecretKey == "" {
var generated bool
path := filepath.Join(GetHomeDir(), "opengist-secret.key")
SecretKey, generated = utils.GenerateSecretKey(path)

if generated {
fmt.Printf("Generated a new secret key at %s\n", path)
} else {
fmt.Printf("Using the secret key from %s\n", path)
}
} else {
SecretKey = []byte(C.SecretKey)
fmt.Println("Using the secret key from config")
}

if err = os.Setenv("OG_OPENGIST_HOME_INTERNAL", GetHomeDir()); err != nil {
return err
Expand Down
61 changes: 61 additions & 0 deletions internal/config/migrate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package config

import (
"fmt"
"os"
"path/filepath"
)

// auto migration for newer versions of Opengist
func migrateConfig() error {
configMigrations := []struct {
Version string
Func func() error
}{
{"1.8.0", v1_8_0},
}

for _, fn := range configMigrations {
err := fn.Func()
if err != nil {
return err
}
}

return nil
}

func v1_8_0() error {
homeDir := GetHomeDir()
sessionsDir := filepath.Join(homeDir, "sessions")

moves := []struct {
oldName string
newName string
}{
{
oldName: filepath.Join(sessionsDir, "session-auth.key"),
newName: filepath.Join(homeDir, "opengist-secret.key"),
},
{
oldName: filepath.Join(sessionsDir, "session-encrypt.key"),
newName: filepath.Join(homeDir, "session-encrypt.key"),
},
}

for _, move := range moves {
moveFile(move.oldName, move.newName)
}

return nil
}

func moveFile(oldPath, newPath string) {
if _, err := os.Stat(oldPath); err != nil {
return
}

if err := os.Rename(oldPath, newPath); err == nil {
fmt.Printf("Automatically moved %s to %s\n", oldPath, newPath)
}
}
5 changes: 3 additions & 2 deletions internal/db/totp.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"encoding/json"
"fmt"
ogtotp "github.com/thomiceli/opengist/internal/auth/totp"
"github.com/thomiceli/opengist/internal/config"
"github.com/thomiceli/opengist/internal/utils"
"slices"
)
Expand All @@ -29,7 +30,7 @@ func GetTOTPByUserID(userID uint) (*TOTP, error) {

func (totp *TOTP) StoreSecret(secret string) error {
secretBytes := []byte(secret)
encrypted, err := utils.AESEncrypt([]byte("tmp"), secretBytes)
encrypted, err := utils.AESEncrypt(config.SecretKey, secretBytes)
if err != nil {
return err
}
Expand All @@ -44,7 +45,7 @@ func (totp *TOTP) ValidateCode(code string) (bool, error) {
return false, err
}

secretBytes, err := utils.AESDecrypt([]byte("tmp"), ciphertext)
secretBytes, err := utils.AESDecrypt(config.SecretKey, ciphertext)
if err != nil {
return false, err
}
Expand Down
8 changes: 5 additions & 3 deletions internal/utils/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import (
"os"
)

func GenerateSecretKey(filePath string) []byte {
// GenerateSecretKey generates a new secret key for sessions
// Returns the key and a boolean indicating if the key was generated
func GenerateSecretKey(filePath string) ([]byte, bool) {
key, err := os.ReadFile(filePath)
if err == nil {
return key
return key, false
}

key = securecookie.GenerateRandomKey(32)
Expand All @@ -22,5 +24,5 @@ func GenerateSecretKey(filePath string) []byte {
log.Fatal().Err(err).Msgf("Failed to save the key to %s", filePath)
}

return key
return key, true
}
6 changes: 2 additions & 4 deletions internal/web/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,10 +167,8 @@ type Server struct {
func NewServer(isDev bool, sessionsPath string) *Server {
dev = isDev
flashStore = sessions.NewCookieStore([]byte("opengist"))
userStore = sessions.NewFilesystemStore(sessionsPath,
utils.GenerateSecretKey(path.Join(sessionsPath, "session-auth.key")),
utils.GenerateSecretKey(path.Join(sessionsPath, "session-encrypt.key")),
)
encryptKey, _ := utils.GenerateSecretKey(path.Join(config.GetHomeDir(), "session-encrypt.key"))
userStore = sessions.NewFilesystemStore(sessionsPath, config.SecretKey, encryptKey)
userStore.MaxLength(10 * 1024)
gothic.Store = userStore

Expand Down

0 comments on commit 7fb30f0

Please sign in to comment.