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

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