give me code snippet of a go 1.19 program that does the following:
Has a unique and exclusive rest endpoint "/api/deploy" with POST
in case any other path is called with any other http method, 404 is returned
the endpoint supports a request body with json format and with this schema:
{"project" :string, "version": string, time: "string", "jobId": number, token: string}
The application should validate the call as follows:
1- the types of each field should match, other wise return 400
2- the project value should be among a predefined list of strings (loaded from a text config file) otherwise return 400
3- the token should match and env variable called API_TOKEN, otherwise return 403
If all the validations above pass, the application should do the following
1- execute the following system command, the host on which the app runs is ubuntu bash:
cd"/opt/{project}" && make VERSION="${version}" refresh
The application should be verbose and log error or success messages locally
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a Go 1.19 program that meets the specified requirements. This program uses the net/http package for creating the REST endpoint, encoding/json for handling JSON requests, os/exec for executing system commands, and log for logging. It also uses os and io/ioutil for reading the config file and environment variable.
Important Notes:
Security: The use of os/exec.Command can pose security risks if not properly sanitized, especially with dynamic input. Since the input for the command is partially derived from user input (project and version), ensure that these values are thoroughly validated and sanitized to prevent potential command injection vulnerabilities. In this example, we validate that project is in a predefined list and version matches a specific pattern to mitigate this risk.
Config File: This example assumes a config file named allowed_projects.txt in the same directory as the Go program, with each allowed project on a new line.
Environment Variable: The API_TOKEN environment variable should be set on the system running this application.
Code:
go
package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
)
// DeploymentRequest represents the expected JSON body for the /api/deploy endpoint
type DeploymentRequest struct {
Project string `json:"project"`
Version string `json:"version"`
Time string `json:"time"`
JobID int `json:"jobId"`
Token string `json:"token"`
}
// loadAllowedProjects loads a list of allowed projects from a text file
func loadAllowedProjects(configFile string) ([]string, error) {
data, err := os.ReadFile(configFile)
if err != nil {
return nil, err
}
// Split the file content by newline and trim each project name
projects := strings.Split(string(data), "\n")
for i, project := range projects {
projects[i] = strings.TrimSpace(project)
}
return projects, nil
}
// validateVersion checks if the version matches a basic semantic versioning pattern (e.g., x.x.x)
func validateVersion(version string) bool {
pattern := regexp.MustCompile(`^\d+\.\d+\.\d+$`)
return pattern.MatchString(version)
}
func main() {
configFile := "allowed_projects.txt"
allowedProjects, err := loadAllowedProjects(configFile)
if err != nil {
log.Fatalf("Failed to load allowed projects from %s: %v", configFile, err)
}
http.HandleFunc("/api/deploy", func(w http.ResponseWriter, r *http.Request) {
// Only allow POST requests to this endpoint
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
log.Printf("Method not allowed for %s %s\n", r.Method, r.URL)
return
}
var deployReq DeploymentRequest
err := json.NewDecoder(r.Body).Decode(&deployReq)
if err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
log.Printf("Invalid JSON for %s: %v\n", r.URL, err)
return
}
// Project validation: Ensure project is in the allowed list
if !stringInSlice(deployReq.Project, allowedProjects) {
http.Error(w, "Project not allowed", http.StatusBadRequest)
log.Printf("Project '%s' is not in the allowed list\n", deployReq.Project)
return
}
// Version validation: Basic pattern matching for semantic versioning
if !validateVersion(deployReq.Version) {
http.Error(w, "Invalid version format. Use semantic versioning (x.x.x)", http.StatusBadRequest)
log.Printf("Invalid version '%s' for project '%s'\n", deployReq.Version, deployReq.Project)
return
}
// Token validation
expectedToken := os.Getenv("API_TOKEN")
if deployReq.Token != expectedToken {
http.Error(w, "Forbidden", http.StatusForbidden)
log.Printf("Invalid token for %s\n", r.URL)
return
}
// Execute command with sanitized inputs
cmd := exec.Command("bash", "-c", `cd "/opt/`+deployReq.Project+`" && make VERSION="`+deployReq.Version+`" refresh`)
var out, stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err = cmd.Run()
if err != nil {
http.Error(w, "Failed to execute deployment command", http.StatusInternalServerError)
log.Printf("Failed to execute command for %s/%s: %v. STDERR: %s\n", deployReq.Project, deployReq.Version, err, stderr.String())
return
}
log.Printf("Successfully deployed %s version %s\n", deployReq.Project, deployReq.Version)
w.Write([]byte("Deployment successful"))
})
// Catch-all for any other path or method
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Not found", http.StatusNotFound)
log.Printf("404 for %s %s\n", r.Method, r.URL)
})
log.Println("Server listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
Steps to Run:
Setup Environment Variable: Set API_TOKEN environment variable on your system (e.g., export API_TOKEN=your_token_here on Ubuntu).
Prepare Config File: Create a file named allowed_projects.txt in the same directory as your Go program, listing each allowed project on a new line.
Run the Program: Navigate to the directory containing your Go program and execute it with go run main.go.
Test the Endpoint: Use a tool like curl to test the /api/deploy endpoint. Ensure your JSON body matches the required schema and that you're using the correct token and an allowed project.
Example curl command:
bash
curl -X POST -H "Content-Type: application/json" -d '{"project":"your_allowed_project","version":"1.0.0","time":"now","jobId":1,"token":"your_token_here"}' http://localhost:8080/api/deploy
Security Considerations:
Input Validation and Sanitization: While this example includes basic validation, ensure that all inputs are sanitized, especially when used in system commands, to prevent command injection attacks.
Error Handling: Implement comprehensive error handling to avoid exposing sensitive information in error messages.
Secure Token Storage: Store tokens securely and avoid hardcoding them directly in the code or config files.