#!/bin/bash
# If authenticated, sign; otherwise, verify.
#
# It is not recommended that we fail delivery on dkim verification failures,
# but leave it to the MUA to handle verifications.
# https://tools.ietf.org/html/rfc6376#section-2.2
#
# We do a verification here so we have a stronger integration test (check
# encodings/dot-stuffing/etc. works ok), but it's not recommended for general
# purposes.
set -e
TF="$(mktemp --tmpdir post-data-XXXXXXXXXX)"
trap 'rm "$TF"' EXIT
# Save the message to the temporary file.
cat > "$TF"
if [ "$AUTH_AS" != "" ]; then
DOMAIN=$( echo "$MAIL_FROM" | cut -d '@' -f 2 )
# Call /usr/bin/dkimsign directly to prevent a conflict with
# driusan/dkim, which the integration tests install in ~/go/bin.
/usr/bin/dkimsign \
"$(cat "domains/$DOMAIN/dkim_selector")" \
"$DOMAIN" \
"../.dkimcerts/private.key" \
< "$TF" > "$TF.dkimout"
# dkimpy doesn't provide a way to just show the new headers, so we
# have to compute the difference.
# ALSOCHANGE(etc/chasquid/hooks/post-data)
diff --changed-group-format='%>' \
--unchanged-group-format='' \
"$TF" "$TF.dkimout" && exit 1
rm "$TF.dkimout"
else
# NOTE: This is using driusan/dkim instead of dkimpy, because dkimpy can't be
# overriden to get the DNS information from anywhere else (text file or custom
# DNS server).
dkimverify -txt ../.dkimcerts/private.dns < "$TF"
fi