-
Notifications
You must be signed in to change notification settings - Fork 139
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Bruno Paz <[email protected]>
- Loading branch information
Showing
5 changed files
with
260 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
/* | ||
Copyright 2023 The Flux authors | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package notifier | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"fmt" | ||
"net/url" | ||
"strings" | ||
|
||
eventv1 "github.com/fluxcd/pkg/apis/event/v1beta1" | ||
"github.com/hashicorp/go-retryablehttp" | ||
) | ||
|
||
const ( | ||
NtfyTagInfo = "information_source" | ||
NtfyTagError = "rotating_light" | ||
) | ||
|
||
type Ntfy struct { | ||
ServerURL string | ||
Topic string | ||
Token string | ||
Username string | ||
Password string | ||
} | ||
|
||
type NtfyMessage struct { | ||
Topic string `json:"topic"` | ||
Message string `json:"message"` | ||
Title string `json:"title"` | ||
Tags []string `json:"tags,omitempty"` | ||
} | ||
|
||
func NewNtfy(serverURL string, topic string, token string, username string, password string) (*Ntfy, error) { | ||
_, err := url.ParseRequestURI(serverURL) | ||
if err != nil { | ||
return nil, fmt.Errorf("invalid Ntfy server URL %s: '%w'", serverURL, err) | ||
} | ||
|
||
if topic == "" { | ||
return nil, errors.New("ntfy topic cannot be empty") | ||
} | ||
|
||
return &Ntfy{ | ||
ServerURL: serverURL, | ||
Topic: topic, | ||
Token: token, | ||
Username: username, | ||
Password: password, | ||
}, nil | ||
} | ||
|
||
func (n *Ntfy) Post(ctx context.Context, event eventv1.Event) error { | ||
|
||
// Skip Git commit status update event. | ||
if event.HasMetadata(eventv1.MetaCommitStatusKey, eventv1.MetaCommitStatusUpdateValue) { | ||
return nil | ||
} | ||
|
||
tags := make([]string, 0) | ||
|
||
switch event.Severity { | ||
case eventv1.EventSeverityInfo: | ||
tags = append(tags, NtfyTagInfo) | ||
case eventv1.EventSeverityError: | ||
tags = append(tags, NtfyTagError) | ||
} | ||
|
||
payload := NtfyMessage{ | ||
Topic: n.Topic, | ||
Title: fmt.Sprintf("FluxCD: %s", event.ReportingController), | ||
Message: n.buildMessageFromEvent(event), | ||
Tags: tags, | ||
} | ||
|
||
err := postMessage(ctx, n.ServerURL, "", nil, payload, func(req *retryablehttp.Request) { | ||
n.addAuthorizationHeader(req) | ||
}) | ||
|
||
return err | ||
} | ||
|
||
func (n *Ntfy) addAuthorizationHeader(req *retryablehttp.Request) { | ||
if n.Username != "" && n.Password != "" { | ||
req.Header.Set("Authorization", fmt.Sprintf("Basic %s", basicAuth(n.Username, n.Password))) | ||
} else if n.Token != "" { | ||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", n.Token)) | ||
} | ||
} | ||
|
||
func (n *Ntfy) buildMessageFromEvent(event eventv1.Event) string { | ||
var messageBuilder strings.Builder | ||
|
||
messageBuilder.WriteString(fmt.Sprintf("%s\n\n", event.Message)) | ||
messageBuilder.WriteString(fmt.Sprintf("Object: %s/%s.%s\n", event.InvolvedObject.Namespace, event.InvolvedObject.Name, event.InvolvedObject.Kind)) | ||
|
||
if event.Metadata != nil { | ||
messageBuilder.WriteString("\nMetadata:\n") | ||
for key, val := range event.Metadata { | ||
messageBuilder.WriteString(fmt.Sprintf("%s: %s\n", key, val)) | ||
} | ||
} | ||
|
||
return messageBuilder.String() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
package notifier | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"io" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestNewNtfy(t *testing.T) { | ||
t.Run("default values", func(t *testing.T) { | ||
n, err := NewNtfy("https://ntfy.sh", "my-topic", "token", "user", "pass") | ||
assert.NoError(t, err) | ||
assert.Equal(t, "https://ntfy.sh", n.ServerURL) | ||
assert.Equal(t, "my-topic", n.Topic) | ||
assert.Equal(t, "token", n.Token) | ||
assert.Equal(t, "user", n.Username) | ||
assert.Equal(t, "pass", n.Password) | ||
}) | ||
|
||
t.Run("invalid URL", func(t *testing.T) { | ||
_, err := NewNtfy("not a url", "my-topic", "", "", "") | ||
assert.Contains(t, err.Error(), "invalid Ntfy server URL") | ||
}) | ||
|
||
t.Run("empty topic", func(t *testing.T) { | ||
_, err := NewNtfy("https://ntfy.sh", "", "", "", "") | ||
assert.Equal(t, err.Error(), "ntfy topic cannot be empty") | ||
}) | ||
} | ||
|
||
func TestNtfy_Post(t *testing.T) { | ||
|
||
t.Run("success", func(t *testing.T) { | ||
evt := testEvent() | ||
|
||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
b, err := io.ReadAll(r.Body) | ||
require.NoError(t, err) | ||
|
||
var payload NtfyMessage | ||
err = json.Unmarshal(b, &payload) | ||
require.NoError(t, err) | ||
|
||
assert.Equal(t, "my-topic", payload.Topic) | ||
assert.Equal(t, "FluxCD: source-controller", payload.Title) | ||
assert.Equal(t, []string{NtfyTagInfo}, payload.Tags) | ||
assert.Equal(t, "message\n\nObject: gitops-system/webapp.GitRepository\n\nMetadata:\ntest: metadata\n", payload.Message) | ||
})) | ||
defer ts.Close() | ||
|
||
ntfy, err := NewNtfy(ts.URL, "my-topic", "", "", "") | ||
require.NoError(t, err) | ||
|
||
err = ntfy.Post(context.Background(), evt) | ||
require.NoError(t, err) | ||
}) | ||
|
||
t.Run("basic authorization", func(t *testing.T) { | ||
evt := testEvent() | ||
|
||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
assert.Equal(t, r.Header.Get("Authorization"), "Basic YmFzaWMtdXNlcjpiYXNpYy1wYXNzd29yZA==") | ||
})) | ||
defer ts.Close() | ||
|
||
ntfy, err := NewNtfy(ts.URL, "my-topic", "", "basic-user", "basic-password") | ||
require.NoError(t, err) | ||
|
||
err = ntfy.Post(context.Background(), evt) | ||
require.NoError(t, err) | ||
}) | ||
|
||
t.Run("access token", func(t *testing.T) { | ||
evt := testEvent() | ||
|
||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
assert.Equal(t, r.Header.Get("Authorization"), "Bearer access-token") | ||
})) | ||
defer ts.Close() | ||
|
||
ntfy, err := NewNtfy(ts.URL, "my-topic", "access-token", "", "") | ||
require.NoError(t, err) | ||
|
||
err = ntfy.Post(context.Background(), evt) | ||
require.NoError(t, err) | ||
}) | ||
} |