# HG changeset patch # User Paul Crowley # Date 1292609971 0 # Node ID 7bae88583a537f51d36d902d03ca8d501819352c # Parent 9f7ad3a71c906bcd6bf09420b554199c5b66f052# Parent f7c64f03cd607f0f814ae48016db2e0aed73a88b Merge in testing code diff -r f7c64f03cd60 -r 7bae88583a53 .hgignore --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.hgignore Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,9 @@ +^build/ +^dev/chroot-test/build/ + +syntax: glob + +*~ +*.pyc +*.orig +*.rej diff -r f7c64f03cd60 -r 7bae88583a53 .hgtags --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.hgtags Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,7 @@ +535502c18eaad098437e49adea1e26a68e4b6d75 release_0.5 +975fb921c3f3ffe7ccde5877f2954a5d1141bb14 release_0.6 +243dd21d0dbc140957afbe7c9e2afb9caaffee37 release_0.7 +1ad9d5841a48a77f68dc5350bd1f941327a6348a release_0.8 +fed42d3f5311c55cab668d6962a61d44ba98645e release_0.9 +8ce190faa5c2b50f63cc5b11e28daf98836498d8 release_1.0 +92cb6640a6417edaf52870c8a97000e11bb8b138 release_1.0.1 diff -r f7c64f03cd60 -r 7bae88583a53 CREDITS --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/CREDITS Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,24 @@ +mercurial-server is by Paul Crowley + +Thanks to: + +Thomas Arendsen Hein +Mathieu PASQUET +Vadim Gelfer +Hubert Plociniczak +Christoph Junghans +Steve Kemp +Cédric Boutillier +Justin B Rye +Wolfgang Karall +Helge Kreutzmann +"Hideki Yamane \(Debian-JP\)" +Michal Simunek +Martin Bagge +Vincenzo Campanella +Ji ZhengYu +Waldemar Augustyn +Steven King + +This credits file may be incomplete - please remind me about people I +should add! diff -r f7c64f03cd60 -r 7bae88583a53 LICENSE --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/LICENSE Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff -r f7c64f03cd60 -r 7bae88583a53 Makefile --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Makefile Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,68 @@ +#!/usr/bin/env make -f + +PREFIX=/usr/local/share +LIBDIR=$(PREFIX)/mercurial-server +DOCDIR=$(PREFIX)/doc/mercurial-server +ETCDIR=/etc/mercurial-server +NEWUSER=hg +DOCBOOK_XSL=/usr/share/xml/docbook/stylesheet/nwalsh + +INSTALL=install + +build: build/html/index.html pythonbuild + +setup-adduser: installfiles adduser inituser + +# WARNING: this is experimental +setup-useradd: installfiles useradd inituser + +installetc: + $(INSTALL) -d $(DESTDIR)$(ETCDIR) + $(INSTALL) -m 644 -t $(DESTDIR)$(ETCDIR) \ + src/init/conf/access.conf + $(INSTALL) -d $(DESTDIR)$(ETCDIR)/remote-hgrc.d + $(INSTALL) -m 644 -t $(DESTDIR)$(ETCDIR)/remote-hgrc.d \ + src/init/conf/remote-hgrc.d/access.rc \ + src/init/conf/remote-hgrc.d/logging.rc + $(INSTALL) -d $(DESTDIR)$(ETCDIR)/keys/root + $(INSTALL) -d $(DESTDIR)$(ETCDIR)/keys/users + +installdoc: build/html/index.html + $(INSTALL) -d $(DESTDIR)$(DOCDIR) + $(INSTALL) -m 644 -t $(DESTDIR)$(DOCDIR) README + $(INSTALL) -d $(DESTDIR)$(DOCDIR)/html + $(INSTALL) -m 644 -t $(DESTDIR)$(DOCDIR)/html build/html/index.html + +build/html/index.html: doc/manual.docbook + xsltproc --nonet -o $@ $(DOCBOOK_XSL)/html/docbook.xsl $^ + +build/pdf/manual.pdf: doc/manual.docbook + mkdir -p build/pdf + fop -xml $^ -xsl $(DOCBOOK_XSL)/fo/docbook.xsl $@ + +pythonbuild: + python setup.py build + +pythoninstall: + python setup.py install \ + --install-purelib=$(DESTDIR)$(LIBDIR) \ + --install-platlib=$(DESTDIR)$(LIBDIR) \ + --install-scripts=$(DESTDIR)$(LIBDIR) \ + --install-data=$(DESTDIR)$(LIBDIR) + +installfiles: installetc installdoc pythoninstall + +adduser: + adduser --system --shell /bin/sh --group --disabled-password \ + --home /var/lib/mercurial-server \ + --gecos "Mercurial repositories" $(NEWUSER) + +# WARNING: this is experimental +useradd: + useradd --system --shell /bin/sh \ + --home /var/lib/mercurial-server --create-home \ + --comment "Mercurial repositories" $(NEWUSER) + +inituser: + su -l -c "$(DESTDIR)$(LIBDIR)/init/hginit $(DESTDIR)$(LIBDIR)" $(NEWUSER) + diff -r f7c64f03cd60 -r 7bae88583a53 NEWS --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/NEWS Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,89 @@ +====================== +mercurial-server 1.1 +====================== + +* New log filename +* Changed logging format to use JSON/YAML +* Add the source IP address and other info in the SSH_CONNECTION environment variable +* Lock log file +* Make sure authorized_keys file is mode 600 + +Upgrading: note the changes to the log file format listed above. + +====================== +mercurial-server 1.0.1 +====================== + +* Fix HGRCPATH brokenness - potential security issue +* Fix rule matching to properly handle the case where we don't know for sure +* Fix error in documentation +* Remove whitespace around paths, said to help with TortoiseHG +* Small refactor of access.py +* Tidy up file prologues; move credits to CREDITS + +Upgrading: repositories whose paths begin or end in white space will no longer +be accessible; if they exist they must be moved to new names. + +==================== +mercurial-server 1.0 +==================== + +* Add "env" section to .mercurial-server instead of special-casing HGRCPATH +* Switch to remote-hgrc.d directory instead of single file. +* Control path of authorized keys file in .mercurial_server +* Overwrite $HOME with value from /etc/passwd +* Use Python's ConfigParser instead of too-new mercurial.config +* Fix very out-of-date comments in hg-ssh +* Belatedly added NEWS file :-) + +Upgrading: move the paths/hgrc entry in .mercurial-server to env/HGRCPATH, +and add an entry under paths that reads +"authorized_keys = ~/.ssh/authorized_keys" + +==================== +mercurial-server 0.9 +==================== + +* Switch to supporting DESTDIR prefix in Makefile for easier packaging + +==================== +mercurial-server 0.8 +==================== + +* Remove .deb-specific stuff in Docbook documentation - let the README + handle that stuff. Also fixes bad version numbers in there. +* Move html docs into subdirectory +* Line wrap README + +==================== +mercurial-server 0.7 +==================== + +* Introduce .mercurial-server file for hg user +* Remove all restrictions on paths, except for dotfiles in repo paths +* Automatically create containing dirs for subdir repos +* Guard against repos in repos +* Switch to Makefile/setup.py based installer +* Switch to Docbook based documentation +* Load purge extension for hgadmin repo +* Guard against setting up hg user who already has .ssh/authorized_keys +* Link to real home page + +Upgrading: you'll need to create a .mercurial-server file +for the hg user - a suitable one is in the init directory. + +==================== +mercurial-server 0.6 +==================== + +* Remove hardcoding of init file path in hginit +* Switch from /usr/lib to /usr/share +* Install documentation +* Don't create "hg" user if install root is not root. + +==================== +mercurial-server 0.5 +==================== + +* First numbered release + diff -r f7c64f03cd60 -r 7bae88583a53 README --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/README Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,44 @@ +mercurial-server + +mercurial-server gives your developers remote read/write access to +centralized Mercurial repositories using SSH public key authentication; it +provides convenient and fine-grained key management and access control. + +http://www.lshift.net/mercurial-server.html + +Copyright (C) 2008-2010 LShift Ltd. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Though mercurial-server is currently targeted at Debian-based systems such +as Ubuntu, other users have reported success getting it running on other +Unix-based systems such as Red Hat. Running it on a non-Unix system such as +Windows is not supported. You will need root privileges to install it. + +The best way to install mercurial-server is using your package management +system - there are pre-built .deb files on the website. However, there is +some provision for installing it directly. On Debian based systems such as +Ubuntu, use the command + + sudo make setup-adduser + +On Red Hat and possibly other variants of Unix, try + + sudo make setup-useradd + +See doc/manual.docbook for the rest of the documentation. + +Paul Crowley, paul@lshift.net, 2010 + diff -r f7c64f03cd60 -r 7bae88583a53 dev/chroot-test/.hgignore --- a/dev/chroot-test/.hgignore Fri Dec 17 18:16:08 2010 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,7 +0,0 @@ -^build/ -syntax: glob - -*~ -*.pyc -*.orig -*.rej diff -r f7c64f03cd60 -r 7bae88583a53 doc/manual.docbook --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/doc/manual.docbook Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,535 @@ + +
+ + Sharing Mercurial repositories with mercurial-server + PaulCrowley + 2008-2010Paul Crowley, LShift Ltd + +
+About mercurial-server + +Home page: + + +mercurial-server gives your developers remote read/write access to +centralized Mercurial +repositories using SSH public key authentication; it provides convenient +and fine-grained key management and access control. + + +Though mercurial-server is currently targeted at Debian-based systems such +as Ubuntu, other users have reported success getting it running on other +Unix-based systems such as Red Hat. Running it on a non-Unix system such as +Windows is not supported. You will need root privileges to install it. + +
+
+Step by step + +mercurial-server authenticates users not using passwords but using SSH +public keys; everyone who wants access to a mercurial-server repository +will need such a key. In combination with ssh-agent (or +equivalents such as the Windows program Pageant), +this means that users will not need to type in a password to access the +repository. If you're not familiar with SSH public keys, the OpenSSH Public +Key Authentication tutorial may be helpful. + +
+Initial access to mercurial-server + +In what follows, we assume that your username is jay, that you usually sit at a machine called +spoon and you have +installed mercurial-server on jeeves using the package management system (see the README for more on installation). We assume that you have created your SSH public key, set up your SSH agent with this key, and that this key gives you access to jeeves. + +jay@spoon:~$ ssh -A jeeves +jay@jeeves:~$ ssh-add -L > my-key +jay@jeeves:~$ sudo mkdir -p /etc/mercurial-server/keys/root/jay +jay@jeeves:~$ sudo cp my-key /etc/mercurial-server/keys/root/jay/spoon +jay@jeeves:~$ sudo -u hg /usr/share/mercurial-server/refresh-auth +jay@jeeves:~$ exit +Connection to jeeves closed. +jay@spoon:~$ + +You can now create repositories on the remote machine and have complete +read-write access to all of them. + +
+
+Creating repositories + +To store a repository on the server, clone it over. + +jay@spoon:~$ cd myproj +jay@spoon:~/myproj$ hg clone . ssh://hg@jeeves/jays/project +searching for changes +remote: adding changesets +remote: adding manifests +remote: adding file changes +remote: added 119 changesets with 284 changes to 61 files +jay@spoon:~/myproj$ hg pull ssh://hg@jeeves/jays/project +pulling from ssh://hg@jeeves/jays/project +searching for changes +no changes found +jay@spoon:~/myproj$ cd .. +jay@spoon:~$ +
+
+Adding other users + +At this stage, no-one but you has any access to any repositories you +create on this system. In order to give anyone else access, you'll need a +copy of their SSH public key; we'll assume you have that key in +~/sam-saucer-key.pub. To manage access, you make changes to the special hgadmin repository. + +jay@spoon:~$ hg clone ssh://hg@jeeves/hgadmin +destination directory: hgadmin +no changes found +updating working directory +0 files updated, 0 files merged, 0 files removed, 0 files unresolved +jay@spoon:~$ cd hgadmin +jay@spoon:~/hgadmin$ mkdir -p keys/users/sam +jay@spoon:~/hgadmin$ cp ~/sam-saucer-key.pub keys/users/sam/saucer +jay@spoon:~/hgadmin$ hg add +adding keys/users/sam/saucer +jay@spoon:~/hgadmin$ hg commit -m "Add Sam's key" +jay@spoon:~/hgadmin$ hg push +pushing to ssh://hg@jeeves/hgadmin +searching for changes +remote: adding changesets +remote: adding manifests +remote: adding file changes +remote: added 1 changesets with 1 changes to 1 files +jay@spoon:~/hgadmin$ + +Sam can now read and write to your +ssh://hg@jeeves/jays/project repository. +Most other changes to access control can be made simply by making and +pushing changes to hgadmin, and you can use Mercurial to +cooperate with other root users in the normal way. + + +If you prefer, you could give them access by +logging into jeeves, +putting the key in the right place under /etc/mercurial-server/keys, and re-running +sudo -u hg /usr/share/mercurial-server/refresh-auth. +However, using hgadmin is usually more convenient if you need to make more than a very few changes; it also makes it easier to share administration with others and provides a log of all changes. + +
+
+
+Access control + +Out of the box, mercurial-server supports two kinds of users: "root" users and normal users. If you followed the steps above, you are a "root" user because your key is under keys/root, while the other user you gave access to is a normal user since their key is under keys/users. Keys that are not in either of these directories will by default have no access to anything. + + +Root users can edit hgadmin, create new repositories and read and write to existing ones. Normal users cannot access hgadmin or create new repositories, but they can read and write to any other repository. + +
+Using access.conf + +mercurial-server offers much more fine-grained access control than this division into two classes of users. Let's suppose you wish to give Pat access to the widget repository, but no other. We first copy Pat's SSH public key into the keys/pat directory in hgadmin. This tells mercurial-server about Pat's key, but gives Pat no access to anything because the key is not under either keys/root or keys/users. To grant this key access, we must give mercurial-server a new access rule, so we create a file in hgadmin called access.conf, with the following contents: +# Give Pat access to the "widget" repository +write repo=widget user=pat/* + + +Pat will have read and write access to the widget repository as soon as we add, commit, and push these files. + + +Each line of access.conf has the following syntax: + +rule condition condition... + + +Blank lines and lines that start with # are ignored. Rule is +one of + + + +init: allow reads, writes, and the creation of new repositories + + +write: allow reads and writes + + +read: allow only read operations + + +deny: deny all requests + + + +A condition is a globpattern matched against a relative path. The two most +important conditions are + + + +user=globpattern: path to the user's key + + +repo=globpattern: path to the repository + + + +* only matches one directory level, where ** +matches as many as you want. More precisely, * matches zero or +more characters not including / while ** matches +zero or more characters including /. So +projects/* matches projects/foo but not projects/foo/bar, while +projects/** matches both. + + +When considering a request, mercurial-server steps through all the rules in +/etc/mercurial-server/access.conf and then all the +rules in access.conf in hgadmin +looking for a rule which matches on every condition. The first match +determines whether the request will be allowed; if there is no match in +either file, the request will be denied. + + +By default, /etc/mercurial-server/access.conf has the +following rules: + +init user=root/** +deny repo=hgadmin +write user=users/** + + +These rules ensure that root users can do any operation on any repository, +that no other users can access the hgadmin repository, +and that those with keys in keys/users can read or write to any repository +but not create repositories. Some examples of how these rules work: + + + +User root/jay creates a repository +foo/bar/baz. This matches the first +rule and so will be allowed. + + +User root/jay changes repository +hgadmin. Again, this matches the +first rule and so will be allowed; later rules have no effect. + + +User users/sam tries to read +repository hgadmin. This does not +match the first rule, but matches the second, and so will be denied. + + +User users/sam tries to create +repository sams-project. This does +not match the first two rules, but matches the third; this is a +write rule, which doesn't grant the privilege to create +repositories, so the request will be denied. + + +User users/sam writes to existing +repository projects/main. Again, +this matches the third rule, which allows the request. + + +User pat tries to write to existing +repository widget. Until we change +the access.conf file in hgadmin, this will match no rule, and so will +be denied. + + +Any request from a user whose key not under the keys directory at all will always be denied, +no matter what rules are in effect; because of the way SSH authentication +works, they will be prompted to enter a password, but no password will +work. This can't be changed. + + +
+
+/etc/mercurial-server and hgadmin + +mercurial-server consults two distinct locations to collect information about what to allow: /etc/mercurial-server and its own hgadmin repository. This is useful for several reasons: + + + +Some users may not need the convenience of access control via mercurial; for these users updating /etc/mercurial-server may offer a simpler route. + + +/etc/mercurial-server is suitable +for management with tools such as Puppet + + +If a change to hgadmin leaves you "locked out", /etc/mercurial-server allows you a way back in. + + +At install time, all users are "locked out", and so some mechanism to allow some users in is needed. + + + +Rules in /etc/mercurial-server/access.conf are checked before those in hgadmin, and keys in /etc/mercurial-server/keys will be present no matter how hgadmin changes. + + +We anticipate that once mercurial-server is successfully installed and +working you will usually want to use hgadmin for most +access control tasks. Once you have the right keys and +access.conf set up in hgadmin, you +can delete /etc/mercurial-server/access.conf and all +of /etc/mercurial-server/keys, +turning control entirely over to hgadmin. + + +/etc/mercurial-server/remote-hgrc.d is in the +HGRCPATH for all remote access to mercurial-server +repositories. This directory contains the hooks that mercurial-server uses for +access control and logging. You can add hooks to this directory, but obviously +breaking the existing hooks will disable the relevant functionality and +isn't advisable. + +
+
+File and branch conditions + +mercurial-server supports file and branch conditions, which restrict an +operation depending on what files it modifies and what branch the work is +on. + +The way these conditions work is subtle and can be counterintuitive. Unless +you need what they provide, ignore this section, stick to user and repo +conditions, and then things are likely to work the way you would expect. If +you do need what they provide, read what follows very carefully. + + +File and branch conditions are added to the conditions against which a rule +matches, just like user and repo conditions; they have this form: + + + +file=globpattern: file within the repo + + +branch=globpattern: Mercurial branch name + + + +However, in order to understand what effect adding these conditions will +have, it helps to understand how and when these rules are applied. + + +The rules file is used to make three decisions: + + + +Whether to allow a repository to be created + + +Whether to allow any access to a repository + + +Whether to allow a changeset + + + +When the first two of these decisions are being made, nothing is known +about any changsets that might be pushed, and so all file and branch +conditions automatically succeed for the purpose of such decisions. For the +third condition, every file changed in the changeset must be allowed by a +write or init rule for the changeset +to be allowed. + + +This means that doing tricky things with file conditions can have +counterintuitive consequences: + + + +You cannot limit read access to a subset of a repository with a read +rule and a file condition: any user who has access to a repository can read +all of it and its full history. Such a rule can only have the effect of +masking a later write rule, as in this example: +read repo=specialrepo file=dontwritethis +write repo=specialrepo + + +allows all users to read specialrepo, and to write to all files +except that any changeset which writes to +dontwritethis will be rejected. + + + +For similar reasons, don't give init rules file conditions. + + +Don't try to deny write access to a particular file on a particular +branch—a developer can write to the file on another branch and then merge +it in. Either deny all writes to the branch from that user, or allow them +to write to all the files they can write to on any branch. + +write user=docs/* branch=docs file=docs/* + + +This rule grants users whose keys are in the docs subdirectory the power to push changesets +into any repository only if those changesets are on the +docs branch and they affect only those files directly +under the docs directory. However, +the rules below have more counterintuitive consequences. + +write user=docs/* branch=docs +write user=docs/* file=docs/* +read user=docs/* + + +These rules grant users whose keys are in the docs subdirectory the power to change any file directly under the docs directory, or any file at all in the docs branch. Indirectly, however, this adds up to the power to change any file on any branch, simply by making the change on the docs branch and then merging the change into another branch. + + + +
+
+
+In detail +
+How mercurial-server works + +All of the repositories controlled by mercurial-server are owned by a +single user, the hg user, which is why all URLs for +mercurial-server repositories start with ssh://hg@.... +Each SSH key that has access to the repository has an entry in +~hg/.ssh/authorized_keys; this is how the SSH daemon +knows to give that key access. When the user connects over SSH, their +commands are run in a custom restricted shell; this shell knows which key +was used to connect, determines what the user is trying to do, checks the +access rules to decide whether to allow it, and if allowed invokes +Mercurial internally, without forking. + + +This restricted shell also ensures that certain Mercurial extensions are +loaded when the user acts on a repository; these extensions check the +access control rules for any changeset that the user tries to commit, and +log all pushes and pulls into a per-repository access log. + + +refresh-auth recurses through the /etc/mercurial-server/keys and the keys directory in the +hgadmin repository, creating an entry in +~hg/.ssh/authorized_keys for each one. This is redone +automatically whenever a change is pushed to hgadmin. + +
+
+Security + +mercurial-server relies entirely on sshd to grant access to remote users. +As a result, it runs no daemons, installs no setuid programs, and no part +of it runs as root except the install process: all programs run as the user +hg. Any attack on mercurial-server can only be started if the attacker +already has a public key in ~hg/.ssh/authorized_keys, +otherwise sshd will bar the way. + + +No matter what command the user tries to run on the remote system via SSH, +mercurial-server is run. It parses the command line the user asked for, and +interprets and runs the corresponding operation itself if access is +allowed, so users can only read and add to history within repositories; +they cannot run any other command. In addition, every push and pull is +logged with a datestamp, changeset ID and the key that performed the +operation. + + +However, while the first paragraph holds no matter what bugs +mercurial-server contains, the second depends on the relevant code being +correct; though the entire codebase is short, like all software mercurial-server may harbour bugs. Backups are essential! + +
+
+Logging + +Every successful access is logged in a file called +~hg/repos/repository/.hg/mercurial-server.log. This file is in YAML format for easy parsing, but if you don't like YAML, simply treat each line as a JSON data structure prepended with - . The log records the time as a +UTC ISO 8601 time, the operation ("push" or "pull"), the path to the key as +used in the access rules, the SSH connection information (including the source IP address), and the hex changeset IDs. + +
+
+Paths and configuration + +For security reasons, all mercurial-server code runs as the hg user. The first thing this code reads when it starts is ~hg/.mercurial-server; if this file is absent or corrupt the code won't run. This file specifies all of the file paths that mercurial-server uses. In particular, it specifies that mercurial-server always uses HGRCPATH = /etc/mercurial-server/remote-hgrc.d for remote operations, overriding any system HGRCPATH. + + +By creating such a file with suitable entries, you can run mercurial-server as a user other than hg, or install it without root privileges; however I strongly recommend that if you need to do this, you use a user account that is used for no other purpose, and take the time to thoroughly understand how mercurial-server works before you attempt it. + +
+
+License + +This program is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License as published by the Free +Software Foundation; either version 2 of the License, or (at your option) +any later version. + + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +more details. + + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., 51 +Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +
+
+Thanks + +Thanks for reading this far. If you use mercurial-server, please tell me about +it. + + +Paul Crowley, paul@lshift.net, 2010 + +
+
+
+ diff -r f7c64f03cd60 -r 7bae88583a53 setup.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/setup.py Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,23 @@ +# WARNING: this file is NOT meant to be directly executed, but +# run from the Makefile. + +from distutils.core import setup + +setup( + name="mercurial-server", + description="Centralized Mercurial repository manager", + url="http://www.lshift.net/mercurial-server.html", + version="1.1", # FIXME: infer this + package_dir = {'': 'src'}, + packages = ["mercurialserver"], + requires = ["mercurial"], # FIXME: what version? + scripts = ['src/hg-ssh', 'src/refresh-auth'], + data_files = [ + ('init', [ + 'src/init/hginit', + 'src/init/dot-mercurial-server', + 'src/init/hgadmin-hgrc' + ]), + ], +) + diff -r f7c64f03cd60 -r 7bae88583a53 src/hg-ssh --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/hg-ssh Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,97 @@ +#!/usr/bin/env python + +""" +hg-ssh - limit access to hg repositories reached via ssh. Part of +mercurial-server. + +It is called by ssh due to an entry in the authorized_keys file, +with the name for the key passed on the command line. + +It uses SSH_ORIGINAL_COMMAND to determine what the user was trying to +do and to what repository, and then checks each rule in the rule file +in turn for a matching rule which decides what to do, defaulting to +disallowing the action. + +""" + +# enable importing on demand to reduce startup time +from mercurial import demandimport; demandimport.enable() + +from mercurial import dispatch + +import sys, os, os.path +import base64 +from mercurialserver import config, ruleset + +def fail(message): + sys.stderr.write("mercurial-server: %s\n" % message) + sys.exit(-1) + +def checkDots(path): + head, tail = os.path.split(path) + if tail.startswith("."): + fail("paths cannot contain dot file components") + if head: + checkDots(head) + +def checkParents(path): + path = os.path.dirname(path) + if path == "": + return + if os.path.exists(path + "/.hg"): + fail("Cannot create repo under existing repo") + checkParents(path) + +def getrepo(op, repo): + # First canonicalise, then check the string, then the rules + # and finally the filesystem. + repo = repo.strip().rstrip("/") + if len(repo) == 0: + fail("path to repository seems to be empty") + if repo.startswith("/"): + fail("absolute paths are not supported") + checkDots(repo) + ruleset.rules.set(repo=repo) + if not ruleset.rules.allow(op, branch=None, file=None): + fail("access denied") + checkParents(repo) + return repo + +config.initExe() + +for k,v in config.getEnv(): + os.environ[k.upper()] = v + +if len(sys.argv) == 3 and sys.argv[1] == "--base64": + ruleset.rules.set(user = base64.b64decode(sys.argv[2])) +elif len(sys.argv) == 2: + ruleset.rules.set(user = sys.argv[1]) +else: + fail("hg-ssh wrongly called, is authorized_keys corrupt? (%s)" + % sys.argv) + +os.chdir(config.getReposPath()) + +for f in config.getAccessPaths(): + if os.path.isfile(f): + ruleset.rules.readfile(f) + +cmd = os.environ.get('SSH_ORIGINAL_COMMAND', None) +if cmd is None: + fail("direct logins on the hg account prohibited") +elif cmd.startswith('hg -R ') and cmd.endswith(' serve --stdio'): + repo = getrepo("read", cmd[6:-14]) + if not os.path.isdir(repo + "/.hg"): + fail("no such repository %s" % repo) + dispatch.dispatch(['-R', repo, 'serve', '--stdio']) +elif cmd.startswith('hg init '): + repo = getrepo("init", cmd[8:]) + if os.path.exists(repo): + fail("%s exists" % repo) + d = os.path.dirname(repo) + if d != "" and not os.path.isdir(d): + os.makedirs(d) + dispatch.dispatch(['init', repo]) +else: + fail("illegal command %r" % cmd) + diff -r f7c64f03cd60 -r 7bae88583a53 src/init/conf/access.conf --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/init/conf/access.conf Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,3 @@ +init user=root/** +deny repo=hgadmin +write user=users/** diff -r f7c64f03cd60 -r 7bae88583a53 src/init/conf/remote-hgrc.d/access.rc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/init/conf/remote-hgrc.d/access.rc Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,5 @@ +# Check that a commit meets access control rules before allowing it + +[hooks] +pretxnchangegroup.access = python:mercurialserver.access.hook + diff -r f7c64f03cd60 -r 7bae88583a53 src/init/conf/remote-hgrc.d/logging.rc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/init/conf/remote-hgrc.d/logging.rc Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,5 @@ +# Log every push and pull to the servelog + +[hooks] +changegroup.aaaaa_servelog = python:mercurialserver.servelog.hook +outgoing.aaaaa_servelog = python:mercurialserver.servelog.hook diff -r f7c64f03cd60 -r 7bae88583a53 src/init/dot-mercurial-server --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/init/dot-mercurial-server Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,15 @@ +# WARNING: a .mercurial-server file in your home directory means +# that refresh-auth can and will trash your ~/.ssh/authorized_keys file. + +[paths] +repos = ~/repos +authorized_keys = ~/.ssh/authorized_keys +keys = /etc/mercurial-server/keys:~/repos/hgadmin/keys +access = /etc/mercurial-server/access.conf:~/repos/hgadmin/access.conf + +[env] +# Use a different hgrc for remote pulls - this way you can set +# up access.py for everything at once without affecting local operations + +HGRCPATH = /etc/mercurial-server/remote-hgrc.d + diff -r f7c64f03cd60 -r 7bae88583a53 src/init/hgadmin-hgrc --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/init/hgadmin-hgrc Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,10 @@ +# WARNING: when these hooks run they will entirely destroy and rewrite +# ~/.ssh/authorized_keys + +[extensions] +hgext.purge = + +[hooks] +changegroup.aaaab_update = hg update -C default > /dev/null +changegroup.aaaac_purge = hg purge --all > /dev/null +changegroup.refreshauth = python:mercurialserver.refreshauth.hook diff -r f7c64f03cd60 -r 7bae88583a53 src/init/hginit --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/init/hginit Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,17 @@ +#!/bin/sh + +set -e + +cd + +if [ -e .ssh/authorized_keys ] ; then + echo "This user already exists with authorized keys, aborting" + exit -1 +fi + +cp $1/init/dot-mercurial-server .mercurial-server +mkdir -p repos/hgadmin .ssh +cd repos/hgadmin +hg init . +cp $1/init/hgadmin-hgrc .hg/hgrc + diff -r f7c64f03cd60 -r 7bae88583a53 src/mercurialserver/__init__.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/mercurialserver/__init__.py Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,1 @@ + diff -r f7c64f03cd60 -r 7bae88583a53 src/mercurialserver/access.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/mercurialserver/access.py Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,28 @@ +"""Mercurial access control hook""" + +from mercurial.i18n import _ +import mercurial.util +import mercurial.node + +import os +from mercurialserver import ruleset +from mercurialserver import changes + +def allow(ctx): + branch = ctx.branch() + if not ruleset.rules.allow("write", branch=branch, file=None): + return False + for f in ctx.files(): + if not ruleset.rules.allow("write", branch=branch, file=f): + return False + return True + +def hook(ui, repo, hooktype, node=None, source=None, **kwargs): + if hooktype != 'pretxnchangegroup': + raise mercurial.util.Abort(_('config error - hook type "%s" cannot stop ' + 'incoming changesets') % hooktype) + for ctx in changes.changes(repo, node): + if not allow(ctx): + raise mercurial.util.Abort(_('%s: access denied for changeset %s') % + (__name__, mercurial.node.short(ctx.node()))) + diff -r f7c64f03cd60 -r 7bae88583a53 src/mercurialserver/changes.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/mercurialserver/changes.py Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,12 @@ +""" +Find all the changes in a node in a way portable across Mercurial versions +""" + +def changes(repo, node): + start = repo.changectx(node).rev() + try: + end = len(repo.changelog) + except: + end = repo.changelog.count() + for rev in xrange(start, end): + yield repo.changectx(rev) diff -r f7c64f03cd60 -r 7bae88583a53 src/mercurialserver/config.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/mercurialserver/config.py Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,52 @@ +""" +Fix $HOME and read ~/.mercurial-server +""" + +import sys +import os +import os.path +import pwd +import ConfigParser + +globalconfig = None + +def _getConf(): + global globalconfig + if globalconfig is None: + globalconfig = ConfigParser.RawConfigParser() + globalconfig.read(os.path.expanduser("~/.mercurial-server")) + return globalconfig + +def _getPath(name): + return os.path.expanduser(_getConf().get("paths", name)) + +def _getPaths(name): + return [os.path.expanduser(p) + for p in _getConf().get("paths", name).split(":")] + +def getReposPath(): return _getPath("repos") +def getAuthorizedKeysPath(): return _getPath("authorized_keys") + +def configExists(): + try: + getAuthorizedKeysPath() + return True + except Exception, e: + print e + return False + +def getKeysPaths(): return _getPaths("keys") +def getAccessPaths(): return _getPaths("access") + +def getEnv(): return _getConf().items("env") + +# Work out where we are, don't use config. +def initExe(): + global _exePath + _exePath = os.path.dirname(os.path.abspath(sys.argv[0])) + # Fix $HOME in case of "sudo -u hg refresh-auth" + os.environ['HOME'] = pwd.getpwuid(os.geteuid()).pw_dir + +def getExePath(): + return _exePath + diff -r f7c64f03cd60 -r 7bae88583a53 src/mercurialserver/refreshauth.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/mercurialserver/refreshauth.py Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,63 @@ +""" +Rewrite ~/.ssh/authorized_keys by recursing through key directories +""" + +import re +import base64 +import os, stat +import os.path +import subprocess +from mercurialserver import config + +goodkey = re.compile("[/A-Za-z0-9._-]+$") + +def refreshAuth(): + akeyfile = config.getAuthorizedKeysPath() + wrappercommand = config.getExePath() + "/hg-ssh" + prefix='no-pty,no-port-forwarding,no-X11-forwarding,no-agent-forwarding,command=' + + if os.path.exists(akeyfile): + f = open(akeyfile) + try: + for l in f: + if not l.startswith(prefix): + raise Exception("Safety check failed, delete %s to continue" % akeyfile) + finally: + f.close() + + akeys = open(akeyfile + "_new", "w") + for keyroot in config.getKeysPaths(): + kr = keyroot + "/" + #print "Processing keyroot", keyroot + for root, dirs, files in os.walk(keyroot): + for fn in files: + ffn = os.path.join(root, fn) + if not ffn.startswith(kr): + raise Exception("Inconsistent behaviour in os.walk, bailing") + #print "Processing file", ffn + keyname = ffn[len(kr):] + if not goodkey.match(keyname): + # Encode it for safe quoting + keyname = "--base64 " + base64.b64encode(keyname) + p = subprocess.Popen(("ssh-keygen", "-i", "-f", ffn), + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + newkey = p.communicate()[0] + if p.wait() == 0: + klines = [l.strip() for l in newkey.split("\n")] + else: + # Conversion failed, read it directly. + kf = open(ffn) + try: + klines = [l.strip() for l in kf] + finally: + kf.close() + for l in klines: + if len(l): + akeys.write('%s"%s %s" %s\n' % (prefix, wrappercommand, keyname, l)) + akeys.close() + os.chmod(akeyfile + "_new", stat.S_IRUSR) + os.rename(akeyfile + "_new", akeyfile) + +def hook(ui, repo, hooktype, node=None, source=None, **kwargs): + refreshAuth() + diff -r f7c64f03cd60 -r 7bae88583a53 src/mercurialserver/ruleset.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/mercurialserver/ruleset.py Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,86 @@ +""" +Glob-based, order-based rules matcher that can answer "maybe" +where the inputs make clear that something is unknown. +""" + +import sys +import re +import os +import os.path + +def globmatcher(pattern): + p = "[^/]*".join(re.escape(c) for c in pattern.split("*")) + # ** means "match recursively" ie "ignore directories" + return re.compile(p.replace("[^/]*[^/]*", ".*") + "$") + +# Returns True for a definite match +# False for a definite non-match +# None where we can't be sure because a key is None +def rule(pairs): + matchers = [(k, globmatcher(v)) for k, v in pairs] + def c(kw): + for k, m in matchers: + if k not in kw: + return False + kkw = kw[k] + if kkw is None: + return None + if m.match(kkw) is None: + return False + return True + return c + +class Ruleset(object): + '''Class representing the rules in a rule file''' + + levels = ["init", "write", "read", "deny"] + + def __init__(self): + self.rules = [] + self.preset = {} + + def add(self, action, conditions): + self.rules.append((action, conditions)) + + def set(self, **kw): + self.preset.update(kw) + + def get(self, k): + return self.preset.get(k, None) + + def matchrules(self, kw): + d = self.preset.copy() + d.update(kw) + res = set() + for a, c in self.rules: + m = c(d) + if m is None: + # "Maybe match" - add it and carry on + res.add(a) + elif m: + # Definite match - add it and stop + res.add(a) + break + return res + + def allow(self, level, **kw): + for a in self.matchrules(kw): + if a in self.levels: + if self.levels.index(a) <= self.levels.index(level): + return True + return False + + def readfile(self, fn): + f = open(fn) + try: + for l in f: + l = l.strip() + if len(l) == 0 or l.startswith("#"): + continue + l = l.split() + self.add(l[0], rule([c.split("=", 1) for c in l[1:]])) + finally: + f.close() + +rules = Ruleset() + diff -r f7c64f03cd60 -r 7bae88583a53 src/mercurialserver/servelog.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/mercurialserver/servelog.py Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,37 @@ +""" +Hook to log changesets pushed and pulled +""" + +from mercurial.i18n import _ +import mercurial.util +import mercurial.node + +import os +import time +import fcntl +import json +from mercurialserver import ruleset, changes + +def hook(ui, repo, hooktype, node=None, source=None, **kwargs): + if hooktype == 'changegroup': + op = "push" + elif hooktype == 'outgoing': + op = "pull" + else: + raise mercurial.util.Abort(_('servelog installed as wrong hook type,' + ' must be changegroup or outgoing but is %s') % hooktype) + log = open(repo.join("mercurial-server.log"), "a+") + try: + fcntl.flock(log.fileno(), fcntl.LOCK_EX) + log.seek(0, os.SEEK_END) + # YAML log file format + log.write("- {0}\n".format(json.dumps(dict( + timestamp=time.strftime("%Y-%m-%d_%H:%M:%S Z", time.gmtime()), + op=op, + key=ruleset.rules.get('user'), + ssh_connection=os.environ['SSH_CONNECTION'], + nodes=[mercurial.node.hex(ctx.node()) + for ctx in changes.changes(repo, node)], + )))) + finally: + log.close() diff -r f7c64f03cd60 -r 7bae88583a53 src/refresh-auth --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/refresh-auth Fri Dec 17 18:19:31 2010 +0000 @@ -0,0 +1,22 @@ +#!/usr/bin/env python +""" +Rewrite ~/.ssh/authorized_keys by recursing through key directories +""" + +import sys +import os +from mercurialserver import refreshauth, config + +if len(sys.argv) != 1: + sys.stderr.write("refresh-auth: must be called with no arguments (%s)\n" % sys.argv) + sys.exit(-1) + +config.initExe() + +# To protect the authorized_keys file for innocent users, you have to have +# a ~/.mercurial-server file to run this. +if not config.configExists(): + print >>sys.stderr, "Must be run as the 'hg' user" + sys.exit(-1) + +refreshauth.refreshAuth()