Files
knowledge-governance/internal/dobotaiops/dsn.go
T

108 lines
3.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package dobotaiops
import (
"fmt"
"net/url"
"os"
"strings"
)
// ReadDSNFile 从仓库外的 secret 文件读 DSN。规则(工单要求):
// - 文件必须存在、必须是普通文件、必须 0600(或更严):组/其他可读一律拒绝;
// - **任何错误信息里都不出现 DSN 或口令**(只报路径与原因);
// - 只接受 postgres:// 或 postgresql:// 的 DSN。
func ReadDSNFile(path string) (string, error) {
if strings.TrimSpace(path) == "" {
return "", fmt.Errorf("%w: DSN file is not configured", ErrUnavailable)
}
info, err := os.Stat(path)
if err != nil {
return "", fmt.Errorf("%w: cannot stat DSN file %s", ErrUnavailable, path)
}
if !info.Mode().IsRegular() {
return "", fmt.Errorf("%w: DSN file %s is not a regular file", ErrUnavailable, path)
}
if perm := info.Mode().Perm(); perm&0o077 != 0 {
return "", fmt.Errorf("%w: DSN file %s must be 0600 (found %04o)", ErrUnavailable, path, perm)
}
raw, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("%w: cannot read DSN file %s", ErrUnavailable, path)
}
dsn, ok := parseDSNLine(string(raw))
if !ok {
return "", fmt.Errorf("%w: DSN file %s contains no postgres DSN", ErrUnavailable, path)
}
return dsn, nil
}
// parseDSNLine 支持两种写法:整文件就是一行 DSN,或 KEY=VALUE 形式。
//
// 关键边界:**裸 DSN 本身就可能含 `=`**(例如 `?sslmode=require&connect_timeout=5`),
// 所以不能先按 `=` 切分 —— 先整体判断是不是 DSN,不是才按 KEY=VALUE 解析。
func parseDSNLine(content string) (string, bool) {
for _, line := range strings.Split(content, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
trimmed := strings.Trim(line, `"'`)
if isPostgresDSN(trimmed) {
return trimmed, true
}
if idx := strings.Index(line, "="); idx >= 0 {
if strings.TrimSpace(line[:idx]) != "DOBOTAI_OPS_READ_DSN" {
continue
}
value := strings.Trim(strings.TrimSpace(line[idx+1:]), `"'`)
if isPostgresDSN(value) {
return value, true
}
}
}
return "", false
}
func isPostgresDSN(value string) bool {
return strings.HasPrefix(value, "postgres://") || strings.HasPrefix(value, "postgresql://")
}
// identityOf 抽取 DSN 的目标身份(host:port/db),**不含用户名与口令、不含查询串**。
// 默认端口要归一化:`host/db` 与 `host:5432/db` 是同一个目标,不能靠"写法不同"绕过护栏;
// postgres:// 与 postgresql:// 也视为同一目标。
func identityOf(dsn string) (string, error) {
parsed, err := url.Parse(dsn)
if err != nil || parsed.Hostname() == "" {
return "", fmt.Errorf("%w: DSN is not a valid URL", ErrUnavailable)
}
port := parsed.Port()
if port == "" {
port = "5432"
}
database := strings.TrimPrefix(parsed.EscapedPath(), "/")
if database == "" {
return "", fmt.Errorf("%w: DSN has no database name", ErrUnavailable)
}
return parsed.Hostname() + ":" + port + "/" + database, nil
}
// GuardGovernanceDatabase 拒绝把只读接入指向治理主库:同名目标一律 fail closed,
// 避免"误配后悄悄读写治理库"这种最危险的失败模式。
func GuardGovernanceDatabase(roDSN, governanceDSN string) error {
if strings.TrimSpace(governanceDSN) == "" {
return nil
}
roIdentity, err := identityOf(roDSN)
if err != nil {
return err
}
governanceIdentity, err := identityOf(governanceDSN)
if err != nil {
return fmt.Errorf("%w: governance database identity could not be verified", ErrUnavailable)
}
if roIdentity == governanceIdentity {
return fmt.Errorf("%w: read DSN points at the governance database (%s)", ErrNotReadOnly, roIdentity)
}
return nil
}