You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LfsConnectionFactory.java 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. /*
  2. * Copyright (C) 2017, Markus Duft <markus.duft@ssi-schaefer.com> and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.lfs.internal;
  11. import static org.eclipse.jgit.util.HttpSupport.ENCODING_GZIP;
  12. import static org.eclipse.jgit.util.HttpSupport.HDR_ACCEPT;
  13. import static org.eclipse.jgit.util.HttpSupport.HDR_ACCEPT_ENCODING;
  14. import static org.eclipse.jgit.util.HttpSupport.HDR_CONTENT_TYPE;
  15. import java.io.IOException;
  16. import java.net.ProxySelector;
  17. import java.net.URISyntaxException;
  18. import java.net.URL;
  19. import java.text.SimpleDateFormat;
  20. import java.util.LinkedList;
  21. import java.util.Map;
  22. import java.util.TreeMap;
  23. import org.eclipse.jgit.annotations.NonNull;
  24. import org.eclipse.jgit.errors.CommandFailedException;
  25. import org.eclipse.jgit.lfs.LfsPointer;
  26. import org.eclipse.jgit.lfs.Protocol;
  27. import org.eclipse.jgit.lfs.errors.LfsConfigInvalidException;
  28. import org.eclipse.jgit.lib.ConfigConstants;
  29. import org.eclipse.jgit.lib.Repository;
  30. import org.eclipse.jgit.lib.StoredConfig;
  31. import org.eclipse.jgit.transport.HttpConfig;
  32. import org.eclipse.jgit.transport.HttpTransport;
  33. import org.eclipse.jgit.transport.URIish;
  34. import org.eclipse.jgit.transport.http.HttpConnection;
  35. import org.eclipse.jgit.util.HttpSupport;
  36. import org.eclipse.jgit.util.SshSupport;
  37. /**
  38. * Provides means to get a valid LFS connection for a given repository.
  39. */
  40. public class LfsConnectionFactory {
  41. private static final int SSH_AUTH_TIMEOUT_SECONDS = 30;
  42. private static final String SCHEME_HTTPS = "https"; //$NON-NLS-1$
  43. private static final String SCHEME_SSH = "ssh"; //$NON-NLS-1$
  44. private static final Map<String, AuthCache> sshAuthCache = new TreeMap<>();
  45. /**
  46. * Determine URL of LFS server by looking into config parameters lfs.url,
  47. * lfs.[remote].url or remote.[remote].url. The LFS server URL is computed
  48. * from remote.[remote].url by appending "/info/lfs". In case there is no
  49. * URL configured, a SSH remote URI can be used to auto-detect the LFS URI
  50. * by using the remote "git-lfs-authenticate" command.
  51. *
  52. * @param db
  53. * the repository to work with
  54. * @param method
  55. * the method (GET,PUT,...) of the request this connection will
  56. * be used for
  57. * @param purpose
  58. * the action, e.g. Protocol.OPERATION_DOWNLOAD
  59. * @return the url for the lfs server. e.g.
  60. * "https://github.com/github/git-lfs.git/info/lfs"
  61. * @throws IOException
  62. */
  63. public static HttpConnection getLfsConnection(Repository db, String method,
  64. String purpose) throws IOException {
  65. StoredConfig config = db.getConfig();
  66. Map<String, String> additionalHeaders = new TreeMap<>();
  67. String lfsUrl = getLfsUrl(db, purpose, additionalHeaders);
  68. URL url = new URL(lfsUrl + Protocol.OBJECTS_LFS_ENDPOINT);
  69. HttpConnection connection = HttpTransport.getConnectionFactory().create(
  70. url, HttpSupport.proxyFor(ProxySelector.getDefault(), url));
  71. connection.setDoOutput(true);
  72. if (url.getProtocol().equals(SCHEME_HTTPS)
  73. && !config.getBoolean(HttpConfig.HTTP,
  74. HttpConfig.SSL_VERIFY_KEY, true)) {
  75. HttpSupport.disableSslVerify(connection);
  76. }
  77. connection.setRequestMethod(method);
  78. connection.setRequestProperty(HDR_ACCEPT,
  79. Protocol.CONTENTTYPE_VND_GIT_LFS_JSON);
  80. connection.setRequestProperty(HDR_CONTENT_TYPE,
  81. Protocol.CONTENTTYPE_VND_GIT_LFS_JSON);
  82. additionalHeaders
  83. .forEach((k, v) -> connection.setRequestProperty(k, v));
  84. return connection;
  85. }
  86. private static String getLfsUrl(Repository db, String purpose,
  87. Map<String, String> additionalHeaders)
  88. throws LfsConfigInvalidException {
  89. StoredConfig config = db.getConfig();
  90. String lfsUrl = config.getString(ConfigConstants.CONFIG_SECTION_LFS,
  91. null,
  92. ConfigConstants.CONFIG_KEY_URL);
  93. Exception ex = null;
  94. if (lfsUrl == null) {
  95. String remoteUrl = null;
  96. for (String remote : db.getRemoteNames()) {
  97. lfsUrl = config.getString(ConfigConstants.CONFIG_SECTION_LFS,
  98. remote,
  99. ConfigConstants.CONFIG_KEY_URL);
  100. // This could be done better (more precise logic), but according
  101. // to https://github.com/git-lfs/git-lfs/issues/1759 git-lfs
  102. // generally only supports 'origin' in an integrated workflow.
  103. if (lfsUrl == null && (remote.equals(
  104. org.eclipse.jgit.lib.Constants.DEFAULT_REMOTE_NAME))) {
  105. remoteUrl = config.getString(
  106. ConfigConstants.CONFIG_KEY_REMOTE, remote,
  107. ConfigConstants.CONFIG_KEY_URL);
  108. break;
  109. }
  110. }
  111. if (lfsUrl == null && remoteUrl != null) {
  112. try {
  113. lfsUrl = discoverLfsUrl(db, purpose, additionalHeaders,
  114. remoteUrl);
  115. } catch (URISyntaxException | IOException
  116. | CommandFailedException e) {
  117. ex = e;
  118. }
  119. } else {
  120. lfsUrl = lfsUrl + Protocol.INFO_LFS_ENDPOINT;
  121. }
  122. }
  123. if (lfsUrl == null) {
  124. if (ex != null) {
  125. throw new LfsConfigInvalidException(
  126. LfsText.get().lfsNoDownloadUrl, ex);
  127. }
  128. throw new LfsConfigInvalidException(LfsText.get().lfsNoDownloadUrl);
  129. }
  130. return lfsUrl;
  131. }
  132. private static String discoverLfsUrl(Repository db, String purpose,
  133. Map<String, String> additionalHeaders, String remoteUrl)
  134. throws URISyntaxException, IOException, CommandFailedException {
  135. URIish u = new URIish(remoteUrl);
  136. if (u.getScheme() == null || SCHEME_SSH.equals(u.getScheme())) {
  137. Protocol.ExpiringAction action = getSshAuthentication(db, purpose,
  138. remoteUrl, u);
  139. additionalHeaders.putAll(action.header);
  140. return action.href;
  141. }
  142. return remoteUrl + Protocol.INFO_LFS_ENDPOINT;
  143. }
  144. private static Protocol.ExpiringAction getSshAuthentication(
  145. Repository db, String purpose, String remoteUrl, URIish u)
  146. throws IOException, CommandFailedException {
  147. AuthCache cached = sshAuthCache.get(remoteUrl);
  148. Protocol.ExpiringAction action = null;
  149. if (cached != null && cached.validUntil > System.currentTimeMillis()) {
  150. action = cached.cachedAction;
  151. }
  152. if (action == null) {
  153. // discover and authenticate; git-lfs does "ssh
  154. // -p <port> -- <host> git-lfs-authenticate
  155. // <project> <upload/download>"
  156. String json = SshSupport.runSshCommand(u.setPath(""), //$NON-NLS-1$
  157. null, db.getFS(),
  158. "git-lfs-authenticate " + extractProjectName(u) + " " //$NON-NLS-1$//$NON-NLS-2$
  159. + purpose,
  160. SSH_AUTH_TIMEOUT_SECONDS);
  161. action = Protocol.gson().fromJson(json,
  162. Protocol.ExpiringAction.class);
  163. // cache the result as long as possible.
  164. AuthCache c = new AuthCache(action);
  165. sshAuthCache.put(remoteUrl, c);
  166. }
  167. return action;
  168. }
  169. /**
  170. * Create a connection for the specified
  171. * {@link org.eclipse.jgit.lfs.Protocol.Action}.
  172. *
  173. * @param repo
  174. * the repo to fetch required configuration from
  175. * @param action
  176. * the action for which to create a connection
  177. * @param method
  178. * the target method (GET or PUT)
  179. * @return a connection. output mode is not set.
  180. * @throws IOException
  181. * in case of any error.
  182. */
  183. @NonNull
  184. public static HttpConnection getLfsContentConnection(
  185. Repository repo, Protocol.Action action, String method)
  186. throws IOException {
  187. URL contentUrl = new URL(action.href);
  188. HttpConnection contentServerConn = HttpTransport.getConnectionFactory()
  189. .create(contentUrl, HttpSupport
  190. .proxyFor(ProxySelector.getDefault(), contentUrl));
  191. contentServerConn.setRequestMethod(method);
  192. if (action.header != null) {
  193. action.header.forEach(
  194. (k, v) -> contentServerConn.setRequestProperty(k, v));
  195. }
  196. if (contentUrl.getProtocol().equals(SCHEME_HTTPS)
  197. && !repo.getConfig().getBoolean(HttpConfig.HTTP,
  198. HttpConfig.SSL_VERIFY_KEY, true)) {
  199. HttpSupport.disableSslVerify(contentServerConn);
  200. }
  201. contentServerConn.setRequestProperty(HDR_ACCEPT_ENCODING,
  202. ENCODING_GZIP);
  203. return contentServerConn;
  204. }
  205. private static String extractProjectName(URIish u) {
  206. String path = u.getPath();
  207. // begins with a slash if the url contains a port (gerrit vs. github).
  208. if (path.startsWith("/")) { //$NON-NLS-1$
  209. path = path.substring(1);
  210. }
  211. if (path.endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT)) {
  212. return path.substring(0, path.length() - 4);
  213. }
  214. return path;
  215. }
  216. /**
  217. * @param operation
  218. * the operation to perform, e.g. Protocol.OPERATION_DOWNLOAD
  219. * @param resources
  220. * the LFS resources affected
  221. * @return a request that can be serialized to JSON
  222. */
  223. public static Protocol.Request toRequest(String operation,
  224. LfsPointer... resources) {
  225. Protocol.Request req = new Protocol.Request();
  226. req.operation = operation;
  227. if (resources != null) {
  228. req.objects = new LinkedList<>();
  229. for (LfsPointer res : resources) {
  230. Protocol.ObjectSpec o = new Protocol.ObjectSpec();
  231. o.oid = res.getOid().getName();
  232. o.size = res.getSize();
  233. req.objects.add(o);
  234. }
  235. }
  236. return req;
  237. }
  238. private static final class AuthCache {
  239. private static final long AUTH_CACHE_EAGER_TIMEOUT = 500;
  240. private static final SimpleDateFormat ISO_FORMAT = new SimpleDateFormat(
  241. "yyyy-MM-dd'T'HH:mm:ss.SSSX"); //$NON-NLS-1$
  242. /**
  243. * Creates a cache entry for an authentication response.
  244. * <p>
  245. * The timeout of the cache token is extracted from the given action. If
  246. * no timeout can be determined, the token will be used only once.
  247. *
  248. * @param action
  249. */
  250. public AuthCache(Protocol.ExpiringAction action) {
  251. this.cachedAction = action;
  252. try {
  253. if (action.expiresIn != null && !action.expiresIn.isEmpty()) {
  254. this.validUntil = (System.currentTimeMillis()
  255. + Long.parseLong(action.expiresIn))
  256. - AUTH_CACHE_EAGER_TIMEOUT;
  257. } else if (action.expiresAt != null
  258. && !action.expiresAt.isEmpty()) {
  259. this.validUntil = ISO_FORMAT.parse(action.expiresAt)
  260. .getTime() - AUTH_CACHE_EAGER_TIMEOUT;
  261. } else {
  262. this.validUntil = System.currentTimeMillis();
  263. }
  264. } catch (Exception e) {
  265. this.validUntil = System.currentTimeMillis();
  266. }
  267. }
  268. long validUntil;
  269. Protocol.ExpiringAction cachedAction;
  270. }
  271. }