Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

APIs for email communication #7

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion .github/workflows/haskell-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ jobs:
run: |
touch cabal.project
echo "packages: $GITHUB_WORKSPACE/source/./azure-auth" >> cabal.project
echo "packages: $GITHUB_WORKSPACE/source/./azure-email" >> cabal.project
echo "packages: $GITHUB_WORKSPACE/source/./azure-key-vault" >> cabal.project
echo "packages: $GITHUB_WORKSPACE/source/./azure-blob-storage" >> cabal.project
cat cabal.project
Expand All @@ -155,6 +156,8 @@ jobs:
run: |
PKGDIR_azure_auth="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/azure-auth-[0-9.]*')"
echo "PKGDIR_azure_auth=${PKGDIR_azure_auth}" >> "$GITHUB_ENV"
PKGDIR_azure_email="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/azure-email-[0-9.]*')"
echo "PKGDIR_azure_email=${PKGDIR_azure_email}" >> "$GITHUB_ENV"
PKGDIR_azure_key_vault="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/azure-key-vault-[0-9.]*')"
echo "PKGDIR_azure_key_vault=${PKGDIR_azure_key_vault}" >> "$GITHUB_ENV"
PKGDIR_azure_blob_storage="$(find "$GITHUB_WORKSPACE/unpacked" -maxdepth 1 -type d -regex '.*/azure-blob-storage-[0-9.]*')"
Expand All @@ -163,17 +166,20 @@ jobs:
touch cabal.project
touch cabal.project.local
echo "packages: ${PKGDIR_azure_auth}" >> cabal.project
echo "packages: ${PKGDIR_azure_email}" >> cabal.project
echo "packages: ${PKGDIR_azure_key_vault}" >> cabal.project
echo "packages: ${PKGDIR_azure_blob_storage}" >> cabal.project
echo "package azure-auth" >> cabal.project
echo " ghc-options: -Werror=missing-methods" >> cabal.project
echo "package azure-email" >> cabal.project
echo " ghc-options: -Werror=missing-methods" >> cabal.project
echo "package azure-key-vault" >> cabal.project
echo " ghc-options: -Werror=missing-methods" >> cabal.project
echo "package azure-blob-storage" >> cabal.project
echo " ghc-options: -Werror=missing-methods" >> cabal.project
cat >> cabal.project <<EOF
EOF
$HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: $_ installed\n" unless /^(azure-auth|azure-blob-storage|azure-key-vault)$/; }' >> cabal.project.local
$HCPKG list --simple-output --names-only | perl -ne 'for (split /\s+/) { print "constraints: $_ installed\n" unless /^(azure-auth|azure-blob-storage|azure-email|azure-key-vault)$/; }' >> cabal.project.local
cat cabal.project
cat cabal.project.local
- name: dump install plan
Expand All @@ -200,6 +206,8 @@ jobs:
run: |
cd ${PKGDIR_azure_auth} || false
${CABAL} -vnormal check
cd ${PKGDIR_azure_email} || false
${CABAL} -vnormal check
cd ${PKGDIR_azure_key_vault} || false
${CABAL} -vnormal check
cd ${PKGDIR_azure_blob_storage} || false
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
SRC=$(shell find azure-auth/ azure-key-vault/ azure-blob-storage/ -type f -name '*.hs')
SRC=$(shell find azure-auth/ azure-key-vault/ azure-blob-storage/ azure-email/ -type f -name '*.hs')

.PHONY: format
format: $(SRC)
Expand Down
119 changes: 119 additions & 0 deletions azure-email/Azure/Email.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}

module Azure.Email
( sendEmail
, sendEmailEither
) where

import Azure.Types (AzureEmailRequest (..), AzureEmailResponse (..))
import Crypto.Hash.SHA256 (hash, hmac)
import Data.Aeson (encode)
import Data.Proxy (Proxy (..))
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8)
import Data.Time (UTCTime, defaultTimeLocale, formatTime, getCurrentTime)
import Network.HTTP.Client.TLS (newTlsManager)
import Servant.API
import Servant.Client (BaseUrl (..), ClientM, Scheme (..), client, mkClientEnv, runClientM)
import UnliftIO (MonadIO (..), throwString)

import qualified Data.ByteString as BS
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Char8 as C8
import qualified Data.Text as Text

{- | Send an email provided a request payload

Errors are thrown in IO. For a variant where error is captured
in an @Left@ branch, see @sendEmailEither@
-}
sendEmail ::
MonadIO m =>
Text ->
Text ->
AzureEmailRequest ->
m AzureEmailResponse
sendEmail apiSecret emailHost payload = do
resp <- sendEmailEither apiSecret emailHost payload
case resp of
Left err -> throwString $ show err
Right r -> pure r

