DetectAndReadInput robustly detects whether input is a file path or direct SQL. This function implements intelligent input detection with security validation. It determines if the input is a file path or direct SQL and returns the appropriate content with full security checks. Detection logic: 1.
(input string)
| 107 | // DetectAndReadInput robustly detects whether input is a file path or direct SQL |
| 108 | // and returns the SQL content with proper validation and security limits |
| 109 | func DetectAndReadInput(input string) (*InputResult, error) { |
| 110 | if input == "" { |
| 111 | return nil, fmt.Errorf("empty input provided") |
| 112 | } |
| 113 | |
| 114 | // Trim whitespace for better detection |
| 115 | input = strings.TrimSpace(input) |
| 116 | |
| 117 | // Check if input looks like a file path using os.Stat |
| 118 | _, statErr := os.Stat(input) |
| 119 | if statErr == nil { |
| 120 | // Input is a valid file path - perform comprehensive security validation |
| 121 | if err := validate.ValidateInputFile(input); err != nil { |
| 122 | return nil, fmt.Errorf("security validation failed: %w", err) |
| 123 | } |
| 124 | |
| 125 | // Read the file |
| 126 | // G304: Path is validated by ValidateInputFile above |
| 127 | content, err := os.ReadFile(input) // #nosec G304 |
| 128 | if err != nil { |
| 129 | return nil, fmt.Errorf("failed to read file %s: %w", input, err) |
| 130 | } |
| 131 | |
| 132 | if len(content) == 0 { |
| 133 | return nil, fmt.Errorf("file is empty: %s", input) |
| 134 | } |
| 135 | |
| 136 | return &InputResult{ |
| 137 | Type: InputTypeFile, |
| 138 | Content: content, |
| 139 | Source: input, |
| 140 | }, nil |
| 141 | } |
| 142 | |
| 143 | // If stat failed, check if it looks like a file path that doesn't exist |
| 144 | // (contains path separators or has .sql extension) |
| 145 | if strings.Contains(input, string(filepath.Separator)) || strings.HasSuffix(strings.ToLower(input), ".sql") { |
| 146 | // Looks like a file path but doesn't exist - return the original stat error |
| 147 | return nil, fmt.Errorf("invalid file path: %w", statErr) |
| 148 | } |
| 149 | |
| 150 | // Input is not a file path, treat as direct SQL |
| 151 | // Validate that it looks like SQL (basic heuristics) |
| 152 | if !looksLikeSQL(input) { |
| 153 | return nil, fmt.Errorf("input does not appear to be valid SQL or a file path: %s", input) |
| 154 | } |
| 155 | |
| 156 | // Security check: SQL length limit |
| 157 | if len(input) > MaxFileSize { |
| 158 | return nil, fmt.Errorf("SQL query too long: %d characters (max %d)", len(input), MaxFileSize) |
| 159 | } |
| 160 | |
| 161 | return &InputResult{ |
| 162 | Type: InputTypeSQL, |
| 163 | Content: []byte(input), |
| 164 | Source: "direct input", |
| 165 | }, nil |
| 166 | } |