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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. * Close resources opened by this store.
  129. * <p>
  130. * If {@link #get(String)} was called, closes the cached object reader created
  131. * by that method. Does not close the underlying repository.
  132. */
  133. public void close() {
  134. if (reader != null) {
  135. reader.close();
  136. reader = null;
  137. commit = null;
  138. }
  139. }
  140. /**
  141. * Get latest push certificate associated with a ref.
  142. * <p>
  143. * Lazily opens {@code refs/meta/push-certs} and reads from the repository as
  144. * necessary. The state is cached between calls to {@code get}; to reread the,
  145. * call {@link #close()} first.
  146. *
  147. * @param refName
  148. * the ref name to get the certificate for.
  149. * @return last certificate affecting the ref, or null if no cert was recorded
  150. * for the last update to this ref.
  151. * @throws IOException
  152. * if a problem occurred reading the repository.
  153. */
  154. public PushCertificate get(String refName) throws IOException {
  155. if (reader == null) {
  156. load();
  157. }
  158. try (TreeWalk tw = newTreeWalk(refName)) {
  159. return read(tw);
  160. }
  161. }
  162. /**
  163. * Iterate over all push certificates affecting a ref.
  164. * <p>
  165. * Only includes push certificates actually stored in the tree; see class
  166. * Javadoc for conditions where this might not include all push certs ever
  167. * seen for this ref.
  168. * <p>
  169. * The returned iterable may be iterated multiple times, and push certs will
  170. * be re-read from the current state of the store on each call to {@link
  171. * Iterable#iterator()}. However, method calls on the returned iterator may
  172. * fail if {@code save} or {@code close} is called on the enclosing store
  173. * during iteration.
  174. *
  175. * @param refName
  176. * the ref name to get certificates for.
  177. * @return iterable over certificates; must be fully iterated in order to
  178. * close resources.
  179. */
  180. public Iterable<PushCertificate> getAll(final String refName) {
  181. return new Iterable<PushCertificate>() {
  182. @Override
  183. public Iterator<PushCertificate> iterator() {
  184. return new Iterator<PushCertificate>() {
  185. private final String path = pathName(refName);
  186. private PushCertificate next;
  187. private RevWalk rw;
  188. {
  189. try {
  190. if (reader == null) {
  191. load();
  192. }
  193. if (commit != null) {
  194. rw = new RevWalk(reader);
  195. rw.setTreeFilter(AndTreeFilter.create(
  196. PathFilterGroup.create(
  197. Collections.singleton(PathFilter.create(path))),
  198. TreeFilter.ANY_DIFF));
  199. rw.setRewriteParents(false);
  200. rw.markStart(rw.parseCommit(commit));
  201. } else {
  202. rw = null;
  203. }
  204. } catch (IOException e) {
  205. throw new RuntimeException(e);
  206. }
  207. }
  208. @Override
  209. public boolean hasNext() {
  210. try {
  211. if (next == null) {
  212. if (rw == null) {
  213. return false;
  214. }
  215. try {
  216. RevCommit c = rw.next();
  217. if (c != null) {
  218. try (TreeWalk tw = TreeWalk.forPath(
  219. rw.getObjectReader(), path, 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. };
  254. }
  255. void load() throws IOException {
  256. close();
  257. reader = db.newObjectReader();
  258. Ref ref = db.getRefDatabase().exactRef(REF_NAME);
  259. if (ref == null) {
  260. // No ref, same as empty.
  261. return;
  262. }
  263. try (RevWalk rw = new RevWalk(reader)) {
  264. commit = rw.parseCommit(ref.getObjectId());
  265. }
  266. }
  267. static PushCertificate read(TreeWalk tw) throws IOException {
  268. if (tw == null || (tw.getRawMode(0) & TYPE_FILE) != TYPE_FILE) {
  269. return null;
  270. }
  271. ObjectLoader loader =
  272. tw.getObjectReader().open(tw.getObjectId(0), OBJ_BLOB);
  273. try (InputStream in = loader.openStream();
  274. Reader r = new BufferedReader(new InputStreamReader(in, UTF_8))) {
  275. return PushCertificateParser.fromReader(r);
  276. }
  277. }
  278. /**
  279. * Put a certificate to be saved to the store.
  280. * <p>
  281. * Writes the contents of this certificate for each ref mentioned. It is up to
  282. * the caller to ensure this certificate accurately represents the state of
  283. * the ref.
  284. * <p>
  285. * Pending certificates added to this method are not returned by {@link
  286. * #get(String)} and {@link #getAll(String)} until after calling {@link
  287. * #save()}.
  288. *
  289. * @param cert
  290. * certificate to store.
  291. * @param ident
  292. * identity for the commit that stores this certificate. Pending
  293. * certificates are sorted by identity timestamp during {@link
  294. * #save()}.
  295. */
  296. public void put(PushCertificate cert, PersonIdent ident) {
  297. put(cert, ident, null);
  298. }
  299. /**
  300. * Put a certificate to be saved to the store, matching a set of commands.
  301. * <p>
  302. * Like {@link #put(PushCertificate, PersonIdent)}, except a value is only
  303. * stored for a push certificate if there is a corresponding command in the
  304. * list that exactly matches the old/new values mentioned in the push
  305. * certificate.
  306. * <p>
  307. * Pending certificates added to this method are not returned by {@link
  308. * #get(String)} and {@link #getAll(String)} until after calling {@link
  309. * #save()}.
  310. *
  311. * @param cert
  312. * certificate to store.
  313. * @param ident
  314. * identity for the commit that stores this certificate. Pending
  315. * certificates are sorted by identity timestamp during {@link
  316. * #save()}.
  317. * @param matching
  318. * only store certs for the refs listed in this list whose values
  319. * match the commands in the cert.
  320. */
  321. public void put(PushCertificate cert, PersonIdent ident,
  322. Collection<ReceiveCommand> matching) {
  323. pending.add(new PendingCert(cert, ident, matching));
  324. }
  325. /**
  326. * Save pending certificates to the store.
  327. * <p>
  328. * One commit is created per certificate added with {@link
  329. * #put(PushCertificate, PersonIdent)}, in order of identity timestamps, and
  330. * a single ref update is performed.
  331. * <p>
  332. * The pending list is cleared if and only the ref update fails, which allows
  333. * for easy retries in case of lock failure.
  334. *
  335. * @return the result of attempting to update the ref.
  336. * @throws IOException
  337. * if there was an error reading from or writing to the
  338. * repository.
  339. */
  340. public RefUpdate.Result save() throws IOException {
  341. ObjectId newId = write();
  342. if (newId == null) {
  343. return RefUpdate.Result.NO_CHANGE;
  344. }
  345. try (ObjectInserter inserter = db.newObjectInserter()) {
  346. RefUpdate.Result result = updateRef(newId);
  347. switch (result) {
  348. case FAST_FORWARD:
  349. case NEW:
  350. case NO_CHANGE:
  351. pending.clear();
  352. break;
  353. default:
  354. break;
  355. }
  356. return result;
  357. } finally {
  358. close();
  359. }
  360. }
  361. /**
  362. * Save pending certificates to the store in an existing batch ref update.
  363. * <p>
  364. * One commit is created per certificate added with {@link
  365. * #put(PushCertificate, PersonIdent)}, in order of identity timestamps, all
  366. * commits are flushed, and a single command is added to the batch.
  367. * <p>
  368. * The cached ref value and pending list are <em>not</em> cleared. If the ref
  369. * update succeeds, the caller is responsible for calling {@link #close()}
  370. * 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 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, new Comparator<PendingCert>() {
  415. @Override
  416. public int compare(PendingCert a, PendingCert b) {
  417. return Long.signum(
  418. a.ident.getWhen().getTime() - b.ident.getWhen().getTime());
  419. }
  420. });
  421. }
  422. private DirCache newDirCache() throws IOException {
  423. if (commit != null) {
  424. return DirCache.read(reader, commit.getTree());
  425. }
  426. return DirCache.newInCore();
  427. }
  428. private ObjectId saveCert(ObjectInserter inserter, DirCache dc,
  429. PendingCert pc, ObjectId curr) throws IOException {
  430. Map<String, ReceiveCommand> byRef;
  431. if (pc.matching != null) {
  432. byRef = new HashMap<>();
  433. for (ReceiveCommand cmd : pc.matching) {
  434. if (byRef.put(cmd.getRefName(), cmd) != null) {
  435. throw new IllegalStateException();
  436. }
  437. }
  438. } else {
  439. byRef = null;
  440. }
  441. DirCacheEditor editor = dc.editor();
  442. String certText = pc.cert.toText() + pc.cert.getSignature();
  443. final ObjectId certId = inserter.insert(OBJ_BLOB, certText.getBytes(UTF_8));
  444. boolean any = false;
  445. for (ReceiveCommand cmd : pc.cert.getCommands()) {
  446. if (byRef != null && !commandsEqual(cmd, byRef.get(cmd.getRefName()))) {
  447. continue;
  448. }
  449. any = true;
  450. editor.add(new PathEdit(pathName(cmd.getRefName())) {
  451. @Override
  452. public void apply(DirCacheEntry ent) {
  453. ent.setFileMode(FileMode.REGULAR_FILE);
  454. ent.setObjectId(certId);
  455. }
  456. });
  457. }
  458. if (!any) {
  459. return curr;
  460. }
  461. editor.finish();
  462. CommitBuilder cb = new CommitBuilder();
  463. cb.setAuthor(pc.ident);
  464. cb.setCommitter(pc.ident);
  465. cb.setTreeId(dc.writeTree(inserter));
  466. if (curr != null) {
  467. cb.setParentId(curr);
  468. } else {
  469. cb.setParentIds(Collections.<ObjectId> emptyList());
  470. }
  471. cb.setMessage(buildMessage(pc.cert));
  472. return inserter.insert(OBJ_COMMIT, cb.build());
  473. }
  474. private static boolean commandsEqual(ReceiveCommand c1, ReceiveCommand c2) {
  475. if (c1 == null || c2 == null) {
  476. return c1 == c2;
  477. }
  478. return c1.getRefName().equals(c2.getRefName())
  479. && c1.getOldId().equals(c2.getOldId())
  480. && c1.getNewId().equals(c2.getNewId());
  481. }
  482. private RefUpdate.Result updateRef(ObjectId newId) throws IOException {
  483. RefUpdate ru = db.updateRef(REF_NAME);
  484. ru.setExpectedOldObjectId(commit != null ? commit : ObjectId.zeroId());
  485. ru.setNewObjectId(newId);
  486. ru.setRefLogIdent(pending.get(pending.size() - 1).ident);
  487. ru.setRefLogMessage(JGitText.get().storePushCertReflog, false);
  488. try (RevWalk rw = new RevWalk(reader)) {
  489. return ru.update(rw);
  490. }
  491. }
  492. private TreeWalk newTreeWalk(String refName) throws IOException {
  493. if (commit == null) {
  494. return null;
  495. }
  496. return TreeWalk.forPath(reader, pathName(refName), commit.getTree());
  497. }
  498. static String pathName(String refName) {
  499. return refName + "@{cert}"; //$NON-NLS-1$
  500. }
  501. private static String buildMessage(PushCertificate cert) {
  502. StringBuilder sb = new StringBuilder();
  503. if (cert.getCommands().size() == 1) {
  504. sb.append(MessageFormat.format(
  505. JGitText.get().storePushCertOneRef,
  506. cert.getCommands().get(0).getRefName()));
  507. } else {
  508. sb.append(MessageFormat.format(
  509. JGitText.get().storePushCertMultipleRefs,
  510. Integer.valueOf(cert.getCommands().size())));
  511. }
  512. return sb.append('\n').toString();
  513. }
  514. }