Fixes/Refinements from Testing
[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                     String thost = primary.getHostName();
197                     host = thost==null?primary.getHostAddress():thost;
198                 }
199
200                 ArtiDAO.Data add = null;
201                 Result<List<ArtiDAO.Data>> ra = artiDAO.read(trans, req.value.mechid, host);
202                 if (ra.isOKhasData()) {
203                     if (add == null) {
204                         add = ra.value.get(0); // single key
205                     }
206                 } else {
207                     ra = artiDAO.read(trans, req.value.mechid, key);
208                     if (ra.isOKhasData()) { // is the Template available?
209                         add = ra.value.get(0);
210                         add.machine = host;
211                         for (String s : fqdns) {
212                             if (!s.equals(add.machine)) {
213                                 add.sans(true).add(s);
214                             }
215                         }
216                         Result<ArtiDAO.Data> rc = artiDAO.create(trans, add); // Create new Artifact from Template
217                         if (rc.notOK()) {
218                             return Result.err(rc);
219                         }
220                     } else {
221                         add = ra.value.get(0);
222                     }
223                 }
224
225                 // Add Artifact listed FQDNs
226                 if (add.sans != null) {
227                     for (String s : add.sans) {
228                         if (!fqdns.contains(s)) {
229                             fqdns.add(s);
230                         }
231                     }
232                 }
233
234                 // Policy 2: If Config marked as Expired, do not create or renew
235                 Date now = new Date();
236                 if (add.expires != null && now.after(add.expires)) {
237                     return Result.err(Result.ERR_Policy, "Configuration for %s %s is expired %s", add.mechid,
238                             add.machine, Chrono.dateFmt.format(add.expires));
239                 }
240
241                 // Policy 3: MechID must be current
242                 Identity muser = org.getIdentity(trans, add.mechid);
243                 if (muser == null) {
244                     return Result.err(Result.ERR_Policy, "MechID must exist in %s", org.getName());
245                 }
246
247                 // Policy 4: Sponsor must be current
248                 Identity ouser = muser.responsibleTo();
249                 if (ouser == null) {
250                     return Result.err(Result.ERR_Policy, "%s does not have a current sponsor at %s", add.mechid,
251                             org.getName());
252                 } else if (!ouser.isFound() || ouser.mayOwn() != null) {
253                     return Result.err(Result.ERR_Policy, "%s reports that %s cannot be responsible for %s",
254                             org.getName(), trans.user());
255                 }
256
257                 // Set Email from most current Sponsor
258                 email = ouser.email();
259
260                 // Policy 5: keep Artifact data current
261                 if (!ouser.fullID().equals(add.sponsor)) {
262                     add.sponsor = ouser.fullID();
263                     artiDAO.update(trans, add);
264                 }
265
266                 // Policy 7: Caller must be the MechID or have specifically delegated
267                 // permissions
268                 if (!(trans.user().equals(req.value.mechid)
269                         || trans.fish(new AAFPermission(mechNS,CERTMAN, ca.getName(), REQUEST)))) {
270                     return Result.err(Status.ERR_Denied, "%s must have access to modify x509 certs in NS %s",
271                             trans.user(), mechNS);
272                 }
273
274                 // Make sure Primary is the first in fqdns
275                 if (fqdns.size() > 1) {
276                     for (int i = 0; i < fqdns.size(); ++i) {
277                         if (primary==null) {
278                             trans.error().log("CMService var primary is null");
279                         } else {
280                             String fg = fqdns.get(i);
281                             if (fg!=null && fg.equals(primary.getHostName())) {
282                                 if (i != 0) {
283                                     String tmp = fqdns.get(0);
284                                     fqdns.set(0, primary.getHostName());
285                                     fqdns.set(i, tmp);
286                                 }
287                             }
288                         }
289                     }
290                 }
291             } catch (Exception e) {
292                 trans.debug().log(e);
293                 return Result.err(Status.ERR_Denied,
294                         "AppID Sponsorship cannot be determined at this time.  Try later.");
295             }
296
297             CSRMeta csrMeta;
298             try {
299                 csrMeta = BCFactory.createCSRMeta(ca, req.value.mechid, email, fqdns);
300                 X509andChain x509ac = ca.sign(trans, csrMeta);
301                 if (x509ac == null) {
302                     return Result.err(Result.ERR_ActionNotCompleted, "x509 Certificate not signed by CA");
303                 }
304                 trans.info().printf("X509 Subject: %s", x509ac.getX509().getSubjectDN());
305
306                 X509Certificate x509 = x509ac.getX509();
307                 CertDAO.Data cdd = new CertDAO.Data();
308                 cdd.ca = ca.getName();
309                 cdd.serial = x509.getSerialNumber();
310                 cdd.id = req.value.mechid;
311                 cdd.x500 = x509.getSubjectDN().getName();
312                 cdd.x509 = Factory.toString(trans, x509);
313                 certDAO.create(trans, cdd);
314
315                 CredDAO.Data crdd = new CredDAO.Data();
316                 crdd.other = Question.random.nextInt();
317                 crdd.cred = getChallenge256SaltedHash(csrMeta.challenge(), crdd.other);
318                 crdd.expires = x509.getNotAfter();
319                 crdd.id = req.value.mechid;
320                 crdd.ns = Question.domain2ns(crdd.id);
321                 crdd.type = CredDAO.CERT_SHA256_RSA;
322                 crdd.tag = cdd.serial.toString(16);
323                 credDAO.create(trans, crdd);
324
325                 CertResp cr = new CertResp(trans, ca, x509, csrMeta, x509ac.getTrustChain(), compileNotes(notes));
326                 return Result.ok(cr);
327             } catch (Exception e) {
328                 trans.debug().log(e);
329                 return Result.err(Result.ERR_ActionNotCompleted, e.getMessage());
330             }
331         } else {
332             return Result.err(req);
333         }
334     }
335
336     public Result<CertResp> renewCert(AuthzTrans trans, Result<CertRenew> renew) {
337         if (renew.isOK()) {
338             return Result.err(Result.ERR_NotImplemented, "Not implemented yet");
339         } else {
340             return Result.err(renew);
341         }
342     }
343
344     public Result<Void> dropCert(AuthzTrans trans, Result<CertDrop> drop) {
345         if (drop.isOK()) {
346             return Result.err(Result.ERR_NotImplemented, "Not implemented yet");
347         } else {
348             return Result.err(drop);
349         }
350     }
351
352     public Result<List<Data>> readCertsByMechID(AuthzTrans trans, String mechID) {
353         // Policy 1: To Read, must have NS Read or is Sponsor
354         String ns = Question.domain2ns(mechID);
355         try {
356             if (trans.user().equals(mechID) || trans.fish(new AAFPermission(ns,ACCESS, "*", "read"))
357                     || (trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, mechID)) == null) {
358                 return certDAO.readID(trans, mechID);
359             } else {
360                 return Result.err(Result.ERR_Denied, "%s is not the ID, Sponsor or NS Owner/Admin for %s at %s",
361                         trans.user(), mechID, trans.org().getName());
362             }
363         } catch (OrganizationException e) {
364             return Result.err(e);
365         }
366     }
367
368     public Result<CertResp> requestPersonalCert(AuthzTrans trans, CA ca) {
369         if (ca.inPersonalDomains(trans.getUserPrincipal())) {
370             Organization org = trans.org();
371
372             // Policy 1: MechID must be current
373             Identity ouser;
374             try {
375                 ouser = org.getIdentity(trans, trans.user());
376             } catch (OrganizationException e1) {
377                 trans.debug().log(e1);
378                 ouser = null;
379             }
380             if (ouser == null) {
381                 return Result.err(Result.ERR_Policy, "Requesting User must exist in %s", org.getName());
382             }
383
384             // Set Email from most current Sponsor
385
386             CSRMeta csrMeta;
387             try {
388                 csrMeta = BCFactory.createPersonalCSRMeta(ca, trans.user(), ouser.email());
389                 X509andChain x509ac = ca.sign(trans, csrMeta);
390                 if (x509ac == null) {
391                     return Result.err(Result.ERR_ActionNotCompleted, "x509 Certificate not signed by CA");
392                 }
393                 X509Certificate x509 = x509ac.getX509();
394                 CertDAO.Data cdd = new CertDAO.Data();
395                 cdd.ca = ca.getName();
396                 cdd.serial = x509.getSerialNumber();
397                 cdd.id = trans.user();
398                 cdd.x500 = x509.getSubjectDN().getName();
399                 cdd.x509 = Factory.toString(trans, x509);
400                 certDAO.create(trans, cdd);
401
402                 CertResp cr = new CertResp(trans, ca, x509, csrMeta, x509ac.getTrustChain(), compileNotes(null));
403                 return Result.ok(cr);
404             } catch (Exception e) {
405                 trans.debug().log(e);
406                 return Result.err(Result.ERR_ActionNotCompleted, e.getMessage());
407             }
408         } else {
409             return Result.err(Result.ERR_Denied, trans.user(), " not supported for CA", ca.getName());
410         }
411     }
412
413     ///////////////
414     // Artifact
415     //////////////
416     public Result<Void> createArtifact(AuthzTrans trans, List<ArtiDAO.Data> list) {
417         CertmanValidator v = new CertmanValidator().artisRequired(list, 1);
418         if (v.err()) {
419             return Result.err(Result.ERR_BadData, v.errs());
420         }
421         for (ArtiDAO.Data add : list) {
422             try {
423                 // Policy 1: MechID must exist in Org
424                 Identity muser = trans.org().getIdentity(trans, add.mechid);
425                 if (muser == null) {
426                     return Result.err(Result.ERR_Denied, "%s is not valid for %s", add.mechid, trans.org().getName());
427                 }
428
429                 // Policy 2: MechID must have valid Organization Owner
430                 Identity emailUser;
431                 if (muser.isPerson()) {
432                     emailUser = muser;
433                 } else {
434                     Identity ouser = muser.responsibleTo();
435                     if (ouser == null) {
436                         return Result.err(Result.ERR_Denied, "%s is not a valid Sponsor for %s at %s", trans.user(),
437                                 add.mechid, trans.org().getName());
438                     }
439
440                     // Policy 3: Calling ID must be MechID Owner
441                     if (!trans.user().startsWith(ouser.id())) {
442                         return Result.err(Result.ERR_Denied, "%s is not the Sponsor for %s at %s", trans.user(),
443                                 add.mechid, trans.org().getName());
444                     }
445                     emailUser = ouser;
446                 }
447
448                 // Policy 4: Renewal Days are between 10 and 60 (constants, may be
449                 // parameterized)
450                 if (add.renewDays < MIN_RENEWAL) {
451                     add.renewDays = STD_RENEWAL;
452                 } else if (add.renewDays > MAX_RENEWAL) {
453                     add.renewDays = MAX_RENEWAL;
454                 }
455
456                 // Policy 5: If Notify is blank, set to Owner's Email
457                 if (add.notify == null || add.notify.length() == 0) {
458                     add.notify = "mailto:" + emailUser.email();
459                 }
460
461                 // Policy 6: Only do Domain by Exception
462                 if (add.machine.startsWith("*")) { // Domain set
463                     CA ca = certManager.getCA(add.ca);
464
465                     if (!trans.fish(new AAFPermission(ca.getPermNS(),ca.getPermType(), add.ca, DOMAIN))) {
466                         return Result.err(Result.ERR_Denied, "Domain Artifacts (%s) requires specific Permission",
467                                 add.machine);
468                     }
469                 }
470
471                 // Set Sponsor from Golden Source
472                 add.sponsor = emailUser.fullID();
473
474             } catch (OrganizationException e) {
475                 return Result.err(e);
476             }
477             // Add to DB
478             Result<ArtiDAO.Data> rv = artiDAO.create(trans, add);
479             //  come up with Partial Reporting Scheme, or allow only one at a time.
480             if (rv.notOK()) {
481                 return Result.err(rv);
482             }
483         }
484         return Result.ok();
485     }
486
487     public Result<List<ArtiDAO.Data>> readArtifacts(AuthzTrans trans, ArtiDAO.Data add) throws OrganizationException {
488         CertmanValidator v = new CertmanValidator().keys(add);
489         if (v.err()) {
490             return Result.err(Result.ERR_BadData, v.errs());
491         }
492         Result<List<ArtiDAO.Data>> data = artiDAO.read(trans, add);
493         if (data.notOKorIsEmpty()) {
494             return data;
495         }
496         add = data.value.get(0);
497         if (trans.user().equals(add.mechid)
498                 || trans.fish(root_read_permission,
499                 new AAFPermission(add.ns,ACCESS, "*", "read"),
500                 new AAFPermission(add.ns,CERTMAN, add.ca, "read"),
501                 new AAFPermission(add.ns,CERTMAN, add.ca, REQUEST))
502                 || (trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, add.mechid)) == null) {
503             return data;
504         } else {
505             return Result.err(Result.ERR_Denied,
506                     "%s is not %s, is not the sponsor, and doesn't have delegated permission.", trans.user(),
507                     add.mechid, add.ns + ".certman|" + add.ca + "|read or ...|request"); // note: reason is set by 2nd
508             // case, if 1st case misses
509         }
510
511     }
512
513     public Result<List<ArtiDAO.Data>> readArtifactsByMechID(AuthzTrans trans, String mechid)
514             throws OrganizationException {
515         CertmanValidator v = new CertmanValidator();
516         v.nullOrBlank("mechid", mechid);
517         if (v.err()) {
518             return Result.err(Result.ERR_BadData, v.errs());
519         }
520         String ns = FQI.reverseDomain(mechid);
521
522         String reason;
523         if (trans.fish(new AAFPermission(ns, ACCESS, "*", "read"))
524                 || (reason = trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, mechid)) == null) {
525             return artiDAO.readByMechID(trans, mechid);
526         } else {
527             return Result.err(Result.ERR_Denied, reason); // note: reason is set by 2nd case, if 1st case misses
528         }
529
530     }
531
532     public Result<List<ArtiDAO.Data>> readArtifactsByMachine(AuthzTrans trans, String machine) {
533         CertmanValidator v = new CertmanValidator();
534         v.nullOrBlank("machine", machine);
535         if (v.err()) {
536             return Result.err(Result.ERR_BadData, v.errs());
537         }
538
539         //  do some checks?
540
541         return artiDAO.readByMachine(trans, machine);
542     }
543
544     public Result<List<ArtiDAO.Data>> readArtifactsByNs(AuthzTrans trans, String ns) {
545         CertmanValidator v = new CertmanValidator();
546         v.nullOrBlank("ns", ns);
547         if (v.err()) {
548             return Result.err(Result.ERR_BadData, v.errs());
549         }
550
551         //  do some checks?
552         return artiDAO.readByNs(trans, ns);
553     }
554
555     public Result<Void> updateArtifact(AuthzTrans trans, List<ArtiDAO.Data> list) throws OrganizationException {
556         CertmanValidator v = new CertmanValidator();
557         v.artisRequired(list, 1);
558         if (v.err()) {
559             return Result.err(Result.ERR_BadData, v.errs());
560         }
561
562         // Check if requesting User is Sponsor
563         //  Shall we do one, or multiples?
564         for (ArtiDAO.Data add : list) {
565             // Policy 1: MechID must exist in Org
566             Identity muser = trans.org().getIdentity(trans, add.mechid);
567             if (muser == null) {
568                 return Result.err(Result.ERR_Denied, "%s is not valid for %s", add.mechid, trans.org().getName());
569             }
570
571             // Policy 2: MechID must have valid Organization Owner
572             Identity ouser = muser.responsibleTo();
573             if (ouser == null) {
574                 return Result.err(Result.ERR_Denied, "%s is not a valid Sponsor for %s at %s", trans.user(), add.mechid,
575                         trans.org().getName());
576             }
577
578             // Policy 3: Renewal Days are between 10 and 60 (constants, may be
579             // parameterized)
580             if (add.renewDays < MIN_RENEWAL) {
581                 add.renewDays = STD_RENEWAL;
582             } else if (add.renewDays > MAX_RENEWAL) {
583                 add.renewDays = MAX_RENEWAL;
584             }
585
586             // Policy 4: Data is always updated with the latest Sponsor
587             // Add to Sponsor, to make sure we are always up to date.
588             add.sponsor = ouser.fullID();
589
590             // Policy 5: If Notify is blank, set to Owner's Email
591             if (add.notify == null || add.notify.length() == 0) {
592                 add.notify = "mailto:" + ouser.email();
593             }
594             // Policy 6: Only do Domain by Exception
595             if (add.machine.startsWith("*")) { // Domain set
596                 CA ca = certManager.getCA(add.ca);
597                 if (ca == null) {
598                     return Result.err(Result.ERR_BadData, "CA is required in Artifact");
599                 }
600                 if (!trans.fish(new AAFPermission(null,ca.getPermType(), add.ca, DOMAIN))) {
601                     return Result.err(Result.ERR_Denied, "Domain Artifacts (%s) requires specific Permission",
602                             add.machine);
603                 }
604             }
605
606             // Policy 7: only Owner may update info
607             if (trans.user().startsWith(ouser.id())) {
608                 return artiDAO.update(trans, add);
609             } else {
610                 return Result.err(Result.ERR_Denied, "%s may not update info for %s", trans.user(), muser.fullID());
611             }
612         }
613         return Result.err(Result.ERR_BadData, "No Artifacts to update");
614     }
615
616     public Result<Void> deleteArtifact(AuthzTrans trans, String mechid, String machine) throws OrganizationException {
617         CertmanValidator v = new CertmanValidator();
618         v.nullOrBlank("mechid", mechid).nullOrBlank("machine", machine);
619         if (v.err()) {
620             return Result.err(Result.ERR_BadData, v.errs());
621         }
622
623         Result<List<ArtiDAO.Data>> rlad = artiDAO.read(trans, mechid, machine);
624         if (rlad.notOKorIsEmpty()) {
625             return Result.err(Result.ERR_NotFound, "Artifact for %s %s does not exist.", mechid, machine);
626         }
627
628         return deleteArtifact(trans, rlad.value.get(0));
629     }
630
631     private Result<Void> deleteArtifact(AuthzTrans trans, ArtiDAO.Data add) throws OrganizationException {
632         // Policy 1: Record should be delete able only by Existing Sponsor.
633         String sponsor = null;
634         Identity muser = trans.org().getIdentity(trans, add.mechid);
635         if (muser != null) {
636             Identity ouser = muser.responsibleTo();
637             if (ouser != null) {
638                 sponsor = ouser.fullID();
639             }
640         }
641         // Policy 1.a: If Sponsorship is deleted in system of Record, then
642         // accept deletion by sponsor in Artifact Table
643         if (sponsor == null) {
644             sponsor = add.sponsor;
645         }
646
647         String ns = FQI.reverseDomain(add.mechid);
648
649         if (trans.fish(new AAFPermission(ns,ACCESS, "*", "write")) || trans.user().equals(sponsor)) {
650             return artiDAO.delete(trans, add, false);
651         }
652         return Result.err(Result.ERR_Denied, "%1 is not allowed to delete this item", trans.user());
653     }
654
655     public Result<Void> deleteArtifact(AuthzTrans trans, List<ArtiDAO.Data> list) {
656         CertmanValidator v = new CertmanValidator().artisRequired(list, 1);
657         if (v.err()) {
658             return Result.err(Result.ERR_BadData, v.errs());
659         }
660
661         try {
662             boolean partial = false;
663             Result<Void> result = null;
664             for (ArtiDAO.Data add : list) {
665                 result = deleteArtifact(trans, add);
666                 if (result.notOK()) {
667                     partial = true;
668                 }
669             }
670             if (result == null) {
671                 result = Result.err(Result.ERR_BadData, "No Artifacts to delete");
672             } else if (partial) {
673                 result.partialContent(true);
674             }
675             return result;
676         } catch (Exception e) {
677             return Result.err(e);
678         }
679     }
680
681     private String[] compileNotes(List<String> notes) {
682         String[] rv;
683         if (notes == null) {
684             rv = NO_NOTES;
685         } else {
686             rv = new String[notes.size()];
687             notes.toArray(rv);
688         }
689         return rv;
690     }
691
692     private ByteBuffer getChallenge256SaltedHash(String challenge, int salt) throws NoSuchAlgorithmException {
693         ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + challenge.length());
694         bb.putInt(salt);
695         bb.put(challenge.getBytes());
696         byte[] hash = Hash.hashSHA256(bb.array());
697         return ByteBuffer.wrap(hash);
698     }
699 }