Martin Kosek wrote:
On 01/28/2014 09:35 PM, Rob Crittenden wrote:
Petr Viktorin wrote:
On 01/23/2014 02:17 PM, Petr Viktorin wrote:
...
The URL endpoint /ipa/rest suggests that if we implement a complete REST
API for IPA it would live here. Is the API supposed to be
future-compatible? (The API itself seems to be a good subset of a
complete REST API, but can we easily add an frontend with
authentication, i18n, etc. here later, and keep the limitations for
unauthenticated access?)
Perhaps /ipa/smartproxy would be a better choice?


It was future-proofing. I'm fine with changing the URI, it is probably a good
thing to save that name.

+1 for moving to /ipa/smartproxy/rest, we will want a complete REST interface
in ipa/rest/ in the future. I rather opened a ticket to track that:

https://fedorahosted.org/freeipa/ticket/4168

Martin


I think I've addressed most of Petr's suggestions with the exception of the global ipa handle and I stuck with *args, **options as this is pretty much standard in IPA calls.

The gssproxy.conf.snippet just makes it easier to copy/paste. I can drop it if you want, I suppose it is duplication.

Note that I ran this past the Foreman design again and as a result added another interface, /realm. It was my understanding that this Foreman design wasn't set into stone but a patch is working its way through their system that followed the spec so I went ahead and added it. It isn't a big deal, the Host() class handles it out of the box.

I also updated the design page a bit to reflect some of the changes made.

Right now there are no plans to backport python-kerberos to F20.

rob
>From 9ef273d6ef13ff6fd420af6f3b673b69b20fa875 Mon Sep 17 00:00:00 2001
From: Rob Crittenden <rcrit...@redhat.com>
Date: Tue, 3 Dec 2013 09:14:00 -0700
Subject: [PATCH] Implement an IPA REST server

This currently server supports only host and hostgroup commands for
retrieving, adding and deleting entries.

The incoming requests are completely unauthenticated and by default
requests must be local.

Utilize GSS-Proxy to manage the TGT.

Configuration information is in the ipa-rest man page.

Design: http://www.freeipa.org/page/V3/Smart_Proxy
---
 Makefile                                   |   5 +-
 freeipa.spec.in                            |  23 +++
 ipalib/util.py                             |  13 +-
 ipatests/test_smartproxy/resttest.py       | 170 +++++++++++++++++
 ipatests/test_smartproxy/test_host.py      | 145 ++++++++++++++
 ipatests/test_smartproxy/test_hostgroup.py |  97 ++++++++++
 smartproxy/Makefile.am                     |  43 +++++
 smartproxy/configure.ac                    |  75 ++++++++
 smartproxy/gssproxy.conf.snippet           |   6 +
 smartproxy/ipa-rest                        | 293 +++++++++++++++++++++++++++++
 smartproxy/ipa-rest.conf                   |  15 ++
 smartproxy/ipa-rest.logrotate              |  11 ++
 smartproxy/ipa-rest.service                |  12 ++
 smartproxy/man/Makefile.am                 |  19 ++
 smartproxy/man/ipa-rest.1                  |  78 ++++++++
 smartproxy/man/ipa-rest.conf.5             |  72 +++++++
 16 files changed, 1071 insertions(+), 6 deletions(-)
 create mode 100644 ipatests/test_smartproxy/resttest.py
 create mode 100644 ipatests/test_smartproxy/test_host.py
 create mode 100644 ipatests/test_smartproxy/test_hostgroup.py
 create mode 100644 smartproxy/Makefile.am
 create mode 100644 smartproxy/configure.ac
 create mode 100644 smartproxy/gssproxy.conf.snippet
 create mode 100755 smartproxy/ipa-rest
 create mode 100644 smartproxy/ipa-rest.conf
 create mode 100644 smartproxy/ipa-rest.logrotate
 create mode 100644 smartproxy/ipa-rest.service
 create mode 100644 smartproxy/man/Makefile.am
 create mode 100644 smartproxy/man/ipa-rest.1
 create mode 100644 smartproxy/man/ipa-rest.conf.5

diff --git a/Makefile b/Makefile
index 0a300b4ba3a0706f85255d74ecc7030fe99b76e2..9d6d93ded9985052c2327adee9a206723671cb82 100644
--- a/Makefile
+++ b/Makefile
@@ -1,6 +1,6 @@
 include VERSION
 
-SUBDIRS=daemons install ipapython ipa-client
+SUBDIRS=daemons install ipapython ipa-client smartproxy
 CLIENTDIRS=ipapython ipa-client
 
 PRJ_PREFIX=freeipa
@@ -74,6 +74,7 @@ bootstrap-autogen: version-update client-autogen
 	@echo "Building IPA $(IPA_VERSION)"
 	cd daemons; if [ ! -e Makefile ]; then ../autogen.sh --prefix=/usr --sysconfdir=/etc --localstatedir=/var --libdir=$(LIBDIR) --with-openldap; fi
 	cd install; if [ ! -e Makefile ]; then ../autogen.sh --prefix=/usr --sysconfdir=/etc --localstatedir=/var --libdir=$(LIBDIR); fi
+	cd smartproxy; if [ ! -e Makefile ]; then ../autogen.sh --prefix=/usr --sysconfdir=/etc --localstatedir=/var --libdir=$(LIBDIR); fi
 
 client-autogen: version-update
 	cd ipa-client; if [ ! -e Makefile ]; then ../autogen.sh --prefix=/usr --sysconfdir=/etc --localstatedir=/var --libdir=$(LIBDIR); fi
@@ -194,6 +195,7 @@ tarballs: local-archive
 	cd dist/$(TARBALL_PREFIX)/ipa-client; ../autogen.sh --prefix=/usr --sysconfdir=/etc --localstatedir=/var --libdir=$(LIBDIR); make distclean
 	cd dist/$(TARBALL_PREFIX)/daemons; ../autogen.sh --prefix=/usr --sysconfdir=/etc --localstatedir=/var --libdir=$(LIBDIR); make distclean
 	cd dist/$(TARBALL_PREFIX)/install; ../autogen.sh --prefix=/usr --sysconfdir=/etc --localstatedir=/var --libdir=$(LIBDIR); make distclean
