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 premium, device authed endpoint to retrieve policies #5967

Merged
merged 10 commits into from
May 31, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions changes/issue-5685-device-policies-endpoint
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Added `/api/_version_/fleet/device/{token}/policies` to retrieve policies for a device. This endpoint can only be accessed with a premium license.
46 changes: 46 additions & 0 deletions docs/Using-Fleet/REST-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
- [Teams](#teams)
- [Translator](#translator)
- [Users](#users)
- [Devices](#devices)
roperzh marked this conversation as resolved.
Show resolved Hide resolved

## Overview

Expand Down Expand Up @@ -6359,6 +6360,51 @@ Deletes the selected user's sessions in Fleet. Also deletes the user's API token

`Status: 200`

## Devices

- [List all software](#list-all-software)
- [List device policies](#list-device-policies)

### List device policies

_Available in Fleet Premium_

`GET /api/_version_/fleet/device/{token}/policies`

#### Parameters

None.

#### Example

`GET /api/latest/fleet/device/880e301e-e6c1-4ffa-ab59-1ecfbae34035/policies`

##### Default response

`Status: 200`

```json
{
"policies": [
{
"id": 3,
"name": "Antivirus healthy (Linux)",
"query": "SELECT score FROM (SELECT case when COUNT(*) = 2 then 1 ELSE 0 END AS score FROM processes WHERE (name = 'clamd') OR (name = 'freshclam')) WHERE score == 1;",
"description": "Checks that both ClamAV's daemon and its updater service (freshclam) are running.",
"author_id": 1,
"author_name": "Admin",
"author_email": "[email protected]",
"team_id": null,
"resolution": "Ensure ClamAV and Freshclam are installed and running.",
"platform": "linux",
"created_at": "2022-05-23T20:53:36Z",
"updated_at": "2022-05-23T20:53:36Z",
"response": "fail"
}
]
}
```

## Debug

- [Get a summary of errors](#get-a-summary-of-errors)
Expand Down
28 changes: 28 additions & 0 deletions ee/server/service/devices.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package service

import (
"context"

"github.com/fleetdm/fleet/v4/server/contexts/authz"
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
"github.com/fleetdm/fleet/v4/server/fleet"
)

func (svc *Service) ListDevicePolicies(ctx context.Context, host *fleet.Host) ([]*fleet.HostPolicy, error) {
if !svc.authz.IsAuthenticatedWith(ctx, authz.AuthnDeviceToken) {
if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {
return nil, err
}

host, err := svc.ds.HostLite(ctx, host.ID)
if err != nil {
return nil, ctxerr.Wrap(ctx, err, "find host for device policies")
}

if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {
return nil, err
}
}
roperzh marked this conversation as resolved.
Show resolved Hide resolved

return svc.ds.ListPoliciesForHost(ctx, host)
}
55 changes: 55 additions & 0 deletions server/datastore/mysql/hosts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ func TestHosts(t *testing.T) {
{"ListFilterAdditional", testHostsListFilterAdditional},
{"ListStatus", testHostsListStatus},
{"ListQuery", testHostsListQuery},
{"ListPoliciesForHost", testListPoliciesForHost},
{"Enroll", testHostsEnroll},
{"LoadHostByNodeKey", testHostsLoadHostByNodeKey},
{"LoadHostByNodeKeyCaseSensitive", testHostsLoadHostByNodeKeyCaseSensitive},
Expand Down Expand Up @@ -4206,3 +4207,57 @@ func testShouldCleanTeamPolicies(t *testing.T, ds *Datastore) {
require.Equal(t, shouldCleanTeamPolicies(c.currentTeamID, c.newTeamID), c.out)
}
}

func testListPoliciesForHost(t *testing.T, ds *Datastore) {
roperzh marked this conversation as resolved.
Show resolved Hide resolved
user := test.NewUser(t, ds, "Alice", "[email protected]", true)
team, err := ds.NewTeam(context.Background(), &fleet.Team{Name: t.Name()})
require.NoError(t, err)

host, err := ds.NewHost(context.Background(), &fleet.Host{
OsqueryHostID: "1234",
DetailUpdatedAt: time.Now(),
LabelUpdatedAt: time.Now(),
PolicyUpdatedAt: time.Now(),
SeenTime: time.Now(),
NodeKey: "1",
UUID: "1",
Hostname: "foo.local",
})
require.NoError(t, err)
require.NoError(t, ds.AddHostsToTeam(context.Background(), &team.ID, []uint{host.ID}))
host, err = ds.Host(context.Background(), host.ID)

tq, err := ds.NewQuery(context.Background(), &fleet.Query{
Name: "query1",
Description: "query1 desc",
Query: "select 1;",
Saved: true,
})
require.NoError(t, err)

teamPolicy, err := ds.NewTeamPolicy(context.Background(), team.ID, &user.ID, fleet.PolicyPayload{
QueryID: &tq.ID,
})
require.NoError(t, err)

gq, err := ds.NewQuery(context.Background(), &fleet.Query{
Name: "query2",
Description: "query2 desc",
Query: "select 2;",
Saved: true,
})
require.NoError(t, err)
globalPolicy, err := ds.NewGlobalPolicy(context.Background(), &user.ID, fleet.PolicyPayload{
QueryID: &gq.ID,
})
require.NoError(t, err)

require.NoError(t, ds.RecordPolicyQueryExecutions(context.Background(), host, map[uint]*bool{teamPolicy.ID: ptr.Bool(false), globalPolicy.ID: ptr.Bool(true)}, time.Now(), false))
require.NoError(t, ds.RecordPolicyQueryExecutions(context.Background(), host, map[uint]*bool{teamPolicy.ID: ptr.Bool(true), globalPolicy.ID: ptr.Bool(false)}, time.Now(), false))

hostPolicies, err := ds.ListPoliciesForHost(context.Background(), host)
require.NoError(t, err)

require.Len(t, hostPolicies, 2)
require.ElementsMatch(t, []*fleet.HostPolicy{&fleet.HostPolicy{teamPolicy.PolicyData, "pass"}, &fleet.HostPolicy{globalPolicy.PolicyData, "fail"}}, hostPolicies)
}
2 changes: 2 additions & 0 deletions server/fleet/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,8 @@ type Service interface {
// ListHostDeviceMapping returns the list of device-mapping of user's email address
// for the host.
ListHostDeviceMapping(ctx context.Context, id uint) ([]*HostDeviceMapping, error)
// ListDevicePolicies lists all policies for the given host, including passing / failing summaries
ListDevicePolicies(ctx context.Context, host *Host) ([]*HostPolicy, error)

MacadminsData(ctx context.Context, id uint) (*MacadminsData, error)
AggregatedMacadminsData(ctx context.Context, teamID *uint) (*AggregatedMacadminsData, error)
Expand Down
42 changes: 42 additions & 0 deletions server/service/devices.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,45 @@ func getDeviceMacadminsDataEndpoint(ctx context.Context, request interface{}, sv
}
return getMacadminsDataResponse{Macadmins: data}, nil
}

////////////////////////////////////////////////////////////////////////////////
// Get Current Device's Policies
////////////////////////////////////////////////////////////////////////////////

type getDevicePoliciesRequest struct {
Token string `url:"token"`
}

func (r *getDevicePoliciesRequest) deviceAuthToken() string {
return r.Token
}

type getDevicePoliciesResponse struct {
Err error `json:"error,omitempty"`
Policies []*fleet.HostPolicy `json:"policies"`
}

func (r getDevicePoliciesResponse) error() error { return r.Err }

func getDevicePoliciesEndpoint(ctx context.Context, request interface{}, svc fleet.Service) (interface{}, error) {
host, ok := hostctx.FromContext(ctx)
if !ok {
err := ctxerr.Wrap(ctx, fleet.NewAuthRequiredError("internal error: missing host from request context"))
return getHostResponse{Err: err}, nil
}

data, err := svc.ListDevicePolicies(ctx, host)
if err != nil {
return getDevicePoliciesResponse{Err: err}, nil
}

return getDevicePoliciesResponse{Policies: data}, nil
}

func (svc *Service) ListDevicePolicies(ctx context.Context, host *fleet.Host) ([]*fleet.HostPolicy, error) {
// skipauth: No authorization check needed due to implementation returning
// only license error.
svc.authz.SkipAuthorization(ctx)

return nil, fleet.ErrMissingLicense
}
46 changes: 46 additions & 0 deletions server/service/devices_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package service

import (
"context"
"errors"
"testing"

"github.com/fleetdm/fleet/v4/server/fleet"
"github.com/fleetdm/fleet/v4/server/mock"
"github.com/fleetdm/fleet/v4/server/ptr"
"github.com/fleetdm/fleet/v4/server/test"
"github.com/stretchr/testify/require"
)

func TestListDevicePolicies(t *testing.T) {
roperzh marked this conversation as resolved.
Show resolved Hide resolved
ds := new(mock.Store)
mockPolicies := []*fleet.HostPolicy{&fleet.HostPolicy{fleet.PolicyData{Name: "test-policy"}, "pass"}}
ds.ListPoliciesForHostFunc = func(ctx context.Context, host *fleet.Host) ([]*fleet.HostPolicy, error) {
return mockPolicies, nil
}

ds.HostLiteFunc = func(ctx context.Context, hostID uint) (*fleet.Host, error) {
if hostID != uint(1) {
return nil, errors.New("test error")
}

return &fleet.Host{ID: hostID, TeamID: ptr.Uint(1)}, nil
}

t.Run("without premium license", func(t *testing.T) {
svc := newTestService(t, ds, nil, nil, &TestServerOpts{License: &fleet.LicenseInfo{Tier: fleet.TierFree}})
_, error := svc.ListDevicePolicies(test.UserContext(test.UserAdmin), &fleet.Host{ID: 1})
require.ErrorIs(t, error, fleet.ErrMissingLicense)
})

t.Run("with premium license", func(t *testing.T) {
svc := newTestService(t, ds, nil, nil, &TestServerOpts{License: &fleet.LicenseInfo{Tier: fleet.TierPremium}})

_, error := svc.ListDevicePolicies(test.UserContext(test.UserAdmin), &fleet.Host{})
require.Error(t, error)

policies, error := svc.ListDevicePolicies(test.UserContext(test.UserAdmin), &fleet.Host{ID: 1})
require.NoError(t, error)
require.Len(t, policies, len(mockPolicies))
})
}
1 change: 1 addition & 0 deletions server/service/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@ func attachFleetAPIRoutes(r *mux.Router, svc fleet.Service, config config.FleetC
de.POST("/api/_version_/fleet/device/{token}/refetch", refetchDeviceHostEndpoint, refetchDeviceHostRequest{})
de.GET("/api/_version_/fleet/device/{token}/device_mapping", listDeviceHostDeviceMappingEndpoint, listDeviceHostDeviceMappingRequest{})
de.GET("/api/_version_/fleet/device/{token}/macadmins", getDeviceMacadminsDataEndpoint, getDeviceMacadminsDataRequest{})
de.GET("/api/_version_/fleet/device/{token}/policies", getDevicePoliciesEndpoint, getDevicePoliciesRequest{})

// host-authenticated endpoints
he := newHostAuthenticatedEndpointer(svc, logger, opts, r, apiVersions...)
Expand Down