-- | Send an email provided a request payload
sendEmailEither ::
MonadIO m =>
Text ->
Text ->
AzureEmailRequest ->
m (Either Text AzureEmailResponse)
sendEmailEither apiSecret emailHost payload =
liftIO $ callSendEmailClient sendEmailApi payload emailHost apiSecret

type SendEmailApi =
"emails:send"
:> QueryParam' '[Required, Strict] "api-version" Text
:> Header' '[Required, Strict] "x-ms-date" Text
:> Header' '[Required, Strict] "Host" Text
:> Header' '[Required, Strict] "x-ms-content-sha256" Text
:> Header' '[Required, Strict] "Authorization" Text
:> ReqBody '[JSON] AzureEmailRequest
:> Post '[JSON] AzureEmailResponse

sendEmailApi :: Text -> Text -> Text -> Text -> Text -> AzureEmailRequest -> ClientM AzureEmailResponse
sendEmailApi = client (Proxy @SendEmailApi)

callSendEmailClient ::
(Text -> Text -> Text -> Text -> Text -> AzureEmailRequest -> ClientM AzureEmailResponse) ->
AzureEmailRequest ->
Text ->
Text ->
IO (Either Text AzureEmailResponse)
callSendEmailClient action req azureEmailHost secret = do
manager <- liftIO newTlsManager
(formatToAzureTime -> now) <- getCurrentTime
encodedPayload <- encodePayload
let stringToSign =
"POST\n"
<> "/emails:send?api-version="
<> apiVersion
<> "\n"
<> now
<> ";"
<> azureEmailHost
<> ";"
<> encodedPayload
let sign = buildSignature stringToSign secret
res <-
liftIO $
runClientM
(action apiVersion now azureEmailHost encodedPayload ("HMAC-SHA256 SignedHeaders=x-ms-date;host;x-ms-content-sha256&Signature=" <> sign) req)
(mkClientEnv manager $ BaseUrl Https (Text.unpack azureEmailHost) 443 "")
pure $ case res of
Left err -> do
Left . Text.pack $ show err
Right r -> do
Right r
where
apiVersion :: Text
apiVersion = "2023-03-31"

encodePayload :: IO Text
encodePayload = do
let contentBytes = encode req
hashedBytes = hash (BS.toStrict contentBytes)
encodedHash = B64.encode hashedBytes
pure $ decodeUtf8 encodedHash

-- TODO: formatToAzureTime and buildSignature are borrowed from azure-blob-storage.
-- We should not be duplicating these utility functions
formatToAzureTime :: UTCTime -> Text
formatToAzureTime time = Text.pack $ formatTime defaultTimeLocale "%FT%TZ" time

buildSignature :: Text -> Text -> Text
buildSignature stringToSign sec =
let decodedSecret = B64.decodeLenient (C8.pack (Text.unpack sec))
encodedStringToSign = C8.pack (Text.unpack stringToSign)
hashedBytes = hmac decodedSecret encodedStringToSign
encodedSignature = B64.encode hashedBytes
in decodeUtf8 encodedSignature
181 changes: 181 additions & 0 deletions azure-email/Azure/Types.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingVia #-}

module Azure.Types
( AzureEmailRequest (..)
, AzureEmailResponse (..)

-- * Types to work with email addresses.

-- These types merely represent the address and
-- are not responsible for validating them whatsoever.
, EmailAddress (..)
, EmailRecipients (..)
, EmailContent (..)
, EmailAttachment (..)

-- * Smart constructors
, newAzureEmailRequest
) where

import Data.Aeson (FromJSON (..), ToJSON (..), object, withObject, withText, (.:), (.=))
import Data.Aeson.Types (parseFail)
import Data.Text (Text)

import qualified Data.Text as Text

{- | Each email is represented as an object with @displayName@
and an associated @address@.

Source: https://learn.microsoft.com/en-us/rest/api/communication/dataplane/email/send?view=rest-communication-dataplane-2023-03-31&tabs=HTTP#emailaddress
-}
data EmailAddress = EmailAddress
{ eaEmail :: !Text
, eaDisplayName :: !Text
}
deriving stock (Eq, Show)

instance ToJSON EmailAddress where
toJSON EmailAddress{..} =
object
[ "address" .= eaEmail
, "displayName" .= eaDisplayName
]

{- | Why text type instead of represting it as @EmailAddress@?

Well, Azure API dictates that sender address should only be the email
instead of a combination of email and display name (EmailAddress in our case).
Therefore, we fallback to use text as a type alias for this one case.
-}
type SenderEmailAddress = Text