+	cd dist/$(TARBALL_PREFIX)/smartproxy; ../autogen.sh --prefix=/usr --sysconfdir=/etc --localstatedir=/var --libdir=$(LIBDIR); make distclean
 	cd dist; tar cfz sources/$(TARBALL) $(TARBALL_PREFIX)
 	rm -rf dist/$(TARBALL_PREFIX)
 
@@ -260,5 +262,6 @@ maintainer-clean: clean
 	cd install && $(MAKE) maintainer-clean
 	cd ipa-client && $(MAKE) maintainer-clean
 	cd ipapython && $(MAKE) maintainer-clean
+	cd smartproxy && $(MAKE) maintainer-clean
 	rm -f version.m4
 	rm -f freeipa.spec
diff --git a/freeipa.spec.in b/freeipa.spec.in
index bbceca37693d0bc47f97b6cd124b2ddf97fc24ee..faef0f23b7bb6e2bf2e314b325a0736dfb4922c7 100644
--- a/freeipa.spec.in
+++ b/freeipa.spec.in
@@ -218,6 +218,19 @@ Cross-realm trusts with Active Directory in IPA require working Samba 4
 installation. This package is provided for convenience to install all required
 dependencies at once.
 
+
+%package server-smartproxy
+Summary: Foreman-compatible REST API for IPA
+Group: System Environment/Base
+Requires: %{name}-client = %version-%release
+Requires: python-cherrypy
+Requires: gssproxy >= 0.3.1
+Requires: python-requests
+Requires: python-kerberos >= 1.1-14
+
+%description server-smartproxy
+A Foreman-compatible REST API for managing hosts and hostgroups.
+
 %endif # ONLY_CLIENT
 
 
@@ -455,6 +468,7 @@ touch %{buildroot}%{_libdir}/krb5/plugins/libkrb5/winbind_krb5_locator.so
 mkdir -p %{buildroot}%{_unitdir}
 install -m 644 init/systemd/ipa.service %{buildroot}%{_unitdir}/ipa.service
 install -m 644 init/systemd/ipa_memcached.service %{buildroot}%{_unitdir}/ipa_memcached.service
+install -m 644 smartproxy/ipa-rest.service %{buildroot}%{_unitdir}/ipa-rest.service
 # END
 mkdir -p %{buildroot}/%{_localstatedir}/lib/ipa/backup
 %endif # ONLY_CLIENT
@@ -779,6 +793,15 @@ fi
 %{python_sitelib}/ipaserver/dcerpc*
 %{python_sitelib}/ipaserver/install/adtrustinstance*
 %ghost %{_libdir}/krb5/plugins/libkrb5/winbind_krb5_locator.so
+
+%files server-smartproxy
+%{_sbindir}/ipa-rest
+%{_mandir}/man1/ipa-rest.1.gz
+%{_mandir}/man5/ipa-rest.conf.5.gz
+%attr(644,root,root) %{_unitdir}/ipa-rest.service
+%config(noreplace) %{_sysconfdir}/ipa/ipa-rest.conf
+%config(noreplace)%{_sysconfdir}/logrotate.d/ipa-rest
+
 %endif # ONLY_CLIENT
 
 %files client
diff --git a/ipalib/util.py b/ipalib/util.py
index fcc4b1591e11365a98094019e8e9f5b87d214f75..89c0680087f840e90c0449d80b304fe3dcafe4a3 100644
--- a/ipalib/util.py
+++ b/ipalib/util.py
@@ -57,12 +57,15 @@ def json_serialize(obj):
 
 def get_current_principal():
     try:
-        # krbV isn't necessarily available on client machines, fail gracefully
-        import krbV
-        return unicode(krbV.default_context().default_ccache().principal().name)
+        import kerberos
+        rc, vc = kerberos.authGSSClientInit("notempty")
+        rc = kerberos.authGSSClientInquireCred(vc)
+        username = kerberos.authGSSClientUserName(vc)
+        kerberos.authGSSClientClean(vc)
+        return unicode(username)
     except ImportError:
-        raise RuntimeError('python-krbV is not available.')
-    except krbV.Krb5Error:
+        raise RuntimeError('python-kerberos is not available.')
+    except kerberos.GSSError, e:
         #TODO: do a kinit?
         raise errors.CCacheError()
 
