Skip to main content

Application Configuration

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. Dependency Analysis
  7. Performance Considerations
  8. Troubleshooting Guide
  9. Conclusion
  10. Appendix

Introduction

This document systematically explains the design and implementation of the application configuration module, focusing on the following aspects:

  • Application basic information configuration: Application name, version number, secret key and key file path, etc.
  • Secret key generation and usage: Symmetric key (HS256) for JWT token generation, RSA public key for signature verification
  • Configuration loading mechanism: Supports multi-format configuration files, environment variable override, default value setting and validation
  • Permissions and authentication: Casbin model and policy path configuration, combined with middleware to implement RBAC
  • Development and production differences: Configuration points and best practices in different environments
  • Configuration priority and override rules: Priority order of files, environment variables, default values
  • Sensitive information security management: Secure storage and minimum exposure principle of secret keys and certificates

Project Structure

The configuration module is located in pkg/config, centered around Viper's configuration loading and deserialization; application startup entry pkg/bootstrap loads configuration and injects globally during initialization phase.

Core Components

  • Application Basic Information Configuration (AppConfig)

    • Fields: Application name, version number, secret key, key file path
    • Purpose: Used for application identification, JWT signing, permission control file path, etc.
  • Aggregated Configuration (Config)

    • Contains HTTP, logging, database, cache, event bus, permissions and other sub-configurations
  • Loader (loader.Load)

    • Multi-format configuration file support, automatic environment variable injection, default value setting, validation
  • Application Startup (bootstrap.NewApp)

    • Initializes configuration, logging, routing, container, etc.

Architecture Overview

Configuration loading process follows the priority of "default values → configuration file → environment variables", finally deserializes into strongly-typed Config object, used by application layers.

Detailed Component Analysis

Application Basic Information Configuration (AppConfig)

Field Description

  • Name: Used for application identification and event bus namespace
  • Version: Used for health checks and observability reporting
  • Secret: Symmetric key for HS256 signature
  • Key Path: Path for permission control (such as Casbin) model and policy files

Default Values and Override

  • Default name, version, secret key, key file path provided by default values
  • Can be overridden through configuration file and environment variables

Usage Scenarios

  • JWT token generation and verification
  • Event bus naming and permission file location

Configuration Loading and Validation

Configuration File Search Paths

  • Current directory, configs directory
  • If appName provided, extends to /etc/<snake_case>/ and $HOME/.<snake_case>/ below

Default Values

  • Provides application, server, CORS, logging, event bus, cache, database, permissions and other default values

Environment Variables

  • Automatic injection, dot to underscore mapping
  • .env file can be loaded first, then overridden by system environment

Validation

  • Basic validation: Application name non-empty, port range legal

JWT Token Generation and Usage

Secret Key Source

  • AppConfig.Secret as HS256 signature key

Token Generation

  • Generate access token and refresh token, set different expiration times respectively
  • Use HS256 signature, key from configuration

Refresh Process

  • Parse old token, verify signature and validity
  • Update issue time, regenerate new token

RSA Authentication Configuration

Configuration Items

  • Request header fields: Client ID, signature, nonce, timestamp
  • Time window: Allowed time deviation (seconds)
  • Storage and cache: NonceStore, SignatureCache, PublicKeyProvider

Implementation

  • Memory implementation: MemoryNonceStore, MemorySignatureCache, MemoryPublicKeyProvider
  • Supports concurrency safety and periodic cleanup

Permission Control Configuration

Configuration Items

  • Model file path, policy file path

Usage

  • Combine with middleware to implement RBAC control
  • Middleware needs to read above paths at runtime

HTTP Server

  • Server address and port
  • CORS allowed origins, methods, headers, credentials and cache duration

Logging and Database

  • Logging: Mode, level, format, output, filename
  • Database: Driver, host, port, user, password, database name, event store database name
  • Cache: Host, port, password, DB index, event store DB index

Dependency Analysis

Configuration Loading Chain

  • bootstrap.NewApp -> config.Load -> viper deserialization -> Config

Key Coupling Points

  • AppConfig.Secret strongly associated with auth token generation
  • AppConfig.KeyPath strongly associated with permission file path (Casbin)
  • ServerConfig associated with HTTP server binding

Possible Circular Dependencies

  • Configuration module only depends downward (loader -> viper), no upward dependencies, avoids circular dependencies

Performance Considerations

Configuration Loading

  • Multi-format attempts and environment variable injection cost is low, suitable for one-time completion during startup phase

Logging

  • JSON output and file writing in high concurrency suggest combining with asynchronous writing and rotation strategy

Database and Cache

  • Connection pool size, timeout settings need tuning combined with business peak

Token Generation

  • HS256 is symmetric algorithm, excellent performance; pay attention to key length and security balance

Troubleshooting Guide

Configuration Not Taking Effect

  • Check if configuration file format and path are correct
  • Confirm if environment variable key names use underscore replacement rule (dot -> underscore)
  • Verify if .env file is overridden by system environment

Port Conflict or Illegal

  • Port should be in range 1-65535

Application Name Empty

  • Ensure configuration file or environment variable provides valid name

Secret Key Issues

  • HS256 key should be sufficiently random and confidential, avoid hard-coding in source code

Permission Control Exception

  • Check if model and policy file paths are correct, files exist and are readable

Conclusion

This configuration module provides flexible and extensible configuration loading capability through Viper, combined with default values, environment variables and strict validation, ensures consistent behavior of application in different environments. Application basic information (name, version, secret key, key file path) is tightly coupled with authentication and permission control, recommend adopting secure key management and minimum exposure principle in production environment, combined with strict permission file access control, ensures system security and stability.

Appendix

Configuration Item Priority and Override Rules

Priority (from high to low)

  1. System environment variables (automatic injection)
  2. .env file (loaded first)
  3. Configuration file (tried by format)
  4. Default values (SetDefaults)

Key Name Mapping

  • Dots in configuration key names will be replaced with underscores to match environment variables

Environment-specific Configuration Recommendations

Development Environment

  • Use shorter key expiration times, convenient for debugging
  • Set log level to debug or info, output to console
  • Database and cache use local default values

Production Environment

  • Keys and certificates centrally managed (such as KMS or key management service)
  • Log output to file and enable rotation
  • Disable debug mode, strictly control CORS and cross-origin sources
  • Permission model and policy files placed in controlled directory, only grant necessary access permissions

Security Management Best Practices

Secret Keys and Certificates

  • Do not write keys into code repository; use environment variables or key management service to inject
  • Regularly rotate keys, retain old key transition period

Permission Files

  • Strictly control file permissions, avoid leaking model and policy

Environment Isolation

  • Use independent configuration files and environment variables for different environments

Configuration Audit

  • Record key configuration changes, establish approval and rollback mechanism