lfs: add basic routing for the server side wire protocol processing
authorMatt Harbison <matt_harbison@yahoo.com>
Sat, 17 Mar 2018 01:23:01 -0400
changeset 37147 a2566597acb5
parent 37146 c37c47e47a95
child 37148 ea6fc58524d7
lfs: add basic routing for the server side wire protocol processing The recent hgweb refactoring yielded a clean point to wrap a function that could handle this, so I moved the routing for this out of the core. While not an hg wire protocol, this seems logically close enough. For now, these handlers do nothing other than check permissions. The protocol requires support for PUT requests, so that has been added to the core, and funnels into the same handler as GET and POST. The permission checking code was assuming that anything not checking 'pull' or None ops should be using POST. But that breaks the upload check if it checks 'push'. So I invented a new 'upload' permission, and used it to avoid the mandate to POST. A function wrap point could be added, but security code should probably stay grouped together. Given that anything not 'pull' or None was requiring POST, the comment on hgweb.common.permhooks is probably wrong- there is no 'read'. The rationale for the URIs is that the spec for the Batch API[1] defines the URL as the LFS server url + '/objects/batch'. The default git URLs are: Git remote: https://git-server.com/foo/bar LFS server: https://git-server.com/foo/bar.git/info/lfs Batch API: https://git-server.com/foo/bar.git/info/lfs/objects/batch '.git/' seems like it's not something a user would normally track. If we adhere to how git defines the URLs, then the hg-git extension should be able to talk to a git based server without any additional work. The URI for the transfer requests starts with '.hg/' to ensure that there are no conflicts with tracked files. Since these are handed out by the Batch API, we can change this at any point in the future. (Specifically, it might be a good idea to use something under the proposed /api/ namespace.) In any case, no files are stored at these locations in the repository directory. I started a new module for this because it seems like a good idea to keep all of the security sensitive server side code together. There's also an issue with `hg verify` in that it will want to download *all* blobs in order to run. Sadly, there's no way in the protocol to ask the server to verify the content of a blob it may have. (The verify action is for storing files on a 3rd party server, and then informing the LFS server when that completes.) So we may end up implementing a custom transfer adapter that simply indicates if the blobs are valid, and fall back to basic transfers for non-hg servers. In other words, this code is likely to get bigger before this is made non-experimental. [1] https://github.com/git-lfs/git-lfs/blob/master/docs/api/batch.md
hgext/lfs/__init__.py
hgext/lfs/wireprotolfsserver.py
mercurial/hgweb/common.py
mercurial/hgweb/server.py
--- a/hgext/lfs/__init__.py	Wed Mar 14 23:34:08 2018 -0400
+++ b/hgext/lfs/__init__.py	Sat Mar 17 01:23:01 2018 -0400
@@ -148,10 +148,12 @@
     util,
     vfs as vfsmod,
     wireproto,
+    wireprotoserver,
 )
 
 from . import (
     blobstore,
+    wireprotolfsserver,
     wrapper,
 )
 
@@ -314,6 +316,8 @@
 
     wrapfunction(exchange, 'push', wrapper.push)
     wrapfunction(wireproto, '_capabilities', wrapper._capabilities)
+    wrapfunction(wireprotoserver, 'handlewsgirequest',
+                 wireprotolfsserver.handlewsgirequest)
 
     wrapfunction(context.basefilectx, 'cmp', wrapper.filectxcmp)
     wrapfunction(context.basefilectx, 'isbinary', wrapper.filectxisbinary)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hgext/lfs/wireprotolfsserver.py	Sat Mar 17 01:23:01 2018 -0400
