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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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.Comparator;
  58. import java.util.HashMap;
  59. import java.util.Iterator;
  60. import java.util.List;
  61. import java.util.Map;
  62. import java.util.NoSuchElementException;
  63. import org.eclipse.jgit.dircache.DirCache;
  64. import org.eclipse.jgit.dircache.DirCacheEditor;
  65. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  66. import org.eclipse.jgit.dircache.DirCacheEntry;
  67. import org.eclipse.jgit.internal.JGitText;
  68. import org.eclipse.jgit.lib.BatchRefUpdate;
  69. import org.eclipse.jgit.lib.CommitBuilder;
  70. import org.eclipse.jgit.lib.Constants;
  71. import org.eclipse.jgit.lib.FileMode;
  72. import org.eclipse.jgit.lib.ObjectId;
  73. import org.eclipse.jgit.lib.ObjectInserter;
  74. import org.eclipse.jgit.lib.ObjectLoader;
  75. import org.eclipse.jgit.lib.ObjectReader;
  76. import org.eclipse.jgit.lib.PersonIdent;
  77. import org.eclipse.jgit.lib.Ref;
  78. import org.eclipse.jgit.lib.RefUpdate;
  79. import org.eclipse.jgit.lib.Repository;
  80. import org.eclipse.jgit.revwalk.RevCommit;
  81. import org.eclipse.jgit.revwalk.RevWalk;
  82. import org.eclipse.jgit.treewalk.TreeWalk;
  83. import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
  84. import org.eclipse.jgit.treewalk.filter.PathFilter;
  85. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  86. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  87. /**
  88. * Storage for recorded push certificates.
  89. * <p>
  90. * Push certificates are stored in a special ref {@code refs/meta/push-certs}.
  91. * The filenames in the tree are ref names followed by the special suffix
  92. * <code>@{cert}</code>, and the contents are the latest push cert affecting
  93. * that ref. The special suffix allows storing certificates for both refs/foo
  94. * and refs/foo/bar in case those both existed at some point.
  95. *
  96. * @since 4.1
  97. */
  98. public class PushCertificateStore implements AutoCloseable {
  99. /** Ref name storing push certificates. */
  100. static final String REF_NAME =
  101. Constants.R_REFS + "meta/push-certs"; //$NON-NLS-1$
  102. private static class PendingCert {
  103. PushCertificate cert;
  104. PersonIdent ident;
  105. Collection<ReceiveCommand> matching;
  106. PendingCert(PushCertificate cert, PersonIdent ident,
  107. Collection<ReceiveCommand> matching) {
  108. this.cert = cert;
  109. this.ident = ident;
  110. this.matching = matching;
  111. }
  112. }
  113. private final Repository db;
  114. private final List<PendingCert> pending;
  115. ObjectReader reader;
  116. RevCommit commit;
  117. /**
  118. * Create a new store backed by the given repository.
  119. *
  120. * @param db
  121. * the repository.
  122. */
  123. public PushCertificateStore(Repository db) {
  124. this.db = db;
  125. pending = new ArrayList<>();
  126. }
  127. /**
  128. * {@inheritDoc}
  129. * <p>
  130. * Close resources opened by this store.
  131. * <p>
  132. * If {@link #get(String)} was called, closes the cached object reader
  133. * created by that method. Does not close the underlying repository.
  134. */
  135. @Override
  136. public void close() {
  137. if (reader != null) {
  138. reader.close();
  139. reader = null;
  140. commit = null;
  141. }
  142. }
  143. /**
  144. * Get latest push certificate associated with a ref.
  145. * <p>
  146. * Lazily opens {@code refs/meta/push-certs} and reads from the repository as
  147. * necessary. The state is cached between calls to {@code get}; to reread the,
  148. * call {@link #close()} first.
  149. *
  150. * @param refName
  151. * the ref name to get the certificate for.
  152. * @return last certificate affecting the ref, or null if no cert was recorded
  153. * for the last update to this ref.
  154. * @throws java.io.IOException
  155. * if a problem occurred reading the repository.
  156. */
  157. public PushCertificate get(String refName) throws IOException {
  158. if (reader == null) {
  159. load();
  160. }
  161. try (TreeWalk tw = newTreeWalk(refName)) {
  162. return read(tw);
  163. }
  164. }
  165. /**
  166. * Iterate over all push certificates affecting a ref.
  167. * <p>
  168. * Only includes push certificates actually stored in the tree; see class
  169. * Javadoc for conditions where this might not include all push certs ever
  170. * seen for this ref.
  171. * <p>
  172. * The returned iterable may be iterated multiple times, and push certs will
  173. * be re-read from the current state of the store on each call to {@link
  174. * Iterable#iterator()}. However, method calls on the returned iterator may
  175. * fail if {@code save} or {@code close} is called on the enclosing store
  176. * during iteration.
  177. *
  178. * @param refName
  179. * the ref name to get certificates for.
  180. * @return iterable over certificates; must be fully iterated in order to
  181. * close resources.
  182. */
  183. public Iterable<PushCertificate> getAll(String refName) {
  184. return new Iterable<PushCertificate>() {
  185. @Override
  186. public Iterator<PushCertificate> iterator() {
  187. return new Iterator<PushCertificate>() {
  188. private final String path = pathName(refName);
  189. private PushCertificate next;
  190. private RevWalk rw;
  191. {
  192. try {
  193. if (reader == null) {
  194. load();
  195. }
  196. if (commit != null) {
  197. rw = new RevWalk(reader);
  198. rw.setTreeFilter(AndTreeFilter.create(
  199. PathFilterGroup.create(
  200. Collections.singleton(PathFilter.create(path))),
  201. TreeFilter.ANY_DIFF));
  202. rw.setRewriteParents(false);
  203. rw.markStart(rw.parseCommit(commit));
  204. } else {
  205. rw = null;
  206. }
  207. } catch (IOException e) {
  208. throw new RuntimeException(e);
  209. }
  210. }
  211. @Override
  212. public boolean hasNext() {
  213. try {
  214. if (next == null) {
  215. if (rw == null) {
  216. return false;
  217. }
  218. try {
  219. RevCommit c = rw.next();
  220. if (c != null) {
  221. try (TreeWalk tw = TreeWalk.forPath(
  222. rw.getObjectReader(), path, c.getTree())) {
  223. next = read(tw);
  224. }
  225. } else {
  226. next = null;
  227. }
  228. } catch (IOException e) {
  229. throw new RuntimeException(e);
  230. }
  231. }
  232. return next != null;
  233. } finally {
  234. if (next == null && rw != null) {
  235. rw.close();
  236. rw = null;
  237. }
  238. }
  239. }
  240. @Override
  241. public PushCertificate next() {
  242. hasNext();
  243. PushCertificate n = next;
  244. if (n == null) {
  245. throw new NoSuchElementException();
  246. }
  247. next = null;
  248. return n;
  249. }
  250. @Override
  251. public void remove() {
  252. throw new UnsupportedOperationException();
  253. }
  254. };
  255. }
  256. };
  257. }
  258. void load() throws IOException {
  259. close();
  260. reader = db.newObjectReader();
  261. Ref ref = db.getRefDatabase().exactRef(REF_NAME);
  262. if (ref == null) {
  263. // No ref, same as empty.
  264. return;
  265. }
  266. try (RevWalk rw = new RevWalk(reader)) {
  267. commit = rw.parseCommit(ref.getObjectId());
  268. }
  269. }
  270. static PushCertificate read(TreeWalk tw) throws IOException {
  271. if (tw == null || (tw.getRawMode(0) & TYPE_FILE) != TYPE_FILE) {
  272. return null;
  273. }
  274. ObjectLoader loader =
  275. tw.getObjectReader().open(tw.getObjectId(0), OBJ_BLOB);
  276. try (InputStream in = loader.openStream();
  277. Reader r = new BufferedReader(
  278. new InputStreamReader(in, UTF_8))) {
  279. return PushCertificateParser.fromReader(r);
  280. }
  281. }
  282. /**
  283. * Put a certificate to be saved to the store.
  284. * <p>
  285. * Writes the contents of this certificate for each ref mentioned. It is up
  286. * to the caller to ensure this certificate accurately represents the state
  287. * of the ref.
  288. * <p>
  289. * Pending certificates added to this method are not returned by
  290. * {@link #get(String)} and {@link #getAll(String)} until after calling
  291. * {@link #save()}.
  292. *
  293. * @param cert
  294. * certificate to store.
  295. * @param ident
  296. * identity for the commit that stores this certificate. Pending
  297. * certificates are sorted by identity timestamp during
  298. * {@link #save()}.
  299. */
  300. public void put(PushCertificate cert, PersonIdent ident) {
  301. put(cert, ident, null);
  302. }
  303. /**
  304. * Put a certificate to be saved to the store, matching a set of commands.
  305. * <p>
  306. * Like {@link #put(PushCertificate, PersonIdent)}, except a value is only
  307. * stored for a push certificate if there is a corresponding command in the
  308. * list that exactly matches the old/new values mentioned in the push
  309. * certificate.
  310. * <p>
  311. * Pending certificates added to this method are not returned by
  312. * {@link #get(String)} and {@link #getAll(String)} until after calling
  313. * {@link #save()}.
  314. *
  315. * @param cert
  316. * certificate to store.
  317. * @param ident
  318. * identity for the commit that stores this certificate. Pending
  319. * certificates are sorted by identity timestamp during
  320. * {@link #save()}.
  321. * @param matching
  322. * only store certs for the refs listed in this list whose values
  323. * match the commands in the cert.
  324. */
  325. public void put(PushCertificate cert, PersonIdent ident,
  326. Collection<ReceiveCommand> matching) {
  327. pending.add(new PendingCert(cert, ident, matching));
  328. }
  329. /**
  330. * Save pending certificates to the store.
  331. * <p>
  332. * One commit is created per certificate added with
  333. * {@link #put(PushCertificate, PersonIdent)}, in order of identity
  334. * timestamps, and a single ref update is performed.
  335. * <p>
  336. * The pending list is cleared if and only the ref update fails, which
  337. * allows for easy retries in case of lock failure.
  338. *
  339. * @return the result of attempting to update the ref.
  340. * @throws java.io.IOException
  341. * if there was an error reading from or writing to the
  342. * repository.
  343. */
  344. public RefUpdate.Result save() throws IOException {
  345. ObjectId newId = write();
  346. if (newId == null) {
  347. return RefUpdate.Result.NO_CHANGE;
  348. }
  349. try (ObjectInserter inserter = db.newObjectInserter()) {
  350. RefUpdate.Result result = updateRef(newId);
  351. switch (result) {
  352. case FAST_FORWARD:
  353. case NEW:
  354. case NO_CHANGE:
  355. pending.clear();
  356. break;
  357. default:
  358. break;
  359. }
  360. return result;
  361. } finally {
  362. close();
  363. }
  364. }
  365. /**
  366. * Save pending certificates to the store in an existing batch ref update.
  367. * <p>
  368. * One commit is created per certificate added with
  369. * {@link #put(PushCertificate, PersonIdent)}, in order of identity
  370. * timestamps, all commits are flushed, and a single command is added to the
  371. * batch.
  372. * <p>
  373. * The cached ref value and pending list are <em>not</em> cleared. If the
  374. * ref update succeeds, the caller is responsible for calling
  375. * {@link #close()} and/or {@link #clear()}.
  376. *
  377. * @param batch
  378. * update to save to.
  379. * @return whether a command was added to the batch.
  380. * @throws java.io.IOException
  381. * if there was an error reading from or writing to the
  382. * repository.
  383. */
  384. public boolean save(BatchRefUpdate batch) throws IOException {
  385. ObjectId newId = write();
  386. if (newId == null || newId.equals(commit)) {
  387. return false;
  388. }
  389. batch.addCommand(new ReceiveCommand(
  390. commit != null ? commit : ObjectId.zeroId(), newId, REF_NAME));
  391. return true;
  392. }
  393. /**
  394. * Clear pending certificates added with {@link #put(PushCertificate,
  395. * PersonIdent)}.
  396. */
  397. public void clear() {
  398. pending.clear();
  399. }
  400. private ObjectId write() throws IOException {
  401. if (pending.isEmpty()) {
  402. return null;
  403. }
  404. if (reader == null) {
  405. load();
  406. }
  407. sortPending(pending);
  408. ObjectId curr = commit;
  409. DirCache dc = newDirCache();
  410. try (ObjectInserter inserter = db.newObjectInserter()) {
  411. for (PendingCert pc : pending) {
  412. curr = saveCert(inserter, dc, pc, curr);
  413. }
  414. inserter.flush();
  415. return curr;
  416. }
  417. }
  418. private static void sortPending(List<PendingCert> pending) {
  419. Collections.sort(pending, new Comparator<PendingCert>() {
  420. @Override
  421. public int compare(PendingCert a, PendingCert b) {
  422. return Long.signum(
  423. a.ident.getWhen().getTime() - b.ident.getWhen().getTime());
  424. }
  425. });
  426. }
  427. private DirCache newDirCache() throws IOException {
  428. if (commit != null) {
  429. return DirCache.read(reader, commit.getTree());
  430. }
  431. return DirCache.newInCore();
  432. }
  433. private ObjectId saveCert(ObjectInserter inserter, DirCache dc,
  434. PendingCert pc, ObjectId curr) throws IOException {
  435. Map<String, ReceiveCommand> byRef;
  436. if (pc.matching != null) {
  437. byRef = new HashMap<>();
  438. for (ReceiveCommand cmd : pc.matching) {
  439. if (byRef.put(cmd.getRefName(), cmd) != null) {
  440. throw new IllegalStateException();
  441. }
  442. }
  443. } else {
  444. byRef = null;
  445. }
  446. DirCacheEditor editor = dc.editor();
  447. String certText = pc.cert.toText() + pc.cert.getSignature();
  448. final ObjectId certId = inserter.insert(OBJ_BLOB, certText.getBytes(UTF_8));
  449. boolean any = false;
  450. for (ReceiveCommand cmd : pc.cert.getCommands()) {
  451. if (byRef != null && !commandsEqual(cmd, byRef.get(cmd.getRefName()))) {
  452. continue;
  453. }
  454. any = true;
  455. editor.add(new PathEdit(pathName(cmd.getRefName())) {
  456. @Override
  457. public void apply(DirCacheEntry ent) {
  458. ent.setFileMode(FileMode.REGULAR_FILE);
  459. ent.setObjectId(certId);
  460. }
  461. });
  462. }
  463. if (!any) {
  464. return curr;
  465. }
  466. editor.finish();
  467. CommitBuilder cb = new CommitBuilder();
  468. cb.setAuthor(pc.ident);
  469. cb.setCommitter(pc.ident);
  470. cb.setTreeId(dc.writeTree(inserter));
  471. if (curr != null) {
  472. cb.setParentId(curr);
  473. } else {
  474. cb.setParentIds(Collections.<ObjectId> emptyList());
  475. }
  476. cb.setMessage(buildMessage(pc.cert));
  477. return inserter.insert(OBJ_COMMIT, cb.build());
  478. }
  479. private static boolean commandsEqual(ReceiveCommand c1, ReceiveCommand c2) {
  480. if (c1 == null || c2 == null) {
  481. return c1 == c2;
  482. }
  483. return c1.getRefName().equals(c2.getRefName())
  484. && c1.getOldId().equals(c2.getOldId())
  485. && c1.getNewId().equals(c2.getNewId());
  486. }
  487. private RefUpdate.Result updateRef(ObjectId newId) throws IOException {
  488. RefUpdate ru = db.updateRef(REF_NAME);
  489. ru.setExpectedOldObjectId(commit != null ? commit : ObjectId.zeroId());
  490. ru.setNewObjectId(newId);
  491. ru.setRefLogIdent(pending.get(pending.size() - 1).ident);
  492. ru.setRefLogMessage(JGitText.get().storePushCertReflog, false);
  493. try (RevWalk rw = new RevWalk(reader)) {
  494. return ru.update(rw);
  495. }
  496. }
  497. private TreeWalk newTreeWalk(String refName) throws IOException {
  498. if (commit == null) {
  499. return null;
  500. }
  501. return TreeWalk.forPath(reader, pathName(refName), commit.getTree());
  502. }
  503. static String pathName(String refName) {
  504. return refName + "@{cert}"; //$NON-NLS-1$
  505. }
  506. private static String buildMessage(PushCertificate cert) {
  507. StringBuilder sb = new StringBuilder();
  508. if (cert.getCommands().size() == 1) {
  509. sb.append(MessageFormat.format(
  510. JGitText.get().storePushCertOneRef,
  511. cert.getCommands().get(0).getRefName()));
  512. } else {
  513. sb.append(MessageFormat.format(
  514. JGitText.get().storePushCertMultipleRefs,
  515. Integer.valueOf(cert.getCommands().size())));
  516. }
  517. return sb.append('\n').toString();
  518. }
  519. }