fleet/server/mdm/maintainedapps/sync.go
Ian Littman 4a1e5340f0
Switch Fleet-maintained apps to use manifest-based structure (#27201)
For #26082.

# Checklist for submitter

If some of the following don't apply, delete the relevant line.

<!-- Note that API documentation changes are now addressed by the
product design team. -->

- [x] Input data is properly validated, `SELECT *` is avoided, SQL
injection is prevented (using placeholders for values in statements)
- [x] If paths of existing endpoints are modified without backwards
compatibility, checked the frontend/CLI for any necessary changes
- [x] If database migrations are included, checked table schema to
confirm autoupdate
- For database migrations:
- [x] Checked schema for all modified table for columns that will
auto-update timestamps during migration.
- [x] Confirmed that updating the timestamps is acceptable, and will not
cause unwanted side effects.
- [x] Ensured the correct collation is explicitly set for character
columns (`COLLATE utf8mb4_unicode_ci`).
- [x] Added/updated automated tests
- [x] A detailed QA plan exists on the associated ticket (if it isn't
there, work with the product group's QA engineer to add it)
- [x] Manual QA for all new/changed functionality
2025-03-20 21:21:56 -05:00

144 lines
4.3 KiB
Go

package maintained_apps
import (
"context"
_ "embed"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
ma "github.com/fleetdm/fleet/v4/ee/maintained-apps"
"github.com/fleetdm/fleet/v4/pkg/fleethttp"
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
"github.com/fleetdm/fleet/v4/server/fleet"
kitlog "github.com/go-kit/log"
)
type appListing struct {
Name string `json:"name"`
Slug string `json:"slug"`
Platform string `json:"platform"`
UniqueIdentifier string `json:"unique_identifier"`
}
type AppsList struct {
Version uint `json:"version"`
Apps []appListing `json:"apps"`
}
const fmaOutputsBase = "https://raw.githubusercontent.com/fleetdm/fleet/refs/heads/main/ee/maintained-apps/outputs"
// Refresh fetches the latest information about maintained apps from FMA's
// apps list on GitHub and updates the Fleet database with the new information.
func Refresh(ctx context.Context, ds fleet.Datastore, logger kitlog.Logger) error {
httpClient := fleethttp.NewClient(fleethttp.WithTimeout(10 * time.Second))
baseURL := fmaOutputsBase
if baseFromEnvVar := os.Getenv("FLEET_DEV_MAINTAINED_APPS_BASE_URL"); baseFromEnvVar != "" {
baseURL = baseFromEnvVar
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s/apps.json", baseURL), nil)
if err != nil {
return ctxerr.Wrap(ctx, err, "create http request")
}
res, err := httpClient.Do(req)
if err != nil {
return ctxerr.Wrap(ctx, err, "execute http request")
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return ctxerr.Wrap(ctx, err, "read http response body")
}
switch res.StatusCode {
case http.StatusOK:
// success, go on
case http.StatusNotFound:
return ctxerr.New(ctx, "maintained apps list not found")
default:
if len(body) > 512 {
body = body[:512]
}
return ctxerr.Errorf(ctx, "apps list returned HTTP status %d: %s", res.StatusCode, string(body))
}
var appsList AppsList
if err := json.Unmarshal(body, &appsList); err != nil {
return ctxerr.Wrap(ctx, err, "unmarshal apps list")
}
if appsList.Version != 2 {
return ctxerr.Errorf(ctx, "apps list is an incompatible version")
}
for _, app := range appsList.Apps {
if _, err = ds.UpsertMaintainedApp(ctx, &fleet.MaintainedApp{
Name: app.Name,
Slug: app.Slug,
Platform: app.Platform,
UniqueIdentifier: app.UniqueIdentifier,
}); err != nil {
return ctxerr.Wrap(ctx, err, "upsert maintained app")
}
}
return nil
}
// Hydrate pulls information from app-level FMA manifests info an FMA skeleton pulled from the database
func Hydrate(ctx context.Context, app *fleet.MaintainedApp) (*fleet.MaintainedApp, error) {
httpClient := fleethttp.NewClient(fleethttp.WithTimeout(10 * time.Second))
baseURL := fmaOutputsBase
if baseFromEnvVar := os.Getenv("FLEET_DEV_MAINTAINED_APPS_BASE_URL"); baseFromEnvVar != "" {
baseURL = baseFromEnvVar
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s/%s.json", baseURL, app.Slug), nil)
if err != nil {
return nil, ctxerr.Wrap(ctx, err, "create http request")
}
res, err := httpClient.Do(req)
if err != nil {
return nil, ctxerr.Wrap(ctx, err, "execute http request")
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, ctxerr.Wrap(ctx, err, "read http response body")
}
switch res.StatusCode {
case http.StatusOK:
// success, go on
case http.StatusNotFound:
return nil, ctxerr.New(ctx, "app not found in Fleet manifests")
default:
if len(body) > 512 {
body = body[:512]
}
return nil, ctxerr.Errorf(ctx, "manifest retrieval returned HTTP status %d: %s", res.StatusCode, string(body))
}
var manifest ma.FMAManifestFile
if err := json.Unmarshal(body, &manifest); err != nil {
return nil, ctxerr.Wrapf(ctx, err, "unmarshal FMA manifest for %s", app.Slug)
}
manifest.Versions[0].Slug = app.Slug
app.Version = manifest.Versions[0].Version
app.Platform = manifest.Versions[0].Platform()
app.InstallerURL = manifest.Versions[0].InstallerURL
app.SHA256 = manifest.Versions[0].SHA256
app.InstallScript = manifest.Refs[manifest.Versions[0].InstallScriptRef]
app.UninstallScript = manifest.Refs[manifest.Versions[0].UninstallScriptRef]
app.AutomaticInstallQuery = manifest.Versions[0].Queries.Exists
return app, nil
}