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

Add support for Application Tokens + Resolve Remaining Issues #164

Merged
merged 6 commits into from
Mar 13, 2024
Merged
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
5 changes: 2 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ COPY main.go ${GOPATH}/src/github.com/rtcamp/action-slack-notify
ENV CGO_ENABLED 0
ENV GOOS linux

RUN go get -v ./...
RUN go build -a -installsuffix cgo -ldflags '-w -extldflags "-static"' -o /go/bin/slack-notify .
RUN go build -a -installsuffix cgo -ldflags '-w -extldflags "-static"' -o /go/bin/slack-notify main.go

# alpine:latest as of 2024-03-11
FROM alpine@sha256:6457d53fb065d6f250e1504b9bc42d5b6c65941d57532c072d929dd0628977d0
Expand All @@ -31,7 +30,7 @@ RUN apk update \
python3 \
py3-pip \
rsync \
&& pip3 install shyaml \
&& python3 -m pip install --break-system-packages shyaml \
&& rm -rf /var/cache/apk/*

# Setup Vault
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,12 @@ SLACK_FOOTER | Powered By rtCamp's GitHub Actions Library | S
MSG_MINIMAL | - | If set to `true`, removes: `Ref`, `Event`, `Actions URL` and `Commit` from the message. You can optionally whitelist any of these 4 removed values by passing it comma separated to the variable instead of `true`. (ex: `MSG_MINIMAL: event` or `MSG_MINIMAL: ref,actions url`, etc.)
SLACKIFY_MARKDOWN | - | If set to `true`, it will convert markdown to slack format. (ex: `*bold*` to `bold`) Note: This only works for custom messages and not for the default message generated by the action. Credits: [slackify-markdown-action](https://github.com/marketplace/actions/slack-markdown-converter)
SLACK_THREAD_TS | - | If you want to send message in a thread, you can pass the timestamp of the parent message to this variable. You can get the timestamp of the parent message from the message URL in Slack. (ex: `SLACK_THREAD_TS: 1586130833.000100`)
SLACK_TOKEN | - | If you want to send message to a channel using a slack token. You will need to pass a channel in order to send messages using token, requiring a value for ``SLACK_CHANNEL``. Note that in case both webhook url and token are provided, webhook url will be prioritized.
SLACK_ON_SUCCESS | - | If set, will send the provided message instead of the default message when the passed status (through ``SLACK_COLOR``) is `success`.
SLACK_ON_FAILURE | - | If set, will send the provided message instead of the default message when the passed status (through ``SLACK_COLOR``) is `failure`.
SLACK_ON_CANCEL | - | If set, will send the provided message instead of the default message when the passed status (through ``SLACK_COLOR``) is `cancelled`.
SLACK_CUSTOM_PAYLOAD | - | If you want to send a custom payload to slack, you can pass it as a string to this variable. This will override all other variables and send the custom payload to slack. Example: `SLACK_CUSTOM_PAYLOAD: '{"text": "Hello, World!"}'`, Note: This payload should be in JSON format, and is not validated by the action.
ENABLE_ESCAPES | - | If set to `true`, will enable backslash escape sequences such as `\n`, `\t`, etc. in the message. Note: This only works for custom messages and not for the default message generated by the action.


You can see the action block with all variables as below:
Expand Down
11 changes: 10 additions & 1 deletion entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

# Check required env variables
flag=0
mode="WEBHOOK"
if [[ -z "$SLACK_WEBHOOK" ]]; then
flag=1
missing_secret="SLACK_WEBHOOK"
Expand All @@ -13,11 +14,19 @@ if [[ -z "$SLACK_WEBHOOK" ]]; then
fi
fi

if [[ "$flag" -eq 1 ]] && [[ -n "$SLACK_TOKEN" || -n "$SLACK_CHANNEL" ]] ; then
# Basically, if both SLACK_TOKEN and SLACK_CHANNEL are provided, then it's a token mode
flag=0
mode="TOKEN"
fi

if [[ "$flag" -eq 1 ]]; then
printf "[\e[0;31mERROR\e[0m] Secret \`$missing_secret\` is missing. Please add it to this action for proper execution.\nRefer https://github.com/rtCamp/action-slack-notify for more information.\n"
echo -e "[\e[0;31mERROR\e[0m] Secret \`$missing_secret\` is missing. Alternatively, a pair of \`SLACK_TOKEN\` and \`SLACK_CHANNEL\` can be provided. Please add it to this action for proper execution.\nRefer https://github.com/rtCamp/action-slack-notify for more information.\n"
exit 1
fi

export MSG_MODE="$mode"

# custom path for files to override default files
custom_path="$GITHUB_WORKSPACE/.github/slack"
main_script="/main.sh"
Expand Down
39 changes: 34 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const (
EnvMinimal = "MSG_MINIMAL"
EnvSlackLinkNames = "SLACK_LINK_NAMES"
EnvThreadTs = "SLACK_THREAD_TS"
EnvMessageMode = "MSG_MODE"
)

type Webhook struct {
Expand Down Expand Up @@ -64,16 +65,24 @@ type Field struct {
func main() {
endpoint := os.Getenv(EnvSlackWebhook)
custom_payload := envOr(EnvSlackCustom, "")
if endpoint == "" {
if os.Getenv(EnvSlackChannel) == "" {
fmt.Fprintln(os.Stderr, "Channel is required for sending message using a token")
os.Exit(1)
}
if os.Getenv(EnvMessageMode) == "TOKEN" {
endpoint = "https://slack.com/api/chat.postMessage"
} else {
fmt.Fprintln(os.Stderr, "URL is required")
os.Exit(2)
}
}
if custom_payload != "" {
if err := send_raw(endpoint, []byte(custom_payload)); err != nil {
fmt.Fprintf(os.Stderr, "Error sending message: %s\n", err)
os.Exit(2)
}
} else {
if endpoint == "" {
fmt.Fprintln(os.Stderr, "URL is required")
os.Exit(2)
}
text := os.Getenv(EnvSlackMessage)
if text == "" {
fmt.Fprintln(os.Stderr, "Message is required")
Expand Down Expand Up @@ -262,7 +271,27 @@ func send(endpoint string, msg Webhook) error {

func send_raw(endpoint string, payload []byte) error {
b := bytes.NewBuffer(payload)
res, err := http.Post(endpoint, "application/json", b)

var res *http.Response
var err error

switch os.Getenv(EnvMessageMode) {
case "WEBHOOK":
res, err = http.Post(endpoint, "application/json", b)
case "TOKEN":
req, err := http.NewRequest("POST", endpoint, b)
if err != nil {
return fmt.Errorf("Error creating request: %s\n", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+os.Getenv("SLACK_TOKEN"))
client := &http.Client{}
res, err = client.Do(req)
default:
fmt.Fprintf(os.Stderr, "Invalid message mode: %s\n", os.Getenv(EnvMessageMode))
os.Exit(6)
}

if err != nil {
return err
}
Expand Down
10 changes: 9 additions & 1 deletion main.sh
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ if [[ -z "$SLACK_WEBHOOK" ]]; then
fi
fi

if [[ -z "$SLACK_WEBHOOK" ]]; then
printf "[\e[0;31mERROR\e[0m] Secret \`SLACK_WEBHOOK\` is missing. Falling back to using \`SLACK_TOKEN\` and \`SLACK_CHANNEL\`.\n"
fi

if [[ -f "$hosts_file" ]]; then
hostname=$(cat "$hosts_file" | shyaml get-value "$GITHUB_BRANCH.hostname")
user=$(cat "$hosts_file" | shyaml get-value "$GITHUB_BRANCH.user")
Expand All @@ -57,10 +61,14 @@ if [[ -n "$SITE_NAME" ]]; then
fi


if [[ -z "$SLACK_MESSAGE" ]]; then
if [[ -z "$SLACK_MESSAGE" && "null" != "$COMMIT_MESSAGE" ]]; then
SLACK_MESSAGE="$COMMIT_MESSAGE"
fi

if [[ -z "$SLACK_MESSAGE" ]]; then
SLACK_MESSAGE="Notification from action run \`$GITHUB_RUN_NUMBER\`, which ran against commit \`${GITHUB_SHA}\` from branch \`${GITHUB_BRANCH}\` of \`${GITHUB_REPOSITORY}\` repository."
fi

if [[ "true" == "$ENABLE_ESCAPES" ]]; then
SLACK_MESSAGE="$(echo -e "$SLACK_MESSAGE")"
fi
Expand Down