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.Loader;
38 import org.onap.aaf.auth.dao.Streamer;
39 import org.onap.aaf.auth.dao.hl.Question;
40 import org.onap.aaf.auth.env.AuthzTrans;
41 import org.onap.aaf.auth.layer.Result;
42 import org.onap.aaf.misc.env.APIException;
43 import org.onap.aaf.misc.env.util.Split;
45 import com.datastax.driver.core.Cluster;
46 import com.datastax.driver.core.Row;
47 import com.datastax.driver.core.exceptions.DriverException;
49 public class RoleDAO extends CassDAOImpl<AuthzTrans,RoleDAO.Data> {
51 public static final String TABLE = "role";
52 public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F
54 private final HistoryDAO historyDAO;
55 private final CacheInfoDAO infoDAO;
57 private PSInfo psChildren, psNS, psName;
59 public RoleDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException {
60 super(trans, RoleDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));
62 historyDAO = new HistoryDAO(trans, this);
63 infoDAO = new CacheInfoDAO(trans,this);
67 public RoleDAO(AuthzTrans trans, HistoryDAO hDAO, CacheInfoDAO ciDAO) {
68 super(trans, RoleDAO.class.getSimpleName(),hDAO,Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));
75 //////////////////////////////////////////
76 // Data Definition, matches Cassandra DM
77 //////////////////////////////////////////
78 private static final int KEYLIMIT = 2;
80 * Data class that matches the Cassandra Table "role"
83 public static class Data extends CacheableData implements Bytification {
86 public Set<String> perms;
87 public String description;
89 ////////////////////////////////////////
91 public Set<String> perms(boolean mutable) {
93 perms = new HashSet<>();
94 } else if (mutable && !(perms instanceof HashSet)) {
95 perms = new HashSet<>(perms);
100 public static Data create(NsDAO.Data ns, String name) {
101 NsSplit nss = new NsSplit(ns,name);
102 RoleDAO.Data rv = new Data();
108 public String fullName() {
109 return ns + '.' + name;
112 public String encode() {
113 return ns + '|' + name;
117 * Decode Perm String, including breaking into appropriate Namespace
124 public static Result<Data> decode(AuthzTrans trans, Question q, String r) {
125 String[] ss = Split.splitTrim('|', r,2);
126 Data data = new Data();
127 if(ss[1]==null) { // older 1 part encoding must be evaluated for NS
128 Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]);
130 return Result.err(nss);
132 data.ns=nss.value.ns;
133 data.name=nss.value.name;
134 } else { // new 4 part encoding
138 return Result.ok(data);
142 * Decode from UserRole Data
146 public static RoleDAO.Data decode(UserRoleDAO.Data urdd) {
147 RoleDAO.Data rd = new RoleDAO.Data();
149 rd.name = urdd.rname;
155 * Decode Perm String, including breaking into appropriate Namespace
162 public static Result<String[]> decodeToArray(AuthzTrans trans, Question q, String p) {
163 String[] ss = Split.splitTrim('|', p,2);
164 if(ss[1]==null) { // older 1 part encoding must be evaluated for NS
165 Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]);
167 return Result.err(nss);
169 ss[0] = nss.value.ns;
170 ss[1] = nss.value.name;
172 return Result.ok(ss);
176 public int[] invalidate(Cached<?,?> cache) {
185 public ByteBuffer bytify() throws IOException {
186 ByteArrayOutputStream baos = new ByteArrayOutputStream();
187 RoleLoader.deflt.marshal(this,new DataOutputStream(baos));
188 return ByteBuffer.wrap(baos.toByteArray());
192 public void reconstitute(ByteBuffer bb) throws IOException {
193 RoleLoader.deflt.unmarshal(this, toDIS(bb));
197 public String toString() {
198 return ns + '.' + name;
202 private static class RoleLoader extends Loader<Data> implements Streamer<Data> {
203 public static final int MAGIC=923577343;
204 public static final int VERSION=1;
205 public static final int BUFF_SIZE=96;
207 public static final RoleLoader deflt = new RoleLoader(KEYLIMIT);
209 public RoleLoader(int keylimit) {
214 public Data load(Data data, Row row) {
215 // Int more efficient
216 data.ns = row.getString(0);
217 data.name = row.getString(1);
218 data.perms = row.getSet(2,String.class);
219 data.description = row.getString(3);
224 protected void key(Data data, int _idx, Object[] obj) {
227 obj[++idx]=data.name;
231 protected void body(Data data, int _idx, Object[] obj) {
234 obj[++idx]=data.description;
238 public void marshal(Data data, DataOutputStream os) throws IOException {
239 writeHeader(os,MAGIC,VERSION);
240 writeString(os, data.ns);
241 writeString(os, data.name);
242 writeStringSet(os,data.perms);
243 writeString(os, data.description);
247 public void unmarshal(Data data, DataInputStream is) throws IOException {
248 /*int version = */readHeader(is,MAGIC,VERSION);
249 // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields
250 byte[] buff = new byte[BUFF_SIZE];
251 data.ns = readString(is, buff);
252 data.name = readString(is,buff);
253 data.perms = readStringSet(is,buff);
254 data.description = readString(is,buff);
258 private void init(AuthzTrans trans) {
259 String[] helpers = setCRUD(trans, TABLE, Data.class, RoleLoader.deflt);
261 psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
262 " WHERE ns = ?", new RoleLoader(1),readConsistency);
264 psName = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
265 " WHERE name = ?", new RoleLoader(1),readConsistency);
267 psChildren = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
268 " WHERE ns=? AND name > ? AND name < ?",
271 protected void key(Data data, int _idx, Object[] obj) {
274 obj[++idx]=data.name + DOT;
275 obj[++idx]=data.name + DOT_PLUS_ONE;
281 public Result<List<Data>> readNS(AuthzTrans trans, String ns) {
282 return psNS.read(trans, R_TEXT + " NS " + ns, new Object[]{ns});
285 public Result<List<Data>> readName(AuthzTrans trans, String name) {
286 return psName.read(trans, R_TEXT + name, new Object[]{name});
289 public Result<List<Data>> readChildren(AuthzTrans trans, String ns, String role) {
290 if(role.length()==0 || "*".equals(role)) {
291 return psChildren.read(trans, R_TEXT, new Object[]{ns, FIRST_CHAR, LAST_CHAR});
293 return psChildren.read(trans, R_TEXT, new Object[]{ns, role+DOT, role+DOT_PLUS_ONE});
298 * Add a single Permission to the Role's Permission Collection
307 public Result<Void> addPerm(AuthzTrans trans, RoleDAO.Data role, PermDAO.Data perm) {
308 // Note: Prepared Statements for Collection updates aren't supported
309 String pencode = perm.encode();
311 getSession(trans).execute(UPDATE_SP + TABLE + " SET perms = perms + {'" +
312 pencode + "'} WHERE " +
313 "ns = '" + role.ns + "' AND name = '" + role.name + "';");
314 } catch (DriverException | APIException | IOException e) {
315 reportPerhapsReset(trans,e);
316 return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG);
319 wasModified(trans, CRUD.update, role, "Added permission " + pencode + " to role " + role.fullName());
324 * Remove a single Permission from the Role's Permission Collection
332 public Result<Void> delPerm(AuthzTrans trans, RoleDAO.Data role, PermDAO.Data perm) {
333 // Note: Prepared Statements for Collection updates aren't supported
335 String pencode = perm.encode();
339 getSession(trans).execute(UPDATE_SP + TABLE + " SET perms = perms - {'" +
340 pencode + "'} WHERE " +
341 "ns = '" + role.ns + "' AND name = '" + role.name + "';");
342 } catch (DriverException | APIException | IOException e) {
343 reportPerhapsReset(trans,e);
344 return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG);
347 //TODO how can we tell when it doesn't?
348 wasModified(trans, CRUD.update, role, "Removed permission " + pencode + " from role " + role.fullName() );
353 * Add description to role
361 public Result<Void> addDescription(AuthzTrans trans, String ns, String name, String description) {
363 getSession(trans).execute(UPDATE_SP + TABLE + " SET description = '"
364 + description + "' WHERE ns = '" + ns + "' AND name = '" + name + "';");
365 } catch (DriverException | APIException | IOException e) {
366 reportPerhapsReset(trans,e);
367 return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG);
370 Data data = new Data();
373 wasModified(trans, CRUD.update, data, "Added description " + description + " to role " + data.fullName(), null );
379 * Log Modification statements to History
380 * @param modified which CRUD action was done
381 * @param data entity data that needs a log entry
382 * @param overrideMessage if this is specified, we use it rather than crafting a history message based on data
385 protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) {
386 boolean memo = override.length>0 && override[0]!=null;
387 boolean subject = override.length>1 && override[1]!=null;
389 HistoryDAO.Data hd = HistoryDAO.newInitedData();
390 hd.user = trans.user();
391 hd.action = modified.name();
393 hd.subject = subject ? override[1] : data.fullName();
394 hd.memo = memo ? override[0] : (data.fullName() + " was " + modified.name() + 'd' );
395 if(modified==CRUD.delete) {
397 hd.reconstruct = data.bytify();
398 } catch (IOException e) {
399 trans.error().log(e,"Could not serialize RoleDAO.Data");
403 if(historyDAO.create(trans, hd).status!=Status.OK) {
404 trans.error().log("Cannot log to History");
406 if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) {
407 trans.error().log("Cannot touch CacheInfo for Role");