1   package com.atlassian.security.auth.trustedapps;
2   
3   import static com.atlassian.security.auth.trustedapps.DefaultTrustedApplication.checkCertificateExpiry;
4   
5   import java.security.PrivateKey;
6   import java.security.PublicKey;
7   
8   import javax.servlet.http.HttpServletRequest;
9   
10  public class DefaultCurrentApplication implements CurrentApplication, TrustedApplication
11  {
12      /**
13       * A current application should only be called by itself, therefore the timeout only needs to be small.
14       */
15      private static final int LOCAL_TIMEOUT = 1000;
16  
17      private final EncryptionProvider encryptionProvider;
18  
19      protected final String id;
20      protected final PublicKey publicKey;
21      protected final PrivateKey privateKey;
22  
23      public DefaultCurrentApplication(final EncryptionProvider encryptionProvider, final PublicKey publicKey, final PrivateKey privateKey, final String id)
24      {
25          Null.not("encryptionProvider", encryptionProvider);
26          Null.not("publicKey", publicKey);
27          Null.not("privateKey", privateKey);
28          Null.not("id", id);
29  
30          this.encryptionProvider = encryptionProvider;
31          this.publicKey = publicKey;
32          this.privateKey = privateKey;
33          this.id = id;
34      }
35  
36      public DefaultCurrentApplication(final PublicKey publicKey, final PrivateKey privateKey, final String id)
37      {
38          this(new BouncyCastleEncryptionProvider(), publicKey, privateKey, id);
39      }
40  
41      /**
42       * Returned String can be used as a certificate to talk
43       * to the server that trusts this application. I.e. the ID of this app and the certificate go into the following header parameters:
44       * {@link CurrentApplication#HEADER_TRUSTED_APP_CERT}
45       * {@link CurrentApplication#HEADER_TRUSTED_APP_ID}
46       */
47      public EncryptedCertificate encode(final String userName)
48      {
49          return encryptionProvider.createEncryptedCertificate(userName, privateKey, getID());
50      }
51  
52      public ApplicationCertificate decode(final EncryptedCertificate encCert, final HttpServletRequest request) throws InvalidCertificateException
53      {
54          final ApplicationCertificate certificate = encryptionProvider.decodeEncryptedCertificate(encCert, publicKey, getID());
55          checkCertificateExpiry(certificate, LOCAL_TIMEOUT);
56          return certificate;
57      }
58  
59      public String getID()
60      {
61          return id;
62      }
63  
64      public PublicKey getPublicKey()
65      {
66          return publicKey;
67      }
68  
69      /**
70       * {@inheritDoc}
71       */
72      public RequestConditions getRequestConditions()
73      {
74          return null;
75      }
76  
77      public String getName()
78      {
79          return null;
80      }
81  }