summaryrefslogtreecommitdiffstats
path: root/base/tps-tomcat/src/org/dogtagpki/server/tps/rest/TokenService.java
blob: 84046a964375cc7f9884249d311bd099c59008d7 (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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
// --- BEGIN COPYRIGHT BLOCK ---
// 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; version 2 of the License.
//
// 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.
//
// (C) 2013 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---

package org.dogtagpki.server.tps.rest;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.dogtagpki.server.tps.TPSSubsystem;
import org.dogtagpki.server.tps.dbs.ActivityDatabase;
import org.dogtagpki.server.tps.dbs.TokenDatabase;
import org.dogtagpki.server.tps.dbs.TokenRecord;
import org.jboss.resteasy.plugins.providers.atom.Link;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.BadRequestException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.PKIException;
import com.netscape.certsrv.tps.token.TokenCollection;
import com.netscape.certsrv.tps.token.TokenData;
import com.netscape.certsrv.tps.token.TokenResource;
import com.netscape.certsrv.tps.token.TokenStatus;
import com.netscape.cms.servlet.base.PKIService;

/**
 * @author Endi S. Dewata
 */
public class TokenService extends PKIService implements TokenResource {

    @Context
    private UriInfo uriInfo;

    @Context
    private HttpHeaders headers;

    @Context
    private Request request;

    @Context
    private HttpServletRequest servletRequest;

    public Map<TokenStatus, Collection<TokenStatus>> transitions = new HashMap<TokenStatus, Collection<TokenStatus>>();

    public TokenService() throws Exception {
        CMS.debug("TokenService.<init>()");
        IConfigStore configStore = CMS.getConfigStore();

        // load allowed token state transitions
        CMS.debug("TokenService: allowed transitions:");

        for (String transition : configStore.getString("tokendb.allowedTransitions").split(",")) {
            String states[] = transition.split(":");
            TokenStatus fromState = TokenStatus.fromInt(Integer.valueOf(states[0]));
            TokenStatus toState = TokenStatus.fromInt(Integer.valueOf(states[1]));
            CMS.debug("TokenService:  - " + fromState + " to " + toState);

            Collection<TokenStatus> nextStates = transitions.get(fromState);
            if (nextStates == null) {
                nextStates = new HashSet<TokenStatus>();
                transitions.put(fromState, nextStates);
            }
            nextStates.add(toState);
        }

    }

    public TokenStatus getTokenStatus(TokenRecord tokenRecord) {
        String status = tokenRecord.getStatus();

        if ("uninitialized".equals(status)) {
            return TokenStatus.UNINITIALIZED;

        } else if ("active".equals(status)) {
            return TokenStatus.ACTIVE;

        } else if ("lost".equals(status)) {
            String reason = tokenRecord.getReason();

            if ("keyCompromise".equals(reason)) {
                return TokenStatus.PERM_LOST;

            } else if ("destroyed".equals(reason)) {
                return TokenStatus.DAMAGED;

            } else if ("onHold".equals(reason)) {
                return TokenStatus.TEMP_LOST;
            }

        } else if ("terminated".equals(status)) {
            return TokenStatus.TERMINATED;
        }

        return TokenStatus.PERM_LOST;
    }

    public void setTokenStatus(TokenRecord tokenRecord, TokenStatus tokenState) {
        switch (tokenState) {
        case UNINITIALIZED:
            tokenRecord.setStatus("uninitialized");
            tokenRecord.setReason(null);
            break;
        case ACTIVE:
            tokenRecord.setStatus("active");
            tokenRecord.setReason(null);
            break;
        case PERM_LOST:
        case TEMP_LOST_PERM_LOST:
            tokenRecord.setStatus("lost");
            tokenRecord.setReason("keyCompromise");
            break;
        case DAMAGED:
            tokenRecord.setStatus("lost");
            tokenRecord.setReason("destroyed");
            break;
        case TEMP_LOST:
            tokenRecord.setStatus("lost");
            tokenRecord.setReason("onHold");
            break;
        case TERMINATED:
            tokenRecord.setStatus("terminated");
            tokenRecord.setReason(null);
            break;
        default:
            throw new PKIException("Unsupported token state: " + tokenState);
        }

    }

    public TokenData createTokenData(TokenRecord tokenRecord) {

        TokenData tokenData = new TokenData();
        tokenData.setID(tokenRecord.getId());
        tokenData.setTokenID(tokenRecord.getId());
        tokenData.setUserID(tokenRecord.getUserID());
        tokenData.setType(tokenRecord.getType());
        tokenData.setStatus(getTokenStatus(tokenRecord));
        tokenData.setAppletID(tokenRecord.getAppletID());
        tokenData.setKeyInfo(tokenRecord.getKeyInfo());
        tokenData.setPolicy(tokenRecord.getPolicy());
        tokenData.setCreateTimestamp(tokenRecord.getCreateTimestamp());
        tokenData.setModifyTimestamp(tokenRecord.getModifyTimestamp());

        String tokenID = tokenRecord.getId();
        try {
            tokenID = URLEncoder.encode(tokenID, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new PKIException(e.getMessage());
        }

        URI uri = uriInfo.getBaseUriBuilder().path(TokenResource.class).path("{tokenID}").build(tokenID);
        tokenData.setLink(new Link("self", uri));

        return tokenData;
    }

    public TokenRecord createTokenRecord(TokenData tokenData) {

        TokenRecord tokenRecord = new TokenRecord();
        tokenRecord.setId(tokenData.getID());
        tokenRecord.setUserID(tokenData.getUserID());
        tokenRecord.setType(tokenData.getType());
        setTokenStatus(tokenRecord, tokenData.getStatus());
        tokenRecord.setAppletID(tokenData.getAppletID());
        tokenRecord.setKeyInfo(tokenData.getKeyInfo());
        tokenRecord.setPolicy(tokenData.getPolicy());
        tokenRecord.setCreateTimestamp(tokenData.getCreateTimestamp());
        tokenRecord.setModifyTimestamp(tokenData.getModifyTimestamp());

        return tokenRecord;
    }

    @Override
    public Response findTokens(String filter, Integer start, Integer size) {

        CMS.debug("TokenService.findTokens()");

        if (filter != null && filter.length() < MIN_FILTER_LENGTH) {
            throw new BadRequestException("Filter is too short.");
        }

        start = start == null ? 0 : start;
        size = size == null ? DEFAULT_SIZE : size;

        try {
            TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
            TokenDatabase database = subsystem.getTokenDatabase();

            Iterator<TokenRecord> tokens = database.findRecords(filter).iterator();

            TokenCollection response = new TokenCollection();
            int i = 0;

            // skip to the start of the page
            for ( ; i<start && tokens.hasNext(); i++) tokens.next();

            // return entries up to the page size
            for ( ; i<start+size && tokens.hasNext(); i++) {
                response.addEntry(createTokenData(tokens.next()));
            }

            // count the total entries
            for ( ; tokens.hasNext(); i++) tokens.next();
            response.setTotal(i);

            if (start > 0) {
                URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build();
                response.addLink(new Link("prev", uri));
            }

            if (start+size < i) {
                URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build();
                response.addLink(new Link("next", uri));
            }

            return createOKResponse(response);

        } catch (Exception e) {
            e.printStackTrace();
            throw new PKIException(e.getMessage());
        }
    }

    @Override
    public Response getToken(String tokenID) {

        if (tokenID == null) throw new BadRequestException("Token ID is null.");

        CMS.debug("TokenService.getToken(\"" + tokenID + "\")");

        try {
            TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
            TokenDatabase database = subsystem.getTokenDatabase();

            return createOKResponse(createTokenData(database.getRecord(tokenID)));

        } catch (Exception e) {
            e.printStackTrace();
            throw new PKIException(e.getMessage());
        }
    }

    @Override
    public Response addToken(TokenData tokenData) {

        if (tokenData == null) throw new BadRequestException("Token data is null.");

        String tokenID = tokenData.getTokenID();
        CMS.debug("TokenService.addToken(\"" + tokenID + "\")");

        String remoteUser = servletRequest.getRemoteUser();
        String ipAddress = servletRequest.getRemoteAddr();

        TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
        TokenRecord tokenRecord = null;
        String msg = "add token";

        try {
            TokenDatabase database = subsystem.getTokenDatabase();

            // new tokens are uninitialized when created
            tokenData.setStatus(TokenStatus.UNINITIALIZED);

            tokenRecord = createTokenRecord(tokenData);
            tokenRecord.setId(tokenID);
            database.addRecord(tokenID, tokenRecord);
            subsystem.tdb.tdbActivity(subsystem, ActivityDatabase.OP_ADD,
                tokenRecord, ipAddress, msg, "success",
                remoteUser);
            tokenData = createTokenData(database.getRecord(tokenID));

            return createCreatedResponse(tokenData, tokenData.getLink().getHref());

        } catch (Exception e) {
            e.printStackTrace();
            subsystem.tdb.tdbActivity(subsystem, ActivityDatabase.OP_ADD,
                tokenRecord, ipAddress, msg, "failure",
                remoteUser);
            msg = msg + ":" + e;

            throw new PKIException(msg);
        }
    }

    @Override
    public Response replaceToken(String tokenID, TokenData tokenData) {

        if (tokenID == null) throw new BadRequestException("Token ID is null.");
        if (tokenData == null) throw new BadRequestException("Token data is null.");

        CMS.debug("TokenService.replaceToken(\"" + tokenID + "\")");

        String remoteUser = servletRequest.getRemoteUser();
        String ipAddress = servletRequest.getRemoteAddr();

        TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
        TokenRecord tokenRecord = null;
        String msg = "replace token";
        try {
            TokenDatabase database = subsystem.getTokenDatabase();

            tokenRecord = database.getRecord(tokenID);
            tokenRecord.setUserID(remoteUser);
            tokenRecord.setType(tokenData.getType());
            tokenRecord.setAppletID(tokenData.getAppletID());
            tokenRecord.setKeyInfo(tokenData.getKeyInfo());
            tokenRecord.setPolicy(tokenData.getPolicy());
            database.updateRecord(tokenID, tokenRecord);
            subsystem.tdb.tdbActivity(subsystem, ActivityDatabase.OP_DO_TOKEN,
                tokenRecord, ipAddress, msg, "success",
                remoteUser);

            tokenData = createTokenData(database.getRecord(tokenID));

            return createOKResponse(tokenData);

        } catch (Exception e) {
            e.printStackTrace();
            subsystem.tdb.tdbActivity(subsystem, ActivityDatabase.OP_DO_TOKEN,
                tokenRecord, ipAddress, msg,
                "failure", remoteUser);
            msg = msg + ":" + e;

            throw new PKIException(msg);
        }
    }

    @Override
    public Response modifyToken(String tokenID, TokenData tokenData) {

        if (tokenID == null) throw new BadRequestException("Token ID is null.");
        if (tokenData == null) throw new BadRequestException("Token data is null.");

        CMS.debug("TokenService.modifyToken(\"" + tokenID + "\")");

        String remoteUser = servletRequest.getRemoteUser();
        String ipAddress = servletRequest.getRemoteAddr();

        TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
        TokenRecord tokenRecord = null;
        String msg = "modify token";
        try {
            TokenDatabase database = subsystem.getTokenDatabase();

            tokenRecord = database.getRecord(tokenID);

            // update user ID if specified
            String userID = tokenData.getUserID();
            if (userID != null) {
                tokenRecord.setUserID(userID);
            }

            // update type if specified
            String type = tokenData.getType();
            if (type != null) {
                tokenRecord.setType(type);
            }

            // update applet ID if specified
            String appletID = tokenData.getAppletID();
            if (appletID != null) {
                tokenRecord.setAppletID(appletID);
            }

            // update key info if specified
            String keyInfo = tokenData.getKeyInfo();
            if (keyInfo != null) {
                tokenRecord.setKeyInfo(keyInfo);
            }

            // update policy if specified
            String policy = tokenData.getPolicy();
            if (policy != null) {
                tokenRecord.setPolicy(policy);
            }

            database.updateRecord(tokenID, tokenRecord);
            subsystem.tdb.tdbActivity(subsystem, ActivityDatabase.OP_DO_TOKEN,
                tokenRecord, ipAddress, msg, "success",
                remoteUser);

            tokenData = createTokenData(database.getRecord(tokenID));

            return createOKResponse(tokenData);

        } catch (Exception e) {
            e.printStackTrace();
            subsystem.tdb.tdbActivity(subsystem, ActivityDatabase.OP_DO_TOKEN,
                tokenRecord, ipAddress, msg,
                "failure", remoteUser);
            msg = msg + ":" + e;

            throw new PKIException(msg);
        }
    }

    @Override
    public Response changeTokenStatus(String tokenID, TokenStatus tokenStatus) {

        if (tokenID == null) throw new BadRequestException("Token ID is null.");
        if (tokenStatus == null) throw new BadRequestException("Token state is null.");

        CMS.debug("TokenService.changeTokenStatus(\"" + tokenID + "\", \"" + tokenStatus + "\")");

        String remoteUser = servletRequest.getRemoteUser();
        String ipAddress = servletRequest.getRemoteAddr();

        TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
        TokenRecord tokenRecord = null;
        String msg = "";
        try {
            TokenDatabase database = subsystem.getTokenDatabase();

            tokenRecord = database.getRecord(tokenID);
            TokenStatus currentTokenStatus = getTokenStatus(tokenRecord);
            CMS.debug("TokenService.changeTokenStatus(): current status: " + currentTokenStatus);
            msg = "change token status from " + currentTokenStatus + " to " + tokenStatus;

            // make sure transition is allowed
            Collection<TokenStatus> nextStatuses = transitions.get(currentTokenStatus);
            CMS.debug("TokenService.changeTokenStatus(): allowed next statuses: " + nextStatuses);
            if (nextStatuses == null || !nextStatuses.contains(tokenStatus)) {
                CMS.debug("TokenService.changeTokenStatus(): next status not allowed: " + tokenStatus);
                msg = msg + ": Invalid token status transition";
                subsystem.tdb.tdbActivity(subsystem, ActivityDatabase.OP_DO_TOKEN,
                    tokenRecord, ipAddress,
                    msg,
                    "failure", remoteUser);
                throw new BadRequestException(msg);
            }

            CMS.debug("TokenService.changeTokenStatus(): next status allowed: " + tokenStatus);
            setTokenStatus(tokenRecord, tokenStatus);
            database.updateRecord(tokenID, tokenRecord);
            subsystem.tdb.tdbActivity(subsystem, ActivityDatabase.OP_DO_TOKEN,
                tokenRecord, ipAddress, msg,
                "success", remoteUser);

            TokenData tokenData = createTokenData(database.getRecord(tokenID));

            return createOKResponse(tokenData);

        } catch (Exception e) {
            e.printStackTrace();
            msg = msg + e;
            subsystem.tdb.tdbActivity(subsystem, ActivityDatabase.OP_DO_TOKEN,
                tokenRecord, ipAddress, msg,
                "failure", remoteUser);

            throw new PKIException(msg);
        }
    }

    @Override
    public Response removeToken(String tokenID) {

        if (tokenID == null) throw new BadRequestException("Token ID is null.");

        CMS.debug("TokenService.removeToken(\"" + tokenID + "\")");

        String remoteUser = servletRequest.getRemoteUser();
        String ipAddress = servletRequest.getRemoteAddr();

        TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
        TokenRecord tokenRecord = null;
        String msg = "remove token";
        try {
            TokenDatabase database = subsystem.getTokenDatabase();
            tokenRecord = database.getRecord(tokenID);
            database.removeRecord(tokenID);
            subsystem.tdb.tdbActivity(subsystem, ActivityDatabase.OP_DELETE,
                tokenRecord, ipAddress, msg, "success",
                remoteUser);

            return createNoContentResponse();

        } catch (Exception e) {
            e.printStackTrace();
            subsystem.tdb.tdbActivity(subsystem, ActivityDatabase.OP_DELETE,
                tokenRecord, ipAddress, msg,
                "failure", remoteUser);
            msg = msg + ":" + e;

            throw new PKIException(msg);
        }
    }
}