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.

PushCertificateStore.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. /*
  2. * Copyright (C) 2015, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.transport;
  44. import static java.nio.charset.StandardCharsets.UTF_8;
  45. import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
  46. import static org.eclipse.jgit.lib.Constants.OBJ_COMMIT;
  47. import static org.eclipse.jgit.lib.FileMode.TYPE_FILE;
  48. import java.io.BufferedReader;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.io.InputStreamReader;
  52. import java.io.Reader;
  53. import java.text.MessageFormat;
  54. import java.util.ArrayList;
  55. import java.util.Collection;
  56. import java.util.Collections;
  57. import java.util.HashMap;
  58. import java.util.Iterator;
  59. import java.util.List;
  60. import java.util.Map;
  61. import java.util.NoSuchElementException;
  62. import org.eclipse.jgit.dircache.DirCache;
  63. import org.eclipse.jgit.dircache.DirCacheEditor;
  64. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  65. import org.eclipse.jgit.dircache.DirCacheEntry;
  66. import org.eclipse.jgit.internal.JGitText;
  67. import org.eclipse.jgit.lib.BatchRefUpdate;
  68. import org.eclipse.jgit.lib.CommitBuilder;
  69. import org.eclipse.jgit.lib.Constants;
  70. import org.eclipse.jgit.lib.FileMode;
  71. import org.eclipse.jgit.lib.ObjectId;
  72. import org.eclipse.jgit.lib.ObjectInserter;
  73. import org.eclipse.jgit.lib.ObjectLoader;
  74. import org.eclipse.jgit.lib.ObjectReader;
  75. import org.eclipse.jgit.lib.PersonIdent;
  76. import org.eclipse.jgit.lib.Ref;
  77. import org.eclipse.jgit.lib.RefUpdate;
  78. import org.eclipse.jgit.lib.Repository;
  79. import org.eclipse.jgit.revwalk.RevCommit;
  80. import org.eclipse.jgit.revwalk.RevWalk;
  81. import org.eclipse.jgit.treewalk.TreeWalk;
  82. import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
  83. import org.eclipse.jgit.treewalk.filter.PathFilter;
  84. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  85. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  86. /**
  87. * Storage for recorded push certificates.
  88. * <p>
  89. * Push certificates are stored in a special ref {@code refs/meta/push-certs}.
  90. * The filenames in the tree are ref names followed by the special suffix
  91. * <code>@{cert}</code>, and the contents are the latest push cert affecting
  92. * that ref. The special suffix allows storing certificates for both refs/foo
  93. * and refs/foo/bar in case those both existed at some point.
  94. *
  95. * @since 4.1
  96. */
  97. public class PushCertificateStore implements AutoCloseable {
  98. /** Ref name storing push certificates. */
  99. static final String REF_NAME =
  100. Constants.R_REFS + "meta/push-certs"; //$NON-NLS-1$
  101. private static class PendingCert {
  102. PushCertificate cert;
  103. PersonIdent ident;
  104. Collection<ReceiveCommand> matching;
  105. PendingCert(PushCertificate cert, PersonIdent ident,
  106. Collection<ReceiveCommand> matching) {
  107. this.cert = cert;
  108. this.ident = ident;
  109. this.matching = matching;
  110. }
  111. }
  112. private final Repository db;
  113. private final List<PendingCert> pending;
  114. ObjectReader reader;
  115. RevCommit commit;
  116. /**
  117. * Create a new store backed by the given repository.
  118. *
  119. * @param db
  120. * the repository.
  121. */
  122. public PushCertificateStore(Repository db) {
  123. this.db = db;
  124. pending = new ArrayList<>();
  125. }
  126. /**
  127. * {@inheritDoc}
  128. * <p>
  129. * Close resources opened by this store.
  130. * <p>
  131. * If {@link #get(String)} was called, closes the cached object reader
  132. * created by that method. Does not close the underlying repository.
  133. */
  134. @Override
  135. public void close() {
  136. if (reader != null) {
  137. reader.close();
  138. reader = null;
  139. commit = null;
  140. }
  141. }
  142. /**
  143. * Get latest push certificate associated with a ref.
  144. * <p>
  145. * Lazily opens {@code refs/meta/push-certs} and reads from the repository as
  146. * necessary. The state is cached between calls to {@code get}; to reread the,
  147. * call {@link #close()} first.
  148. *
  149. * @param refName
  150. * the ref name to get the certificate for.
  151. * @return last certificate affecting the ref, or null if no cert was recorded
  152. * for the last update to this ref.
  153. * @throws java.io.IOException
  154. * if a problem occurred reading the repository.
  155. */
  156. public PushCertificate get(String refName) throws IOException {
  157. if (reader == null) {
  158. load();
  159. }
  160. try (TreeWalk tw = newTreeWalk(refName)) {
  161. return read(tw);
  162. }
  163. }
  164. /**
  165. * Iterate over all push certificates affecting a ref.
  166. * <p>
  167. * Only includes push certificates actually stored in the tree; see class
  168. * Javadoc for conditions where this might not include all push certs ever
  169. * seen for this ref.
  170. * <p>
  171. * The returned iterable may be iterated multiple times, and push certs will
  172. * be re-read from the current state of the store on each call to {@link
  173. * Iterable#iterator()}. However, method calls on the returned iterator may
  174. * fail if {@code save} or {@code close} is called on the enclosing store
  175. * during iteration.
  176. *
  177. * @param refName
  178. * the ref name to get certificates for.
  179. * @return iterable over certificates; must be fully iterated in order to
  180. * close resources.
  181. */
  182. public Iterable<PushCertificate> getAll(String refName) {
  183. return () -> new Iterator<PushCertificate>() {
  184. private final String path = pathName(refName);
  185. private PushCertificate next;
  186. private RevWalk rw;
  187. {
  188. try {
  189. if (reader == null) {
  190. load();
  191. }
  192. if (commit != null) {
  193. rw = new RevWalk(reader);
  194. rw.setTreeFilter(AndTreeFilter.create(
  195. PathFilterGroup.create(Collections
  196. .singleton(PathFilter.create(path))),
  197. TreeFilter.ANY_DIFF));
  198. rw.setRewriteParents(false);
  199. rw.markStart(rw.parseCommit(commit));
  200. } else {
  201. rw = null;
  202. }
  203. } catch (IOException e) {
  204. throw new RuntimeException(e);
  205. }
  206. }
  207. @Override
  208. public boolean hasNext() {
  209. try {
  210. if (next == null) {
  211. if (rw == null) {
  212. return false;
  213. }
  214. try {
  215. RevCommit c = rw.next();
  216. if (c != null) {
  217. try (TreeWalk tw = TreeWalk.forPath(
  218. rw.getObjectReader(), path,
  219. c.getTree())) {
  220. next = read(tw);
  221. }
  222. } else {
  223. next = null;
  224. }
  225. } catch (IOException e) {
  226. throw new RuntimeException(e);
  227. }
  228. }
  229. return next != null;
  230. } finally {
  231. if (next == null && rw != null) {
  232. rw.close();
  233. rw = null;
  234. }
  235. }
  236. }
  237. @Override
  238. public PushCertificate next() {
  239. hasNext();
  240. PushCertificate n = next;
  241. if (n == null) {
  242. throw new NoSuchElementException();
  243. }
  244. next = null;
  245. return n;
  246. }
  247. @Override
  248. public void remove() {
  249. throw new UnsupportedOperationException();
  250. }
  251. };
  252. }
  253. void load() throws IOException {
  254. close();
  255. reader = db.newObjectReader();
  256. Ref ref = db.getRefDatabase().exactRef(REF_NAME);
  257. if (ref == null) {
  258. // No ref, same as empty.
  259. return;
  260. }
  261. try (RevWalk rw = new RevWalk(reader)) {
  262. commit = rw.parseCommit(ref.getObjectId());
  263. }
  264. }
  265. static PushCertificate read(TreeWalk tw) throws IOException {
  266. if (tw == null || (tw.getRawMode(0) & TYPE_FILE) != TYPE_FILE) {
  267. return null;
  268. }
  269. ObjectLoader loader =
  270. tw.getObjectReader().open(tw.getObjectId(0), OBJ_BLOB);
  271. try (InputStream in = loader.openStream();
  272. Reader r = new BufferedReader(
  273. new InputStreamReader(in, UTF_8))) {
  274. return PushCertificateParser.fromReader(r);
  275. }
  276. }
  277. /**
  278. * Put a certificate to be saved to the store.
  279. * <p>
  280. * Writes the contents of this certificate for each ref mentioned. It is up
  281. * to the caller to ensure this certificate accurately represents the state
  282. * of the ref.
  283. * <p>
  284. * Pending certificates added to this method are not returned by
  285. * {@link #get(String)} and {@link #getAll(String)} until after calling
  286. * {@link #save()}.
  287. *
  288. * @param cert
  289. * certificate to store.
  290. * @param ident
  291. * identity for the commit that stores this certificate. Pending
  292. * certificates are sorted by identity timestamp during
  293. * {@link #save()}.
  294. */
  295. public void put(PushCertificate cert, PersonIdent ident) {
  296. put(cert, ident, null);
  297. }
  298. /**
  299. * Put a certificate to be saved to the store, matching a set of commands.
  300. * <p>
  301. * Like {@link #put(PushCertificate, PersonIdent)}, except a value is only
  302. * stored for a push certificate if there is a corresponding command in the
  303. * list that exactly matches the old/new values mentioned in the push
  304. * certificate.
  305. * <p>
  306. * Pending certificates added to this method are not returned by
  307. * {@link #get(String)} and {@link #getAll(String)} until after calling
  308. * {@link #save()}.
  309. *
  310. * @param cert
  311. * certificate to store.
  312. * @param ident
  313. * identity for the commit that stores this certificate. Pending
  314. * certificates are sorted by identity timestamp during
  315. * {@link #save()}.
  316. * @param matching
  317. * only store certs for the refs listed in this list whose values
  318. * match the commands in the cert.
  319. */
  320. public void put(PushCertificate cert, PersonIdent ident,
  321. Collection<ReceiveCommand> matching) {
  322. pending.add(new PendingCert(cert, ident, matching));
  323. }
  324. /**
  325. * Save pending certificates to the store.
  326. * <p>
  327. * One commit is created per certificate added with
  328. * {@link #put(PushCertificate, PersonIdent)}, in order of identity
  329. * timestamps, and a single ref update is performed.
  330. * <p>
  331. * The pending list is cleared if and only the ref update fails, which
  332. * allows for easy retries in case of lock failure.
  333. *
  334. * @return the result of attempting to update the ref.
  335. * @throws java.io.IOException
  336. * if there was an error reading from or writing to the
  337. * repository.
  338. */
  339. public RefUpdate.Result save() throws IOException {
  340. ObjectId newId = write();
  341. if (newId == null) {
  342. return RefUpdate.Result.NO_CHANGE;
  343. }
  344. try (ObjectInserter inserter = db.newObjectInserter()) {
  345. RefUpdate.Result result = updateRef(newId);
  346. switch (result) {
  347. case FAST_FORWARD:
  348. case NEW:
  349. case NO_CHANGE:
  350. pending.clear();
  351. break;
  352. default:
  353. break;
  354. }
  355. return result;
  356. } finally {
  357. close();
  358. }
  359. }
  360. /**
  361. * Save pending certificates to the store in an existing batch ref update.
  362. * <p>
  363. * One commit is created per certificate added with
  364. * {@link #put(PushCertificate, PersonIdent)}, in order of identity
  365. * timestamps, all commits are flushed, and a single command is added to the
  366. * batch.
  367. * <p>
  368. * The cached ref value and pending list are <em>not</em> cleared. If the
  369. * ref update succeeds, the caller is responsible for calling
  370. * {@link #close()} and/or {@link #clear()}.
  371. *
  372. * @param batch
  373. * update to save to.
  374. * @return whether a command was added to the batch.
  375. * @throws java.io.IOException
  376. * if there was an error reading from or writing to the
  377. * repository.
  378. */
  379. public boolean save(BatchRefUpdate batch) throws IOException {
  380. ObjectId newId = write();
  381. if (newId == null || newId.equals(commit)) {
  382. return false;
  383. }
  384. batch.addCommand(new ReceiveCommand(
  385. commit != null ? commit : ObjectId.zeroId(), newId, REF_NAME));
  386. return true;
  387. }
  388. /**
  389. * Clear pending certificates added with {@link #put(PushCertificate,
  390. * PersonIdent)}.
  391. */
  392. public void clear() {
  393. pending.clear();
  394. }
  395. private ObjectId write() throws IOException {
  396. if (pending.isEmpty()) {
  397. return null;
  398. }
  399. if (reader == null) {
  400. load();
  401. }
  402. sortPending(pending);
  403. ObjectId curr = commit;
  404. DirCache dc = newDirCache();
  405. try (ObjectInserter inserter = db.newObjectInserter()) {
  406. for (PendingCert pc : pending) {
  407. curr = saveCert(inserter, dc, pc, curr);
  408. }
  409. inserter.flush();
  410. return curr;
  411. }
  412. }
  413. private static void sortPending(List<PendingCert> pending) {
  414. Collections.sort(pending, (PendingCert a, PendingCert b) -> Long.signum(
  415. a.ident.getWhen().getTime() - b.ident.getWhen().getTime()));
  416. }
  417. private DirCache newDirCache() throws IOException {
  418. if (commit != null) {
  419. return DirCache.read(reader, commit.getTree());
  420. }
  421. return DirCache.newInCore();
  422. }
  423. private ObjectId saveCert(ObjectInserter inserter, DirCache dc,
  424. PendingCert pc, ObjectId curr) throws IOException {
  425. Map<String, ReceiveCommand> byRef;
  426. if (pc.matching != null) {
  427. byRef = new HashMap<>();
  428. for (ReceiveCommand cmd : pc.matching) {
  429. if (byRef.put(cmd.getRefName(), cmd) != null) {
  430. throw new IllegalStateException();
  431. }
  432. }
  433. } else {
  434. byRef = null;
  435. }
  436. DirCacheEditor editor = dc.editor();
  437. String certText = pc.cert.toText() + pc.cert.getSignature();
  438. final ObjectId certId = inserter.insert(OBJ_BLOB, certText.getBytes(UTF_8));
  439. boolean any = false;
  440. for (ReceiveCommand cmd : pc.cert.getCommands()) {
  441. if (byRef != null && !commandsEqual(cmd, byRef.get(cmd.getRefName()))) {
  442. continue;
  443. }
  444. any = true;
  445. editor.add(new PathEdit(pathName(cmd.getRefName())) {
  446. @Override
  447. public void apply(DirCacheEntry ent) {
  448. ent.setFileMode(FileMode.REGULAR_FILE);
  449. ent.setObjectId(certId);
  450. }
  451. });
  452. }
  453. if (!any) {
  454. return curr;
  455. }
  456. editor.finish();
  457. CommitBuilder cb = new CommitBuilder();
  458. cb.setAuthor(pc.ident);
  459. cb.setCommitter(pc.ident);
  460. cb.setTreeId(dc.writeTree(inserter));
  461. if (curr != null) {
  462. cb.setParentId(curr);
  463. } else {
  464. cb.setParentIds(Collections.<ObjectId> emptyList());
  465. }
  466. cb.setMessage(buildMessage(pc.cert));
  467. return inserter.insert(OBJ_COMMIT, cb.build());
  468. }
  469. private static boolean commandsEqual(ReceiveCommand c1, ReceiveCommand c2) {
  470. if (c1 == null || c2 == null) {
  471. return c1 == c2;
  472. }
  473. return c1.getRefName().equals(c2.getRefName())
  474. && c1.getOldId().equals(c2.getOldId())
  475. && c1.getNewId().equals(c2.getNewId());
  476. }
  477. private RefUpdate.Result updateRef(ObjectId newId) throws IOException {
  478. RefUpdate ru = db.updateRef(REF_NAME);
  479. ru.setExpectedOldObjectId(commit != null ? commit : ObjectId.zeroId());
  480. ru.setNewObjectId(newId);
  481. ru.setRefLogIdent(pending.get(pending.size() - 1).ident);
  482. ru.setRefLogMessage(JGitText.get().storePushCertReflog, false);
  483. try (RevWalk rw = new RevWalk(reader)) {
  484. return ru.update(rw);
  485. }
  486. }
  487. private TreeWalk newTreeWalk(String refName) throws IOException {
  488. if (commit == null) {
  489. return null;
  490. }
  491. return TreeWalk.forPath(reader, pathName(refName), commit.getTree());
  492. }
  493. static String pathName(String refName) {
  494. return refName + "@{cert}"; //$NON-NLS-1$
  495. }
  496. private static String buildMessage(PushCertificate cert) {
  497. StringBuilder sb = new StringBuilder();
  498. if (cert.getCommands().size() == 1) {
  499. sb.append(MessageFormat.format(
  500. JGitText.get().storePushCertOneRef,
  501. cert.getCommands().get(0).getRefName()));
  502. } else {
  503. sb.append(MessageFormat.format(
  504. JGitText.get().storePushCertMultipleRefs,
  505. Integer.valueOf(cert.getCommands().size())));
  506. }
  507. return sb.append('\n').toString();
  508. }
  509. }