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 StringBuilder sb = new StringBuilder();
113 sb.append(ns.indexOf('@')<0?'.':':');
116 return sb.toString();
119 public String encode() {
120 return ns + '|' + name;
124 * Decode Perm String, including breaking into appropriate Namespace
131 public static Result<Data> decode(AuthzTrans trans, Question q, String r) {
132 String[] ss = Split.splitTrim('|', r,2);
133 Data data = new Data();
134 if (ss[1]==null) { // older 1 part encoding must be evaluated for NS
135 Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]);
137 return Result.err(nss);
139 data.ns=nss.value.ns;
140 data.name=nss.value.name;
141 } else { // new 4 part encoding
145 return Result.ok(data);
149 * Decode from UserRole Data
153 public static RoleDAO.Data decode(UserRoleDAO.Data urdd) {
154 RoleDAO.Data rd = new RoleDAO.Data();
156 rd.name = urdd.rname;
162 * Decode Perm String, including breaking into appropriate Namespace
169 public static Result<String[]> decodeToArray(AuthzTrans trans, Question q, String p) {
170 String[] ss = Split.splitTrim('|', p,2);
171 if (ss[1]==null) { // older 1 part encoding must be evaluated for NS
172 Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]);
174 return Result.err(nss);
176 ss[0] = nss.value.ns;
177 ss[1] = nss.value.name;
179 return Result.ok(ss);
183 public int[] invalidate(Cached<?,?> cache) {
192 public ByteBuffer bytify() throws IOException {
193 ByteArrayOutputStream baos = new ByteArrayOutputStream();
194 RoleLoader.deflt.marshal(this,new DataOutputStream(baos));
195 return ByteBuffer.wrap(baos.toByteArray());
199 public void reconstitute(ByteBuffer bb) throws IOException {
200 RoleLoader.deflt.unmarshal(this, toDIS(bb));
204 public String toString() {
205 return ns + '.' + name;
209 private static class RoleLoader extends Loader<Data> implements Streamer<Data> {
210 public static final int MAGIC=923577343;
211 public static final int VERSION=1;
212 public static final int BUFF_SIZE=96;
214 public static final RoleLoader deflt = new RoleLoader(KEYLIMIT);
216 public RoleLoader(int keylimit) {
221 public Data load(Data data, Row row) {
222 // Int more efficient
223 data.ns = row.getString(0);
224 data.name = row.getString(1);
225 data.perms = row.getSet(2,String.class);
226 data.description = row.getString(3);
231 protected void key(Data data, int _idx, Object[] obj) {
234 obj[++idx]=data.name;
238 protected void body(Data data, int _idx, Object[] obj) {
241 obj[++idx]=data.description;
245 public void marshal(Data data, DataOutputStream os) throws IOException {
246 writeHeader(os,MAGIC,VERSION);
247 writeString(os, data.ns);
248 writeString(os, data.name);
249 writeStringSet(os,data.perms);
250 writeString(os, data.description);
254 public void unmarshal(Data data, DataInputStream is) throws IOException {
255 /*int version = */readHeader(is,MAGIC,VERSION);
256 // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields
257 byte[] buff = new byte[BUFF_SIZE];
258 data.ns = readString(is, buff);
259 data.name = readString(is,buff);
260 data.perms = readStringSet(is,buff);
261 data.description = readString(is,buff);
265 private void init(AuthzTrans trans) {
266 String[] helpers = setCRUD(trans, TABLE, Data.class, RoleLoader.deflt);
268 psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
269 " WHERE ns = ?", new RoleLoader(1),readConsistency);
271 psName = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
272 " WHERE name = ?", new RoleLoader(1),readConsistency);
274 psChildren = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +
275 " WHERE ns=? AND name > ? AND name < ?",
278 protected void key(Data data, int _idx, Object[] obj) {
281 obj[++idx]=data.name + DOT;
282 obj[++idx]=data.name + DOT_PLUS_ONE;
288 public Result<List<Data>> readNS(AuthzTrans trans, String ns) {
289 return psNS.read(trans, R_TEXT + " NS " + ns, new Object[]{ns});
292 public Result<List<Data>> readName(AuthzTrans trans, String name) {
293 return psName.read(trans, R_TEXT + name, new Object[]{name});
296 public Result<List<Data>> readChildren(AuthzTrans trans, String ns, String role) {
297 if (role.length()==0 || "*".equals(role)) {
298 return psChildren.read(trans, R_TEXT, new Object[]{ns, FIRST_CHAR, LAST_CHAR});
300 return psChildren.read(trans, R_TEXT, new Object[]{ns, role+DOT, role+DOT_PLUS_ONE});
305 * Add a single Permission to the Role's Permission Collection
314 public Result<Void> addPerm(AuthzTrans trans, RoleDAO.Data role, PermDAO.Data perm) {
315 // Note: Prepared Statements for Collection updates aren't supported
316 String pencode = perm.encode();
318 getSession(trans).execute(UPDATE_SP + TABLE + " SET perms = perms + {'" +
319 pencode + "'} WHERE " +
320 "ns = '" + role.ns + "' AND name = '" + role.name + "';");
321 } catch (DriverException | APIException | IOException e) {
322 reportPerhapsReset(trans,e);
323 return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG);
326 wasModified(trans, CRUD.update, role, "Added permission " + pencode + " to role " + role.fullName());
331 * Remove a single Permission from the Role's Permission Collection
339 public Result<Void> delPerm(AuthzTrans trans, RoleDAO.Data role, PermDAO.Data perm) {
340 // Note: Prepared Statements for Collection updates aren't supported
342 String pencode = perm.encode();
346 getSession(trans).execute(UPDATE_SP + TABLE + " SET perms = perms - {'" +
347 pencode + "'} WHERE " +
348 "ns = '" + role.ns + "' AND name = '" + role.name + "';");
349 } catch (DriverException | APIException | IOException e) {
350 reportPerhapsReset(trans,e);
351 return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG);
354 //TODO how can we tell when it doesn't?
355 wasModified(trans, CRUD.update, role, "Removed permission " + pencode + " from role " + role.fullName() );
360 * Add description to role
368 public Result<Void> addDescription(AuthzTrans trans, String ns, String name, String description) {
370 getSession(trans).execute(UPDATE_SP + TABLE + " SET description = '"
371 + description + "' WHERE ns = '" + ns + "' AND name = '" + name + "';");
372 } catch (DriverException | APIException | IOException e) {
373 reportPerhapsReset(trans,e);
374 return Result.err(Result.ERR_Backend, CassAccess.ERR_ACCESS_MSG);
377 Data data = new Data();
380 wasModified(trans, CRUD.update, data, "Added description " + description + " to role " + data.fullName(), null );
386 * Log Modification statements to History
387 * @param modified which CRUD action was done
388 * @param data entity data that needs a log entry
389 * @param overrideMessage if this is specified, we use it rather than crafting a history message based on data
392 protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) {
393 boolean memo = override.length>0 && override[0]!=null;
394 boolean subject = override.length>1 && override[1]!=null;
396 HistoryDAO.Data hd = HistoryDAO.newInitedData();
397 hd.user = trans.user();
398 hd.action = modified.name();
400 hd.subject = subject ? override[1] : data.fullName();
401 hd.memo = memo ? override[0] : (data.fullName() + " was " + modified.name() + 'd' );
402 if (modified==CRUD.delete) {
404 hd.reconstruct = data.bytify();
405 } catch (IOException e) {
406 trans.error().log(e,"Could not serialize RoleDAO.Data");
410 if (historyDAO.create(trans, hd).status!=Status.OK) {
411 trans.error().log("Cannot log to History");
413 if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) {
414 trans.error().log("Cannot touch CacheInfo for Role");