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