|
| 1 | +package services |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "regexp" |
| 8 | + |
| 9 | + "github.com/AxeForging/aigate/domain" |
| 10 | +) |
| 11 | + |
| 12 | +// builtinPresets maps preset names to their regex pattern and how many leading |
| 13 | +// bytes to preserve before the *** replacement (0 = fully masked). |
| 14 | +var builtinPresets = map[string]struct { |
| 15 | + pattern string |
| 16 | + showPrefix int |
| 17 | +}{ |
| 18 | + // OpenAI: sk-... or sk-proj-... |
| 19 | + "openai": {`sk-[a-zA-Z0-9\-_]{20,}`, 3}, |
| 20 | + // Anthropic: sk-ant-api03-... |
| 21 | + "anthropic": {`sk-ant-[a-zA-Z0-9\-_]{20,}`, 7}, |
| 22 | + // AWS access key ID |
| 23 | + "aws_key": {`AKIA[0-9A-Z]{16}`, 4}, |
| 24 | + // GitHub PATs: ghp_, gho_, ghu_, ghs_, ghr_ |
| 25 | + "github": {`gh[pousr]_[A-Za-z0-9_]{36,}`, 4}, |
| 26 | + // Generic Bearer token in headers/logs |
| 27 | + "bearer": {`(?i)Bearer [A-Za-z0-9._\-]{20,}`, 7}, |
| 28 | +} |
| 29 | + |
| 30 | +// BuiltinPresetNames returns the sorted list of available preset names. |
| 31 | +// Used for validation and documentation. |
| 32 | +func BuiltinPresetNames() []string { |
| 33 | + names := make([]string, 0, len(builtinPresets)) |
| 34 | + for k := range builtinPresets { |
| 35 | + names = append(names, k) |
| 36 | + } |
| 37 | + return names |
| 38 | +} |
| 39 | + |
| 40 | +type maskRule struct { |
| 41 | + re *regexp.Regexp |
| 42 | + showPrefix int |
| 43 | +} |
| 44 | + |
| 45 | +// MaskingWriter wraps an io.Writer and redacts secrets from each line before |
| 46 | +// forwarding to the underlying writer. It buffers across Write calls so that |
| 47 | +// secrets spanning chunk boundaries on the same line are still caught. |
| 48 | +type MaskingWriter struct { |
| 49 | + out io.Writer |
| 50 | + rules []maskRule |
| 51 | + buf []byte |
| 52 | +} |
| 53 | + |
| 54 | +// NewMaskingWriter builds a MaskingWriter from the given MaskStdout config. |
| 55 | +// Returns (nil, nil) when no presets or patterns are configured — callers |
| 56 | +// should fall back to the raw writer in that case. |
| 57 | +func NewMaskingWriter(out io.Writer, cfg domain.MaskStdout) (*MaskingWriter, error) { |
| 58 | + var rules []maskRule |
| 59 | + |
| 60 | + for _, name := range cfg.Presets { |
| 61 | + p, ok := builtinPresets[name] |
| 62 | + if !ok { |
| 63 | + return nil, fmt.Errorf("unknown mask_stdout preset %q (available: openai, anthropic, aws_key, github, bearer)", name) |
| 64 | + } |
| 65 | + re, err := regexp.Compile(p.pattern) |
| 66 | + if err != nil { |
| 67 | + return nil, fmt.Errorf("internal error compiling preset %q: %w", name, err) |
| 68 | + } |
| 69 | + rules = append(rules, maskRule{re: re, showPrefix: p.showPrefix}) |
| 70 | + } |
| 71 | + |
| 72 | + for _, mp := range cfg.Patterns { |
| 73 | + pattern := mp.Regex |
| 74 | + if mp.CaseInsensitive { |
| 75 | + pattern = "(?i)" + pattern |
| 76 | + } |
| 77 | + re, err := regexp.Compile(pattern) |
| 78 | + if err != nil { |
| 79 | + return nil, fmt.Errorf("invalid mask_stdout pattern %q: %w", mp.Regex, err) |
| 80 | + } |
| 81 | + rules = append(rules, maskRule{re: re, showPrefix: mp.ShowPrefix}) |
| 82 | + } |
| 83 | + |
| 84 | + if len(rules) == 0 { |
| 85 | + return nil, nil |
| 86 | + } |
| 87 | + return &MaskingWriter{out: out, rules: rules}, nil |
| 88 | +} |
| 89 | + |
| 90 | +// Write buffers p, flushes complete lines through the redactor, and returns |
| 91 | +// len(p) so callers treat the write as fully consumed. |
| 92 | +func (m *MaskingWriter) Write(p []byte) (int, error) { |
| 93 | + m.buf = append(m.buf, p...) |
| 94 | + for { |
| 95 | + idx := bytes.IndexByte(m.buf, '\n') |
| 96 | + if idx < 0 { |
| 97 | + break |
| 98 | + } |
| 99 | + line := m.buf[:idx+1] |
| 100 | + if _, err := m.out.Write(m.redact(line)); err != nil { |
| 101 | + return 0, err |
| 102 | + } |
| 103 | + m.buf = m.buf[idx+1:] |
| 104 | + } |
| 105 | + return len(p), nil |
| 106 | +} |
| 107 | + |
| 108 | +// Flush writes any remaining buffered bytes (last line without a trailing newline). |
| 109 | +// Call this after the child process exits. |
| 110 | +func (m *MaskingWriter) Flush() error { |
| 111 | + if len(m.buf) == 0 { |
| 112 | + return nil |
| 113 | + } |
| 114 | + _, err := m.out.Write(m.redact(m.buf)) |
| 115 | + m.buf = m.buf[:0] |
| 116 | + return err |
| 117 | +} |
| 118 | + |
| 119 | +// redact applies all masking rules to a single line. |
| 120 | +func (m *MaskingWriter) redact(line []byte) []byte { |
| 121 | + result := line |
| 122 | + for _, rule := range m.rules { |
| 123 | + result = rule.re.ReplaceAllFunc(result, func(match []byte) []byte { |
| 124 | + if rule.showPrefix > 0 && len(match) > rule.showPrefix { |
| 125 | + out := make([]byte, rule.showPrefix+3) |
| 126 | + copy(out, match[:rule.showPrefix]) |
| 127 | + copy(out[rule.showPrefix:], "***") |
| 128 | + return out |
| 129 | + } |
| 130 | + return []byte("***") |
| 131 | + }) |
| 132 | + } |
| 133 | + return result |
| 134 | +} |
0 commit comments