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