aboutsummaryrefslogtreecommitdiffstats
path: root/odl-aaa-moon/aaa/aaa-authn-sssd/src/main/java/org/opendaylight/aaa/sssd/SssdClaimAuth.java
blob: 0ae23b48e9ac9a85ec5a47876afb3871c4d37568 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/*
 * Copyright (c) 2014, 2015 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.aaa.sssd;

import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonValue;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonGeneratorFactory;
import org.apache.felix.dm.Component;
import org.opendaylight.aaa.ClaimBuilder;
import org.opendaylight.aaa.api.Claim;
import org.opendaylight.aaa.api.ClaimAuth;
import org.opendaylight.aaa.idpmapping.RuleProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * An SSSD {@link ClaimAuth} implementation.
 *
 * @author John Dennis <jdennis@redhat.com>
 */
public class SssdClaimAuth implements ClaimAuth {
    private static final Logger LOG = LoggerFactory.getLogger(SssdClaimAuth.class);

    private static final String DEFAULT_MAPPING_RULES_PATHNAME = "etc/idp_mapping_rules.json";
    private JsonGeneratorFactory generatorFactory = null;
    private RuleProcessor ruleProcessor = null;

    // Called by DM when all required dependencies are satisfied.
    void init(Component c) {
        LOG.info("Initializing SSSD Plugin");
        Map<String, Object> properties = new HashMap<String, Object>(1);
        properties.put(JsonGenerator.PRETTY_PRINTING, true);
        generatorFactory = Json.createGeneratorFactory(properties);

        String mappingRulesFile = DEFAULT_MAPPING_RULES_PATHNAME;
        if (mappingRulesFile == null || mappingRulesFile.isEmpty()) {
            LOG.warn("mapping rules file is not configured, " + "SssdClaimAuth will be disabled");
            return;
        }

        Path mappingRulesPath = Paths.get(mappingRulesFile);

        if (!Files.exists(mappingRulesPath)) {
            LOG.warn(String.format("mapping rules file (%s) "
                    + "does not exist, SssdClaimAuth will be disabled", mappingRulesFile));
            return;
        }

        try {
            ruleProcessor = new RuleProcessor(mappingRulesPath, null);
        } catch (Exception e) {
            LOG.error(String.format("mapping rules file (%s) "
                    + "could not be loaded, SssdClaimAuth will be disabled. " + "error = %s",
                    mappingRulesFile, e));
        }
    }

    /**
     * Transform a Map of assertions into a {@link Claim} via a set of mapping
     * rules.
     *
     * A set of mapping rules have been previously loaded. the incoming
     * assertion is converted to a JSON document and presented to the
     * {@link RuleProcessor}. If the RuleProcessor can successfully transform
     * the assertion given the site specific set of rules it will return a Map
     * of values which will then be used to build a {@link Claim}. The rule
     * should return one or more of the following which will be used to populate
     * the Claim.
     *
     * <dl>
     * <dt>ClientId</dt>
     * <dd>A string.
     *
     * @see org.opendaylight.aaa.api.Claim#clientId() </dd>
     *
     *      <dt>UserId</dt> <dd>A string.
     * @see org.opendaylight.aaa.api.Claim#userId() </dd>
     *
     *      <dt>User</dt> <dd>A string.
     * @see org.opendaylight.aaa.api.Claim#user() </dd>
     *
     *      <dt>Domain</dt> <dd>A string.
     * @see org.opendaylight.aaa.api.Claim#domain() </dd>
     *
     *      <dt>Roles</dt> <dd>An array of strings.
     * @see org.opendaylight.aaa.api.Claim#roles() </dd>
     *
     *      </dl>
     *
     * @param assertion
     *            A Map of name/value assertions provided by an external IdP
     * @return A {@link Claim} if successful, null otherwise.
     */

    @Override
    public Claim transform(Map<String, Object> assertion) {
        String assertionJson;
        Map<String, Object> mapped;
        assertionJson = claimToJson(assertion);

        if (ruleProcessor == null) {
            LOG.debug("ruleProcessor not configured");
            return null;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("assertionJson=\n{}", assertionJson);
        }

        mapped = ruleProcessor.process(assertionJson);
        if (mapped == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("RuleProcessor returned null");
            }
            return null;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("RuleProcessor returned: {}", mapped);
        }

        ClaimBuilder cb = new ClaimBuilder();
        if (mapped.containsKey("ClientId")) {
            cb.setClientId((String) mapped.get("ClientId"));
        }
        if (mapped.containsKey("UserId")) {
            cb.setUserId((String) mapped.get("UserId"));
        }
        if (mapped.containsKey("User")) {
            cb.setUser((String) mapped.get("User"));
        }
        if (mapped.containsKey("Domain")) {
            cb.setDomain((String) mapped.get("Domain"));
        }
        if (mapped.containsKey("Roles")) {
            @SuppressWarnings("unchecked")
            List<String> roles = (List<String>) mapped.get("roles");
            for (String role : roles) {
                cb.addRole(role);
            }
        }
        Claim claim = cb.build();

        if (LOG.isDebugEnabled()) {
            LOG.debug("returns claim = {}", claim.toString());
        }

        return claim;
    }

    /**
     * Convert a Claim Map into a JSON object.
     *
     * Given a Map of name/value pairs convert it into a JSON object and return
     * it as a string. This is not a general purpose routine used to convert any
     * Map into JSON because a claim has the restriction that each value must be
     * a scalar and those scalars are restricted to the following types:
     *
     * <ul>
     * <li>String</li>
     * <li>Integer</li>
     * <li>Long</li>
     * <li>Double</li>
     * <li>Boolean</li>
     * <li>null</li>
     * </ul>
     *
     * See also {@link ClaimAuth}.
     *
     * @param claim
     *            The Map containing assertion claims to be converted into a
     *            JSON assertion document.
     * @return A string formatted as a JSON object.
     */

    public String claimToJson(Map<String, Object> claim) {
        StringWriter stringWriter = new StringWriter();
        JsonGenerator generator = generatorFactory.createGenerator(stringWriter);

        generator.writeStartObject();
        for (Map.Entry<String, Object> entry : claim.entrySet()) {
            String name = entry.getKey();
            Object value = entry.getValue();

            if (value instanceof String) {
                generator.write(name, (String) value);
            } else if (value instanceof Integer) {
                generator.write(name, ((Integer) value).intValue());
            } else if (value instanceof Long) {
                generator.write(name, ((Long) value).longValue());
            } else if (value instanceof Double) {
                generator.write(name, ((Double) value).doubleValue());
            } else if (value instanceof Boolean) {
                generator.write(name, ((Boolean) value).booleanValue());
            } else if (value == null) {
                generator.write(name, JsonValue.NULL);
            } else {
                LOG.warn(String.format("ignoring claim unsupported value type "
                        + "entry %s has type %s", name, value.getClass().getSimpleName()));
            }
        }
        generator.writeEnd();
        generator.close();
        return stringWriter.toString();
    }
}