RequireAPIKeyOrWorkspaceAgent is middleware that should be inserted after optional ExtractAPIKey and ExtractWorkspaceAgent middlewares to ensure one of the two is provided. If both are provided an error is returned to avoid misuse.
()
| 42 | // |
| 43 | // If both are provided an error is returned to avoid misuse. |
| 44 | func RequireAPIKeyOrWorkspaceAgent() func(http.Handler) http.Handler { |
| 45 | return func(next http.Handler) http.Handler { |
| 46 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 47 | _, hasAPIKey := APIKeyOptional(r) |
| 48 | _, hasWorkspaceAgent := WorkspaceAgentOptional(r) |
| 49 | |
| 50 | if hasAPIKey && hasWorkspaceAgent { |
| 51 | httpapi.Write(r.Context(), w, http.StatusBadRequest, codersdk.Response{ |
| 52 | Message: "API key and workspace agent token provided, but only one is allowed", |
| 53 | }) |
| 54 | return |
| 55 | } |
| 56 | if !hasAPIKey && !hasWorkspaceAgent { |
| 57 | httpapi.Write(r.Context(), w, http.StatusUnauthorized, codersdk.Response{ |
| 58 | Message: "API key or workspace agent token required, but none provided", |
| 59 | }) |
| 60 | return |
| 61 | } |
| 62 | |
| 63 | next.ServeHTTP(w, r) |
| 64 | }) |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | // RequireAPIKeyOrProvisionerDaemonAuth is middleware that should be inserted |
| 69 | // after optional ExtractAPIKey and ExtractProvisionerDaemonAuthenticated |
no test coverage detected