-- | Fields to represent @cc@, @bcc@ and @to@ in an email
data EmailRecipients = EmailRecipients
{ ccRecipients :: ![EmailAddress]
, bccRecipients :: ![EmailAddress]
, toRecipients :: ![EmailAddress]
}
deriving stock (Show)

instance ToJSON EmailRecipients where
toJSON EmailRecipients{..} =
object
[ "to" .= toRecipients
, "cc" .= ccRecipients
, "bcc" .= bccRecipients
]

-- | Azure email requires both HTML and plain text format email content
data EmailContent = EmailContent
{ ecHtml :: !Text
-- ^ Html version of the email message.
, ecPlainText :: !Text
-- ^ Plain text version of the email message.
, ecSubject :: !Text
-- ^ Subject of the email message.
}
deriving stock (Eq, Show)

instance ToJSON EmailContent where
toJSON EmailContent{..} =
object
[ "plainText" .= ecPlainText
, "html" .= ecHtml
, "subject" .= ecSubject
]

data EmailAttachment = EmailAttachment
{ eaContentInBase64 :: !Text
-- ^ Base64 encoded contents of the attachment
, eaContentType :: !Text
-- ^ MIME type of the attachment
, eaName :: !Text
-- ^ Name of the attachment
}
deriving stock (Show)

instance ToJSON EmailAttachment where
toJSON EmailAttachment{..} =
object
[ "name" .= eaName
, "contentType" .= eaContentType
, "contentInBase64" .= eaContentInBase64
]

{- | Represents the payload for sending an email message.

Source: https://learn.microsoft.com/en-us/rest/api/communication/dataplane/email/send?view=rest-communication-dataplane-2023-03-31&tabs=HTTP#emailmessage
-}
data AzureEmailRequest = AzureEmailRequest
{ aerContent :: !EmailContent
, aerRecipients :: !EmailRecipients
, aerSenderAddress :: !SenderEmailAddress
, aerReplyTo :: ![EmailAddress] -- TODO: Should this be NonEmpty instead?
, aerAttachments :: ![EmailAttachment]
, aerUserEngagementTrackingDisabled :: !Bool
}
deriving stock (Show)

instance ToJSON AzureEmailRequest where
toJSON AzureEmailRequest{..} =
object
[ "content" .= aerContent
, "recipients" .= aerRecipients
, "senderAddress" .= aerSenderAddress
, "replyTo" .= aerReplyTo
, "attachments" .= aerAttachments
, "userEngagementTrackingDisabled" .= aerUserEngagementTrackingDisabled
]

{- | Smart constructor to build a send email request.

This is very priliminary in nature and facilitates quickly building an email request
with 1 recipient and sender with the content.
There are few default settings that the caller needs to be aware of:
1. @replyTo@ for recipient is the sender's email address. In case there needs to be multiple
email addresses in @replyTo@ field, it is advised to build a custom request based on the
exposed data types instead.
2. Attachements are not included.
3. Enagagement tracking is disabled.
-}
newAzureEmailRequest ::
SenderEmailAddress ->
EmailAddress ->
EmailContent ->
AzureEmailRequest
newAzureEmailRequest senderAddress recipient content =
let senderEmailAddress = EmailAddress senderAddress Text.empty
in AzureEmailRequest content (EmailRecipients [] [] [recipient]) senderAddress [senderEmailAddress] [] True

{- | Possible states once a send email action is triggered.
Source: https://learn.microsoft.com/en-us/rest/api/communication/dataplane/email/send?view=rest-communication-dataplane-2023-03-31&tabs=HTTP#emailsendstatus
-}
data EmailSendStatus
= Canceled
| Failed
| NotStarted
| Running
| Succeeded
deriving stock (Eq, Show, Enum, Bounded)

instance FromJSON EmailSendStatus where
parseJSON = withText "EmailSendStatus" $ \case
"Canceled" -> pure Canceled
"Failed" -> pure Failed
"NotStarted" -> pure NotStarted
"Running" -> pure Running
"Succeeded" -> pure Succeeded
invalidStatus -> parseFail $ "Unexpected EmailSendStatus: " <> show invalidStatus

data AzureEmailResponse = AzureEmailResponse
{ aerId :: !Text
, aerStatus :: !EmailSendStatus
}
deriving stock (Eq, Show)

instance FromJSON AzureEmailResponse where
parseJSON = withObject "AzureEmailResponse" $ \o -> do
aerId <- o .: "id"
aerStatus <- o .: "status"
pure AzureEmailResponse{..}
5 changes: 5 additions & 0 deletions azure-email/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Revision history for azure-auth

## 0.1.0.0 -- YYYY-mm-dd

* First version. Released on an unsuspecting world.
21 changes: 21 additions & 0 deletions azure-email/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Holmusk

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Loading
Loading