@@ -0,0 +1,75 @@
+# wireprotolfsserver.py - lfs protocol server side implementation
+#
+# Copyright 2018 Matt Harbison <matt_harbison@yahoo.com>
+#
+# This software may be used and distributed according to the terms of the
+# GNU General Public License version 2 or any later version.
+
+from __future__ import absolute_import
+
+from mercurial.hgweb import (
+    common as hgwebcommon,
+)
+
+from mercurial import (
+    pycompat,
+)
+
+def handlewsgirequest(orig, rctx, req, res, checkperm):
+    """Wrap wireprotoserver.handlewsgirequest() to possibly process an LFS
+    request if it is left unprocessed by the wrapped method.
+    """
+    if orig(rctx, req, res, checkperm):
+        return True
+
+    if not req.dispatchpath:
+        return False
+
+    try:
+        if req.dispatchpath == b'.git/info/lfs/objects/batch':
+            checkperm(rctx, req, 'pull')
+            return _processbatchrequest(rctx.repo, req, res)
+        # TODO: reserve and use a path in the proposed http wireprotocol /api/
+        #       namespace?
+        elif req.dispatchpath.startswith(b'.hg/lfs/objects'):
+            return _processbasictransfer(rctx.repo, req, res,
+                                         lambda perm:
+                                                checkperm(rctx, req, perm))
+        return False
+    except hgwebcommon.ErrorResponse as e:
+        # XXX: copied from the handler surrounding wireprotoserver._callhttp()
+        #      in the wrapped function.  Should this be moved back to hgweb to
+        #      be a common handler?
+        for k, v in e.headers:
+            res.headers[k] = v
+        res.status = hgwebcommon.statusmessage(e.code, pycompat.bytestr(e))
+        res.setbodybytes(b'0\n%s\n' % pycompat.bytestr(e))
+        return True
+
+def _processbatchrequest(repo, req, res):
+    """Handle a request for the Batch API, which is the gateway to granting file
+    access.
+
+    https://github.com/git-lfs/git-lfs/blob/master/docs/api/batch.md
+    """
+    return False
+
+def _processbasictransfer(repo, req, res, checkperm):
+    """Handle a single file upload (PUT) or download (GET) action for the Basic
+    Transfer Adapter.
+
+    After determining if the request is for an upload or download, the access
+    must be checked by calling ``checkperm()`` with either 'pull' or 'upload'
+    before accessing the files.
+
+    https://github.com/git-lfs/git-lfs/blob/master/docs/api/basic-transfers.md
+    """
+
+    method = req.method
+
+    if method == b'PUT':
+        checkperm('upload')
+    elif method == b'GET':
+        checkperm('pull')
+
+    return False
--- a/mercurial/hgweb/common.py	Wed Mar 14 23:34:08 2018 -0400
+++ b/mercurial/hgweb/common.py	Sat Mar 17 01:23:01 2018 -0400
@@ -61,8 +61,13 @@
     elif op == 'pull' or op is None: # op is None for interface requests
         return
 
+    # Allow LFS uploading via PUT requests
+    if op == 'upload':
+        if req.method != 'PUT':
+            msg = 'upload requires PUT request'
+            raise ErrorResponse(HTTP_METHOD_NOT_ALLOWED, msg)
     # enforce that you can only push using POST requests
-    if req.method != 'POST':
+    elif req.method != 'POST':
         msg = 'push requires POST request'
         raise ErrorResponse(HTTP_METHOD_NOT_ALLOWED, msg)
 
@@ -81,7 +86,7 @@
 
 # Hooks for hgweb permission checks; extensions can add hooks here.
 # Each hook is invoked like this: hook(hgweb, request, operation),
-# where operation is either read, pull or push. Hooks should either
+# where operation is either read, pull, push or upload. Hooks should either
 # raise an ErrorResponse exception, or just return.
 #
 # It is possible to do both authentication and authorization through
--- a/mercurial/hgweb/server.py	Wed Mar 14 23:34:08 2018 -0400
+++ b/mercurial/hgweb/server.py	Sat Mar 17 01:23:01 2018 -0400
@@ -112,6 +112,9 @@
             self.log_error(r"Exception happened during processing "
                            r"request '%s':%s%s", self.path, newline, tb)
 
+    def do_PUT(self):
+        self.do_POST()
+
     def do_GET(self):
         self.do_POST()