github.com/miguelangel-nubla/oauth2commander@v0.3.7/oauth2server/command.go (about) 1 package oauth2server 2 3 import ( 4 "bufio" 5 "bytes" 6 _ "embed" 7 "encoding/json" 8 "io" 9 "log" 10 "net/http" 11 "os" 12 "os/exec" 13 "sync" 14 "text/template" 15 "time" 16 ) 17 18 //go:embed defaultPage.html 19 var defaultPage string 20 21 type Endpoint struct { 22 Path string `json:"path"` 23 Public bool `json:"public,omitempty"` 24 RequiredGroups []string `json:"requiredGroups,omitempty"` 25 Command []string `json:"command"` 26 BinaryOutput bool `json:"binaryOutput,omitempty"` 27 HTMLFile string `json:"htmlFile"` 28 } 29 30 type templateVariables struct { 31 HTTPRequestHeaders map[string]string 32 HTTPResponseHeaders map[string]string // empty map 33 CSRFToken string 34 AuthClaims *idTokenClaims 35 } 36 37 type outputLine struct { 38 Timestamp time.Time `json:"timestamp"` 39 Source string `json:"source"` 40 Text string `json:"text"` 41 } 42 43 func (app *Oauth2Commander) HandleCommandConfirm(w http.ResponseWriter, r *http.Request, e Endpoint) { 44 templateVariables := app.templateVariables(w, r) 45 46 var tmpl *template.Template 47 var err error 48 49 if _, err := os.Stat(e.HTMLFile); err == nil { 50 tmpl, err = template.ParseFiles(e.HTMLFile) 51 } else { 52 if e.HTMLFile != "" { 53 http.Error(w, "Failed to load HTML file: "+err.Error(), http.StatusInternalServerError) 54 return 55 } 56 tmpl, err = template.New("defaultPage").Parse(defaultPage) 57 } 58 59 if err != nil { 60 http.Error(w, err.Error(), http.StatusInternalServerError) 61 return 62 } 63 64 tmpl.Execute(w, templateVariables) 65 } 66 67 func (app *Oauth2Commander) HandleCommandRun(w http.ResponseWriter, r *http.Request, e Endpoint) { 68 if !app.validateCSRFToken(r) { 69 http.Error(w, "Invalid CSRF token", http.StatusBadRequest) 70 return 71 } 72 73 err := app.executeCommand(w, r, e) 74 if err != nil { 75 http.Error(w, "Failed to execute command: "+err.Error(), http.StatusInternalServerError) 76 return 77 } 78 } 79 80 func (app *Oauth2Commander) executeCommand(w http.ResponseWriter, r *http.Request, e Endpoint) error { 81 command, err := app.parseCommand(w, r, e) 82 if err != nil { 83 return err 84 } 85 86 log.Printf("%s requested %s, running: %s\n", app.auth(r).IDTokenClaims.PreferredUsername, e.Path, command) 87 88 cmd := exec.Command(command[0], command[1:]...) 89 90 stdout, err := cmd.StdoutPipe() 91 if err != nil { 92 return err 93 } 94 stderr, err := cmd.StderrPipe() 95 if err != nil { 96 return err 97 } 98 99 if err := cmd.Start(); err != nil { 100 return err 101 } 102 103 var wg sync.WaitGroup 104 var writeMutex sync.Mutex 105 106 if e.BinaryOutput { 107 w.Header().Set("Content-Type", "application/octet-stream") 108 wg.Add(1) 109 go func() { 110 defer wg.Done() 111 io.Copy(w, stdout) // Only streaming stdout for binary data 112 }() 113 } else { 114 w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8") 115 wg.Add(2) 116 117 go func() { 118 defer wg.Done() 119 scanner := bufio.NewScanner(stdout) 120 for scanner.Scan() { 121 line := outputLine{ 122 Timestamp: time.Now(), 123 Source: "stdout", 124 Text: scanner.Text(), 125 } 126 jsonLine, _ := json.Marshal(line) 127 128 writeMutex.Lock() 129 w.Write(jsonLine) 130 w.Write([]byte("\n")) 131 writeMutex.Unlock() 132 } 133 }() 134 135 go func() { 136 defer wg.Done() 137 scanner := bufio.NewScanner(stderr) 138 for scanner.Scan() { 139 line := outputLine{ 140 Timestamp: time.Now(), 141 Source: "stderr", 142 Text: scanner.Text(), 143 } 144 jsonLine, _ := json.Marshal(line) 145 146 writeMutex.Lock() 147 w.Write(jsonLine) 148 w.Write([]byte("\n")) 149 writeMutex.Unlock() 150 } 151 }() 152 } 153 154 wg.Wait() // Wait for all goroutines to finish 155 156 if err := cmd.Wait(); err != nil { 157 return err 158 } 159 return nil 160 } 161 162 func (app *Oauth2Commander) parseCommand(w http.ResponseWriter, r *http.Request, e Endpoint) ([]string, error) { 163 templateVariables := app.templateVariables(w, r) 164 165 parsedCommand := make([]string, len(e.Command)) 166 for i, v := range e.Command { 167 tmpl, err := template.New("command").Parse(v) 168 if err != nil { 169 return nil, err 170 } 171 172 var buf bytes.Buffer 173 err = tmpl.Execute(&buf, templateVariables) 174 if err != nil { 175 return nil, err 176 } 177 parsedCommand[i] = buf.String() 178 } 179 180 return parsedCommand, nil 181 } 182 183 func (app *Oauth2Commander) templateVariables(w http.ResponseWriter, r *http.Request) templateVariables { 184 templateVariables := templateVariables{ 185 CSRFToken: app.csrfToken(r), 186 AuthClaims: &app.auth(r).IDTokenClaims, 187 } 188 189 templateVariables.HTTPRequestHeaders = make(map[string]string) 190 for k, v := range r.Header { 191 templateVariables.HTTPRequestHeaders[k] = v[0] 192 } 193 194 templateVariables.HTTPResponseHeaders = make(map[string]string) 195 for k, v := range w.Header() { 196 templateVariables.HTTPResponseHeaders[k] = v[0] 197 } 198 199 return templateVariables 200 }