diff --git a/ipatests/test_smartproxy/resttest.py b/ipatests/test_smartproxy/resttest.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc355471fc356da10fdcc2df2b6624dd0ddfb6a8
--- /dev/null
+++ b/ipatests/test_smartproxy/resttest.py
@@ -0,0 +1,170 @@
+# Authors:
+#   Rob Crittenden <rcrit...@redhat.com>
+#
+# Copyright (C) 2014  Red Hat
+# see file 'COPYING' for use and warranty information
+#
+# 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 3 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, see <http://www.gnu.org/licenses/>.
+
+"""
+Base class for all REST tests
+"""
+
+import requests
+import json
+import nose
+from ipatests.util import assert_deepequal, Fuzzy
+from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_uuid, fuzzy_password
+
+FQDN = 'localhost'
+PORT = 8090
+
+EXPECTED = """Expected %r to raise %s.
+  options = %r
+  output = %r"""
+
+UNEXPECTED = """Expected %r to raise %s, but caught different.
+  options = %r
+  %s: %s"""
+
+try:
+    response = requests.get(
+        'http://%s:%d/ipa/smartproxy/host/host.example.com' % (FQDN, PORT),
+        data={})
+    server_available = True
+except requests.ConnectionError:
+    server_available = False
+
+
+class REST_test(object):
+    """
+    Base class for all REST tests
+
+    A Declarative test suite is controlled by the ``tests`` and
+    ``cleanup`` class variables.
+
+    The ``tests`` is a list of dictionaries with the following keys:
+
+    ``desc``
+        A name/description of the test
+    ``command``
+        A (command, args, kwargs) triple specifying the command to run
+    ``expected``
+        Can be either an ``errors.PublicError`` instance, in which case
+        the command must fail with the given error; or the
+        expected result.
+        The result is checked with ``tests.util.assert_deepequal``.
+    ``extra_check`` (optional)
+        A checking function that is called with the response. It must
+        return true for the test to pass.
+
+    The ``cleanup`` is a list of (command, args, kwargs)
+    triples. These are commands get run both before and after tests,
+    and must not fail.
+    """
+
+    cleanup = tuple()
+    tests = tuple()
+
+    @classmethod
+    def setUpClass(cls):
+        if not server_available:
+            raise nose.SkipTest('%r: Server not available' %
+                                cls.__module__)
+
+    def cleanup_generate(self, stage):
+        for (i, request) in enumerate(self.cleanup):
+            func = lambda: self.run_cleanup(request)
+            func.description = '%s %s-cleanup[%d]: %r' % (
+                self.__class__.__name__, stage, i, request
+            )
+            yield (func,)
+
+    def make_request(self, method, uri, data=None):
+        request = method('http://%s:%d%s' % (FQDN, PORT, uri), data=data)
+        return request
+
+    def run_cleanup(self, request):
+        (uri, data) = request
+        try:
+            result = self.make_request(requests.delete, uri, data)
+            assert request.status_code in [401, 201, 200]
+        except Exception:
+            pass
+
+    def test_generator(self):
+        """
+        Iterate through tests.
+
+        nose reports each one as a separate test.
+        """
+
+        # Iterate through pre-cleanup:
+        for tup in self.cleanup_generate('pre'):
+            yield tup
+
+        # Iterate through the tests:
+        name = self.__class__.__name__
+        for (i, test) in enumerate(self.tests):
+            nice = '%s[%d]: %s: %s' % (
+                name, i, test['request'][0], test.get('desc', '')
+            )
+            func = lambda: self.check(nice, **test)
+            func.description = nice
+            yield (func,)
+
+        # Iterate through post-cleanup:
+        for tup in self.cleanup_generate('post'):
+            yield tup
+
+    def check(self, nice, desc, request, method, expected_status, expected):
+        (uri, data) = request
+        if isinstance(expected, Exception):
+            self.check_exception(nice, method, uri, data, expected)
+        else:
+            self.check_result(nice,
+                              method,
+                              uri,
+                              data,
+                              expected_status,
+                              expected)
+
+    def check_exception(self, nice, method, uri, data, expected):
+        klass = expected.__class__
+        name = klass.__name__
+        try:
+            output = self.make_request(method, uri, data)
+        except StandardError, e:
+            pass
+        else:
+            raise AssertionError(
+                EXPECTED % (uri, name, method, data, output)
+            )
+        if not isinstance(e, klass):
+            raise AssertionError(
+                UNEXPECTED % (uri, name, method, data, e.__class__.__name__, e)
+            )
+
+    def check_result(self, nice, method, uri, data, expected_status, expected):
+        request = self.make_request(method, uri, data)
+        assert expected_status == request.status_code
+
+        if request.status_code in [200, 201]:
+            try:
+                data = json.loads(request.text)
+            except ValueError, e:
+                raise AssertionError(
+                    'Could not parse JSON: %s' % e
+                )
+            assert_deepequal(expected, data, nice)
diff --git a/ipatests/test_smartproxy/test_host.py b/ipatests/test_smartproxy/test_host.py
new file mode 100644
index 0000000000000000000000000000000000000000..6dc90de535ba2f22fcd2529006659818b9d49226
--- /dev/null
+++ b/ipatests/test_smartproxy/test_host.py
@@ -0,0 +1,145 @@
+# Authors:
+#   Rob Crittenden <rcrit...@redhat.com>
+#
+# Copyright (C) 2014  Red Hat
+# see file 'COPYING' for use and warranty information
+#
+# 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 3 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, see <http://www.gnu.org/licenses/>.
+
+from ipalib import api
+from ipapython.dn import DN
+from resttest import REST_test, fuzzy_uuid, fuzzy_password
+from ipatests.test_xmlrpc import objectclasses
+import requests
+
+fqdn1 = u'testhost.example.com'
+dn1 = DN(('fqdn',fqdn1),('cn','computers'),('cn','accounts'),
+         api.env.basedn)
+fqdn2 = u'testhost2.example.com'
+dn2 = DN(('fqdn',fqdn2),('cn','computers'),('cn','accounts'),
+         api.env.basedn)
+
+class test_host(REST_test):
+
+    cleanup = [
+        ('/ipa/smartproxy/host/%s' % fqdn1, {}),
+        ('/ipa/smartproxy/host/%s' % fqdn2, {}),
+    ]
+
+    tests = [
+
+        dict(
+            desc='Get a non-existent host',
+            request=('/ipa/smartproxy/host/notfound', {}),
+            method=requests.get,
+            expected_status=404,
+            expected={},
+        ),
+
+        dict(
+            desc='Create a host',
+            request=('/ipa/smartproxy/host', {'hostname': fqdn1}),
+            method=requests.post,
+            expected_status=201,
+            expected=dict(
+                dn=dn1,
+                has_keytab=False,
+                krbprincipalname= [u'host/%s@%s' % (fqdn1, api.env.realm)],
+                objectclass=objectclasses.host,
+                fqdn=[fqdn1],
+                has_password=False,
+                ipauniqueid=[fuzzy_uuid],
+                managedby_host=[fqdn1],
+            ),
+        ),
+
+        dict(
+            desc='Get the host',
+            request=('/ipa/smartproxy/host/%s' % fqdn1, {}),
+            method=requests.get,
+            expected_status=200,
+            expected=dict(
+                dn=dn1,
+                has_keytab=False,
+                fqdn=[u'testhost.example.com'],
+                has_password=False,
+                managedby_host=[fqdn1],
+                krbprincipalname=[u'host/%s@%s' % (fqdn1, api.env.realm)],
+            ),
+        ),
+
+        dict(
+            desc='Add a duplicate host',
+            request=('/ipa/smartproxy/host', {'hostname': fqdn1}),
+            method=requests.post,
+            expected_status=400,
+            expected={},
+        ),
+
+        dict(
+            desc='Remove the host',
+            request=('/ipa/smartproxy/host/%s' % fqdn1, {}),
+            method=requests.delete,
+            expected_status=200,
+            expected=dict(failed=u''),
+        ),
+
+        dict(
+            desc='Create a host with a random password',
+            request=('/ipa/smartproxy/host', {'hostname': fqdn1, 'random': True}),
+            method=requests.post,
+            expected_status=201,
+            expected=dict(
+                dn=dn1,
+                has_keytab=False,
+                objectclass=[u'ipasshhost', u'ipaSshGroupOfPubKeys',
+                             u'ieee802device', u'ipaobject',
+                             u'nshost', u'ipahost', u'pkiuser',
+                             u'ipaservice', u'top',],
+                fqdn=[fqdn1],
+                has_password=True,
+                ipauniqueid=[fuzzy_uuid],
+                randompassword=fuzzy_password,
+                managedby_host=[fqdn1],
+            ),
+        ),
+
+        dict(
+            desc='Create a host with a fixed password',
+            request=('/ipa/smartproxy/host', {'hostname': fqdn2, 'password': 'Secret123'}),
+            method=requests.post,
+            expected_status=201,
+            expected=dict(
+                dn=dn2,
+                has_keytab=False,
+                objectclass=[u'ipasshhost', u'ipaSshGroupOfPubKeys',
+                             u'ieee802device', u'ipaobject',
+                             u'nshost', u'ipahost', u'pkiuser',
+                             u'ipaservice', u'top',],
+                fqdn=[fqdn2],
+                has_password=True,
+                ipauniqueid=[fuzzy_uuid],
+                managedby_host=[fqdn2],
+            ),
+        ),
+
+        dict(
+            desc='Remove a non-existent host',
+            request=('/ipa/smartproxy/host/notfound', {}),
+            method=requests.delete,
+            expected_status=404,
+            expected={},
+        ),
+
+    ]
diff --git a/ipatests/test_smartproxy/test_hostgroup.py b/ipatests/test_smartproxy/test_hostgroup.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec2daab5c2eb012768c49e14b5d8375b42ca6ac7
--- /dev/null
+++ b/ipatests/test_smartproxy/test_hostgroup.py
@@ -0,0 +1,97 @@
+# Authors:
+#   Rob Crittenden <rcrit...@redhat.com>
+#
+# Copyright (C) 2014  Red Hat
+# see file 'COPYING' for use and warranty information
+#
+# 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 3 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, see <http://www.gnu.org/licenses/>.
+
+from ipalib import api
+from ipapython.dn import DN
+from resttest import REST_test, fuzzy_uuid
+from ipatests.test_xmlrpc import objectclasses
+import requests
+
+hostgroup1 = u'testhostgroup'
+dn1 = DN(('cn', hostgroup1),('cn','hostgroups'),('cn','accounts'),
+         api.env.basedn)
+
+class test_hostgroup(REST_test):
+
+    cleanup = [
+        ('/ipa/smartproxy/hostgroup/%s' % hostgroup1, {}),
+    ]
+
+    tests = [
+
+        dict(
+            desc='Get a non-existent hostgroup',
+            request=('/ipa/smartproxy/hostgroup/notfound', {}),
+            method=requests.get,
+            expected_status=404,
+            expected={},
+        ),
+
+        dict(
+            desc='Create a hostgroup',
+            request=('/ipa/smartproxy/hostgroup', {'name': hostgroup1, 'description': u'test'}),
+            method=requests.post,
+            expected_status=201,
+            expected=dict(
+                dn=dn1,
+                cn=[hostgroup1],
+                objectclass=objectclasses.hostgroup,
+                description=[u'test'],
+                mepmanagedentry=[DN(('cn',hostgroup1),('cn','ng'),('cn','alt'),
+                                        api.env.basedn)],
+                ipauniqueid=[fuzzy_uuid],
+            ),
+        ),
+
+        dict(
+            desc='Get the hostgroup',
+            request=('/ipa/smartproxy/hostgroup/%s' % hostgroup1, {}),
+            method=requests.get,
+            expected_status=200,
+            expected=dict(
+                dn=dn1,
+                cn=[u'testhostgroup'],
+                description=[u'test'],
+            ),
+        ),
+
+        dict(
+            desc='Add a duplicate hostgroup',
+            request=('/ipa/smartproxy/hostgroup', {'name': hostgroup1, 'description': u'test'}),
+            method=requests.post,
+            expected_status=400,
+            expected={},
+        ),
+
+        dict(
+            desc='Remove the hostgroup',
+            request=('/ipa/smartproxy/hostgroup/%s' % hostgroup1, {}),
+            method=requests.delete,
+            expected_status=200,
+            expected=dict(failed=u''),
+        ),
+
+        dict(
+            desc='Remove a non-existent hostgroup',
+            request=('/ipa/smartproxy/hostgroup/%s' % hostgroup1, {}),
+            method=requests.delete,
+            expected_status=404,
+            expected={},
+        ),
+    ]
diff --git a/smartproxy/Makefile.am b/smartproxy/Makefile.am
new file mode 100644
index 0000000000000000000000000000000000000000..be6788aa56023914c8e6506a25565dc6620f7323
--- /dev/null
+++ b/smartproxy/Makefile.am
@@ -0,0 +1,43 @@
+# This file will be processed with automake-1.7 to create Makefile.in
+
+AUTOMAKE_OPTIONS = 1.7
+
+NULL =
+
+etcdir = $(IPA_SYSCONF_DIR)
+etc_DATA =			\
+	ipa-rest.conf		\
+	$(NULL)
+
+sbin_SCRIPTS =			\
+	ipa-rest		\
+	$(NULL)
+
+rotatedir = $(LOGROTATE_DIR)
+rotate_DATA =			\
+	ipa-rest.logrotate	\
+	$(NULL)
+
+SUBDIRS =			\
+	man			\
+	$(NULL)
+
+EXTRA_DIST =			\
+	$(etc_DATA)		\
+	$(rotate_DATA)		\
+	$(NULL)
+
+DISTCLEANFILES =		\
+	$(NULL)
+
+MAINTAINERCLEANFILES =		\
+	*~			\
+	aclocal.m4		\
+	configure		\
+	install-sh		\
+	missing			\
+	Makefile.in		\
+	$(NULL)
+
+install-data-hook:
+	mv $(DESTDIR)/$(LOGROTATE_DIR)/ipa-rest.logrotate $(DESTDIR)/$(LOGROTATE_DIR)/ipa-rest
diff --git a/smartproxy/configure.ac b/smartproxy/configure.ac
new file mode 100644
index 0000000000000000000000000000000000000000..5908a7f13bc7d19df4e3086b42a176167b5c2546
--- /dev/null
+++ b/smartproxy/configure.ac
@@ -0,0 +1,75 @@
+AC_PREREQ(2.59)
+m4_include(../version.m4)
+AC_INIT([ipa-server],
+        IPA_VERSION,
+        [https://hosted.fedoraproject.org/projects/freeipa/newticket])
+
+AM_INIT_AUTOMAKE([foreign])
+
+AM_MAINTAINER_MODE
+
+AC_SUBST(VERSION)
+AC_SUBST([INSTALL_DATA], ['$(INSTALL) -m 644 -p'])
+
+AC_PROG_MKDIR_P
+AC_PROG_AWK
+AC_PROG_SED
+
+AC_PATH_PROG(XGETTEXT, xgettext, [no])
+if test "x$XGETTEXT" = "xno"; then
+    AC_MSG_ERROR([xgettext not found, install gettext])
+fi
+
+AC_PATH_PROG(MSGFMT, msgfmt, [no])
+if test "x$MSGFMT" = "xno"; then
+    AC_MSG_ERROR([msgfmt not found, install gettext])
+fi
+
+AC_PATH_PROG(MSGINIT, msginit, [no])
+if test "x$MSGINIT" = "xno"; then
+    AC_MSG_ERROR([msginit not found, install gettext])
+fi
+
+AC_PATH_PROG(MSGMERGE, msgmerge, [no])
+if test "x$MSGMERGE" = "xno"; then
+    AC_MSG_ERROR([msgmerge not found, install gettext])
+fi
+
+AC_PATH_PROG(MSGCMP, msgcmp, [no])
+if test "x$MSGCMP" = "xno"; then
+    AC_MSG_ERROR([msgcmp not found, install gettext])
+fi
+
+AC_PATH_PROG(MSGATTRIB, msgattrib, [no])
+if test "x$MSGATTRIB" = "xno"; then
+    AC_MSG_ERROR([msgattrib not found, install gettext])
+fi
+
+AC_PATH_PROG(TX, tx, [/usr/bin/tx])
+
+AC_ARG_WITH([gettext_domain],
+  [AS_HELP_STRING([--with-gettext-domain=name],
+    [set the name of the i18n message catalog])],
+  [],
+  [with_gettext_domain=ipa])
+AC_SUBST(GETTEXT_DOMAIN, $with_gettext_domain)
+
+dnl ---------------------------------------------------------------------------
+dnl - Set the data install directory since we don't use pkgdatadir
+dnl ---------------------------------------------------------------------------
+
+IPA_DATA_DIR="$datadir/ipa"
+IPA_SYSCONF_DIR="$sysconfdir/ipa"
+LOGROTATE_DIR="$sysconfdir/logrotate.d"
+AC_SUBST(IPA_DATA_DIR)
+AC_SUBST(IPA_SYSCONF_DIR)
+AC_SUBST(LOGROTATE_DIR)
+
+# Files
+
+AC_CONFIG_FILES([
+    Makefile
+    man/Makefile
+])
+
+AC_OUTPUT
diff --git a/smartproxy/gssproxy.conf.snippet b/smartproxy/gssproxy.conf.snippet
new file mode 100644
index 0000000000000000000000000000000000000000..536dcaff2dd9e0339b92a71d6be8d0a658ac87db
--- /dev/null
+++ b/smartproxy/gssproxy.conf.snippet
@@ -0,0 +1,6 @@
+[service/rest]
+  mechs = krb5
+  cred_store = client_keytab:/etc/ipa/ipa-rest.keytab
+  cred_store = ccache:/var/lib/gssproxy/clients/krb5cc_%U
+  cred_usage = initiate
+  euid = 48
diff --git a/smartproxy/ipa-rest b/smartproxy/ipa-rest
new file mode 100755
index 0000000000000000000000000000000000000000..2c260d79cd03a9f839ed5bed14b44c084b2af557
--- /dev/null
+++ b/smartproxy/ipa-rest
@@ -0,0 +1,293 @@
+#!/usr/bin/python2 -E
+#
+# Authors:
+#   Rob Crittenden <rcrit...@redhat.com>
+#
+# Copyright (C) 2014  Red Hat
+# see file 'COPYING' for use and warranty information
+#
+# 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 3 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, see <http://www.gnu.org/licenses/>.
+
+import sys
+import os
+import cherrypy
+import json
+import syslog
+import pwd
+from optparse import OptionParser
+from functools import wraps
+from cherrypy import response
+from cherrypy.process import plugins
+from ipalib import api
+from ipalib import errors
+from ipaserver.rpcserver import json_encode_binary
+
+
+def jsonout(func):
+    '''JSON output decorator'''
+    @wraps(func)
+    def wrapper(*args, **kw):
+        value = func(*args, **kw)
+        response.headers["Content-Type"] = "application/json;charset=utf-8"
+        data = json_encode_binary(value)
+        return json.dumps(data, sort_keys=True, indent=2)
+
+    return wrapper
+
+
+def handle_error(status, message, traceback, version):
+    """
+    Return basic messages to user and log backtrace in case of 500
+    error. Note that this is buffered by CherryPy to 512 bytes to
+    satisfy IE.
+
+    The class configuration needs to know to call this via an
+    option like:
+        'error_page.500': handle_error
+    """
+    if status.startswith('500'):
+        cherrypy.log(msg=message + '\n', context='IPA', traceback=True)
+
+    resp = cherrypy.response
+    resp.headers['Content-Type'] = 'application/json'
+    return json.dumps({'status': status, 'message': message})
+
+
+def convert_unicode(value):
+    """
+    IPA requires all incoming values to be unicode. Recursively
+    convert the values.
+    """
+    if not isinstance(value, basestring):
+        return value
+
+    if value is not None:
+        return unicode(value)
+    else:
+        return None
+
+
+def Command(command, *args, **options):
+    if (cherrypy.request.config.get('local_only', False) and
+       cherrypy.request.remote.ip not in ['::1', '127.0.0.1']):
+        raise cherrypy.HTTPError(
+            status=401,
+            message="Not a local request"
+        )
+
+    if not api.Backend.rpcclient.isconnected():
+        api.Backend.rpcclient.connect()
+    try:
+        if not api.Backend.rpcclient.isconnected():
+            api.Backend.rpcclient.connect()
+    except errors.CCacheError, e:
+        raise cherrypy.HTTPError(
+            status=401,
+            message=str(e)
+        )
+
+    # IPA wants all its strings as unicode
+    args = map(lambda v: convert_unicode(v), args)
+    options = dict(zip(options, map(convert_unicode, options.values())))
+
+    params = api.Command[command].args_options_2_params(*args, **options)
+    cherrypy.log(context='IPA', msg='%s(%s)' %
+        (command, ', '.join(api.Command[command]._repr_iter(**params))))
+    try:
+        return api.Command[command](*args, **options)['result']
+    except (errors.DuplicateEntry, errors.DNSNotARecordError,
+            errors.ValidationError, errors.ConversionError,) as e:
+        raise cherrypy.HTTPError(
+            status=400,
+            message="%s: %s" % (e.__class__.__name__, e)
+        )
+    except errors.ACIError, e:
+        raise cherrypy.HTTPError(
+            status=401,
+            message="%s: %s" % (e.__class__.__name__, e)
+        )
+    except errors.NotFound, e:
+        raise cherrypy.HTTPError(
+            status=404,
+            message="%s: %s" % (e.__class__.__name__, e)
+        )
+    except Exception, e:
+        raise cherrypy.HTTPError(
+            status=500,
+            message="%s: %s" % (e.__class__.__name__, e)
+        )
+
+
+@jsonout
+def GET(command, *args, **options):
+    return Command(command, *args, **options)
+
+
+@jsonout
+def POST(command, *args, **options):
+    cherrypy.response.status = 201
+    return Command(command, *args, **options)
+
+
+@jsonout
+def DELETE(command, *args, **options):
+    return Command(command, *args, **options)
+
+
+class Host(object):
+
+    exposed = True
+
+    def GET(self, fqdn=None):
+
+        if fqdn is None:
+            command = 'host_find'
+        else:
+            command = 'host_show'
+
+        return GET(command, fqdn)
+
+    def POST(self, hostname, description=None, force=False, random=False,
+             macaddress=None, userclass=None, ip_address=None,
+             password=None):
+        return POST('host_add', hostname,
+                    description=description, random=random,
+                    force=force, macaddress=macaddress,
+                    userclass=userclass, ip_address=ip_address,
+                    userpassword=password)
+
+    def DELETE(self, fqdn):
+        return DELETE('host_del', fqdn)
+
+
+class Hostgroup(object):
+
+    exposed = True
+
+    def GET(self, name=None):
+
+        if name is None:
+            command = 'hostgroup_find'
+        else:
+            command = 'hostgroup_show'
+
+        return GET(command, name)
+
+    def POST(self, name=None, description=None):
+        cherrypy.response.status = 201
+        return POST('hostgroup_add', name,
+                    description=description,)
+
+    def DELETE(self, name):
+        return DELETE('hostgroup_del', name)
+
+
+def start(config=None, daemonize=False, pidfile=None):
+    # Set the umask so only the owner can read the log files
+    old_umask = os.umask(077)
+
+    cherrypy.tree.mount(
+        Host(), '/ipa/smartproxy/host',
+        {'/':
+            {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}
+        }
+    )
+    cherrypy.tree.mount(
+        Hostgroup(), '/ipa/smartproxy/hostgroup',
+        {'/':
+            {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}
+        }
+    )
+
+    api.bootstrap(context='iparest')
+    api.finalize()
+
+    # Register the domain for requests from Foreman
+    cherrypy.tree.mount(
+        Host(), '/realm/%s' % api.env.domain,
+        {'/':
+            {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}
+        }
+    )
+
+    for c in config or []:
+        try:
+            cherrypy.config.update(c)
+        except (IOError, OSError), e:
+            cherrypy.log(msg="Exception trying to load %s: %s" % (c, e),
+                context='IPA', traceback=False)
+            return 1
+
+    # Log files are created, reset umask
+    os.umask(old_umask)
+
+    user = cherrypy.config.get('user', None)
+    if user is None:
+        cherrypy.log(msg="User is required", context='IPA', traceback=False)
+        return 1
+    pent = pwd.getpwnam(user)
+
+    if daemonize:
+        cherrypy.config.update({'log.screen': False})
+        plugins.Daemonizer(cherrypy.engine).subscribe()
+
+    if pidfile:
+        plugins.PIDFile(cherrypy.engine, pidfile).subscribe()
+
+    cherrypy.engine.signal_handler.subscribe()
+
+    cherrypy.config.update({'error_page.400': handle_error,
+                            'error_page.401': handle_error,
+                            'error_page.404': handle_error,
+                            'error_page.500': handle_error, })
+
+    # If you don't use GSS-Proxy you're on your own in ensuring that
+    # there is always a valid ticket for the smartproxy to use.
+    if cherrypy.config.get('use_gssproxy', False):
+        cherrypy.log(msg="Enabling GSS-Proxy", context='IPA')
+        os.environ['GSS_USE_PROXY'] = '1'
+
+    if os.geteuid() == 0:
+        cherrypy.log(msg="Dropping root privileges to %s" % user,
+                     context='IPA')
+        plugins.DropPrivileges(cherrypy.engine,
+                               uid=pent.pw_uid,
+                               gid=pent.pw_gid).subscribe()
+
+    try:
+        cherrypy.engine.start()
+    except Exception:
+        return 1
+    else:
+        cherrypy.engine.block()
+
+    return 0
+
+if __name__ == '__main__':
+    p = OptionParser()
+    p.add_option('-c', '--config', action="append", dest='config',
+                 help="specify config file(s)")
+    p.add_option('-d', action="store_true", dest='daemonize',
+                 help="run the server as a daemon")
+    p.add_option('-p', '--pidfile', dest='pidfile', default=None,
+                 help="store the process id in the given file")
+    options, args = p.parse_args()
+
+    try:
+        sys.exit(start(options.config, options.daemonize, options.pidfile))
+    except Exception, e:
+        cherrypy.log(msg="Exception trying to start: %s" % e,
+                     context='IPA',
+                     traceback=True)
+        syslog.syslog(syslog.LOG_ERR, "Exception trying to start: %s" % e)
diff --git a/smartproxy/ipa-rest.conf b/smartproxy/ipa-rest.conf
new file mode 100644
index 0000000000000000000000000000000000000000..17d934146bbf5bedf3d0dbad7ebe8ec0aa645120
--- /dev/null
+++ b/smartproxy/ipa-rest.conf
@@ -0,0 +1,15 @@
+[global]
+server.socket_port: 8090
+#server.socket_host: 'server.example.com'
+
+log.access_file: '/var/log/ipa-rest.access'
+log.error_file: '/var/log/ipa-rest.errors'
+
+request.show_tracebacks: False
+
+# Only handle requests on 127.0.0.1 or ::1
+local_only: True
+
+use_gssproxy: True
+
+user: 'apache'
diff --git a/smartproxy/ipa-rest.logrotate b/smartproxy/ipa-rest.logrotate
new file mode 100644
index 0000000000000000000000000000000000000000..b143a60e25a80341afbefef96cd5c00fcfb06d3c
--- /dev/null
+++ b/smartproxy/ipa-rest.logrotate
@@ -0,0 +1,11 @@
+/var/log/ipa-rest.access /var/log/ipa-rest.errors {
+    weekly
+    missingok
+    notifempty
+    sharedscripts
+    rotate 52
+    compress
+    postrotate
+        /bin/systemctl reload ipa-rest.service > /dev/null 2>/dev/null || true
+    endscript
+}
diff --git a/smartproxy/ipa-rest.service b/smartproxy/ipa-rest.service
new file mode 100644
index 0000000000000000000000000000000000000000..e44e5cb9aa60b41046bb7d8f28367939853bf2d4
--- /dev/null
+++ b/smartproxy/ipa-rest.service
@@ -0,0 +1,12 @@
+[Unit]
+Description=REST API for IPA
+After=ipa.target
+
+[Service]
+ExecStart=/usr/sbin/ipa-rest -c /etc/ipa/ipa-rest.conf -d -p /var/run/ipa-rest.pid
+ExecReload=/bin/kill -USR1 $MAINPID
+Type=forking
+PIDFile=/var/run/ipa-rest.pid
+
+[Install]
+WantedBy=multi-user.target
diff --git a/smartproxy/man/Makefile.am b/smartproxy/man/Makefile.am
new file mode 100644
index 0000000000000000000000000000000000000000..2345dfda65f1508088b5f9fa77ec6e6a6b534d28
--- /dev/null
+++ b/smartproxy/man/Makefile.am
@@ -0,0 +1,19 @@
+# This file will be processed with automake-1.7 to create Makefile.in
+
+AUTOMAKE_OPTIONS = 1.7
+
+NULL =
+
+man1_MANS = 				\
+		ipa-rest.1
+
+man5_MANS =				\
+		ipa-rest.conf.5
+
+install-data-hook:
+	@for i in $(man1_MANS) ; do gzip -f $(DESTDIR)$(man1dir)/$$i ; done
+	@for i in $(man5_MANS) ; do gzip -f $(DESTDIR)$(man5dir)/$$i ; done
+
+MAINTAINERCLEANFILES =          \
+	Makefile.in		\
+	$(NULL)
diff --git a/smartproxy/man/ipa-rest.1 b/smartproxy/man/ipa-rest.1
new file mode 100644
index 0000000000000000000000000000000000000000..f0e687ae8b7c58161bfbff80b2d33e90945dc880
--- /dev/null
+++ b/smartproxy/man/ipa-rest.1
@@ -0,0 +1,78 @@
+.\" A man page for ipa-rest
+.\" Copyright (C) 2014 Red Hat, Inc.
+.\"
+.\" 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 3 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, see <http://www.gnu.org/licenses/>.
+.\"
+.\" Author: Rob Crittenden <rcrit...@redhat.com>
+.TH "ipa-rest" "1" "Jan 8 2014" "FreeIPA" "FreeIPA Manual Pages"
+.SH "NAME"
+ipa\-rest \- IPA REST API
+.SH "SYNOPSIS"
+python ipa\-rest.py [\fIOPTION\fR]...
+.SH "DESCRIPTION"
+A CherryPy\-based server that provides a REST API for a subset of IPA commands.
+
+The REST interface is not authenticated so it is expected that the server is not generally accessible. By default it listens only on the localhost interface.
+
+The server needs access to an principal that is granted permission to perform host and hostgroup operations on an IPA master.
+
+REST server\-specific privileges and roles can be created with this:
+
+.na
+ $ ipa privilege\-add 'REST host management' \-\-desc='REST host management'
+ $ ipa privilege\-add\-permission 'REST host management' \-\-permission='add hosts' \-\-permission='remove hosts'
+ $ ipa role\-add 'REST management' \-\-desc='REST management'
+ $ ipa role\-add\-privilege 'REST management' \-\-privilege='REST host management' \-\-privilege='Host Group Administrators'
+
+Create a host or user whose credentials will be used by the server to make requests and add it to the role:
+
+ $ ipa user\-add \-\-first=REST \-\-last=Server rest
+ $ ipa role\-add\-member \-\-users=rest 'REST management'
+
+On the REST server create a keytab for this user:
+
+ # kinit admin
+ # ipa\-getkeytab \-s ipa.example.com \-p r...@example.com \-k /etc/ipa/ipa\-rest.keytab
+ # chown root:root /etc/ipa/ipa\-rest.keytab
+ # chmod 600 /etc/ipa/ipa\-rest.keytab
+
+Configure the GSS\-Proxy to manage the credentials. Add this to the top of the gssproxy configuration file (by default /etc/gssproxy/gssproxy.conf), before any other services:
+
+  [service/rest]
+    mechs = krb5
+    cred_store = client_keytab:/etc/ipa/ipa\-rest.keytab
+    cred_store = ccache:/var/lib/gssproxy/clients/krb5cc_%U
+    cred_usage = initiate
+    euid = 48  (where 48 is the apache user uid)
+
+Some startup and operational errors may also be logged to the syslog.
+.SH "OPTIONS"
+.TP
+\fB\-c\fR \fICONFIG\fR
+The configuration file(s) to be loaded. This option may be passed multiple times to load more than one configuration file.
+.TP
+\fB\-d\fR
+Run the server as a daemon.
+.TP
+\fB\-p\fR \fIPIDFILE\fR
+The location to write the server PID file.
+.TP
+\fB\-h\fR
+Show the help message.
+.SH "EXIT STATUS"
+0 if the server execution was successful
+
+1 if an error occurred
+.SH "SEE ALSO"
+.BR ipa\-rest.conf(5)
diff --git a/smartproxy/man/ipa-rest.conf.5 b/smartproxy/man/ipa-rest.conf.5
new file mode 100644
index 0000000000000000000000000000000000000000..0e2631351d9307142ce5d3083c941d0d1e659d0b
--- /dev/null
+++ b/smartproxy/man/ipa-rest.conf.5
@@ -0,0 +1,72 @@
+.\" A man page for ipa-rest.conf
+.\" Copyright (C) 2014 Red Hat, Inc.
+.\"
+.\" 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 3 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, see <http://www.gnu.org/licenses/>.
+.\"
+.\" Author: Rob Crittenden <rcritten@@redhat.com>
+.\"
+.TH "ipa-rest.conf" "5" "Jan 8 2014" "FreeIPA" "FreeIPA Manual Pages"
+.SH "NAME"
+ipa\-rest.conf \- IPA REST server configuration file
+.SH "SYNOPSIS"
+/etc/ipa/ipa\-rest.conf
+.SH "DESCRIPTION"
+The \fIipa\-rest.conf \fRconfiguration file is used to set system\-wide defaults to be applied when running the IPA REST server.
+.SH "SYNTAX"
+The configuration options are not case sensitive. The values may be case sensitive, depending on the option.
+
+Blank lines are ignored.
+
+Lines beginning with # are comments and are ignored.
+
+Valid lines consist of an option name, an equals sign and a value. Spaces surrounding equals sign are ignored. An option terminates at the end of a line.
+
+The value is a Python object so needs to adhere to Python rules. If the value should be an integer then it needs to be passed as an integer (like port). If the value is a string then it must be quoted.
+
+Options must appear in the section named [global]. There are no other sections defined or used currently.
+
+Options may be defined that are not used by the IPA REST server. Be careful of misspellings, they will not be rejected.
+.SH "OPTIONS"
+The IPA REST server runs using the CherryPy so all the CherryPy configuration options are valid. Here are some common ones.
+
+.TP
+.B server.socket_port\fR <port>
+Port for the server to listen on.
+.TP
+.B server.socket_host\fR <host>
+If not specified then the server will listen on localhost. This is the expected mode. Specifiy a hostname or IP address to listen on another address. See also the .B local_only\fR option if setting this to something other than a local address.
+.TP
+.B log.access_file\fR <path>
+Path to the server access log
+.TP
+.B log.error_file\fR <path>
+Path to the server error log
+.TP
+.B request.show_tracebacks\fR <boolean>
+Display tracebacks to the client when errors occur. Errors will always log on the server side. The default is False.
+.TP
+.B local_only\fR <boolean>
+If True then requires that all requests be local. It is not recommended that this be enabled because this server accepts unathenticated requests to manage IPA entries.
+.TP
+.B use_gssproxy\fR <boolean>
+When True uses the gss\-proxy service to manage the Kerberos credentials needed to make IPA requests. If False then the user must ensure that the process has the right Kerberos credentials to make IPA requests.
+.TP
+.B user\fR <user>
+The user to run the server as. Required.
+.SH "FILES"
+.TP
+.I /etc/ipa/ipa\-rest.conf
+IPA REST server configuration file
+.SH "SEE ALSO"
+.BR ipa\-rest (1)
-- 
1.8.5.3

_______________________________________________
Freeipa-devel mailing list
Freeipa-devel@redhat.com
https://www.redhat.com/mailman/listinfo/freeipa-devel

Reply via email to