2 * ============LICENSE_START====================================================
4 * ===========================================================================
5 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6 * ===========================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END====================================================
22 package org.onap.aaf.auth.dao.cass;
24 import java.io.ByteArrayOutputStream;
25 import java.io.DataInputStream;
26 import java.io.DataOutputStream;
27 import java.io.IOException;
28 import java.nio.ByteBuffer;
29 import java.util.HashSet;
30 import java.util.List;
33 import org.onap.aaf.auth.dao.Bytification;
34 import org.onap.aaf.auth.dao.Cached;
35 import org.onap.aaf.auth.dao.CassAccess;
36 import org.onap.aaf.auth.dao.CassDAOImpl;
37 import org.onap.aaf.auth.dao.DAOException;
38 import org.onap.aaf.auth.dao.Loader;
39 import org.onap.aaf.auth.dao.Streamer;
40 import org.onap.aaf.auth.dao.hl.Question;
41 import org.onap.aaf.auth.env.AuthzTrans;
42 import org.onap.aaf.auth.layer.Result;
43 import org.onap.aaf.misc.env.APIException;
44 import org.onap.aaf.misc.env.util.Split;
46 import com.datastax.driver.core.Cluster;
47 import com.datastax.driver.core.Row;
48 import com.datastax.driver.core.exceptions.DriverException;
50 public class PermDAO extends CassDAOImpl<AuthzTrans,PermDAO.Data> {
52 public static final String TABLE = "perm";
54 public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F
55 private static final String STAR = "*";
57 private final HistoryDAO historyDAO;
58 private final CacheInfoDAO infoDAO;
60 private PSInfo psNS, psChildren, psByType;
62 public PermDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException {
63 super(trans, PermDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));
65 historyDAO = new HistoryDAO(trans, this);
66 infoDAO = new CacheInfoDAO(trans,this);
69 public PermDAO(AuthzTrans trans, HistoryDAO hDAO, CacheInfoDAO ciDAO) {
70 super(trans, PermDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));
77 private static final int KEYLIMIT = 4;
78 public static class Data extends CacheableData implements Bytification {
81 public String instance;
83 public Set<String> roles;
84 public String description;
88 public Data(NsSplit nss, String instance, String action) {
91 this.instance = instance;
95 public String fullType() {
96 StringBuilder sb = new StringBuilder();
101 sb.append(ns.indexOf('@')<0?'.':':');
104 return sb.toString();
107 public String fullPerm() {
108 StringBuilder sb = new StringBuilder();
113 sb.append(ns.indexOf('@')<0?'.':':');
120 return sb.toString();
123 public String encode() {
124 return ns + '|' + type + '|' + instance + '|' + action;
128 * Decode Perm String, including breaking into appropriate Namespace
135 public static Result<Data> decode(AuthzTrans trans, Question q, String p) {
136 String[] ss = Split.splitTrim('|', p,4);
138 return Result.err(Status.ERR_BadData,"Perm Encodings must be separated by '|'");
140 Data data = new Data();
141 if (ss[3]==null) { // older 3 part encoding must be evaluated for NS
142 Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]);
144 return Result.err(nss);
146 data.ns=nss.value.ns;
147 data.type=nss.value.name;
150 } else { // new 4 part encoding
156 return Result.ok(data);
160 * Decode Perm String, including breaking into appropriate Namespace
167 public static Result<String[]> decodeToArray(AuthzTrans trans, Question q, String p) {
168 String[] ss = Split.splitTrim('|', p,4);
170 return Result.err(Status.ERR_BadData,"Perm Encodings must be separated by '|'");
173 if (ss[3]==null) { // older 3 part encoding must be evaluated for NS
176 Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]);
178 return Result.err(nss);
180 ss[1] = nss.value.name;
181 ss[0] = nss.value.ns;
183 return Result.ok(ss);
186 public static Data create(NsDAO.Data ns, String name) {
187 NsSplit nss = new NsSplit(ns,name);
188 Data rv = new Data();
190 String[] s = nss.name.split("\\|");
210 public static Data create(AuthzTrans trans, Question q, String name) {
211 String[] s = name.split("\\|");
212 Result<NsSplit> rdns = q.deriveNsSplit(trans, s[0]);
213 Data rv = new PermDAO.Data();
214 if (rdns.isOKhasData()) {
244 ////////////////////////////////////////
246 public Set<String> roles(boolean mutable) {
248 roles = new HashSet<>();
249 } else if (mutable && !(roles instanceof HashSet)) {
250 roles = new HashSet<>(roles);
256 public int[] invalidate(Cached<?,?> cache) {
260 seg(cache,ns,type,STAR),
261 seg(cache,ns,type,instance,action)
266 public ByteBuffer bytify() throws IOException {
267 ByteArrayOutputStream baos = new ByteArrayOutputStream();
268 PermLoader.deflt.marshal(this, new DataOutputStream(baos));
269 return ByteBuffer.wrap(baos.toByteArray());
273 public void reconstitute(ByteBuffer bb) throws IOException {
274 PermLoader.deflt.unmarshal(this, toDIS(bb));
278 public String toString() {
283 private static class PermLoader extends Loader<Data> implements Streamer<Data> {
284 public static final int MAGIC=283939453;
285 public static final int VERSION=1;
286 public static final int BUFF_SIZE=96;
288 public static final PermLoader deflt = new PermLoader(KEYLIMIT);
290 public PermLoader(int keylimit) {
295 public Data load(Data data, Row row) {
296 // Int more efficient Match "fields" string
297 data.ns = row.getString(0);
298 data.type = row.getString(1);
299 data.instance = row.getString(2);
300 data.action = row.getString(3);
301 data.roles = row.getSet(4,String.class);
302 data.description = row.getString(5);
307 protected void key(Data data, int _idx, Object[] obj) {
310 obj[++idx]=data.type;
311 obj[++idx]=data.instance;
312 obj[++idx]=data.action;
316 protected void body(Data data, int _idx, Object[] obj) {
319 obj[++idx]=data.description;
323 public void marshal(Data data, DataOutputStream os) throws IOException {
324 writeHeader(os,MAGIC,VERSION);
325 writeString(os, data.ns);
326 writeString(os, data.type);
327 writeString(os, data.instance);
328 writeString(os, data.action);
329 writeStringSet(os, data.roles);
330 writeString(os, data.description);
334 public void unmarshal(Data data, DataInputStream is) throws IOException {
335 /*int version = */readHeader(is,MAGIC,VERSION);
336 // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields
337 byte[] buff = new byte[BUFF_SIZE];
338 data.ns = readString(is, buff);
339 data.type = readString(is,buff);
340 data.instance = readString(is,buff);
341 data.action = readString(is,buff);
342 data.roles = readStringSet(is,buff);
343 data.description = readString(is,buff);
347 private void init(AuthzTrans trans) {
348 // the 3 is the number of key fields
349 String[] helpers = setCRUD(trans, TABLE, Data.class, PermLoader.deflt);
351 // Other SELECT style statements... match with a local Method
352 psByType = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
353 " WHERE ns = ? AND type = ?", new PermLoader(2) {
355 protected void key(Data data, int idx, Object[] obj) {
360 psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
361 " WHERE ns = ?", new PermLoader(1),readConsistency);
363 psChildren = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
364 " WHERE ns=? AND type > ? AND type < ?",
367 protected void key(Data data, int _idx, Object[] obj) {
370 obj[++idx]=data.type + DOT;
371 obj[++idx]=data.type + DOT_PLUS_ONE;
379 * Add a single Permission to the Role's Permission Collection
382 * @param roleFullName
388 public Result<Void> addRole(AuthzTrans trans, PermDAO.Data perm, String roleFullName) {
389 // Note: Prepared Statements for Collection updates aren't supported
392 getSession(trans).execute(UPDATE_SP + TABLE + " SET roles = roles + {'" + roleFullName + "'} " +
394 "ns = '" + perm.ns + "' AND " +
395 "type = '" + perm.type + "' AND " +
396 "instance = '" + perm.instance + "' AND " +
397 "action = '" + perm.action + "';"
399 } catch (DriverException | APIException | IOException e) {
400 reportPerhapsReset(trans,e);
401 return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG);
404 wasModified(trans, CRUD.update, perm, "Added role " + roleFullName + " to perm " +
405 perm.ns + '.' + perm.type + '|' + perm.instance + '|' + perm.action);
410 * Remove a single Permission from the Role's Permission Collection
412 * @param roleFullName
418 public Result<Void> delRole(AuthzTrans trans, PermDAO.Data perm, String roleFullName) {
419 // Note: Prepared Statements for Collection updates aren't supported
422 getSession(trans).execute(UPDATE_SP + TABLE + " SET roles = roles - {'" + roleFullName + "'} " +
424 "ns = '" + perm.ns + "' AND " +
425 "type = '" + perm.type + "' AND " +
426 "instance = '" + perm.instance + "' AND " +
427 "action = '" + perm.action + "';"
429 } catch (DriverException | APIException | IOException e) {
430 reportPerhapsReset(trans,e);
431 return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG);
434 //TODO how can we tell when it doesn't?
435 wasModified(trans, CRUD.update, perm, "Removed role " + roleFullName + " from perm " +
436 perm.ns + '.' + perm.type + '|' + perm.instance + '|' + perm.action);
444 * Select all Permissions by Name
448 * @throws DAOException
450 public Result<List<Data>> readByType(AuthzTrans trans, String ns, String type) {
451 return psByType.read(trans, R_TEXT, new Object[]{ns, type});
454 public Result<List<Data>> readChildren(AuthzTrans trans, String ns, String type) {
455 return psChildren.read(trans, R_TEXT, new Object[]{ns, type+DOT, type + DOT_PLUS_ONE});
458 public Result<List<Data>> readNS(AuthzTrans trans, String ns) {
459 return psNS.read(trans, R_TEXT, new Object[]{ns});
463 * Add description to this permission
473 public Result<Void> addDescription(AuthzTrans trans, String ns, String type,
474 String instance, String action, String description) {
476 getSession(trans).execute(UPDATE_SP + TABLE + " SET description = '"
477 + description + "' WHERE ns = '" + ns + "' AND type = '" + type + "'"
478 + "AND instance = '" + instance + "' AND action = '" + action + "';");
479 } catch (DriverException | APIException | IOException e) {
480 reportPerhapsReset(trans,e);
481 return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG);
484 Data data = new Data();
487 data.instance=instance;
489 wasModified(trans, CRUD.update, data, "Added description " + description + " to permission "
490 + data.encode(), null );
495 * Log Modification statements to History
498 protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) {
499 boolean memo = override.length>0 && override[0]!=null;
500 boolean subject = override.length>1 && override[1]!=null;
502 // Need to update history
503 HistoryDAO.Data hd = HistoryDAO.newInitedData();
504 hd.user = trans.user();
505 hd.action = modified.name();
507 hd.subject = subject ? override[1] : data.fullType();
509 hd.memo = String.format("%s", override[0]);
511 hd.memo = String.format("%sd %s|%s|%s", modified.name(),data.fullType(),data.instance,data.action);
514 if (modified==CRUD.delete) {
516 hd.reconstruct = data.bytify();
517 } catch (IOException e) {
518 trans.error().log(e,"Could not serialize PermDAO.Data");
522 if (historyDAO.create(trans, hd).status!=Status.OK) {
523 trans.error().log("Cannot log to History");
525 if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) {
526 trans.error().log("Cannot touch CacheInfo");