Skip to content
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
2 changes: 2 additions & 0 deletions lib/web/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -1169,6 +1169,8 @@ func (h *Handler) bindDefaultEndpoints() {
// Delete Machine ID bot
h.DELETE("/webapi/sites/:site/machine-id/bot/:name", h.WithClusterAuth(h.deleteBot))

// GET Machine ID instance for a bot by id
h.GET("/webapi/sites/:site/machine-id/bot/:name/bot-instance/:id", h.WithClusterAuth(h.getBotInstance))
// GET Machine ID bot instances (paged)
h.GET("/webapi/sites/:site/machine-id/bot-instance", h.WithClusterAuth(h.listBotInstances))

Expand Down
40 changes: 40 additions & 0 deletions lib/web/machineid.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"strconv"
"time"

yaml "github.com/ghodss/yaml"
"github.com/gravitational/trace"
"github.com/julienschmidt/httprouter"
"google.golang.org/protobuf/types/known/fieldmaskpb"
Expand Down Expand Up @@ -262,6 +263,45 @@ type updateBotRequest struct {
Roles []string `json:"roles"`
}

// getBotInstance retrieves a bot instance by id
func (h *Handler) getBotInstance(w http.ResponseWriter, r *http.Request, p httprouter.Params, sctx *SessionContext, site reversetunnelclient.RemoteSite) (any, error) {
botName := p.ByName("name")
instanceId := p.ByName("id")
if botName == "" {
return nil, trace.BadParameter("empty bot name")
}
if instanceId == "" {
return nil, trace.BadParameter("empty id")
}

clt, err := sctx.GetUserClient(r.Context(), site)
if err != nil {
return nil, trace.Wrap(err)
}
instance, err := clt.BotInstanceServiceClient().GetBotInstance(r.Context(), &machineidv1.GetBotInstanceRequest{
InstanceId: instanceId,
BotName: botName,
})
if err != nil {
return nil, trace.Wrap(err, "error querying bot instance")
}

yaml, err := yaml.Marshal(types.ProtoResource153ToLegacy(instance))
if err != nil {
return nil, trace.Wrap(err, "error stringifying to yaml")
}

return GetBotInstanceResponse{
BotInstance: instance,
YAML: string(yaml),
}, nil
}

type GetBotInstanceResponse struct {
BotInstance *machineidv1.BotInstance `json:"bot_instance"`
YAML string `json:"yaml"`
}

// listBotInstances returns a list of bot instances for a given cluster site.
func (h *Handler) listBotInstances(_ http.ResponseWriter, r *http.Request, _ httprouter.Params, sctx *SessionContext, site reversetunnelclient.RemoteSite) (any, error) {
clt, err := sctx.GetUserClient(r.Context(), site)
Expand Down
77 changes: 71 additions & 6 deletions lib/web/machineid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import (
"github.com/gravitational/trace"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/timestamppb"

machineidv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/machineid/v1"
Expand Down Expand Up @@ -372,14 +373,14 @@ func TestListBotInstances(t *testing.T) {
"bot-instance",
)

instanceId := uuid.New().String()
instanceID := uuid.New().String()

_, err := env.server.Auth().CreateBotInstance(ctx, &machineidv1.BotInstance{
Kind: types.KindBotInstance,
Version: types.V1,
Spec: &machineidv1.BotInstanceSpec{
BotName: "test-bot",
InstanceId: instanceId,
InstanceId: instanceID,
},
Status: &machineidv1.BotInstanceStatus{
LatestHeartbeats: []*machineidv1.BotInstanceStatusHeartbeat{
Expand Down Expand Up @@ -420,7 +421,7 @@ func TestListBotInstances(t *testing.T) {
require.Empty(t, cmp.Diff(instances, ListBotInstancesResponse{
BotInstances: []BotInstance{
{
InstanceId: instanceId,
InstanceId: instanceID,
BotName: "test-bot",
JoinMethodLatest: "test-join-method",
HostNameLatest: "test-hostname",
Expand All @@ -447,14 +448,14 @@ func TestListBotInstancesWithInitialHeartbeat(t *testing.T) {
"bot-instance",
)

instanceId := uuid.New().String()
instanceID := uuid.New().String()

_, err := env.server.Auth().CreateBotInstance(ctx, &machineidv1.BotInstance{
Kind: types.KindBotInstance,
Version: types.V1,
Spec: &machineidv1.BotInstanceSpec{
BotName: "test-bot",
InstanceId: instanceId,
InstanceId: instanceID,
},
Status: &machineidv1.BotInstanceStatus{
InitialHeartbeat: &machineidv1.BotInstanceStatusHeartbeat{
Expand Down Expand Up @@ -482,7 +483,7 @@ func TestListBotInstancesWithInitialHeartbeat(t *testing.T) {
require.Empty(t, cmp.Diff(instances, ListBotInstancesResponse{
BotInstances: []BotInstance{
{
InstanceId: instanceId,
InstanceId: instanceID,
BotName: "test-bot",
JoinMethodLatest: "test-join-method",
HostNameLatest: "test-hostname",
Expand Down Expand Up @@ -722,3 +723,67 @@ func TestListBotInstancesWithSearchTermFilter(t *testing.T) {
})
}
}

func TestGetBotInstance(t *testing.T) {
ctx := context.Background()
env := newWebPack(t, 1)
proxy := env.proxies[0]
pack := proxy.authPack(t, "admin", []types.Role{services.NewPresetEditorRole()})
clusterName := env.server.ClusterName()

botName := "test-bot"
instanceID := uuid.New().String()

_, err := env.server.Auth().CreateBotInstance(ctx, &machineidv1.BotInstance{
Kind: types.KindBotInstance,
Version: types.V1,
Spec: &machineidv1.BotInstanceSpec{
BotName: botName,
InstanceId: instanceID,
},
Status: &machineidv1.BotInstanceStatus{
InitialHeartbeat: &machineidv1.BotInstanceStatusHeartbeat{
RecordedAt: &timestamppb.Timestamp{
Seconds: 1,
Nanos: 0,
},
},
},
})
require.NoError(t, err)

endpoint := pack.clt.Endpoint(
"webapi",
"sites",
clusterName,
"machine-id",
"bot",
botName,
"bot-instance",
instanceID,
)
response, err := pack.clt.Get(ctx, endpoint, url.Values{})
require.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code(), "unexpected status code")

var resp GetBotInstanceResponse
require.NoError(t, json.Unmarshal(response.Bytes(), &resp), "invalid response received")

require.Empty(t, cmp.Diff(resp.BotInstance, machineidv1.BotInstance{
Kind: types.KindBotInstance,
Version: types.V1,
Spec: &machineidv1.BotInstanceSpec{
BotName: botName,
InstanceId: instanceID,
},
Status: &machineidv1.BotInstanceStatus{
InitialHeartbeat: &machineidv1.BotInstanceStatusHeartbeat{
RecordedAt: &timestamppb.Timestamp{
Seconds: 1,
Nanos: 0,
},
},
},
}, protocmp.Transform(), protocmp.IgnoreFields(&machineidv1.BotInstance{}, "metadata")))
assert.YAMLEq(t, fmt.Sprintf("kind: bot_instance\nmetadata:\n name: %[1]s\n revision: %[2]s\nspec:\n bot_name: test-bot\n instance_id: %[1]s\nstatus:\n initial_heartbeat:\n recorded_at: \"1970-01-01T00:00:01Z\"\nversion: v1\n", instanceID, resp.BotInstance.Metadata.Revision), resp.YAML)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* Teleport
* Copyright (C) 2025 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { copyToClipboard } from 'design/utils/copyToClipboard';
import { fireEvent, render, screen } from 'design/utils/testing';

import { CopyButton } from './CopyButton';

jest.mock('design/utils/copyToClipboard', () => {
return {
__esModule: true,
copyToClipboard: jest.fn(),
};
});

describe('CopyButton', () => {
it('prevents parent elements from stealing clicks', () => {
const parentClick = jest.fn();

render(
<div onClick={parentClick}>
<CopyButton name="copy data" />
</div>
);

fireEvent.click(screen.getByLabelText('copy'));

expect(parentClick).toHaveBeenCalledTimes(0);
expect(copyToClipboard).toHaveBeenCalledTimes(1);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { useEffect, useRef, useState } from 'react';
import { MouseEventHandler, useEffect, useRef, useState } from 'react';

import Box from 'design/Box';
import ButtonIcon from 'design/ButtonIcon';
Expand Down Expand Up @@ -46,7 +46,9 @@ export function CopyButton({
}
};

const handleCopy = () => {
const handleCopy: MouseEventHandler<unknown> = e => {
e.stopPropagation(); // Prevent parent onClick callbacks from stealing the click

clearCurrentTimeout();
setCopiedText(copySuccess);
copyToClipboard(name);
Expand All @@ -63,7 +65,12 @@ export function CopyButton({
return (
<Box mr={mr} ml={ml}>
<HoverTooltip tipContent={copiedText}>
<ButtonIcon setRef={copyAnchorEl} size={0} onClick={handleCopy}>
<ButtonIcon
setRef={copyAnchorEl}
size={0}
onClick={handleCopy}
aria-label="copy"
>
{copiedText === copySuccess ? (
<Check size="small" />
) : (
Expand Down
15 changes: 15 additions & 0 deletions web/packages/teleport/src/BotInstances/BotInstances.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ import {
FeatureHeader,
FeatureHeaderTitle,
} from 'teleport/components/Layout/Layout';
import cfg from 'teleport/config';
import { listBotInstances } from 'teleport/services/bot/bot';
import { BotInstanceSummary } from 'teleport/services/bot/types';

import { BotInstancesList } from './List/BotInstancesList';

Expand Down Expand Up @@ -87,6 +89,18 @@ export function BotInstances() {
});
}, []);

const onItemSelected = useCallback(
(item: BotInstanceSummary) => {
history.push(
cfg.getBotInstanceDetailsRoute({
botName: item.bot_name,
instanceId: item.instance_id,
})
);
},
[history]
);

return (
<FeatureBox>
<FeatureHeader justifyContent="space-between">
Expand All @@ -112,6 +126,7 @@ export function BotInstances() {
onFetchPrev={hasPrevPage ? handleFetchPrev : undefined}
onSearchChange={handleSearchChange}
searchTerm={searchTerm}
onItemSelected={onItemSelected}
/>
) : undefined}
</FeatureBox>
Expand Down
Loading
Loading