package config import ( "fmt" "io" "net/url" "os" "regexp" "strings" "github.com/go-errors/errors" "github.com/jackc/pgx/v5" ) const ( // EnvDatabasePasswordFile names a file that holds the postgres password. // It replaces password_file from the config file when set. EnvDatabasePasswordFile = "PHISHINGCLUB_DATABASE_PASSWORD_FILE" // maxPasswordFileSize bounds the password file, a password is short maxPasswordFileSize = 4096 ) var ( // ErrDatabasePasswordTwice is a DSN that already holds a password while // another password is given ErrDatabasePasswordTwice = errors.New("the DSN already holds a password, remove it from the DSN or do not give a second one") // ErrDatabaseDSNWithoutUser is a postgres URL without a user ErrDatabaseDSNWithoutUser = errors.New("the postgres DSN has no user, add one before the host (postgres://user@host/db)") // ErrDatabasePasswordNotAdded is a DSN the password could not be added to // without changing what the DSN means ErrDatabasePasswordNotAdded = errors.New("the password could not be added to the DSN, check the DSN for a trailing backslash or an unclosed quote, or put the password in the DSN instead") // ErrDatabasePasswordFile is a password file that can not be used. The // error never holds the content of the file. ErrDatabasePasswordFile = errors.New("the database password file can not be used") // keyValuePasswordRegex finds a password key in a key value DSN keyValuePasswordRegex = regexp.MustCompile(`(^|\s)password\s*=`) ) // DSNWithPassword adds the password to a postgres URL or key value DSN. The // result is parsed again and refused unless it holds exactly that password // and the same hosts, user, database and parameters as the DSN without it, // so a typo in the DSN can never move the password into another field. The // errors never hold the DSN or the password. func DSNWithPassword(dsn, password string) (string, error) { if password == "" { return dsn, nil } var merged string if isPostgresURL(dsn) { u, err := url.Parse(dsn) if err != nil { return "", ErrDatabasePasswordNotAdded } if u.User == nil || u.User.Username() == "" { return "", ErrDatabaseDSNWithoutUser } if _, set := u.User.Password(); set { return "", ErrDatabasePasswordTwice } if u.Query().Has("password") { return "", ErrDatabasePasswordTwice } u.User = url.UserPassword(u.User.Username(), password) merged = u.String() } else { if keyValuePasswordRegex.MatchString(strings.ToLower(dsn)) { return "", ErrDatabasePasswordTwice } merged = dsn + " password=" + quoteKeywordValue(password) } before, err := pgx.ParseConfig(dsn) if err != nil { return "", ErrInvalidDatabaseDSN } after, err := pgx.ParseConfig(merged) if err != nil { return "", ErrDatabasePasswordNotAdded } if after.Password != password || !sameTarget(before, after) { return "", ErrDatabasePasswordNotAdded } return merged, nil } // sameTarget is true when both configs reach the same hosts as the same // user with the same parameters, the password is not compared func sameTarget(a, b *pgx.ConnConfig) bool { if a.Host != b.Host || a.Port != b.Port || a.User != b.User || a.Database != b.Database { return false } if len(a.Fallbacks) != len(b.Fallbacks) { return false } for i := range a.Fallbacks { if a.Fallbacks[i].Host != b.Fallbacks[i].Host || a.Fallbacks[i].Port != b.Fallbacks[i].Port { return false } } if len(a.RuntimeParams) != len(b.RuntimeParams) { return false } for k, v := range a.RuntimeParams { if w, ok := b.RuntimeParams[k]; !ok || w != v { return false } } return transportOf(a.TLSConfig) == transportOf(b.TLSConfig) && a.DefaultQueryExecMode == b.DefaultQueryExecMode } // quoteKeywordValue quotes a value for a key value DSN: in single quotes, // with backslash and single quote escaped by a backslash func quoteKeywordValue(v string) string { v = strings.ReplaceAll(v, `\`, `\\`) v = strings.ReplaceAll(v, `'`, `\'`) return "'" + v + "'" } // readDatabasePasswordFile returns the password in the file: the whole // content without the line breaks at its end. An empty file is refused. func readDatabasePasswordFile(path string) (string, error) { f, err := os.Open(path) // #nosec G304 path from the config or the environment of the operator if err != nil { return "", fmt.Errorf("%w: %s can not be read", ErrDatabasePasswordFile, path) } defer f.Close() return ReadDatabasePassword(f, path) } // ReadDatabasePassword returns the password in r, the content of the // password file at path: the whole content without the line breaks at its // end. An empty file is refused. The path is only used in errors. func ReadDatabasePassword(r io.Reader, path string) (string, error) { content, err := io.ReadAll(io.LimitReader(r, maxPasswordFileSize+1)) if err != nil { return "", fmt.Errorf("%w: %s can not be read", ErrDatabasePasswordFile, path) } if len(content) > maxPasswordFileSize { return "", fmt.Errorf("%w: %s is larger than %d bytes", ErrDatabasePasswordFile, path, maxPasswordFileSize) } password := strings.TrimRight(string(content), "\r\n") if password == "" { return "", fmt.Errorf("%w: %s is empty", ErrDatabasePasswordFile, path) } return password, nil }