12483: Merge branch 'master' into 12483-writable-fs
[arvados.git] / services / arv-git-httpd / auth_handler.go
index 9f92cd1b7213f5a720a771ae349fac7dd6558b39..617c73282f633ac6ddbca83c2094c1acfe8f3f18 100644 (file)
@@ -1,3 +1,7 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
 package main
 
 import (
@@ -39,6 +43,29 @@ func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
 
        w := httpserver.WrapResponseWriter(wOrig)
 
+       if r.Method == "OPTIONS" {
+               method := r.Header.Get("Access-Control-Request-Method")
+               if method != "GET" && method != "POST" {
+                       w.WriteHeader(http.StatusMethodNotAllowed)
+                       return
+               }
+               w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
+               w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
+               w.Header().Set("Access-Control-Allow-Origin", "*")
+               w.Header().Set("Access-Control-Max-Age", "86400")
+               w.WriteHeader(http.StatusOK)
+               return
+       }
+
+       if r.Header.Get("Origin") != "" {
+               // Allow simple cross-origin requests without user
+               // credentials ("user credentials" as defined by CORS,
+               // i.e., cookies, HTTP authentication, and client-side
+               // SSL certificates. See
+               // http://www.w3.org/TR/cors/#user-credentials).
+               w.Header().Set("Access-Control-Allow-Origin", "*")
+       }
+
        defer func() {
                if w.WroteStatus() == 0 {
                        // Nobody has called WriteHeader yet: that
@@ -74,7 +101,7 @@ func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
        // "foo/bar".
        pathParts := strings.SplitN(r.URL.Path[1:], ".git/", 2)
        if len(pathParts) != 2 {
-               statusCode, statusText = http.StatusBadRequest, "bad request"
+               statusCode, statusText = http.StatusNotFound, "not found"
                return
        }
        repoName = pathParts[0]
@@ -161,5 +188,5 @@ func (h *authHandler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
        }
        r.URL.Path = rewrittenPath
 
-       h.handler.ServeHTTP(&w, r)
+       h.handler.ServeHTTP(w, r)
 }