parser.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package config // import "miniflux.app/v2/internal/config"
  4. import (
  5. "bufio"
  6. "bytes"
  7. "crypto/rand"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "log/slog"
  12. "net/url"
  13. "os"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. type configParser struct {
  19. options *configOptions
  20. }
  21. func NewConfigParser() *configParser {
  22. return &configParser{
  23. options: NewConfigOptions(),
  24. }
  25. }
  26. func (cp *configParser) ParseEnvironmentVariables() (*configOptions, error) {
  27. if err := cp.parseLines(os.Environ()); err != nil {
  28. return nil, err
  29. }
  30. return cp.options, nil
  31. }
  32. func (cp *configParser) ParseFile(filename string) (*configOptions, error) {
  33. fp, err := os.Open(filename)
  34. if err != nil {
  35. return nil, err
  36. }
  37. defer fp.Close()
  38. if err := cp.parseLines(parseFileContent(fp)); err != nil {
  39. return nil, err
  40. }
  41. return cp.options, nil
  42. }
  43. // Validate checks for invalid or incomplete option combinations.
  44. func (c *configOptions) Validate() error {
  45. if c.OAuth2Provider() == "oidc" && c.OAuth2OIDCDiscoveryEndpoint() == "" {
  46. return errors.New("OAUTH2_OIDC_DISCOVERY_ENDPOINT must be configured when using the OIDC provider")
  47. }
  48. if c.DisableLocalAuth() {
  49. if c.OAuth2Provider() == "" && c.AuthProxyHeader() == "" && !c.WebAuthn() {
  50. return errors.New("DISABLE_LOCAL_AUTH is enabled but none of OAUTH2_PROVIDER, AUTH_PROXY_HEADER, or WEBAUTHN is set. Please enable at least one authentication source")
  51. }
  52. }
  53. if c.AuthProxyHeader() != "" && len(c.TrustedReverseProxyNetworks()) == 0 {
  54. return errors.New("TRUSTED_REVERSE_PROXY_NETWORKS must be configured when AUTH_PROXY_HEADER is used")
  55. }
  56. if (c.CertFile() != "") != (c.CertKeyFile() != "") {
  57. return errors.New("CERT_FILE and KEY_FILE must both be provided")
  58. }
  59. if c.CertDomain() != "" && c.CertFile() != "" {
  60. return errors.New("CERT_DOMAIN and CERT_FILE/KEY_FILE are mutually exclusive")
  61. }
  62. if (c.MetricsUsername() != "") != (c.MetricsPassword() != "") {
  63. return errors.New("METRICS_USERNAME and METRICS_PASSWORD must both be provided")
  64. }
  65. if c.MetricsCollector() && !metricsSupported {
  66. return errors.New("METRICS_COLLECTOR cannot be enabled: Prometheus support was disabled at build time with noprometheus")
  67. }
  68. if c.DatabaseMinConns() > c.DatabaseMaxConns() {
  69. return errors.New("DATABASE_MIN_CONNS must be less than or equal to DATABASE_MAX_CONNS")
  70. }
  71. if c.SchedulerRoundRobinMinInterval() > c.SchedulerRoundRobinMaxInterval() {
  72. return errors.New("SCHEDULER_ROUND_ROBIN_MIN_INTERVAL must be less than or equal to SCHEDULER_ROUND_ROBIN_MAX_INTERVAL")
  73. }
  74. if c.SchedulerEntryFrequencyMinInterval() > c.SchedulerEntryFrequencyMaxInterval() {
  75. return errors.New("SCHEDULER_ENTRY_FREQUENCY_MIN_INTERVAL must be less than or equal to SCHEDULER_ENTRY_FREQUENCY_MAX_INTERVAL")
  76. }
  77. return nil
  78. }
  79. func (cp *configParser) postParsing() error {
  80. // Parse basePath and rootURL based on BASE_URL
  81. baseURL := cp.options.options["BASE_URL"].parsedStringValue
  82. baseURL = strings.TrimSuffix(baseURL, "/")
  83. parsedURL, err := url.Parse(baseURL)
  84. if err != nil {
  85. return fmt.Errorf("invalid BASE_URL: %v", err)
  86. }
  87. scheme := strings.ToLower(parsedURL.Scheme)
  88. if scheme != "https" && scheme != "http" {
  89. return errors.New("BASE_URL scheme must be http or https")
  90. }
  91. cp.options.options["BASE_URL"].parsedStringValue = baseURL
  92. cp.options.basePath = parsedURL.Path
  93. parsedURL.Path = ""
  94. cp.options.rootURL = parsedURL.String()
  95. // Parse YouTube embed domain based on YOUTUBE_EMBED_URL_OVERRIDE
  96. youTubeEmbedURLOverride := cp.options.options["YOUTUBE_EMBED_URL_OVERRIDE"].parsedStringValue
  97. if youTubeEmbedURLOverride != "" {
  98. parsedYouTubeEmbedURL, err := url.Parse(youTubeEmbedURLOverride)
  99. if err != nil {
  100. return fmt.Errorf("invalid YOUTUBE_EMBED_URL_OVERRIDE: %v", err)
  101. }
  102. cp.options.youTubeEmbedDomain = parsedYouTubeEmbedURL.Hostname()
  103. }
  104. // Generate a media proxy private key if not set
  105. if len(cp.options.options["MEDIA_PROXY_PRIVATE_KEY"].parsedBytesValue) == 0 {
  106. randomKey := make([]byte, 16)
  107. rand.Read(randomKey)
  108. cp.options.options["MEDIA_PROXY_PRIVATE_KEY"].parsedBytesValue = randomKey
  109. }
  110. // Override LISTEN_ADDR with PORT if set (for compatibility reasons)
  111. if cp.options.Port() != "" {
  112. cp.options.options["LISTEN_ADDR"].parsedStringList = []string{":" + cp.options.Port()}
  113. cp.options.options["LISTEN_ADDR"].rawValue = ":" + cp.options.Port()
  114. }
  115. return nil
  116. }
  117. func (cp *configParser) parseLines(lines []string) error {
  118. for lineNum, line := range lines {
  119. key, value, ok := strings.Cut(line, "=")
  120. if !ok {
  121. return fmt.Errorf("unable to parse configuration, invalid format on line %d", lineNum)
  122. }
  123. key, value = strings.TrimSpace(key), strings.TrimSpace(value)
  124. if err := cp.parseLine(key, value); err != nil {
  125. return err
  126. }
  127. }
  128. if err := cp.postParsing(); err != nil {
  129. return err
  130. }
  131. return nil
  132. }
  133. func (cp *configParser) parseLine(key, value string) error {
  134. field, exists := cp.options.options[key]
  135. if !exists {
  136. if key == "FILTER_ENTRY_MAX_AGE_DAYS" {
  137. slog.Warn("Configuration option FILTER_ENTRY_MAX_AGE_DAYS is deprecated; use user filter rule max-age:<duration> instead")
  138. }
  139. // Ignore unknown configuration keys to avoid parsing unrelated environment variables.
  140. return nil
  141. }
  142. // Validate the option if a validator is provided
  143. if field.validator != nil {
  144. if err := field.validator(value); err != nil {
  145. return fmt.Errorf("invalid value for key %s: %v", key, err)
  146. }
  147. }
  148. // Convert the raw value based on its type
  149. switch field.valueType {
  150. case stringType:
  151. field.parsedStringValue = parseStringValue(value, field.parsedStringValue)
  152. field.rawValue = value
  153. case stringListType:
  154. field.parsedStringList = parseStringListValue(value, field.parsedStringList)
  155. field.rawValue = value
  156. case boolType:
  157. parsedValue, err := parseBoolValue(value, field.parsedBoolValue)
  158. if err != nil {
  159. return fmt.Errorf("invalid boolean value for key %s: %v", key, err)
  160. }
  161. field.parsedBoolValue = parsedValue
  162. field.rawValue = value
  163. case intType:
  164. field.parsedIntValue = parseIntValue(value, field.parsedIntValue)
  165. field.rawValue = value
  166. case int64Type:
  167. field.parsedInt64Value = ParsedInt64Value(value, field.parsedInt64Value)
  168. field.rawValue = value
  169. case secondType:
  170. field.parsedDuration = parseDurationValue(value, time.Second, field.parsedDuration)
  171. field.rawValue = value
  172. case minuteType:
  173. field.parsedDuration = parseDurationValue(value, time.Minute, field.parsedDuration)
  174. field.rawValue = value
  175. case hourType:
  176. field.parsedDuration = parseDurationValue(value, time.Hour, field.parsedDuration)
  177. field.rawValue = value
  178. case dayType:
  179. field.parsedDuration = parseDurationValue(value, time.Hour*24, field.parsedDuration)
  180. field.rawValue = value
  181. case urlType:
  182. parsedURL, err := parseURLValue(value, field.parsedURLValue)
  183. if err != nil {
  184. return fmt.Errorf("invalid URL for key %s: %v", key, err)
  185. }
  186. field.parsedURLValue = parsedURL
  187. field.rawValue = value
  188. case secretFileType:
  189. secretValue, err := readSecretFileValue(value)
  190. if err != nil {
  191. return fmt.Errorf("error reading secret file for key %s: %v", key, err)
  192. }
  193. if field.targetKey != "" {
  194. if targetField, ok := cp.options.options[field.targetKey]; ok {
  195. targetField.parsedStringValue = secretValue
  196. targetField.rawValue = secretValue
  197. }
  198. }
  199. field.rawValue = value
  200. case bytesType:
  201. if value != "" {
  202. field.parsedBytesValue = []byte(value)
  203. field.rawValue = value
  204. }
  205. }
  206. return nil
  207. }
  208. func parseStringValue(value string, fallback string) string {
  209. if value == "" {
  210. return fallback
  211. }
  212. return value
  213. }
  214. func parseBoolValue(value string, fallback bool) (bool, error) {
  215. if value == "" {
  216. return fallback, nil
  217. }
  218. value = strings.ToLower(value)
  219. if value == "1" || value == "yes" || value == "true" || value == "on" {
  220. return true, nil
  221. }
  222. if value == "0" || value == "no" || value == "false" || value == "off" {
  223. return false, nil
  224. }
  225. return false, fmt.Errorf("invalid boolean value: %q", value)
  226. }
  227. func parseIntValue(value string, fallback int) int {
  228. if value == "" {
  229. return fallback
  230. }
  231. v, err := strconv.Atoi(value)
  232. if err != nil {
  233. return fallback
  234. }
  235. return v
  236. }
  237. func ParsedInt64Value(value string, fallback int64) int64 {
  238. if value == "" {
  239. return fallback
  240. }
  241. v, err := strconv.ParseInt(value, 10, 64)
  242. if err != nil {
  243. return fallback
  244. }
  245. return v
  246. }
  247. func parseStringListValue(value string, fallback []string) []string {
  248. if value == "" {
  249. return fallback
  250. }
  251. var strList []string
  252. present := make(map[string]bool)
  253. for item := range strings.SplitSeq(value, ",") {
  254. if itemValue := strings.TrimSpace(item); itemValue != "" {
  255. if !present[itemValue] {
  256. present[itemValue] = true
  257. strList = append(strList, itemValue)
  258. }
  259. }
  260. }
  261. return strList
  262. }
  263. func parseDurationValue(value string, unit time.Duration, fallback time.Duration) time.Duration {
  264. if value == "" {
  265. return fallback
  266. }
  267. v, err := strconv.Atoi(value)
  268. if err != nil {
  269. return fallback
  270. }
  271. return time.Duration(v) * unit
  272. }
  273. func parseURLValue(value string, fallback *url.URL) (*url.URL, error) {
  274. if value == "" {
  275. return fallback, nil
  276. }
  277. parsedURL, err := url.Parse(value)
  278. if err != nil {
  279. return fallback, err
  280. }
  281. return parsedURL, nil
  282. }
  283. func readSecretFileValue(filename string) (string, error) {
  284. data, err := os.ReadFile(filename)
  285. if err != nil {
  286. return "", err
  287. }
  288. value := string(bytes.TrimSpace(data))
  289. if value == "" {
  290. return "", errors.New("secret file is empty")
  291. }
  292. return value, nil
  293. }
  294. func parseFileContent(r io.Reader) (lines []string) {
  295. scanner := bufio.NewScanner(r)
  296. for scanner.Scan() {
  297. line := strings.TrimSpace(scanner.Text())
  298. if !strings.HasPrefix(line, "#") && strings.Index(line, "=") > 0 {
  299. lines = append(lines, line)
  300. }
  301. }
  302. return lines
  303. }