Compare commits
3
Commits
554ec28709
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
125457a391
|
||
|
|
87337522df
|
||
|
|
6fec20896b
|
No files matched your search
@@ -94,16 +94,16 @@ func (h *host) actionTypes() []*connectorv1.ActionType {
|
||||
Description: "Delete the regular files directly or deeply under a directory on a host whose name matches a glob and that were not modified for at least a number of hours. The directory must be under the host's configured roots.",
|
||||
InputSchema: []byte(`{"type":"object","required":["host","directory","pattern","older_than_hours"],"additionalProperties":false,"properties":{` + hostProp +
|
||||
`,"directory":{"type":"string","description":"An absolute directory."},"pattern":{"type":"string","description":"A file name glob such as *.log; no path separators."},"older_than_hours":{"type":"integer","minimum":1}}}`),
|
||||
Effect: &connectorv1.Effect{Reversibility: connectorv1.Reversibility_REVERSIBILITY_IRREVERSIBLE, Summary: "Deletes files; irreversible unless the directory is one the host declares disposable."},
|
||||
Effect: &connectorv1.Effect{EffectsDeclared: true, Reversibility: connectorv1.Reversibility_REVERSIBILITY_IRREVERSIBLE, Summary: "Deletes files; irreversible unless the directory is one the host declares disposable."},
|
||||
Idempotent: true,
|
||||
}}
|
||||
if timers {
|
||||
schema := []byte(`{"type":"object","required":["host","timer"],"additionalProperties":false,"properties":{` + hostProp + `,"timer":{"type":"string","description":"A systemd timer unit name from the host's allow-list."}}}`)
|
||||
types = append(types,
|
||||
&connectorv1.ActionType{Name: actionDisableTimer, Description: "Disable and stop a systemd timer on a host.", InputSchema: schema, Idempotent: true,
|
||||
Effect: &connectorv1.Effect{Reversibility: connectorv1.Reversibility_REVERSIBILITY_UNDONE_AUTOMATICALLY, Summary: "Disables and stops a timer; enabling it again undoes this."}},
|
||||
Effect: &connectorv1.Effect{EffectsDeclared: true, Reversibility: connectorv1.Reversibility_REVERSIBILITY_UNDONE_AUTOMATICALLY, Summary: "Disables and stops a timer; enabling it again undoes this."}},
|
||||
&connectorv1.ActionType{Name: actionEnableTimer, Description: "Enable and start a systemd timer on a host.", InputSchema: schema, Idempotent: true,
|
||||
Effect: &connectorv1.Effect{Reversibility: connectorv1.Reversibility_REVERSIBILITY_UNDONE_AUTOMATICALLY, Summary: "Enables and starts a timer; disabling it again undoes this."}},
|
||||
Effect: &connectorv1.Effect{EffectsDeclared: true, Reversibility: connectorv1.Reversibility_REVERSIBILITY_UNDONE_AUTOMATICALLY, Summary: "Enables and starts a timer; disabling it again undoes this."}},
|
||||
)
|
||||
}
|
||||
if configs {
|
||||
@@ -112,7 +112,7 @@ func (h *host) actionTypes() []*connectorv1.ActionType {
|
||||
Description: "Set one KEY=VALUE line in a config file the host allows, keeping a backup of the file as it was.",
|
||||
InputSchema: []byte(`{"type":"object","required":["host","file","key","value"],"additionalProperties":false,"properties":{` + hostProp +
|
||||
`,"file":{"type":"string","description":"An absolute path from the host's allow-list."},"key":{"type":"string"},"value":{"type":"string","description":"A single line."}}}`),
|
||||
Effect: &connectorv1.Effect{Reversibility: connectorv1.Reversibility_REVERSIBILITY_RECOVERABLE, Summary: "Changes one setting in a config file; the previous file is kept beside it."},
|
||||
Effect: &connectorv1.Effect{EffectsDeclared: true, Reversibility: connectorv1.Reversibility_REVERSIBILITY_RECOVERABLE, Summary: "Changes one setting in a config file; the previous file is kept beside it."},
|
||||
Idempotent: true,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archipelago/sdk/connector"
|
||||
connectorv1 "github.com/samcharles93/archipelago/sdk/connector/v1"
|
||||
)
|
||||
|
||||
@@ -351,3 +352,13 @@ func TestCommandsDoWhatTheyReport(t *testing.T) {
|
||||
t.Fatalf("appended config = %q", body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEveryToolDeclaresItsEffects guards the chat prohibition: chat offers only
|
||||
// lookups and actions that state whether they change privileges or access
|
||||
// secrets.
|
||||
func TestEveryToolDeclaresItsEffects(t *testing.T) {
|
||||
h, _ := fakeHost(t, execResult{})
|
||||
if names := connector.UndeclaredEffects(h.Describe()); len(names) > 0 {
|
||||
t.Fatalf("no declared effects for %v", names)
|
||||
}
|
||||
}
|
||||
@@ -100,16 +100,19 @@ func (h *host) Describe() connector.Description {
|
||||
Name: "filesystem_usage",
|
||||
Description: "Size, used and available bytes and inode use of the filesystem holding a path on a host.",
|
||||
InputSchema: []byte(`{"type":"object","required":["host","path"],"additionalProperties":false,"properties":{"host":{"type":"string"},"path":{"type":"string","description":"An absolute path."}}}`),
|
||||
Effect: connector.NoPrivilegedEffects(),
|
||||
},
|
||||
{
|
||||
Name: "directory_sizes",
|
||||
Description: "The largest entries directly under a directory on a host, by total size, staying on its filesystem.",
|
||||
InputSchema: []byte(`{"type":"object","required":["host","path"],"additionalProperties":false,"properties":{"host":{"type":"string"},"path":{"type":"string","description":"An absolute path."},"limit":{"type":"integer","minimum":1,"maximum":50}}}`),
|
||||
Effect: connector.NoPrivilegedEffects(),
|
||||
},
|
||||
{
|
||||
Name: "old_files",
|
||||
Description: "The largest files under a directory on a host not modified for at least a number of hours, staying on its filesystem.",
|
||||
InputSchema: []byte(`{"type":"object","required":["host","path"],"additionalProperties":false,"properties":{"host":{"type":"string"},"path":{"type":"string","description":"An absolute path."},"older_than_hours":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}}}`),
|
||||
Effect: connector.NoPrivilegedEffects(),
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -143,10 +143,12 @@ func (c *incusConnector) Describe() connector.Description {
|
||||
{
|
||||
Name: lookupList, Description: "Containers in a project with their state.",
|
||||
InputSchema: []byte(`{"type":"object","required":["project"],"additionalProperties":false,"properties":{"project":{"type":"string"}}}`),
|
||||
Effect: connector.NoPrivilegedEffects(),
|
||||
},
|
||||
{
|
||||
Name: lookupCommand, Description: "Run an allowed read-only command inside a container and return its exit code and output.",
|
||||
InputSchema: cmdSchema,
|
||||
Effect: connector.NoPrivilegedEffects(),
|
||||
},
|
||||
},
|
||||
Actions: []*connectorv1.ActionType{
|
||||
@@ -154,8 +156,9 @@ func (c *incusConnector) Describe() connector.Description {
|
||||
Name: actionSnapshot, Description: "Take a snapshot of a container.",
|
||||
InputSchema: []byte(`{"type":"object","required":["project","container"],"additionalProperties":false,"properties":{"project":{"type":"string"},"container":{"type":"string"}}}`),
|
||||
Effect: &connectorv1.Effect{
|
||||
Reversibility: connectorv1.Reversibility_REVERSIBILITY_UNDONE_AUTOMATICALLY,
|
||||
Summary: "Takes a snapshot of the container; the snapshot can be deleted to undo it.",
|
||||
EffectsDeclared: true,
|
||||
Reversibility: connectorv1.Reversibility_REVERSIBILITY_UNDONE_AUTOMATICALLY,
|
||||
Summary: "Takes a snapshot of the container; the snapshot can be deleted to undo it.",
|
||||
},
|
||||
Idempotent: true,
|
||||
},
|
||||
@@ -163,8 +166,9 @@ func (c *incusConnector) Describe() connector.Description {
|
||||
Name: actionDeleteCache, Description: "Delete a cache directory or file inside a container, under one of the container's allowed cache paths.",
|
||||
InputSchema: []byte(`{"type":"object","required":["project","container","path"],"additionalProperties":false,"properties":{"project":{"type":"string"},"container":{"type":"string"},"path":{"type":"string","description":"An absolute path under an allowed cache path."}}}`),
|
||||
Effect: &connectorv1.Effect{
|
||||
Reversibility: connectorv1.Reversibility_REVERSIBILITY_IRREVERSIBLE,
|
||||
Summary: "Deletes the path and everything under it inside the container; recoverable only from a recent snapshot.",
|
||||
EffectsDeclared: true,
|
||||
Reversibility: connectorv1.Reversibility_REVERSIBILITY_IRREVERSIBLE,
|
||||
Summary: "Deletes the path and everything under it inside the container; recoverable only from a recent snapshot.",
|
||||
},
|
||||
Idempotent: true,
|
||||
},
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archipelago/sdk/connector"
|
||||
connectorv1 "github.com/samcharles93/archipelago/sdk/connector/v1"
|
||||
)
|
||||
|
||||
@@ -194,3 +195,13 @@ func TestResolve(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestEveryToolDeclaresItsEffects guards the chat prohibition: chat offers only
|
||||
// lookups and actions that state whether they change privileges or access
|
||||
// secrets.
|
||||
func TestEveryToolDeclaresItsEffects(t *testing.T) {
|
||||
|
||||
if names := connector.UndeclaredEffects((&incusConnector{}).Describe()); len(names) > 0 {
|
||||
t.Fatalf("no declared effects for %v", names)
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,12 @@ type Template struct {
|
||||
// "irreversible".
|
||||
Reversibility string `json:"reversibility"`
|
||||
Summary string `json:"summary"`
|
||||
// PrivilegeChange and SecretAccess say whether the template grants
|
||||
// access, changes identities or policies, or reads or exports secrets.
|
||||
// A template that sets both states its effects; one that omits either
|
||||
// is unavailable in chat.
|
||||
PrivilegeChange *bool `json:"privilege_change"`
|
||||
SecretAccess *bool `json:"secret_access"`
|
||||
} `json:"effect"`
|
||||
Target struct {
|
||||
Kind string `json:"kind"`
|
||||
@@ -146,7 +152,13 @@ func reversibility(name string, readOnly bool) (connectorv1.Reversibility, error
|
||||
|
||||
func (s *semaphore) effect(t Template) *connectorv1.Effect {
|
||||
r, _ := reversibility(t.Effect.Reversibility, t.Effect.ReadOnly)
|
||||
return &connectorv1.Effect{ReadOnly: t.Effect.ReadOnly, Reversibility: r, Summary: t.Effect.Summary}
|
||||
e := &connectorv1.Effect{ReadOnly: t.Effect.ReadOnly, Reversibility: r, Summary: t.Effect.Summary}
|
||||
if t.Effect.PrivilegeChange != nil && t.Effect.SecretAccess != nil {
|
||||
e.EffectsDeclared = true
|
||||
e.PrivilegeChange = *t.Effect.PrivilegeChange
|
||||
e.SecretAccess = *t.Effect.SecretAccess
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func (s *semaphore) Describe() connector.Description {
|
||||
|
||||
@@ -197,3 +197,31 @@ func TestALaunchRunsOnlyOnItsHost(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTemplatesDeclareEffectsExplicitly guards the chat prohibition: a template
|
||||
// is offered in chat only when the operator states both whether it changes
|
||||
// privileges and whether it accesses secrets.
|
||||
func TestTemplatesDeclareEffectsExplicitly(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
effect string
|
||||
want [3]bool
|
||||
}{
|
||||
{name: "neither stated", effect: `{"reversibility":"irreversible"}`},
|
||||
{name: "only one stated", effect: `{"reversibility":"irreversible","privilege_change":false}`},
|
||||
{name: "both false", effect: `{"reversibility":"irreversible","privilege_change":false,"secret_access":false}`, want: [3]bool{true, false, false}},
|
||||
{name: "secret access", effect: `{"reversibility":"irreversible","privilege_change":false,"secret_access":true}`, want: [3]bool{true, false, true}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var tpl Template
|
||||
if err := json.Unmarshal([]byte(`{"action":"run","template_id":7,"effect":`+tt.effect+`}`), &tpl); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e := (&semaphore{}).effect(tpl)
|
||||
if got := [3]bool{e.GetEffectsDeclared(), e.GetPrivilegeChange(), e.GetSecretAccess()}; got != tt.want {
|
||||
t.Fatalf("declared, privilege change, secret access = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archipelago/sdk/connector"
|
||||
connectorv1 "github.com/samcharles93/archipelago/sdk/connector/v1"
|
||||
)
|
||||
|
||||
@@ -29,6 +30,7 @@ func calendarLookups() []*connectorv1.LookupType {
|
||||
Name: blackoutsLookup,
|
||||
Description: "Active change-calendar blackouts, which the Timing guard reads as a freeze.",
|
||||
InputSchema: blackoutsInputSchema,
|
||||
Effect: connector.NoPrivilegedEffects(),
|
||||
}}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"github.com/samcharles93/archipelago/sdk/connector"
|
||||
connectorv1 "github.com/samcharles93/archipelago/sdk/connector/v1"
|
||||
)
|
||||
|
||||
@@ -34,16 +35,19 @@ func cmdbLookups() []*connectorv1.LookupType {
|
||||
Name: ownerLookup,
|
||||
Description: "Resolve a target to its CMDB owner, delegate and support group: server CI, then application CI, then any CI.",
|
||||
InputSchema: cmdbInputSchema,
|
||||
Effect: connector.NoPrivilegedEffects(),
|
||||
},
|
||||
{
|
||||
Name: environmentLookup,
|
||||
Description: "The target's environment from the CMDB, for example production.",
|
||||
InputSchema: cmdbInputSchema,
|
||||
Effect: connector.NoPrivilegedEffects(),
|
||||
},
|
||||
{
|
||||
Name: dataClassLookup,
|
||||
Description: "The target's data class from the CMDB.",
|
||||
InputSchema: cmdbInputSchema,
|
||||
Effect: connector.NoPrivilegedEffects(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,3 +229,13 @@ func TestDescribeDeclaresEveryArea(t *testing.T) {
|
||||
t.Fatalf("actions = %d, want 0: ServiceNow records, it doesn't change targets", len(d.Actions))
|
||||
}
|
||||
}
|
||||
|
||||
// TestEveryToolDeclaresItsEffects guards the chat prohibition: chat offers only
|
||||
// lookups and actions that state whether they change privileges or access
|
||||
// secrets.
|
||||
func TestEveryToolDeclaresItsEffects(t *testing.T) {
|
||||
s, _ := newTestConnector(t)
|
||||
if names := connector.UndeclaredEffects(s.Describe()); len(names) > 0 {
|
||||
t.Fatalf("no declared effects for %v", names)
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,8 @@ var (
|
||||
messageSchema = []byte(`{"type":"object","additionalProperties":false,"required":["title"],"properties":{` +
|
||||
`"title":{"type":"string"},"body":{"type":"string"},` +
|
||||
`"approval_request_id":{"type":"string","description":"Present on an approval request: adds Approve and Deny buttons."}}}`)
|
||||
chatMessageSchema = []byte(`{"type":"object","additionalProperties":false,"required":["chat_id","text"],"properties":{` +
|
||||
`"chat_id":{"type":"string","description":"The Telegram user id of an allowed user."},"text":{"type":"string"}}}`)
|
||||
answerSchema = []byte(`{"type":"object","required":["request_id","approved","by"],"properties":{` +
|
||||
`"request_id":{"type":"string"},"approved":{"type":"boolean"},` +
|
||||
`"by":{"type":"string","description":"telegram:<user id>"},"by_name":{"type":"string"}}}`)
|
||||
@@ -73,6 +75,8 @@ func (t *telegram) Describe() connector.Description {
|
||||
return connector.Description{
|
||||
Deliveries: []*connectorv1.DeliveryType{{
|
||||
Name: "message", Description: "A message to every allowed user's private chat.", InputSchema: messageSchema,
|
||||
}, {
|
||||
Name: "chat_message", Description: "Text to one allowed user's private chat.", InputSchema: chatMessageSchema,
|
||||
}},
|
||||
Events: []*connectorv1.EventType{{
|
||||
Name: answerType, Description: "An allowed user tapped Approve or Deny.", Schema: answerSchema,
|
||||
@@ -86,15 +90,24 @@ type message struct {
|
||||
ApprovalRequestID string `json:"approval_request_id"`
|
||||
}
|
||||
|
||||
// Deliver writes the message to each allowed user. One message holds at most
|
||||
// 4096 UTF-16 code units, so a longer body goes out as several messages in
|
||||
// order, with an approval request's buttons on the last. Telegram can't dedupe
|
||||
// a send, so a delivery fails only when no chat got it: retrying a partial one
|
||||
// Deliver sends the named delivery. "message" writes to each allowed user and
|
||||
// "chat_message" to one of them. One message holds at most 4096 UTF-16 code
|
||||
// units, so a longer text goes out as several messages in order, with an
|
||||
// approval request's buttons on the last. Telegram cannot deduplicate a send, so a
|
||||
// "message" delivery fails only when no chat got it: retrying a partial one
|
||||
// would repeat it to the users who already have it.
|
||||
func (t *telegram) Deliver(ctx context.Context, delivery string, input jsontext.Value, _ string) (string, error) {
|
||||
if delivery != "message" {
|
||||
switch delivery {
|
||||
case "message":
|
||||
return t.deliverMessage(ctx, input)
|
||||
case "chat_message":
|
||||
return t.deliverChatMessage(ctx, input)
|
||||
default:
|
||||
return "", fmt.Errorf("no delivery named %q", delivery)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *telegram) deliverMessage(ctx context.Context, input jsontext.Value) (string, error) {
|
||||
var m message
|
||||
if err := json.Unmarshal(input, &m, json.RejectUnknownMembers(true)); err != nil {
|
||||
return "", fmt.Errorf("message: %w", err)
|
||||
@@ -105,24 +118,11 @@ func (t *telegram) Deliver(ctx context.Context, delivery string, input jsontext.
|
||||
}
|
||||
var ids []string
|
||||
var failed []error
|
||||
parts := telegramtext.Split(text, telegramtext.MaxLen)
|
||||
for _, chat := range t.users {
|
||||
for i, part := range parts {
|
||||
body := map[string]any{"chat_id": chat, "text": part, "link_preview_options": map[string]any{"is_disabled": true}}
|
||||
if i == len(parts)-1 && m.ApprovalRequestID != "" {
|
||||
body["reply_markup"] = map[string]any{"inline_keyboard": [][]map[string]any{{
|
||||
{"text": "Approve", "callback_data": answerPrefix + "yes:" + m.ApprovalRequestID},
|
||||
{"text": "Deny", "callback_data": answerPrefix + "no:" + m.ApprovalRequestID},
|
||||
}}}
|
||||
}
|
||||
var sent struct {
|
||||
MessageID int64 `json:"message_id"`
|
||||
}
|
||||
if err := t.call(ctx, "sendMessage", body, &sent); err != nil {
|
||||
failed = append(failed, fmt.Errorf("chat %d: %w", chat, err))
|
||||
break
|
||||
}
|
||||
ids = append(ids, strconv.FormatInt(chat, 10)+"/"+strconv.FormatInt(sent.MessageID, 10))
|
||||
sent, err := t.sendText(ctx, chat, text, m.ApprovalRequestID)
|
||||
ids = append(ids, sent...)
|
||||
if err != nil {
|
||||
failed = append(failed, fmt.Errorf("chat %d: %w", chat, err))
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
@@ -131,6 +131,53 @@ func (t *telegram) Deliver(ctx context.Context, delivery string, input jsontext.
|
||||
return strings.Join(ids, ","), nil
|
||||
}
|
||||
|
||||
type chatMessage struct {
|
||||
ChatID string `json:"chat_id"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// deliverChatMessage sends text to one chat. Only an allowed user's chat is
|
||||
// addressable, so a workflow can't make the bot message anyone else.
|
||||
func (t *telegram) deliverChatMessage(ctx context.Context, input jsontext.Value) (string, error) {
|
||||
var m chatMessage
|
||||
if err := json.Unmarshal(input, &m, json.RejectUnknownMembers(true)); err != nil {
|
||||
return "", fmt.Errorf("chat_message: %w", err)
|
||||
}
|
||||
chat, err := strconv.ParseInt(m.ChatID, 10, 64)
|
||||
if err != nil || !slices.Contains(t.users, chat) {
|
||||
return "", connector.Permanent(fmt.Errorf("chat %q is not an allowed user", m.ChatID))
|
||||
}
|
||||
sent, err := t.sendText(ctx, chat, m.Text, "")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.Join(sent, ","), nil
|
||||
}
|
||||
|
||||
// sendText sends text to one chat in parts that fit a message, and returns the
|
||||
// id of each message sent before any failure.
|
||||
func (t *telegram) sendText(ctx context.Context, chat int64, text, approvalRequestID string) ([]string, error) {
|
||||
var ids []string
|
||||
parts := telegramtext.Split(text, telegramtext.MaxLen)
|
||||
for i, part := range parts {
|
||||
body := map[string]any{"chat_id": chat, "text": part, "link_preview_options": map[string]any{"is_disabled": true}}
|
||||
if i == len(parts)-1 && approvalRequestID != "" {
|
||||
body["reply_markup"] = map[string]any{"inline_keyboard": [][]map[string]any{{
|
||||
{"text": "Approve", "callback_data": answerPrefix + "yes:" + approvalRequestID},
|
||||
{"text": "Deny", "callback_data": answerPrefix + "no:" + approvalRequestID},
|
||||
}}}
|
||||
}
|
||||
var sent struct {
|
||||
MessageID int64 `json:"message_id"`
|
||||
}
|
||||
if err := t.call(ctx, "sendMessage", body, &sent); err != nil {
|
||||
return ids, err
|
||||
}
|
||||
ids = append(ids, strconv.FormatInt(chat, 10)+"/"+strconv.FormatInt(sent.MessageID, 10))
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
type update struct {
|
||||
UpdateID int64 `json:"update_id"`
|
||||
Callback *struct {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
json "encoding/json/v2"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -196,3 +197,44 @@ func TestAFailedCallNeverShowsTheToken(t *testing.T) {
|
||||
t.Fatalf("err = %v, want an error without the token", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAChatMessageReachesOnlyAnAllowedUser guards the chat_message delivery: a
|
||||
// workflow names the chat, and a chat that isn't an allowed user's is refused
|
||||
// permanently, so the bot can't be made to message anyone else.
|
||||
func TestAChatMessageReachesOnlyAnAllowedUser(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
chatID string
|
||||
wantSent []string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "an allowed user's chat gets the text", chatID: "42", wantSent: []string{"cleaned web-1"}},
|
||||
{name: "another chat is refused", chatID: "7", wantErr: true},
|
||||
{name: "a chat id that isn't a number is refused", chatID: "ops", wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
bot := &fakeBot{}
|
||||
srv := httptest.NewServer(bot)
|
||||
defer srv.Close()
|
||||
tg, err := newTelegram(connector.Config{
|
||||
Settings: map[string]string{"user_ids": "42"}, Secrets: map[string]string{"bot.token": fakeToken},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tg.api = srv.URL
|
||||
input, err := json.Marshal(map[string]string{"chat_id": tt.chatID, "text": "cleaned web-1"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = tg.Deliver(t.Context(), "chat_message", input, "k")
|
||||
if tt.wantErr != (err != nil) || (err != nil && !connector.IsPermanent(err)) {
|
||||
t.Fatalf("deliver error = %v, want an error: %v, permanent", err, tt.wantErr)
|
||||
}
|
||||
if got := textsOf(bot.sent); !slices.Equal(got, tt.wantSent) {
|
||||
t.Fatalf("sent %q, want %q", got, tt.wantSent)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,30 @@ type Description struct {
|
||||
Deliveries []*connectorv1.DeliveryType
|
||||
}
|
||||
|
||||
// NoPrivilegedEffects declares a lookup or action that changes no privileges
|
||||
// and accesses no secrets. Chat offers only tools that declare their effects,
|
||||
// so a tool that never states them is unavailable there.
|
||||
func NoPrivilegedEffects() *connectorv1.Effect {
|
||||
return &connectorv1.Effect{EffectsDeclared: true}
|
||||
}
|
||||
|
||||
// UndeclaredEffects names every action and lookup in d that doesn't state
|
||||
// whether it changes privileges or accesses secrets.
|
||||
func UndeclaredEffects(d Description) []string {
|
||||
var names []string
|
||||
for _, a := range d.Actions {
|
||||
if !a.GetEffect().GetEffectsDeclared() {
|
||||
names = append(names, "action "+a.GetName())
|
||||
}
|
||||
}
|
||||
for _, l := range d.Lookups {
|
||||
if !l.GetEffect().GetEffectsDeclared() {
|
||||
names = append(names, "lookup "+l.GetName())
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// Event is one typed event parsed from a verified payload.
|
||||
type Event struct {
|
||||
Type string
|
||||
|
||||
+532
-142
File diff suppressed because it is too large.
Load diff
@@ -19,14 +19,15 @@ import (
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
ConnectorService_Configure_FullMethodName = "/connector.v1.ConnectorService/Configure"
|
||||
ConnectorService_Describe_FullMethodName = "/connector.v1.ConnectorService/Describe"
|
||||
ConnectorService_Parse_FullMethodName = "/connector.v1.ConnectorService/Parse"
|
||||
ConnectorService_Resolve_FullMethodName = "/connector.v1.ConnectorService/Resolve"
|
||||
ConnectorService_Invoke_FullMethodName = "/connector.v1.ConnectorService/Invoke"
|
||||
ConnectorService_Lookup_FullMethodName = "/connector.v1.ConnectorService/Lookup"
|
||||
ConnectorService_Deliver_FullMethodName = "/connector.v1.ConnectorService/Deliver"
|
||||
ConnectorService_Listen_FullMethodName = "/connector.v1.ConnectorService/Listen"
|
||||
ConnectorService_Configure_FullMethodName = "/connector.v1.ConnectorService/Configure"
|
||||
ConnectorService_Describe_FullMethodName = "/connector.v1.ConnectorService/Describe"
|
||||
ConnectorService_Parse_FullMethodName = "/connector.v1.ConnectorService/Parse"
|
||||
ConnectorService_Resolve_FullMethodName = "/connector.v1.ConnectorService/Resolve"
|
||||
ConnectorService_Invoke_FullMethodName = "/connector.v1.ConnectorService/Invoke"
|
||||
ConnectorService_Lookup_FullMethodName = "/connector.v1.ConnectorService/Lookup"
|
||||
ConnectorService_Deliver_FullMethodName = "/connector.v1.ConnectorService/Deliver"
|
||||
ConnectorService_Listen_FullMethodName = "/connector.v1.ConnectorService/Listen"
|
||||
ConnectorService_TargetFacts_FullMethodName = "/connector.v1.ConnectorService/TargetFacts"
|
||||
)
|
||||
|
||||
// ConnectorServiceClient is the client API for ConnectorService service.
|
||||
@@ -59,12 +60,20 @@ type ConnectorServiceClient interface {
|
||||
// delivery is never offered to an agent: hard rules apply to it, guards
|
||||
// don't. The host retries a failed delivery, so a connector should make a
|
||||
// repeat with the same idempotency key harmless where its service allows.
|
||||
// A connector returns InvalidArgument, FailedPrecondition, PermissionDenied
|
||||
// or NotFound when the service rejects the delivery permanently: the host
|
||||
// records the reason and stops retrying. Any other status is retried.
|
||||
Deliver(ctx context.Context, in *DeliverRequest, opts ...grpc.CallOption) (*DeliverResponse, error)
|
||||
// Listen streams the events of a source the connector holds its own
|
||||
// connection to, such as a chat long poll, from cursor on. Each response
|
||||
// carries the cursor to resume after its events, which the host keeps only
|
||||
// once those events are stored.
|
||||
Listen(ctx context.Context, in *ListenRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ListenResponse], error)
|
||||
// TargetFacts answers what the connector's system of record knows about a
|
||||
// target, such as who owns it, at the moment an action on it is judged. The
|
||||
// host asks only connectors that declare target_facts, and never stores the
|
||||
// answer.
|
||||
TargetFacts(ctx context.Context, in *TargetFactsRequest, opts ...grpc.CallOption) (*TargetFactsResponse, error)
|
||||
}
|
||||
|
||||
type connectorServiceClient struct {
|
||||
@@ -164,6 +173,16 @@ func (c *connectorServiceClient) Listen(ctx context.Context, in *ListenRequest,
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type ConnectorService_ListenClient = grpc.ServerStreamingClient[ListenResponse]
|
||||
|
||||
func (c *connectorServiceClient) TargetFacts(ctx context.Context, in *TargetFactsRequest, opts ...grpc.CallOption) (*TargetFactsResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(TargetFactsResponse)
|
||||
err := c.cc.Invoke(ctx, ConnectorService_TargetFacts_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ConnectorServiceServer is the server API for ConnectorService service.
|
||||
// All implementations must embed UnimplementedConnectorServiceServer
|
||||
// for forward compatibility.
|
||||
@@ -194,12 +213,20 @@ type ConnectorServiceServer interface {
|
||||
// delivery is never offered to an agent: hard rules apply to it, guards
|
||||
// don't. The host retries a failed delivery, so a connector should make a
|
||||
// repeat with the same idempotency key harmless where its service allows.
|
||||
// A connector returns InvalidArgument, FailedPrecondition, PermissionDenied
|
||||
// or NotFound when the service rejects the delivery permanently: the host
|
||||
// records the reason and stops retrying. Any other status is retried.
|
||||
Deliver(context.Context, *DeliverRequest) (*DeliverResponse, error)
|
||||
// Listen streams the events of a source the connector holds its own
|
||||
// connection to, such as a chat long poll, from cursor on. Each response
|
||||
// carries the cursor to resume after its events, which the host keeps only
|
||||
// once those events are stored.
|
||||
Listen(*ListenRequest, grpc.ServerStreamingServer[ListenResponse]) error
|
||||
// TargetFacts answers what the connector's system of record knows about a
|
||||
// target, such as who owns it, at the moment an action on it is judged. The
|
||||
// host asks only connectors that declare target_facts, and never stores the
|
||||
// answer.
|
||||
TargetFacts(context.Context, *TargetFactsRequest) (*TargetFactsResponse, error)
|
||||
mustEmbedUnimplementedConnectorServiceServer()
|
||||
}
|
||||
|
||||
@@ -234,6 +261,9 @@ func (UnimplementedConnectorServiceServer) Deliver(context.Context, *DeliverRequ
|
||||
func (UnimplementedConnectorServiceServer) Listen(*ListenRequest, grpc.ServerStreamingServer[ListenResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method Listen not implemented")
|
||||
}
|
||||
func (UnimplementedConnectorServiceServer) TargetFacts(context.Context, *TargetFactsRequest) (*TargetFactsResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method TargetFacts not implemented")
|
||||
}
|
||||
func (UnimplementedConnectorServiceServer) mustEmbedUnimplementedConnectorServiceServer() {}
|
||||
func (UnimplementedConnectorServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
@@ -392,6 +422,24 @@ func _ConnectorService_Listen_Handler(srv interface{}, stream grpc.ServerStream)
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type ConnectorService_ListenServer = grpc.ServerStreamingServer[ListenResponse]
|
||||
|
||||
func _ConnectorService_TargetFacts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(TargetFactsRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(ConnectorServiceServer).TargetFacts(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: ConnectorService_TargetFacts_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(ConnectorServiceServer).TargetFacts(ctx, req.(*TargetFactsRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// ConnectorService_ServiceDesc is the grpc.ServiceDesc for ConnectorService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
@@ -427,6 +475,10 @@ var ConnectorService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "Deliver",
|
||||
Handler: _ConnectorService_Deliver_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "TargetFacts",
|
||||
Handler: _ConnectorService_TargetFacts_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user