Merge "Fixed major sonar issues in CMService"
[aaf/authz.git] / auth / auth-certman / src / main / java / org / onap / aaf / auth / cm / service / CMService.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2018 IBM.
7  * ===========================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END====================================================
20  *
21  */
22
23 package org.onap.aaf.auth.cm.service;
24
25 import java.io.IOException;
26 import java.net.InetAddress;
27 import java.net.UnknownHostException;
28 import java.nio.ByteBuffer;
29 import java.security.NoSuchAlgorithmException;
30 import java.security.cert.X509Certificate;
31 import java.util.ArrayList;
32 import java.util.Date;
33 import java.util.HashSet;
34 import java.util.List;
35 import java.util.Set;
36
37 import org.onap.aaf.auth.cm.AAF_CM;
38 import org.onap.aaf.auth.cm.ca.CA;
39 import org.onap.aaf.auth.cm.ca.X509andChain;
40 import org.onap.aaf.auth.cm.cert.BCFactory;
41 import org.onap.aaf.auth.cm.cert.CSRMeta;
42 import org.onap.aaf.auth.cm.data.CertDrop;
43 import org.onap.aaf.auth.cm.data.CertRenew;
44 import org.onap.aaf.auth.cm.data.CertReq;
45 import org.onap.aaf.auth.cm.data.CertResp;
46 import org.onap.aaf.auth.cm.validation.CertmanValidator;
47 import org.onap.aaf.auth.dao.CassAccess;
48 import org.onap.aaf.auth.dao.cass.ArtiDAO;
49 import org.onap.aaf.auth.dao.cass.CacheInfoDAO;
50 import org.onap.aaf.auth.dao.cass.CertDAO;
51 import org.onap.aaf.auth.dao.cass.CertDAO.Data;
52 import org.onap.aaf.auth.dao.cass.CredDAO;
53 import org.onap.aaf.auth.dao.cass.HistoryDAO;
54 import org.onap.aaf.auth.dao.cass.Status;
55 import org.onap.aaf.auth.dao.hl.Question;
56 import org.onap.aaf.auth.env.AuthzTrans;
57 import org.onap.aaf.auth.layer.Result;
58 import org.onap.aaf.auth.org.Organization;
59 import org.onap.aaf.auth.org.Organization.Identity;
60 import org.onap.aaf.auth.org.OrganizationException;
61 import org.onap.aaf.cadi.Hash;
62 import org.onap.aaf.cadi.Permission;
63 import org.onap.aaf.cadi.aaf.AAFPermission;
64 import org.onap.aaf.cadi.config.Config;
65 import org.onap.aaf.cadi.configure.Factory;
66 import org.onap.aaf.cadi.util.FQI;
67 import org.onap.aaf.misc.env.APIException;
68 import org.onap.aaf.misc.env.util.Chrono;
69
70 public class CMService {
71     // If we add more CAs, may want to parameterize
72     private static final int STD_RENEWAL = 30;
73     private static final int MAX_RENEWAL = 60;
74     private static final int MIN_RENEWAL = 10;
75
76     public static final String REQUEST = "request";
77     public static final String IGNORE_IPS = "ignoreIPs";
78     public static final String RENEW = "renew";
79     public static final String DROP = "drop";
80     public static final String DOMAIN = "domain";
81
82     private static final String CERTMAN = "certman";
83     private static final String ACCESS = "access";
84
85     private static final String[] NO_NOTES = new String[0];
86     private final Permission root_read_permission;
87     private final CertDAO certDAO;
88     private final CredDAO credDAO;
89     private final ArtiDAO artiDAO;
90     private AAF_CM certManager;
91
92     // @SuppressWarnings("unchecked")
93     public CMService(final AuthzTrans trans, AAF_CM certman) throws APIException, IOException {
94         // Jonathan 4/2015 SessionFilter unneeded... DataStax already deals with
95         // Multithreading well
96
97         HistoryDAO hd = new HistoryDAO(trans, certman.cluster, CassAccess.KEYSPACE);
98         CacheInfoDAO cid = new CacheInfoDAO(trans, hd);
99         certDAO = new CertDAO(trans, hd, cid);
100         credDAO = new CredDAO(trans, hd, cid);
101         artiDAO = new ArtiDAO(trans, hd, cid);
102
103         this.certManager = certman;
104
105         root_read_permission=new AAFPermission(
106                 trans.getProperty(Config.AAF_ROOT_NS, Config.AAF_ROOT_NS_DEF),
107                 ACCESS,
108                 "*",
109                 "read"
110         );
111     }
112
113     public Result<CertResp> requestCert(final AuthzTrans trans, final Result<CertReq> req, final CA ca) {
114         if (req.isOK()) {
115
116             if (req.value.fqdns.isEmpty()) {
117                 return Result.err(Result.ERR_BadData, "No Machines passed in Request");
118             }
119
120             String key = req.value.fqdns.get(0);
121
122             // Policy 6: Requester must be granted Change permission in Namespace requested
123             String mechNS = FQI.reverseDomain(req.value.mechid);
124             if (mechNS == null) {
125                 return Result.err(Status.ERR_Denied, "%s does not reflect a valid AAF Namespace", req.value.mechid);
126             }
127
128             List<String> notes = null;
129             List<String> fqdns = new ArrayList<>(req.value.fqdns);
130
131             String email = null;
132
133             try {
134                 Organization org = trans.org();
135
136                 boolean ignoreIPs = trans.fish(new AAFPermission(mechNS,CERTMAN, ca.getName(), IGNORE_IPS));
137
138                 InetAddress primary = null;
139                 // Organize incoming information to get to appropriate Artifact
140                 if (!fqdns.isEmpty()) {
141                     // Accept domain wild cards, but turn into real machines
142                     // Need *domain.com:real.machine.domain.com:san.machine.domain.com:...
143                     if (fqdns.get(0).startsWith("*")) { // Domain set
144                         if (!trans.fish(new AAFPermission(null,ca.getPermType(), ca.getName(), DOMAIN))) {
145                             return Result.err(Result.ERR_Denied,
146                                     "Domain based Authorizations (" + fqdns.get(0) + ") requires Exception");
147                         }
148
149                         // check for Permission in Add Artifact?
150                         String domain = fqdns.get(0).substring(1);
151                         fqdns.remove(0);
152                         if (fqdns.isEmpty()) {
153                             return Result.err(Result.ERR_Denied, "Requests using domain require machine declaration");
154                         }
155
156                         if (!ignoreIPs) {
157                             InetAddress ia = InetAddress.getByName(fqdns.get(0));
158                             if (ia == null) {
159                                 return Result.err(Result.ERR_Denied,
160                                         "Request not made from matching IP matching domain");
161                             } else if (ia.getHostName().endsWith(domain)) {
162                                 primary = ia;
163                             }
164                         }
165
166                     } else {
167                         for (String cn : req.value.fqdns) {
168                             if (!ignoreIPs) {
169                                 try {
170                                     InetAddress[] ias = InetAddress.getAllByName(cn);
171                                     Set<String> potentialSanNames = new HashSet<>();
172                                     for (InetAddress ia1 : ias) {
173                                         InetAddress ia2 = InetAddress.getByAddress(ia1.getAddress());
174                                         if (primary == null && ias.length == 1 && trans.ip().equals(ia1.getHostAddress())) {
175                                             primary = ia1;
176                                         } else if (!cn.equals(ia1.getHostName())
177                                                 && !ia2.getHostName().equals(ia2.getHostAddress())) {
178                                             potentialSanNames.add(ia1.getHostName());
179                                         }
180                                     }
181                                 } catch (UnknownHostException e1) {
182                                     trans.debug().log(e1);
183                                     return Result.err(Result.ERR_BadData, "There is no DNS lookup for %s", cn);
184                                 }
185                             }
186                         }
187                     }
188                 }
189
190                 final String host;
191                 if (ignoreIPs) {
192                     host = req.value.fqdns.get(0);
193                 } else if (primary == null) {
194                     return Result.err(Result.ERR_Denied, "Request not made from matching IP (%s)", trans.ip());
195                 } else {
196                     host = primary.getHostAddress();
197                 }
198
199                 ArtiDAO.Data add = null;
200                 Result<List<ArtiDAO.Data>> ra = artiDAO.read(trans, req.value.mechid, host);
201                 if (ra.isOKhasData()) {
202                     if (add == null) {
203                         add = ra.value.get(0); // single key
204                     }
205                 } else {
206                     ra = artiDAO.read(trans, req.value.mechid, key);
207                     if (ra.isOKhasData()) { // is the Template available?
208                         add = ra.value.get(0);
209                         add.machine = host;
210                         for (String s : fqdns) {
211                             if (!s.equals(add.machine)) {
212                                 add.sans(true).add(s);
213                             }
214                         }
215                         Result<ArtiDAO.Data> rc = artiDAO.create(trans, add); // Create new Artifact from Template
216                         if (rc.notOK()) {
217                             return Result.err(rc);
218                         }
219                     } else {
220                         add = ra.value.get(0);
221                     }
222                 }
223
224                 // Add Artifact listed FQDNs
225                 if (add.sans != null) {
226                     for (String s : add.sans) {
227                         if (!fqdns.contains(s)) {
228                             fqdns.add(s);
229                         }
230                     }
231                 }
232
233                 // Policy 2: If Config marked as Expired, do not create or renew
234                 Date now = new Date();
235                 if (add.expires != null && now.after(add.expires)) {
236                     return Result.err(Result.ERR_Policy, "Configuration for %s %s is expired %s", add.mechid,
237                             add.machine, Chrono.dateFmt.format(add.expires));
238                 }
239
240                 // Policy 3: MechID must be current
241                 Identity muser = org.getIdentity(trans, add.mechid);
242                 if (muser == null) {
243                     return Result.err(Result.ERR_Policy, "MechID must exist in %s", org.getName());
244                 }
245
246                 // Policy 4: Sponsor must be current
247                 Identity ouser = muser.responsibleTo();
248                 if (ouser == null) {
249                     return Result.err(Result.ERR_Policy, "%s does not have a current sponsor at %s", add.mechid,
250                             org.getName());
251                 } else if (!ouser.isFound() || ouser.mayOwn() != null) {
252                     return Result.err(Result.ERR_Policy, "%s reports that %s cannot be responsible for %s",
253                             org.getName(), trans.user());
254                 }
255
256                 // Set Email from most current Sponsor
257                 email = ouser.email();
258
259                 // Policy 5: keep Artifact data current
260                 if (!ouser.fullID().equals(add.sponsor)) {
261                     add.sponsor = ouser.fullID();
262                     artiDAO.update(trans, add);
263                 }
264
265                 // Policy 7: Caller must be the MechID or have specifically delegated
266                 // permissions
267                 if (!(trans.user().equals(req.value.mechid)
268                         || trans.fish(new AAFPermission(mechNS,CERTMAN, ca.getName(), REQUEST)))) {
269                     return Result.err(Status.ERR_Denied, "%s must have access to modify x509 certs in NS %s",
270                             trans.user(), mechNS);
271                 }
272
273                 // Make sure Primary is the first in fqdns
274                 if (fqdns.size() > 1) {
275                     for (int i = 0; i < fqdns.size(); ++i) {
276                         if (primary==null) {
277                             trans.error().log("CMService var primary is null");
278                         } else {
279                             String fg = fqdns.get(i);
280                             if (fg!=null && fg.equals(primary.getHostName())) {
281                                 if (i != 0) {
282                                     String tmp = fqdns.get(0);
283                                     fqdns.set(0, primary.getHostName());
284                                     fqdns.set(i, tmp);
285                                 }
286                             }
287                         }
288                     }
289                 }
290             } catch (Exception e) {
291                 trans.debug().log(e);
292                 return Result.err(Status.ERR_Denied,
293                         "AppID Sponsorship cannot be determined at this time.  Try later.");
294             }
295
296             CSRMeta csrMeta;
297             try {
298                 csrMeta = BCFactory.createCSRMeta(ca, req.value.mechid, email, fqdns);
299                 X509andChain x509ac = ca.sign(trans, csrMeta);
300                 if (x509ac == null) {
301                     return Result.err(Result.ERR_ActionNotCompleted, "x509 Certificate not signed by CA");
302                 }
303                 trans.info().printf("X509 Subject: %s", x509ac.getX509().getSubjectDN());
304
305                 X509Certificate x509 = x509ac.getX509();
306                 CertDAO.Data cdd = new CertDAO.Data();
307                 cdd.ca = ca.getName();
308                 cdd.serial = x509.getSerialNumber();
309                 cdd.id = req.value.mechid;
310                 cdd.x500 = x509.getSubjectDN().getName();
311                 cdd.x509 = Factory.toString(trans, x509);
312                 certDAO.create(trans, cdd);
313
314                 CredDAO.Data crdd = new CredDAO.Data();
315                 crdd.other = Question.random.nextInt();
316                 crdd.cred = getChallenge256SaltedHash(csrMeta.challenge(), crdd.other);
317                 crdd.expires = x509.getNotAfter();
318                 crdd.id = req.value.mechid;
319                 crdd.ns = Question.domain2ns(crdd.id);
320                 crdd.type = CredDAO.CERT_SHA256_RSA;
321                 credDAO.create(trans, crdd);
322
323                 CertResp cr = new CertResp(trans, ca, x509, csrMeta, x509ac.getTrustChain(), compileNotes(notes));
324                 return Result.ok(cr);
325             } catch (Exception e) {
326                 trans.debug().log(e);
327                 return Result.err(Result.ERR_ActionNotCompleted, e.getMessage());
328             }
329         } else {
330             return Result.err(req);
331         }
332     }
333
334     public Result<CertResp> renewCert(AuthzTrans trans, Result<CertRenew> renew) {
335         if (renew.isOK()) {
336             return Result.err(Result.ERR_NotImplemented, "Not implemented yet");
337         } else {
338             return Result.err(renew);
339         }
340     }
341
342     public Result<Void> dropCert(AuthzTrans trans, Result<CertDrop> drop) {
343         if (drop.isOK()) {
344             return Result.err(Result.ERR_NotImplemented, "Not implemented yet");
345         } else {
346             return Result.err(drop);
347         }
348     }
349
350     public Result<List<Data>> readCertsByMechID(AuthzTrans trans, String mechID) {
351         // Policy 1: To Read, must have NS Read or is Sponsor
352         String ns = Question.domain2ns(mechID);
353         try {
354             if (trans.user().equals(mechID) || trans.fish(new AAFPermission(ns,ACCESS, "*", "read"))
355                     || (trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, mechID)) == null) {
356                 return certDAO.readID(trans, mechID);
357             } else {
358                 return Result.err(Result.ERR_Denied, "%s is not the ID, Sponsor or NS Owner/Admin for %s at %s",
359                         trans.user(), mechID, trans.org().getName());
360             }
361         } catch (OrganizationException e) {
362             return Result.err(e);
363         }
364     }
365
366     public Result<CertResp> requestPersonalCert(AuthzTrans trans, CA ca) {
367         if (ca.inPersonalDomains(trans.getUserPrincipal())) {
368             Organization org = trans.org();
369
370             // Policy 1: MechID must be current
371             Identity ouser;
372             try {
373                 ouser = org.getIdentity(trans, trans.user());
374             } catch (OrganizationException e1) {
375                 trans.debug().log(e1);
376                 ouser = null;
377             }
378             if (ouser == null) {
379                 return Result.err(Result.ERR_Policy, "Requesting User must exist in %s", org.getName());
380             }
381
382             // Set Email from most current Sponsor
383
384             CSRMeta csrMeta;
385             try {
386                 csrMeta = BCFactory.createPersonalCSRMeta(ca, trans.user(), ouser.email());
387                 X509andChain x509ac = ca.sign(trans, csrMeta);
388                 if (x509ac == null) {
389                     return Result.err(Result.ERR_ActionNotCompleted, "x509 Certificate not signed by CA");
390                 }
391                 X509Certificate x509 = x509ac.getX509();
392                 CertDAO.Data cdd = new CertDAO.Data();
393                 cdd.ca = ca.getName();
394                 cdd.serial = x509.getSerialNumber();
395                 cdd.id = trans.user();
396                 cdd.x500 = x509.getSubjectDN().getName();
397                 cdd.x509 = Factory.toString(trans, x509);
398                 certDAO.create(trans, cdd);
399
400                 CertResp cr = new CertResp(trans, ca, x509, csrMeta, x509ac.getTrustChain(), compileNotes(null));
401                 return Result.ok(cr);
402             } catch (Exception e) {
403                 trans.debug().log(e);
404                 return Result.err(Result.ERR_ActionNotCompleted, e.getMessage());
405             }
406         } else {
407             return Result.err(Result.ERR_Denied, trans.user(), " not supported for CA", ca.getName());
408         }
409     }
410
411     ///////////////
412     // Artifact
413     //////////////
414     public Result<Void> createArtifact(AuthzTrans trans, List<ArtiDAO.Data> list) {
415         CertmanValidator v = new CertmanValidator().artisRequired(list, 1);
416         if (v.err()) {
417             return Result.err(Result.ERR_BadData, v.errs());
418         }
419         for (ArtiDAO.Data add : list) {
420             try {
421                 // Policy 1: MechID must exist in Org
422                 Identity muser = trans.org().getIdentity(trans, add.mechid);
423                 if (muser == null) {
424                     return Result.err(Result.ERR_Denied, "%s is not valid for %s", add.mechid, trans.org().getName());
425                 }
426
427                 // Policy 2: MechID must have valid Organization Owner
428                 Identity emailUser;
429                 if (muser.isPerson()) {
430                     emailUser = muser;
431                 } else {
432                     Identity ouser = muser.responsibleTo();
433                     if (ouser == null) {
434                         return Result.err(Result.ERR_Denied, "%s is not a valid Sponsor for %s at %s", trans.user(),
435                                 add.mechid, trans.org().getName());
436                     }
437
438                     // Policy 3: Calling ID must be MechID Owner
439                     if (!trans.user().startsWith(ouser.id())) {
440                         return Result.err(Result.ERR_Denied, "%s is not the Sponsor for %s at %s", trans.user(),
441                                 add.mechid, trans.org().getName());
442                     }
443                     emailUser = ouser;
444                 }
445
446                 // Policy 4: Renewal Days are between 10 and 60 (constants, may be
447                 // parameterized)
448                 if (add.renewDays < MIN_RENEWAL) {
449                     add.renewDays = STD_RENEWAL;
450                 } else if (add.renewDays > MAX_RENEWAL) {
451                     add.renewDays = MAX_RENEWAL;
452                 }
453
454                 // Policy 5: If Notify is blank, set to Owner's Email
455                 if (add.notify == null || add.notify.length() == 0) {
456                     add.notify = "mailto:" + emailUser.email();
457                 }
458
459                 // Policy 6: Only do Domain by Exception
460                 if (add.machine.startsWith("*")) { // Domain set
461                     CA ca = certManager.getCA(add.ca);
462
463                     if (!trans.fish(new AAFPermission(ca.getPermNS(),ca.getPermType(), add.ca, DOMAIN))) {
464                         return Result.err(Result.ERR_Denied, "Domain Artifacts (%s) requires specific Permission",
465                                 add.machine);
466                     }
467                 }
468
469                 // Set Sponsor from Golden Source
470                 add.sponsor = emailUser.fullID();
471
472             } catch (OrganizationException e) {
473                 return Result.err(e);
474             }
475             // Add to DB
476             Result<ArtiDAO.Data> rv = artiDAO.create(trans, add);
477             //  come up with Partial Reporting Scheme, or allow only one at a time.
478             if (rv.notOK()) {
479                 return Result.err(rv);
480             }
481         }
482         return Result.ok();
483     }
484
485     public Result<List<ArtiDAO.Data>> readArtifacts(AuthzTrans trans, ArtiDAO.Data add) throws OrganizationException {
486         CertmanValidator v = new CertmanValidator().keys(add);
487         if (v.err()) {
488             return Result.err(Result.ERR_BadData, v.errs());
489         }
490         Result<List<ArtiDAO.Data>> data = artiDAO.read(trans, add);
491         if (data.notOKorIsEmpty()) {
492             return data;
493         }
494         add = data.value.get(0);
495         if (trans.user().equals(add.mechid)
496                 || trans.fish(root_read_permission,
497                 new AAFPermission(add.ns,ACCESS, "*", "read"),
498                 new AAFPermission(add.ns,CERTMAN, add.ca, "read"),
499                 new AAFPermission(add.ns,CERTMAN, add.ca, REQUEST))
500                 || (trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, add.mechid)) == null) {
501             return data;
502         } else {
503             return Result.err(Result.ERR_Denied,
504                     "%s is not %s, is not the sponsor, and doesn't have delegated permission.", trans.user(),
505                     add.mechid, add.ns + ".certman|" + add.ca + "|read or ...|request"); // note: reason is set by 2nd
506             // case, if 1st case misses
507         }
508
509     }
510
511     public Result<List<ArtiDAO.Data>> readArtifactsByMechID(AuthzTrans trans, String mechid)
512             throws OrganizationException {
513         CertmanValidator v = new CertmanValidator();
514         v.nullOrBlank("mechid", mechid);
515         if (v.err()) {
516             return Result.err(Result.ERR_BadData, v.errs());
517         }
518         String ns = FQI.reverseDomain(mechid);
519
520         String reason;
521         if (trans.fish(new AAFPermission(ns, ACCESS, "*", "read"))
522                 || (reason = trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, mechid)) == null) {
523             return artiDAO.readByMechID(trans, mechid);
524         } else {
525             return Result.err(Result.ERR_Denied, reason); // note: reason is set by 2nd case, if 1st case misses
526         }
527
528     }
529
530     public Result<List<ArtiDAO.Data>> readArtifactsByMachine(AuthzTrans trans, String machine) {
531         CertmanValidator v = new CertmanValidator();
532         v.nullOrBlank("machine", machine);
533         if (v.err()) {
534             return Result.err(Result.ERR_BadData, v.errs());
535         }
536
537         //  do some checks?
538
539         return artiDAO.readByMachine(trans, machine);
540     }
541
542     public Result<List<ArtiDAO.Data>> readArtifactsByNs(AuthzTrans trans, String ns) {
543         CertmanValidator v = new CertmanValidator();
544         v.nullOrBlank("ns", ns);
545         if (v.err()) {
546             return Result.err(Result.ERR_BadData, v.errs());
547         }
548
549         //  do some checks?
550         return artiDAO.readByNs(trans, ns);
551     }
552
553     public Result<Void> updateArtifact(AuthzTrans trans, List<ArtiDAO.Data> list) throws OrganizationException {
554         CertmanValidator v = new CertmanValidator();
555         v.artisRequired(list, 1);
556         if (v.err()) {
557             return Result.err(Result.ERR_BadData, v.errs());
558         }
559
560         // Check if requesting User is Sponsor
561         //  Shall we do one, or multiples?
562         for (ArtiDAO.Data add : list) {
563             // Policy 1: MechID must exist in Org
564             Identity muser = trans.org().getIdentity(trans, add.mechid);
565             if (muser == null) {
566                 return Result.err(Result.ERR_Denied, "%s is not valid for %s", add.mechid, trans.org().getName());
567             }
568
569             // Policy 2: MechID must have valid Organization Owner
570             Identity ouser = muser.responsibleTo();
571             if (ouser == null) {
572                 return Result.err(Result.ERR_Denied, "%s is not a valid Sponsor for %s at %s", trans.user(), add.mechid,
573                         trans.org().getName());
574             }
575
576             // Policy 3: Renewal Days are between 10 and 60 (constants, may be
577             // parameterized)
578             if (add.renewDays < MIN_RENEWAL) {
579                 add.renewDays = STD_RENEWAL;
580             } else if (add.renewDays > MAX_RENEWAL) {
581                 add.renewDays = MAX_RENEWAL;
582             }
583
584             // Policy 4: Data is always updated with the latest Sponsor
585             // Add to Sponsor, to make sure we are always up to date.
586             add.sponsor = ouser.fullID();
587
588             // Policy 5: If Notify is blank, set to Owner's Email
589             if (add.notify == null || add.notify.length() == 0) {
590                 add.notify = "mailto:" + ouser.email();
591             }
592             // Policy 6: Only do Domain by Exception
593             if (add.machine.startsWith("*")) { // Domain set
594                 CA ca = certManager.getCA(add.ca);
595                 if (ca == null) {
596                     return Result.err(Result.ERR_BadData, "CA is required in Artifact");
597                 }
598                 if (!trans.fish(new AAFPermission(null,ca.getPermType(), add.ca, DOMAIN))) {
599                     return Result.err(Result.ERR_Denied, "Domain Artifacts (%s) requires specific Permission",
600                             add.machine);
601                 }
602             }
603
604             // Policy 7: only Owner may update info
605             if (trans.user().startsWith(ouser.id())) {
606                 return artiDAO.update(trans, add);
607             } else {
608                 return Result.err(Result.ERR_Denied, "%s may not update info for %s", trans.user(), muser.fullID());
609             }
610         }
611         return Result.err(Result.ERR_BadData, "No Artifacts to update");
612     }
613
614     public Result<Void> deleteArtifact(AuthzTrans trans, String mechid, String machine) throws OrganizationException {
615         CertmanValidator v = new CertmanValidator();
616         v.nullOrBlank("mechid", mechid).nullOrBlank("machine", machine);
617         if (v.err()) {
618             return Result.err(Result.ERR_BadData, v.errs());
619         }
620
621         Result<List<ArtiDAO.Data>> rlad = artiDAO.read(trans, mechid, machine);
622         if (rlad.notOKorIsEmpty()) {
623             return Result.err(Result.ERR_NotFound, "Artifact for %s %s does not exist.", mechid, machine);
624         }
625
626         return deleteArtifact(trans, rlad.value.get(0));
627     }
628
629     private Result<Void> deleteArtifact(AuthzTrans trans, ArtiDAO.Data add) throws OrganizationException {
630         // Policy 1: Record should be delete able only by Existing Sponsor.
631         String sponsor = null;
632         Identity muser = trans.org().getIdentity(trans, add.mechid);
633         if (muser != null) {
634             Identity ouser = muser.responsibleTo();
635             if (ouser != null) {
636                 sponsor = ouser.fullID();
637             }
638         }
639         // Policy 1.a: If Sponsorship is deleted in system of Record, then
640         // accept deletion by sponsor in Artifact Table
641         if (sponsor == null) {
642             sponsor = add.sponsor;
643         }
644
645         String ns = FQI.reverseDomain(add.mechid);
646
647         if (trans.fish(new AAFPermission(ns,ACCESS, "*", "write")) || trans.user().equals(sponsor)) {
648             return artiDAO.delete(trans, add, false);
649         }
650         return Result.err(Result.ERR_Denied, "%1 is not allowed to delete this item", trans.user());
651     }
652
653     public Result<Void> deleteArtifact(AuthzTrans trans, List<ArtiDAO.Data> list) {
654         CertmanValidator v = new CertmanValidator().artisRequired(list, 1);
655         if (v.err()) {
656             return Result.err(Result.ERR_BadData, v.errs());
657         }
658
659         try {
660             boolean partial = false;
661             Result<Void> result = null;
662             for (ArtiDAO.Data add : list) {
663                 result = deleteArtifact(trans, add);
664                 if (result.notOK()) {
665                     partial = true;
666                 }
667             }
668             if (result == null) {
669                 result = Result.err(Result.ERR_BadData, "No Artifacts to delete");
670             } else if (partial) {
671                 result.partialContent(true);
672             }
673             return result;
674         } catch (Exception e) {
675             return Result.err(e);
676         }
677     }
678
679     private String[] compileNotes(List<String> notes) {
680         String[] rv;
681         if (notes == null) {
682             rv = NO_NOTES;
683         } else {
684             rv = new String[notes.size()];
685             notes.toArray(rv);
686         }
687         return rv;
688     }
689
690     private ByteBuffer getChallenge256SaltedHash(String challenge, int salt) throws NoSuchAlgorithmException {
691         ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + challenge.length());
692         bb.putInt(salt);
693         bb.put(challenge.getBytes());
694         byte[] hash = Hash.hashSHA256(bb.array());
695         return ByteBuffer.wrap(hash);
696     }
697 }