fleet/server/fleet/utils.go
Jordan Montgomery 994672ca20
Hydrant CA Feature Branch (#31807)
There are still some TODOs particularly within Gitops test code which
will be worked on in a followup PR

# Checklist for submitter

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

- [x] Changes file added for user-visible changes in `changes/`,
`orbit/changes/` or `ee/fleetd-chrome/changes`.
See [Changes
files](https://github.com/fleetdm/fleet/blob/main/docs/Contributing/guides/committing-changes.md#changes-files)
for more information.

- [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

## Testing

- [x] Added/updated automated tests
- [x] Where appropriate, [automated tests simulate multiple hosts and
test for host
isolation](https://github.com/fleetdm/fleet/blob/main/docs/Contributing/reference/patterns-backend.md#unit-testing)
(updates to one hosts's records do not affect another)

- [ ] QA'd all new/changed functionality manually

For unreleased bug fixes in a release candidate, one of:

- [x] Confirmed that the fix is not expected to adversely impact load
test results
- [x] Alerted the release DRI if additional load testing is needed

## Database migrations

- [x] Checked table schema to confirm autoupdate
- [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`).

## New Fleet configuration settings

- [ ] Setting(s) is/are explicitly excluded from GitOps

If you didn't check the box above, follow this checklist for
GitOps-enabled settings:

- [ ] Verified that the setting is exported via `fleetctl
generate-gitops`
- [x] Verified the setting is documented in a separate PR to [the GitOps
documentation](https://github.com/fleetdm/fleet/blob/main/docs/Configuration/yaml-files.md#L485)
- [x] Verified that the setting is cleared on the server if it is not
supplied in a YAML file (or that it is documented as being optional)
- [x] Verified that any relevant UI is disabled when GitOps mode is
enabled

---------

Co-authored-by: Gabriel Hernandez <ghernandez345@gmail.com>
Co-authored-by: Magnus Jensen <magnus@fleetdm.com>
Co-authored-by: Sarah Gillespie <73313222+gillespi314@users.noreply.github.com>
2025-09-04 12:39:41 -04:00

109 lines
3.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package fleet
import (
"encoding/json"
"errors"
"io"
"regexp"
"strings"
"github.com/Masterminds/semver/v3"
"github.com/fatih/color"
"golang.org/x/text/unicode/norm"
)
func WriteExpiredLicenseBanner(w io.Writer) {
warningColor := color.New(color.FgWhite, color.Bold, color.BgRed)
warningColor.Fprintf(
w,
"Your license for Fleet Premium is about to expire. If youd like to renew or have questions about "+
"downgrading, please navigate to "+
"https://fleetdm.com/docs/using-fleet/faq#how-do-i-downgrade-from-fleet-premium-to-fleet-free and "+
"contact us for help.",
)
// We need to disable color and print a new line to make it look somewhat neat, otherwise colors continue to the
// next line
warningColor.DisableColor()
warningColor.Fprintln(w)
}
func WriteAppleBMTermsExpiredBanner(w io.Writer) {
warningColor := color.New(color.FgWhite, color.Bold, color.BgRed)
warningColor.Fprintf(
w,
`Your organization cant automatically enroll macOS hosts until you accept the new terms `+
`and conditions for Apple Business Manager (ABM). An ABM administrator can accept these terms. `+
`Go to ABM: https://business.apple.com/`,
)
// We need to disable color and print a new line to make it look somewhat neat, otherwise colors continue to the
// next line
warningColor.DisableColor()
warningColor.Fprintln(w)
}
// JSONStrictDecode unmarshals the JSON value from the provided reader r into
// the destination value v. It returns an error if the unmarshaling fails.
// Compared to standard json.Unmarshal, this function will return an error if
// any unknown key is specified in the JSON value, and if there is any trailing
// byte after the JSON value.
func JSONStrictDecode(r io.Reader, v interface{}) error {
dec := json.NewDecoder(r)
dec.DisallowUnknownFields()
if err := dec.Decode(v); err != nil {
return err
}
var extra json.RawMessage
if dec.Decode(&extra) != io.EOF {
return errors.New("json: extra bytes after end of object")
}
return nil
}
// Preprocess trims and normalises unicode characters of the given input
func Preprocess(input string) string {
// Remove leading/trailing whitespace.
input = strings.TrimSpace(input)
// Normalize Unicode characters.
return norm.NFC.String(input)
}
// CompareVersions returns an integer comparing two versions according to semantic version
// precedence. The result will be 0 if a == b, -1 if a < b, or +1 if a > b.
// An invalid semantic version string is considered less than a valid one. All invalid semantic
// version strings compare equal to each other.
func CompareVersions(a string, b string) int {
verA, errA := VersionToSemverVersion(a)
verB, errB := VersionToSemverVersion(b)
switch {
case errA != nil && errB != nil:
return 0
case errA != nil:
return -1
case errB != nil:
return 1
default:
return verA.Compare(verB)
}
}
// IsAtLeastVersion returns whether currentVersion is at least minimumVersion, using semantics
// of CompareVersions for version validity
func IsAtLeastVersion(currentVersion string, minimumVersion string) bool {
return CompareVersions(currentVersion, minimumVersion) >= 0
}
var macOSRapidSecurityResponseVersionSuffix = regexp.MustCompile(` \([a-z]\)`)
// VersionToSemvarVersion converts a version string to a semver version. This wrap semver.NewVersion
// and applies some additional formatting to the version string.
// Formatting applied:
// - Strip mac rapid security response suffix - "13.3.1 (a)" -> "13.3.1"
func VersionToSemverVersion(version string) (*semver.Version, error) {
ver, err := semver.NewVersion(macOSRapidSecurityResponseVersionSuffix.ReplaceAllString(version, ``))
if err != nil {
return nil, err
}
return ver, nil
}