Skip to content
Merged

Dev #97

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
22 changes: 22 additions & 0 deletions api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http"
"net/url"
"strings"
"sync"
"time"

"github.com/fosrl/newt/logger"
Expand Down Expand Up @@ -65,6 +66,22 @@ func (e *APIError) Unwrap() error {
return e.Err
}

// RequiresReauthentication reports whether the session is no longer accepted
// and logging in again would fix it: a 401, or the 403 an org's access policy
// sends once its maximum session length has passed. Other policy failures
// (two-factor required, password expired) need more than a new login, so they
// don't count. The server sends no code for the policy case, only this message.
func (e *APIError) RequiresReauthentication() bool {
if e == nil || e.Type != ErrorTypeHTTPError {
return false
}
if e.Status == 401 {
return true
}
return e.Status == 403 &&
(strings.HasPrefix(e.Message, "Your session has expired") || strings.HasPrefix(e.Message, "Your session is invalid"))
}

// APIClient handles HTTP requests to the Pangolin API
type APIClient struct {
baseURL string
Expand All @@ -73,6 +90,11 @@ type APIClient struct {
csrfToken string
client *http.Client
onUnauthorized func()

// launcherNoTypeFilter holds servers whose launcher rejected the
// `resourceType` filter, so it isn't sent to them again.
launcherMu sync.Mutex
launcherNoTypeFilter map[string]bool
}

// NewAPIClient creates a new API client instance
Expand Down
88 changes: 88 additions & 0 deletions api/methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/http"
"net/url"
"strconv"
"strings"
"time"

"github.com/fosrl/windows-linux/config"
Expand Down Expand Up @@ -410,3 +411,90 @@ func (c *APIClient) ListGatewayResources(orgID string) ([]SiteResource, error) {

return gateways, nil
}

// ListLauncherPrivateResources returns one page of the private resources the
// user can reach in orgID, searched and sorted by name on the server.
//
// Servers that predate the `resourceType` filter reject it as an unknown
// parameter (400). Those get the unfiltered list, with public resources dropped
// here, so a page may hold fewer than pageSize items while the pagination still
// counts every resource.
func (c *APIClient) ListLauncherPrivateResources(orgID, query string, page, pageSize int) (*ListLauncherResourcesResponse, error) {
params := url.Values{}
params.Set("groupBy", "none")
params.Set("groupKey", "__all__")
params.Set("sort_by", "name")
params.Set("order", "asc")
params.Set("page", strconv.Itoa(page))
params.Set("pageSize", strconv.Itoa(pageSize))
if q := strings.TrimSpace(query); q != "" {
params.Set("query", q)
}
path := fmt.Sprintf("/org/%s/launcher/resources", url.PathEscape(orgID))

fetch := func(p url.Values) (*ListLauncherResourcesResponse, error) {
data, resp, err := c.makeRequest("GET", path+"?"+p.Encode(), nil)
if err != nil {
return nil, err
}
var result ListLauncherResourcesResponse
if err := c.parseResponse(data, resp, &result); err != nil {
return nil, err
}
return &result, nil
}

server := c.CurrentBaseURL()
c.launcherMu.Lock()
noFilter := c.launcherNoTypeFilter[server]
c.launcherMu.Unlock()

var result *ListLauncherResourcesResponse
var err error
if noFilter {
result, err = fetch(params)
} else {
filtered := url.Values{}
for k, v := range params {
filtered[k] = v
}
filtered.Set("resourceType", "site")
result, err = fetch(filtered)
var apiErr *APIError
if errors.As(err, &apiErr) && apiErr.Status == 400 {
result, err = fetch(params)
if err == nil {
c.launcherMu.Lock()
if c.launcherNoTypeFilter == nil {
c.launcherNoTypeFilter = map[string]bool{}
}
c.launcherNoTypeFilter[server] = true
c.launcherMu.Unlock()
}
}
}
if err != nil {
return nil, err
}

private := result.Resources[:0]
for _, r := range result.Resources {
if r.IsPrivate() {
private = append(private, r)
}
}
result.Resources = private
return result, nil
}

// InvalidateLauncherCache drops the server's cached launcher results for this
// user, so the next list reflects changes made in the last minute.
func (c *APIClient) InvalidateLauncherCache(orgID string) error {
path := fmt.Sprintf("/org/%s/launcher/invalidate-cache", url.PathEscape(orgID))
data, resp, err := c.makeRequest("POST", path, []byte("{}"))
if err != nil {
return err
}
var empty EmptyResponse
return c.parseResponse(data, resp, &empty)
}
56 changes: 56 additions & 0 deletions api/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,3 +200,59 @@ type ListSiteResourcesResponse struct {
type MyClientSettingsResponse struct {
Settings *config.ClientSettings `json:"settings"`
}

// LauncherLabel is a label on a launcher resource.
type LauncherLabel struct {
LabelID int `json:"labelId"`
Name string `json:"name"`
Color string `json:"color"`
}

// LauncherSite is a site serving a launcher resource.
type LauncherSite struct {
SiteID int `json:"siteId"`
Name string `json:"name"`
NiceID string `json:"niceId"`
Type string `json:"type"`
Online *bool `json:"online"`
}

// LauncherResource is a resource from GET /org/:orgId/launcher/resources.
// ResourceType is "site" for private resources and "public" for public ones.
type LauncherResource struct {
Key string `json:"launcherResourceKey"`
ResourceType string `json:"resourceType"`
ResourceID int `json:"resourceId"`
SiteResourceID *int `json:"siteResourceId"`
NiceID string `json:"niceId"`
Name string `json:"name"`
AccessDisplay string `json:"accessDisplay"`
AccessCopyValue string `json:"accessCopyValue"`
AccessURL *string `json:"accessUrl"`
Enabled bool `json:"enabled"`
Mode string `json:"mode"`
// Alias and PamMode are private resources only, and missing from older servers.
Alias *string `json:"alias"`
PamMode *string `json:"pamMode"`
Labels []LauncherLabel `json:"labels"`
Sites []LauncherSite `json:"sites"`
}

// IsPrivate reports whether this is a private (site) resource.
func (r LauncherResource) IsPrivate() bool { return r.ResourceType == "site" }

// LauncherPagination is the paging info of a launcher list.
type LauncherPagination struct {
Total int `json:"total"`
Page int `json:"page"`
PageSize int `json:"pageSize"`
}

// ListLauncherResourcesResponse is the inner `data` of GET /org/:orgId/launcher/resources.
type ListLauncherResourcesResponse struct {
Resources []LauncherResource `json:"resources"`
Pagination LauncherPagination `json:"pagination"`
}

// HasMore reports whether pages after this one exist.
func (p LauncherPagination) HasMore() bool { return p.Page*p.PageSize < p.Total }
45 changes: 45 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ type Config struct {
CheckForUpdatesButtonEnabled *bool `json:"checkForUpdatesButtonEnabled,omitempty"`
UpdateCheckIntervalSeconds *int `json:"updateCheckIntervalSeconds,omitempty"`
AutoDownloadUpdatesEnabled *bool `json:"autoDownloadUpdatesEnabled,omitempty"`
// ShowResourcesInMenu shows the Resources section in the tray popup (default on).
ShowResourcesInMenu *bool `json:"showResourcesInMenu,omitempty"`
// ResourcesCollapsed folds the tray popup's Resources section to its header.
ResourcesCollapsed *bool `json:"resourcesCollapsed,omitempty"`

// Orgs holds per-org overrides, keyed by org ID. Precedence when connecting
// to an org: server settings > its entry here > the global settings above.
Expand Down Expand Up @@ -300,6 +304,31 @@ func (cm *ConfigManager) UserConfigExists() bool {
return err == nil
}

// GetShowResourcesInMenu reports whether the tray popup lists the private
// resources the user can reach. On unless turned off.
func (cm *ConfigManager) GetShowResourcesInMenu() bool {
cm.mu.RLock()
defer cm.mu.RUnlock()
return cm.config == nil || cm.config.ShowResourcesInMenu == nil || *cm.config.ShowResourcesInMenu
}

// GetResourcesCollapsed reports whether the tray popup's Resources section is
// folded to its header.
func (cm *ConfigManager) GetResourcesCollapsed() bool {
cm.mu.RLock()
defer cm.mu.RUnlock()
return cm.config != nil && cm.config.ResourcesCollapsed != nil && *cm.config.ResourcesCollapsed
}

// SetResourcesCollapsed folds or unfolds the tray popup's Resources section.
func (cm *ConfigManager) SetResourcesCollapsed(value bool) bool {
cm.mu.Lock()
defer cm.mu.Unlock()
cfg := cm.getConfigCopy()
cfg.ResourcesCollapsed = &value
return cm.save(cfg)
}

// GetOnboardingSeenWelcome reports whether the setup welcome page was completed.
func (cm *ConfigManager) GetOnboardingSeenWelcome() bool {
cm.mu.RLock()
Expand Down Expand Up @@ -802,6 +831,14 @@ func mergeConfig(base, override *Config) *Config {
v := *override.AutoDownloadUpdatesEnabled
merged.AutoDownloadUpdatesEnabled = &v
}
if override.ShowResourcesInMenu != nil {
v := *override.ShowResourcesInMenu
merged.ShowResourcesInMenu = &v
}
if override.ResourcesCollapsed != nil {
v := *override.ResourcesCollapsed
merged.ResourcesCollapsed = &v
}
if override.OnboardingSeenWelcome != nil {
v := *override.OnboardingSeenWelcome
merged.OnboardingSeenWelcome = &v
Expand Down Expand Up @@ -907,6 +944,14 @@ func copyConfig(src *Config) *Config {
autoDownloadUpdatesEnabled := *src.AutoDownloadUpdatesEnabled
cfg.AutoDownloadUpdatesEnabled = &autoDownloadUpdatesEnabled
}
if src.ShowResourcesInMenu != nil {
showResourcesInMenu := *src.ShowResourcesInMenu
cfg.ShowResourcesInMenu = &showResourcesInMenu
}
if src.ResourcesCollapsed != nil {
resourcesCollapsed := *src.ResourcesCollapsed
cfg.ResourcesCollapsed = &resourcesCollapsed
}
if src.OnboardingSeenWelcome != nil {
onboardingSeenWelcome := *src.OnboardingSeenWelcome
cfg.OnboardingSeenWelcome = &onboardingSeenWelcome
Expand Down
8 changes: 5 additions & 3 deletions docs/dev/linux.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,11 @@ admins install immediately; others are asked via polkit (`pkcheck
`packaging/linux/net.pangolin.client.policy` must be installed (all packages
and `install-linux` do). pkcheck exit codes: 1 not authorized, 2 no
authentication agent in the session, 3 cancelled, 127 + "is not registered" =
policy missing. The install downloads `pangolin-cli_linux_<arch>` from the
CLI's latest GitHub release (`managers/cli_release.go`, shared with Windows),
checks it's an ELF, and renames it into `/usr/local/bin/pangolin` (same place
policy missing. The install gets the latest CLI version and asset checksums
from the Fossorial API (`api.fossorial.io/api/v1/versions/cli`, as `get-cli.sh`
does), downloads `pangolin-cli_linux_<arch>` from that version's GitHub release
(`managers/cli_release.go`, shared with Windows), checks its sha256 and that
it's an ELF, and renames it into `/usr/local/bin/pangolin` (same place
`get-cli.sh` uses). Test with network: `PANGOLIN_TEST_CLI_DOWNLOAD=1 go test ./managers -run CLI`.

## Secrets (`managers/secretstore/filestore_linux.go`)
Expand Down
14 changes: 7 additions & 7 deletions managers/cli_installer_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import (
"github.com/fosrl/newt/logger"
)

// The daemon installs the CLI binary from the CLI's GitHub release into the
// same place its install script (get-cli.sh) does.
// The daemon installs the CLI binary (see cli_release.go) into the same place
// its install script (get-cli.sh) does.
var cliInstallDir = "/usr/local/bin"

const cliBinaryName = "pangolin"
Expand Down Expand Up @@ -77,15 +77,15 @@ func InstallCLI(userToken uintptr) error {
if err != nil {
return err
}
release, err := getLatestCLIRelease(cliInstallerRepo)
release, err := getLatestCLIRelease()
if err != nil {
return err
}
url, err := release.assetURL(asset)
url, digest, err := release.asset(asset)
if err != nil {
return err
}
logger.Info("Installing Pangolin CLI %s from %s", release.TagName, url)
logger.Info("Installing Pangolin CLI %s from %s", release.Version, url)

if err := os.MkdirAll(cliInstallDir, 0o755); err != nil {
return err
Expand All @@ -102,7 +102,7 @@ func InstallCLI(userToken uintptr) error {
if err := os.Remove(tmpPath); err != nil {
return err
}
if err := downloadCLIAsset(url, tmpPath); err != nil {
if err := downloadCLIAsset(url, tmpPath, digest); err != nil {
return err
}
if err := checkELF(tmpPath); err != nil {
Expand All @@ -115,7 +115,7 @@ func InstallCLI(userToken uintptr) error {
if err := os.Rename(tmpPath, target); err != nil {
return fmt.Errorf("failed to install %s: %w", target, err)
}
logger.Info("Installed Pangolin CLI %s at %s", release.TagName, target)
logger.Info("Installed Pangolin CLI %s at %s", release.Version, target)
return nil
}

Expand Down
10 changes: 7 additions & 3 deletions managers/cli_installer_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"os/exec"
"path/filepath"
"syscall"

"github.com/fosrl/newt/logger"
)

const cliInstallerAssetName = "pangolin-cli_windows_installer.msi"
Expand Down Expand Up @@ -34,23 +36,25 @@ func authorizeCLIInstall(s *ManagerService) (userToken, error) {
}

func InstallCLI(userToken uintptr) error {
release, err := getLatestCLIRelease(cliInstallerRepo)
release, err := getLatestCLIRelease()
if err != nil {
return err
}

installerURL, err := release.assetURL(cliInstallerAssetName)
installerURL, digest, err := release.asset(cliInstallerAssetName)
if err != nil {
return err
}
logger.Info("Installing Pangolin CLI %s from %s", release.Version, installerURL)

tempDir, err := os.MkdirTemp("", "pangolin-cli-install-*")
if err != nil {
return fmt.Errorf("failed to create temp dir: %w", err)
}
defer os.RemoveAll(tempDir)

installerPath := filepath.Join(tempDir, cliInstallerAssetName)
if err := downloadCLIAsset(installerURL, installerPath); err != nil {
if err := downloadCLIAsset(installerURL, installerPath, digest); err != nil {
return err
}

Expand Down
Loading