|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/base64" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "log" |
| 9 | + "net/http" |
| 10 | + "os" |
| 11 | + "strings" |
| 12 | + "sync" |
| 13 | + "time" |
| 14 | +) |
| 15 | + |
| 16 | +// JWT token management |
| 17 | +var ( |
| 18 | + jwtToken string |
| 19 | + jwtExpiration int64 |
| 20 | + tokenRefreshMutex sync.Mutex |
| 21 | +) |
| 22 | + |
| 23 | +// JWT payload structure |
| 24 | +type JWTPayload struct { |
| 25 | + Exp int64 `json:"exp"` |
| 26 | +} |
| 27 | + |
| 28 | +// OIDCResponse structure |
| 29 | +type OIDCResponse struct { |
| 30 | + Value string `json:"value"` |
| 31 | +} |
| 32 | + |
| 33 | +// Auth Request from Envoy |
| 34 | +type AuthRequest struct { |
| 35 | + Attributes struct { |
| 36 | + Request struct { |
| 37 | + Http struct { |
| 38 | + Method string `json:"method"` |
| 39 | + Path string `json:"path"` |
| 40 | + Host string `json:"host"` |
| 41 | + Headers map[string]string `json:"headers"` |
| 42 | + Protocol string `json:"protocol"` |
| 43 | + } `json:"http"` |
| 44 | + } `json:"request"` |
| 45 | + } `json:"attributes"` |
| 46 | +} |
| 47 | + |
| 48 | +// Auth Response to Envoy |
| 49 | +type AuthResponse struct { |
| 50 | + Status struct { |
| 51 | + Code int `json:"code"` |
| 52 | + } `json:"status"` |
| 53 | + HttpResponse struct { |
| 54 | + Headers map[string]string `json:"headers"` |
| 55 | + } `json:"httpResponse"` |
| 56 | +} |
| 57 | + |
| 58 | +// Decode the JWT payload |
| 59 | +func decodeJWTPayload(jwt string) (*JWTPayload, error) { |
| 60 | + parts := strings.Split(jwt, ".") |
| 61 | + if len(parts) != 3 { |
| 62 | + return nil, fmt.Errorf("invalid JWT format") |
| 63 | + } |
| 64 | + |
| 65 | + // Add padding if needed |
| 66 | + payload := parts[1] |
| 67 | + if l := len(payload) % 4; l > 0 { |
| 68 | + payload += strings.Repeat("=", 4-l) |
| 69 | + } |
| 70 | + |
| 71 | + // Decode the base64 encoded payload |
| 72 | + decoded, err := base64.URLEncoding.DecodeString(payload) |
| 73 | + if err != nil { |
| 74 | + return nil, fmt.Errorf("failed to decode payload: %v", err) |
| 75 | + } |
| 76 | + |
| 77 | + // Parse the JSON payload |
| 78 | + var payloadObj JWTPayload |
| 79 | + if err := json.Unmarshal(decoded, &payloadObj); err != nil { |
| 80 | + return nil, fmt.Errorf("failed to parse payload: %v", err) |
| 81 | + } |
| 82 | + |
| 83 | + return &payloadObj, nil |
| 84 | +} |
| 85 | + |
| 86 | +// Fetch a new JWT token from GitHub |
| 87 | +func fetchGitHubOIDCToken() (string, int64, error) { |
| 88 | + tokenRefreshMutex.Lock() |
| 89 | + defer tokenRefreshMutex.Unlock() |
| 90 | + |
| 91 | + // Check if we already have a valid token |
| 92 | + now := time.Now().Unix() |
| 93 | + if jwtToken != "" && jwtExpiration > now+60 { |
| 94 | + log.Printf("Using existing token, expires in %d seconds", jwtExpiration-now) |
| 95 | + return jwtToken, jwtExpiration, nil |
| 96 | + } |
| 97 | + |
| 98 | + log.Println("Fetching new GitHub OIDC token") |
| 99 | + |
| 100 | + // Prepare the URL and headers |
| 101 | + audience := "gap" |
| 102 | + requestURL := os.Getenv("ACTIONS_ID_TOKEN_REQUEST_URL") + "&audience=" + audience |
| 103 | + hostname := os.Getenv("GITHUB_OIDC_HOSTNAME") |
| 104 | + authToken := os.Getenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN") |
| 105 | + |
| 106 | + // Create a new HTTP request |
| 107 | + req, err := http.NewRequest("GET", requestURL, nil) |
| 108 | + if err != nil { |
| 109 | + return "", 0, fmt.Errorf("failed to create request: %v", err) |
| 110 | + } |
| 111 | + |
| 112 | + // Set headers |
| 113 | + req.Host = hostname |
| 114 | + req.Header.Set("Authorization", "Bearer "+authToken) |
| 115 | + req.Header.Set("Accept", "application/json") |
| 116 | + |
| 117 | + // Send the request |
| 118 | + client := &http.Client{Timeout: 5 * time.Second} |
| 119 | + resp, err := client.Do(req) |
| 120 | + if err != nil { |
| 121 | + return "", 0, fmt.Errorf("request failed: %v", err) |
| 122 | + } |
| 123 | + defer resp.Body.Close() |
| 124 | + |
| 125 | + // Check the response status |
| 126 | + if resp.StatusCode != http.StatusOK { |
| 127 | + return "", 0, fmt.Errorf("request failed with status: %d", resp.StatusCode) |
| 128 | + } |
| 129 | + |
| 130 | + // Read the response body |
| 131 | + body, err := io.ReadAll(resp.Body) |
| 132 | + if err != nil { |
| 133 | + return "", 0, fmt.Errorf("failed to read response: %v", err) |
| 134 | + } |
| 135 | + |
| 136 | + // Parse the JSON response |
| 137 | + var oidcResp OIDCResponse |
| 138 | + if err := json.Unmarshal(body, &oidcResp); err != nil { |
| 139 | + return "", 0, fmt.Errorf("failed to parse response: %v", err) |
| 140 | + } |
| 141 | + |
| 142 | + // Extract the token |
| 143 | + token := oidcResp.Value |
| 144 | + if token == "" { |
| 145 | + return "", 0, fmt.Errorf("empty token received") |
| 146 | + } |
| 147 | + |
| 148 | + // Parse the JWT to get expiration |
| 149 | + payload, err := decodeJWTPayload(token) |
| 150 | + if err != nil { |
| 151 | + log.Printf("Failed to decode JWT payload: %v", err) |
| 152 | + // If we can't parse expiration, use a conservative default (5 minutes) |
| 153 | + jwtToken = token |
| 154 | + jwtExpiration = now + 300 // 5 minute default |
| 155 | + log.Printf("Could not parse token expiration, using 5 min default. Expires at: %s", |
| 156 | + time.Unix(jwtExpiration, 0).Format(time.RFC3339)) |
| 157 | + return jwtToken, jwtExpiration, nil |
| 158 | + } |
| 159 | + |
| 160 | + // Store the token and expiration in global variables |
| 161 | + jwtToken = token |
| 162 | + jwtExpiration = payload.Exp |
| 163 | + |
| 164 | + log.Printf("Token fetched successfully, expires at %s", time.Unix(jwtExpiration, 0).Format(time.RFC3339)) |
| 165 | + return jwtToken, jwtExpiration, nil |
| 166 | +} |
| 167 | + |
| 168 | +// handleCheck processes auth requests from Envoy |
| 169 | +func handleCheck(w http.ResponseWriter, r *http.Request) { |
| 170 | + log.Printf("Handle Check: %s %s %s", r.Method, r.URL.Path, r.UserAgent()) |
| 171 | + |
| 172 | + // Fetch or refresh the token |
| 173 | + token, _, err := fetchGitHubOIDCToken() |
| 174 | + if err != nil { |
| 175 | + log.Printf("Error fetching token: %v", err) |
| 176 | + http.Error(w, "Failed to fetch token", http.StatusInternalServerError) |
| 177 | + return |
| 178 | + } |
| 179 | + |
| 180 | + // Prepare the response |
| 181 | + authResp := AuthResponse{} |
| 182 | + authResp.Status.Code = 200 |
| 183 | + authResp.HttpResponse.Headers = make(map[string]string) |
| 184 | + |
| 185 | + headerName := os.Getenv("GITHUB_OIDC_TOKEN_HEADER_NAME") |
| 186 | + // todo: do not log the token |
| 187 | + log.Printf("Adding %s (%s)", headerName, token) |
| 188 | + authResp.HttpResponse.Headers[headerName] = "Bearer " + token |
| 189 | + |
| 190 | + githubRepository := os.Getenv("GITHUB_REPOSITORY") |
| 191 | + log.Printf("Adding x-repository (%s)", githubRepository) |
| 192 | + authResp.HttpResponse.Headers["x-repository"] = githubRepository |
| 193 | + |
| 194 | + // Send the response |
| 195 | + w.Header().Set("Content-Type", "application/json") |
| 196 | + json.NewEncoder(w).Encode(authResp) |
| 197 | +} |
| 198 | + |
| 199 | +// handleHealthz is a simple health check endpoint |
| 200 | +func handleHealthz(w http.ResponseWriter, r *http.Request) { |
| 201 | + log.Printf("Health check request: %s", r.URL.Path) |
| 202 | + fmt.Fprint(w, "OK") |
| 203 | +} |
| 204 | + |
| 205 | +// handleNotFound handles all other paths, logs the request path, and returns a 404 |
| 206 | +func handleNotFound(w http.ResponseWriter, r *http.Request) { |
| 207 | + log.Printf("Not found request: %s %s", r.Method, r.URL.Path) |
| 208 | + http.Error(w, "Not Found", http.StatusNotFound) |
| 209 | +} |
| 210 | + |
| 211 | +func main() { |
| 212 | + port := os.Getenv("AUTH_SERVICE_PORT") |
| 213 | + if port == "" { |
| 214 | + log.Fatal("AUTH_SERVICE_PORT environment variable is required.") |
| 215 | + os.Exit(1) |
| 216 | + } |
| 217 | + |
| 218 | + // Initialize token |
| 219 | + _, _, err := fetchGitHubOIDCToken() |
| 220 | + if err != nil { |
| 221 | + log.Printf("Initial token fetch failed: %v", err) |
| 222 | + // Continue anyway, we'll retry on first request |
| 223 | + } |
| 224 | + |
| 225 | + // Set up HTTP server with custom mux |
| 226 | + mux := http.NewServeMux() |
| 227 | + |
| 228 | + // Register /check and /check/* endpoints |
| 229 | + mux.HandleFunc("/check/", handleCheck) |
| 230 | + mux.HandleFunc("/check", handleCheck) |
| 231 | + |
| 232 | + mux.HandleFunc("/healthz", handleHealthz) |
| 233 | + |
| 234 | + // Set up a catch-all handler for any other paths |
| 235 | + mux.HandleFunc("/", handleNotFound) |
| 236 | + |
| 237 | + // Start the server |
| 238 | + address := fmt.Sprintf("0.0.0.0:%s", port) |
| 239 | + log.Printf("Starting auth service on %s", address) |
| 240 | + if err := http.ListenAndServe(address, mux); err != nil { |
| 241 | + log.Fatalf("Failed to start server: %v", err) |
| 242 | + } |
| 243 | +} |
0 commit comments